dispach 0.1.0 → 0.1.2
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 +131 -31
- package/dist/App-b1yrwrcq.js +11 -0
- package/dist/{App-dxqm39zx.js.map → App-b1yrwrcq.js.map} +1 -1
- package/dist/{ConfigEditor-7v5nebvy.js → ConfigEditor-n8hdw6r7.js} +4 -4
- package/dist/{ConfigEditor-7v5nebvy.js.map → ConfigEditor-n8hdw6r7.js.map} +1 -1
- package/dist/{KeyProbe-vjhmdpx6.js → KeyProbe-9jjeze5r.js} +3 -3
- package/dist/{KeyProbe-vjhmdpx6.js.map → KeyProbe-9jjeze5r.js.map} +1 -1
- package/dist/{Picker-jxaesaxy.js → Picker-hfeh1g6m.js} +3 -3
- package/dist/{Picker-jxaesaxy.js.map → Picker-hfeh1g6m.js.map} +1 -1
- package/dist/{SessionPicker-z2t0p4b5.js → SessionPicker-zyqkg4dn.js} +3 -3
- package/dist/{SessionPicker-z2t0p4b5.js.map → SessionPicker-zyqkg4dn.js.map} +1 -1
- package/dist/{SkillBrowser-yyf2gy0q.js → SkillBrowser-3qdp8080.js} +3 -3
- package/dist/{SkillBrowser-yyf2gy0q.js.map → SkillBrowser-3qdp8080.js.map} +1 -1
- package/dist/WizardApp-vzpbydy3.js +5 -0
- package/dist/{WizardApp-12ndxgqv.js.map → WizardApp-vzpbydy3.js.map} +1 -1
- package/dist/client.js +10 -10
- package/dist/client.js.map +5 -5
- package/dist/{config-yz0nz51b.js → config-g7za9x13.js} +13 -13
- package/dist/{config-yz0nz51b.js.map → config-g7za9x13.js.map} +1 -1
- package/dist/credential-npr6z8c8.js +19 -0
- package/dist/{credential-wgt4gvcz.js.map → credential-npr6z8c8.js.map} +2 -2
- package/dist/index-02dn6m2j.js +7 -0
- package/dist/{index-h2yds678.js.map → index-02dn6m2j.js.map} +1 -1
- package/dist/index-0d93hyfc.js +6 -0
- package/dist/{index-rqbtm761.js.map → index-0d93hyfc.js.map} +1 -1
- package/dist/index-1c5113t4.js +66 -0
- package/dist/index-1c5113t4.js.map +12 -0
- package/dist/{index-3nwfz9jq.js → index-258d8bzg.js} +10 -10
- package/dist/{index-3nwfz9jq.js.map → index-258d8bzg.js.map} +1 -1
- package/dist/{index-9d011p3q.js → index-3g3ny01d.js} +4 -4
- package/dist/{index-9d011p3q.js.map → index-3g3ny01d.js.map} +1 -1
- package/dist/{index-8bmhd2hj.js → index-4cf6v9nb.js} +4 -4
- package/dist/{index-8bmhd2hj.js.map → index-4cf6v9nb.js.map} +1 -1
- package/dist/{index-bwckzbf8.js → index-4z7axw4r.js} +4 -4
- package/dist/{index-bwckzbf8.js.map → index-4z7axw4r.js.map} +1 -1
- package/dist/{index-xgqzk5cq.js → index-6p999cx4.js} +6 -6
- package/dist/{index-xgqzk5cq.js.map → index-6p999cx4.js.map} +1 -1
- package/dist/index-6q4wf8e3.js +6 -0
- package/dist/{index-jym27m75.js.map → index-6q4wf8e3.js.map} +1 -1
- package/dist/{index-cx3vz7sf.js → index-9r0wyj6w.js} +4 -4
- package/dist/{index-cx3vz7sf.js.map → index-9r0wyj6w.js.map} +1 -1
- package/dist/{index-j97vttdt.js → index-ammv5st7.js} +6 -6
- package/dist/{index-j97vttdt.js.map → index-ammv5st7.js.map} +1 -1
- package/dist/{index-qc2vrq9z.js → index-cqqb6gaq.js} +5 -5
- package/dist/{index-qc2vrq9z.js.map → index-cqqb6gaq.js.map} +1 -1
- package/dist/{index-jk0def33.js → index-d4x6yvqh.js} +4 -4
- package/dist/{index-jk0def33.js.map → index-d4x6yvqh.js.map} +1 -1
- package/dist/index-fecm8xe7.js +77 -0
- package/dist/index-fecm8xe7.js.map +12 -0
- package/dist/{index-e8n70sgj.js → index-fex44816.js} +4 -4
- package/dist/{index-e8n70sgj.js.map → index-fex44816.js.map} +1 -1
- package/dist/{index-gbnc99j8.js → index-ff514z3y.js} +9 -9
- package/dist/{index-gbnc99j8.js.map → index-ff514z3y.js.map} +1 -1
- package/dist/{index-t1xvacym.js → index-gme2egyq.js} +4 -4
- package/dist/{index-t1xvacym.js.map → index-gme2egyq.js.map} +1 -1
- package/dist/{index-mrtb5y08.js → index-gz9x25tz.js} +4 -4
- package/dist/{index-mrtb5y08.js.map → index-gz9x25tz.js.map} +1 -1
- package/dist/{index-9nsfs0vy.js → index-h9mw7b9d.js} +4 -4
- package/dist/{index-9nsfs0vy.js.map → index-h9mw7b9d.js.map} +1 -1
- package/dist/{index-6b7qvh1x.js → index-hwpvhaza.js} +4 -4
- package/dist/{index-6b7qvh1x.js.map → index-hwpvhaza.js.map} +1 -1
- package/dist/{index-6z0yr17z.js → index-j55s3ehk.js} +7 -7
- package/dist/{index-6z0yr17z.js.map → index-j55s3ehk.js.map} +1 -1
- package/dist/{index-mgdgx22q.js → index-j7gyr5nx.js} +6 -6
- package/dist/{index-mgdgx22q.js.map → index-j7gyr5nx.js.map} +1 -1
- package/dist/{index-7da4fqcr.js → index-mtn0g9vc.js} +5 -5
- package/dist/{index-7da4fqcr.js.map → index-mtn0g9vc.js.map} +1 -1
- package/dist/{index-rqzg861g.js → index-qdbq8crg.js} +4 -4
- package/dist/{index-rqzg861g.js.map → index-qdbq8crg.js.map} +1 -1
- package/dist/{index-xqyms08r.js → index-s9mbq7h6.js} +4 -4
- package/dist/{index-xqyms08r.js.map → index-s9mbq7h6.js.map} +1 -1
- package/dist/{index-9f9pp2ef.js → index-tf71ap9v.js} +4 -4
- package/dist/{index-9f9pp2ef.js.map → index-tf71ap9v.js.map} +1 -1
- package/dist/index-ttwyrdjs.js +427 -0
- package/dist/index-ttwyrdjs.js.map +11 -0
- package/dist/{index-2cvtz0fy.js → index-tv4yv7d2.js} +228 -228
- package/dist/{index-2cvtz0fy.js.map → index-tv4yv7d2.js.map} +9 -9
- package/dist/{index-fvhg0xyd.js → index-ty24n0jh.js} +79 -79
- package/dist/{index-fvhg0xyd.js.map → index-ty24n0jh.js.map} +1 -1
- package/dist/index-v8e92nfw.js +6 -0
- package/dist/{index-b8zwg8a3.js.map → index-v8e92nfw.js.map} +1 -1
- package/dist/index-vgc3y3rm.js +6 -0
- package/dist/{index-my5cjx00.js.map → index-vgc3y3rm.js.map} +1 -1
- package/dist/index-whaw4b18.js +6 -0
- package/dist/index-whaw4b18.js.map +10 -0
- package/dist/index.js +202 -198
- package/dist/index.js.map +6 -6
- package/dist/lib/bootstrap.d.ts +13 -0
- package/dist/lib/bootstrap.d.ts.map +1 -1
- package/dist/lib/commands.d.ts.map +1 -1
- package/dist/lib/init-flow.d.ts +17 -4
- package/dist/lib/init-flow.d.ts.map +1 -1
- package/dist/lib/provision.d.ts.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/{web-w7r68df1.js → web-vkb16r62.js} +5 -5
- package/dist/{web-w7r68df1.js.map → web-vkb16r62.js.map} +1 -1
- package/dist/wire.js +10 -10
- package/dist/wire.js.map +4 -4
- package/package.json +2 -2
- package/dist/App-dxqm39zx.js +0 -11
- package/dist/WizardApp-12ndxgqv.js +0 -5
- package/dist/credential-wgt4gvcz.js +0 -19
- package/dist/index-9pj1ws0p.js +0 -77
- package/dist/index-9pj1ws0p.js.map +0 -12
- package/dist/index-b5wwtxzk.js +0 -66
- package/dist/index-b5wwtxzk.js.map +0 -12
- package/dist/index-b8zwg8a3.js +0 -6
- package/dist/index-bry9bzt3.js +0 -427
- package/dist/index-bry9bzt3.js.map +0 -11
- package/dist/index-h2yds678.js +0 -7
- package/dist/index-jym27m75.js +0 -6
- package/dist/index-my5cjx00.js +0 -6
- package/dist/index-rqbtm761.js +0 -6
- package/dist/index-yr25dnf5.js +0 -6
- package/dist/index-yr25dnf5.js.map +0 -10
package/dist/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{Mt,e,E,tr,t,_e,fn,Ie,mt,je,H,hn,kr,Sr,ye,xr,ze,we,mn,pt,T,x,R,yt,He,wt,gn,We,_,M,$r,L,yn,Rr,Ir,m,Co}from"./index-tv4yv7d2.js";import{Me,Fn,Un,jn}from"./index-1c5113t4.js";import{A,O,Y,N,X,C,fr,et,hr,Ht,G,Kr,Hr,Wr,Mn,ce,tt,ke,Ln,Se,nt,qr,Gr}from"./index-ty24n0jh.js";import{Ko}from"./index-d4x6yvqh.js";import{Et}from"./index-gme2egyq.js";import{ct,ut,cn,Nt,un,ft,Qn,Ct,Pt,Fe,Te,ht,er}from"./index-ttwyrdjs.js";import{Rt,le,Ot}from"./index-whaw4b18.js";import{on,sn,$t,Xn,lt,bo,ko,So}from"./index-258d8bzg.js";import"./index-cqqb6gaq.js";import{cr,Lr,Xe,Dr,Fr,Ur}from"./index-fecm8xe7.js";import{Ye,Pr}from"./index-ammv5st7.js";import{jr}from"./index-hwpvhaza.js";import{zr,Pn,Br,Ce,Pe,St,xt,Je,Qe,Kt}from"./index-qdbq8crg.js";import{Wt,pe,Zr,b,Vr,J,ue,Dn,Yr,Z,ie}from"./index-6p999cx4.js";import{Ee,ee,B,w,Xt,Jt,ao,K,te}from"./index-mtn0g9vc.js";import{Hn}from"./index-4cf6v9nb.js";import{_o,$o}from"./index-tf71ap9v.js";import{Ro}from"./index-s9mbq7h6.js";import{q}from"./index-h9mw7b9d.js";import{l,p,d,c,bt,or,vt,qe}from"./index-j7gyr5nx.js";import{jo,Bo}from"./index-3g3ny01d.js";import{_n,Jo,ve,j,An,Cn,n,s,Bt,us}from"./index-vgc3y3rm.js";async function Gt(r){let o=await L.create({agents:[...r.manifestPaths],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m(r.manifestPaths),store:w(),lease:!1});b(()=>o.stop("cli-exit"));let a=o.list().map((f)=>f.describe()),u=new Map;for(let f of await o.store.leases.all()){if(f.runtimeId===o.runtimeId||!_(f.pid))continue;let h=Date.now()-Date.parse(f.startedAt);u.set(f.agentId,`serving · ${f.mode} · pid ${f.pid}${Number.isFinite(h)?` · up ${or(h)}`:""}`)}if(r.json===!0)return process.stdout.write(`${JSON.stringify({agents:a.map((f)=>({...f,serving:u.get(f.id)??null}))},null,2)}
|
|
3
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
|
|
5
|
-
${l(r.rows)}`}function
|
|
6
|
-
`),u=Object.entries(r.environment).map(([f,h])=>` <key>${
|
|
7
|
-
<string>${
|
|
4
|
+
`),n}import{closeSync as Wo,existsSync as Tr,mkdirSync as Go,openSync as qo,readFileSync as Vo,readSync as Xo,statSync as Ar}from"node:fs";import{homedir as Yn}from"node:os";import{dirname as kn,join as Or,resolve as zo}from"node:path";function qt(r){let o=[];if(r.problem!==void 0)o.push({code:"daemon_agent_unreadable",severity:"warn",message:`Agent "${r.agentId}" could not be read: ${r.problem}`,hint:"The host skips an agent whose manifest will not load and serves the rest, so this is a warning rather than a refusal — `validate` on that agent says exactly what is wrong with it."});if(r.envFileMode!==void 0&&(r.envFileMode&63)!==0)o.push({code:"daemon_env_world_readable",severity:"warn",message:`${r.agentId}'s .env is mode ${(r.envFileMode&511).toString(8)} and holds its only secrets.`,hint:`Under a service manager that file is the *only* path credentials arrive by — a unit carries none on purpose, because its manager echoes the environment in plaintext. \`chmod 600 ${r.agentDir}/.env\`.`});return o}function Eo(r){let o=[];if(r.gitRoot!==void 0)o.push({code:"daemon_binary_in_checkout",severity:"warn",message:`The binary resolves to ${r.scriptPath}, inside a git checkout at ${r.gitRoot}.`,hint:"A rebuild, a branch switch or a `git clean` changes or breaks what the service runs, and the failure arrives with no obvious connection to the change. Fine for testing; install a released build for a service you intend to leave running."});if(/[/.](nvm|fnm|volta|asdf)\//.test(r.execPath))o.push({code:"daemon_versioned_runtime",severity:"warn",message:`The interpreter is a version-managed install: ${r.execPath}`,hint:"The absolute path is baked into the service definition, so removing that runtime version later kills the service with a message only the log file sees. A system or Homebrew install is more durable."});return o}function Vt(r){let o=[];for(let a of r.retiring)o.push({code:"daemon_per_agent_retired",severity:"warn",message:`Retiring ${a} — one service hosts every agent now.`,hint:"It is unloaded, re-enabled and its definition removed. The re-enable is not cosmetic: a `disable` row persists across boots and no verb deletes it, so a label left disabled makes any future job with that name install cleanly and silently never start. Per-agent on/off is `stop <agent>`, which persists in the store instead."});if(r.servedElsewhere.length>0){let a=r.servedElsewhere[0];o.push({code:"daemon_agents_held_elsewhere",severity:"warn",message:`${r.servedElsewhere.length} agent(s) are held by other live processes — ${a?.agentId} by pid ${a?.pid} (${a?.mode}).`,hint:"The service will start and serve everything else, and report those as served elsewhere rather than fighting for them — one listener per bot token is the whole reason the lease exists. `stop` with no agent ends the other processes."})}return o.push(...Eo(r.binary)),o}function Io(r,o="serving on"){let a=r.lastIndexOf(o);return a===-1?r:r.slice(a)}function zt(r){let o=Io(r),a=[],u=new Set;for(let i of o.matchAll(/denied — Sender "([^"]+)" is not in channel "([^"]+)"/g))if(i[1]!==void 0)u.add(`${i[1]}|${i[2]??""}`);for(let i of u){let[f,h]=i.split("|");a.push({code:"inbound_denied",summary:`messages from ${f} are being refused — they are not on channel "${h}"'s allowFrom list`,fix:`add ${f} to allowFrom in agent.yaml, then restart. An allowlist that is empty, or that has a typo in it, refuses silently from the sender's side: they see nothing at all.`})}if(/channel_telegram_unauthorized|telegram_token_missing/.test(o))a.push({code:"channel_unauthorized",summary:"the channel rejected its token",fix:"check the token in the .env beside the manifest, then restart."});return a}var To=3;function Yt(r,o){let a=Ao(o),u=[];if(o.pid!==void 0)u.push({label:"state",value:`running · pid ${o.pid}`,...o.uptimeMs===void 0?{}:{note:`up ${or(o.uptimeMs)}`}});else if(o.leasePid!==void 0)u.push({label:"state",value:`running in a terminal · pid ${o.leasePid}`,note:"not installed as a service"});if(o.runs!==void 0&&o.runs>1)u.push({label:"starts",value:String(o.runs),...a==="restart-loop"?{note:`launchd has restarted this ${o.runs} times`}:{note:"since the service was installed"}});if(a!=="running"&&o.lastExitCode!==void 0&&o.lastExitCode!==0)u.push({label:"last exit",value:`code ${o.lastExitCode}`});if(o.stderrPath!==void 0)u.push({label:"logs",value:o.stderrPath,...o.stderrBytes===void 0?{}:{note:`(${bt(o.stderrBytes)})`}});return{verdict:a,healthy:a==="running",headline:a==="restart-loop"?`${r} — RESTART LOOP`:`${r} — ${Oo(a)}`,rows:u,wantsStderrTail:a==="restart-loop"||a==="failed"||a==="installed-idle"}}function Ao(r){if(!r.installed)return r.leasePid===void 0?"absent":"running";if(r.pid!==void 0)return"running";if(r.disabled)return"stopped";if((r.runs??0)>=To&&(r.lastExitCode??0)!==0)return"restart-loop";if((r.lastExitCode??0)!==0)return"failed";return"installed-idle"}function Oo(r){switch(r){case"running":return"running";case"failed":return"STOPPED AFTER A FAILURE";case"restart-loop":return"exited · nothing is running";case"stopped":return"stopped by you";case"installed-idle":return"installed · not running";case"absent":return"not installed"}}function Qt(r){return`${r.headline}
|
|
5
|
+
${l(r.rows)}`}function dn(r){return["HOME","PATH","TMPDIR",`${r}SERVICE`,`${r}HOME`]}class Wn extends Error{code="daemon_secret_in_service";hint;constructor(r,o,a){super(`The service definition would carry an environment variable named ${r}.`);this.hint=`A ${a} unit is readable and its manager echoes every environment value in plaintext to any process running as this user — so a credential here is a credential published. The agent reads its own secrets from the .env beside its manifest, which is what the service is pointed at. Only these may appear: ${o.join(", ")}.`}}function ln(r,o,a){let u=dn(o);for(let i of Object.keys(r))if(!u.includes(i))throw new Wn(i,u,a)}var No={Crashed:!0},Be=30,Ge=30;function pn(r,o){return`${r}.agent.${o}`}function Ke(r){return`${r}.server`}function Re(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function wn(r,o){ln(r.environment,o,"launchd");let a=r.programArguments.map((f)=>` <string>${Re(f)}</string>`).join(`
|
|
6
|
+
`),u=Object.entries(r.environment).map(([f,h])=>` <key>${Re(f)}</key>
|
|
7
|
+
<string>${Re(h)}</string>`).join(`
|
|
8
8
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
9
9
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
10
10
|
<!--
|
|
11
|
-
${r.provenance.map((f)=>` ${
|
|
11
|
+
${r.provenance.map((f)=>` ${Re(f)}`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
-->
|
|
14
14
|
<plist version="1.0">
|
|
15
15
|
<dict>
|
|
16
16
|
<key>Label</key>
|
|
17
|
-
<string>${
|
|
17
|
+
<string>${Re(r.label)}</string>
|
|
18
18
|
<key>ProgramArguments</key>
|
|
19
19
|
<array>
|
|
20
20
|
${a}
|
|
@@ -24,7 +24,7 @@ ${a}
|
|
|
24
24
|
<key>KeepAlive</key>
|
|
25
25
|
<dict>
|
|
26
26
|
<key>Crashed</key>
|
|
27
|
-
<${
|
|
27
|
+
<${No.Crashed}/>
|
|
28
28
|
</dict>
|
|
29
29
|
<key>ThrottleInterval</key>
|
|
30
30
|
<integer>${Be}</integer>
|
|
@@ -33,25 +33,25 @@ ${a}
|
|
|
33
33
|
<key>ProcessType</key>
|
|
34
34
|
<string>Adaptive</string>
|
|
35
35
|
<key>WorkingDirectory</key>
|
|
36
|
-
<string>${
|
|
36
|
+
<string>${Re(r.workingDirectory)}</string>
|
|
37
37
|
<key>StandardOutPath</key>
|
|
38
|
-
<string>${
|
|
38
|
+
<string>${Re(r.stdoutPath)}</string>
|
|
39
39
|
<key>StandardErrorPath</key>
|
|
40
|
-
<string>${
|
|
40
|
+
<string>${Re(r.stderrPath)}</string>
|
|
41
41
|
<key>EnvironmentVariables</key>
|
|
42
42
|
<dict>
|
|
43
43
|
${u}
|
|
44
44
|
</dict>
|
|
45
45
|
</dict>
|
|
46
46
|
</plist>
|
|
47
|
-
`}function
|
|
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
|
|
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
|
|
50
|
-
`)){let u=/^\s*"(.+)"\s*=>\s*(disabled|true)\s*$/.exec(a);if(u?.[1]!==void 0)o.push(u[1])}return o}function
|
|
47
|
+
`}function Zt(r){let o=[];for(let a of r.split(`
|
|
48
|
+
`)){let u=a.split("\t");if(u.length<3)continue;let[i,f,h]=u;if(h===void 0||h==="Label"||h==="")continue;let g=Number.parseInt(f??"",10);o.push({...i===void 0||i==="-"?{}:{pid:Number.parseInt(i,10)},status:Number.isFinite(g)?g:0,label:h})}return o}function nr(r){let o={};for(let a of r.split(`
|
|
49
|
+
`)){let u=a.trim(),i=/^pid = (\d+)$/.exec(u);if(i?.[1]!==void 0)o.pid=Number.parseInt(i[1],10);let f=/^runs = (\d+)$/.exec(u);if(f?.[1]!==void 0)o.runs=Number.parseInt(f[1],10);let h=/^last exit code = (-?\d+)$/.exec(u);if(h?.[1]!==void 0)o.lastExitCode=Number.parseInt(h[1],10);let g=/^state = (.+)$/.exec(u);if(g?.[1]!==void 0)o.jobState=g[1];let v=/^stdout path = (.+)$/.exec(u);if(v?.[1]!==void 0)o.stdoutPath=v[1];let k=/^stderr path = (.+)$/.exec(u);if(k?.[1]!==void 0)o.stderrPath=k[1]}return o}function rr(r){let o=[];for(let a of r.split(`
|
|
50
|
+
`)){let u=/^\s*"(.+)"\s*=>\s*(disabled|true)\s*$/.exec(a);if(u?.[1]!==void 0)o.push(u[1])}return o}function Fo(r,o){if(o<r)return{from:0,to:o,truncated:!0};return{from:r,to:o,truncated:!1}}async function sr(r,o,a){let u=new Map(r.map((f)=>[f.path,a.offsets[f.path]??0])),i;while(!o.stopped()){for(let f of r){let h=o.sizeOf(f.path);if(h===void 0)continue;let g=Fo(u.get(f.path)??0,h);if(u.set(f.path,g.to),g.truncated)o.write(`
|
|
51
51
|
── ${f.label} was emptied ──
|
|
52
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
53
|
── ${f.label} ──
|
|
54
|
-
`),i=f.label;o.write(v)}await o.wait(a.intervalMs)}}import{existsSync as
|
|
54
|
+
`),i=f.label;o.write(v)}await o.wait(a.intervalMs)}}import{existsSync as Mo,mkdirSync as qn,readdirSync as ur,rmSync as mr,writeFileSync as pr}from"node:fs";import{basename as Uo,dirname as vn,join as lr}from"node:path";import{join as ir}from"node:path";function ar(r,o,a=process.env){let u=a.XDG_CONFIG_HOME,i=u===void 0||u===""?ir(o,".config"):u;return ir(i,"systemd","user",`${r}.service`)}function Gn(r,o){if(/[\r\n]/.test(r))throw Error(`${o} contains a newline, which systemd cannot express. hint: a unit value runs to end of line, so this would silently truncate rather than fail — rename the path.`)}function Lo(r){if(!/[\s"\\]/.test(r))return r;return`"${r.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function bn(r,o){ln(r.environment,o,"systemd");for(let f of r.programArguments)Gn(f,"ExecStart");Gn(r.workingDirectory,"WorkingDirectory");for(let[f,h]of Object.entries(r.environment))Gn(h,`Environment=${f}`);let a=r.programArguments.map(Lo).join(" "),u=Object.entries(r.environment).map(([f,h])=>`Environment=${f}=${h}`).join(`
|
|
55
55
|
`);return`${r.provenance.map((f)=>`# ${f}`).join(`
|
|
56
56
|
`)}
|
|
57
57
|
|
|
@@ -76,14 +76,14 @@ KillMode=mixed
|
|
|
76
76
|
|
|
77
77
|
[Install]
|
|
78
78
|
WantedBy=default.target
|
|
79
|
-
`}function
|
|
79
|
+
`}function dr(r,o){return["systemctl --user daemon-reload",`systemctl --user enable --now ${r}`,`loginctl enable-linger ${o}`]}var Do=6000,Ho=200,gr=(r,o)=>{let a=Ro({command:r,args:o});return{code:a.code,stdout:a.stdout,stderr:a.stderr}};function Ue(r,o){if(r==="darwin")return new br(o);if(r==="linux")return new wr(o);throw Vn(r)}function yr(r){return r==="darwin"}function Vn(r,o){let a=o===void 0?"":` For a systemd user unit, the line to write is:
|
|
80
80
|
|
|
81
81
|
${o}
|
|
82
82
|
Restart=on-failure
|
|
83
83
|
RestartSec=30
|
|
84
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
|
|
86
|
-
${l([{label:"runs",value:`${
|
|
85
|
+
Put no secrets in the unit: the agent reads the .env beside its manifest, and \`systemctl show\` echoes Environment= to anyone.`;return new t({code:"daemon_platform_unsupported",message:`daemon installs a macOS LaunchAgent or a systemd user unit, and this platform is ${r}.`,hint:`No service manager is implemented for this platform.${a} In a container, run \`serve\` in the foreground and let the container runtime supervise it; that is the deployment this runtime is designed around.`})}class wr{id="systemd";#r;#e;#s;#t;constructor(r){this.#r=r.home,this.#e=r.envPrefix,this.#s=r.exec??gr,this.#t=r.env??process.env}unitPath(r){return ar(r,this.#r,this.#t)}install(r){let o=this.unitPath(r.label),a=bn(r,this.#e);qn(vn(o),{recursive:!0}),pr(o,a,{encoding:"utf8",mode:384})}uninstall(r){mr(this.unitPath(r),{force:!0})}stop(r){throw this.#n(`systemctl --user stop ${r}`)}start(r){throw this.#n(`systemctl --user start ${r}`)}restart(r){throw this.#n(`systemctl --user restart ${r}`)}state(r){return{installed:Mo(this.unitPath(r)),disabled:!1,liveness:!1}}labels(r){try{return ur(vn(this.unitPath(r))).filter((o)=>o.startsWith(r)&&o.endsWith(".service")).map((o)=>o.slice(0,-8)).sort()}catch{return[]}}followUp(r){return dr(r,this.#o())}caution(){let r=this.#o(),o=this.#s("loginctl",["show-user",r,"--property=Linger"]);if(o.code===0&&/Linger=yes/i.test(o.stdout))return;return`A systemd user unit stops when your last session ends. \`loginctl enable-linger ${r}\` is what keeps it running after you log out or close an SSH connection.`}#o(){return this.#t.USER??this.#t.LOGNAME??Uo(this.#r)}#n(r){return new t({code:"daemon_manual_step",message:`This has to be run yourself: ${r}`,hint:`Unit files are written and read from here, and the lifecycle is not driven from here — nothing in this project's test environment can run \`systemctl --user\` (a container has no systemd, and a CI runner has no user session bus), and a command that reported success while nothing happened would be worse than this sentence. The unit is at ${this.unitPath(r.split(" ").pop()??"")}.`})}}class br{id="launchd";#r;#e;#s;#t;constructor(r){this.#r=r.home,this.#e=`gui/${r.uid}`,this.#s=r.envPrefix,this.#t=r.exec??gr}unitPath(r){return lr(this.#r,"Library","LaunchAgents",`${r}.plist`)}install(r){let o=this.unitPath(r.label),a=wn(r,this.#s);if(qn(vn(o),{recursive:!0}),qn(vn(r.stdoutPath),{recursive:!0}),this.#n(["bootout",`${this.#e}/${r.label}`],{tolerate:!0}),this.#o(r.label),pr(o,a,{encoding:"utf8",mode:384}),this.#n(["enable",`${this.#e}/${r.label}`],{tolerate:!0}),this.#n(["bootstrap",this.#e,o]),!this.state(r.label).installed)throw new t({code:"daemon_not_loaded",message:`${r.label} was written to ${o} but launchd did not load it.`,hint:`\`launchctl bootstrap\` returned success and \`launchctl print ${this.#e}/${r.label}\` finds nothing, which usually means an earlier copy was still unloading. Try again in a moment. Over SSH with no desktop session the ${this.#e} domain is unavailable and no LaunchAgent can load at all.`})}#o(r){let o=Date.now()+Do;while(Date.now()<o){if(this.#t("launchctl",["print",`${this.#e}/${r}`]).code!==0)return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Ho)}}uninstall(r){this.#n(["bootout",`${this.#e}/${r}`],{tolerate:!0}),this.#n(["enable",`${this.#e}/${r}`],{tolerate:!0}),mr(this.unitPath(r),{force:!0})}stop(r){this.#n(["disable",`${this.#e}/${r}`],{tolerate:!0}),this.#n(["bootout",`${this.#e}/${r}`],{tolerate:!0})}start(r){this.#n(["enable",`${this.#e}/${r}`],{tolerate:!0}),this.#n(["bootstrap",this.#e,this.unitPath(r)])}restart(r){this.#n(["kickstart","-k",`${this.#e}/${r}`])}state(r){let o=this.#t("launchctl",["print",`${this.#e}/${r}`]),a=rr(this.#t("launchctl",["print-disabled",this.#e]).stdout).includes(r);if(o.code!==0)return{installed:!1,disabled:a,liveness:!0};let u=nr(o.stdout);return{installed:!0,disabled:a,liveness:!0,print:u,...u.pid===void 0?{}:{pid:u.pid}}}labels(r){let o=Zt(this.#t("launchctl",["list"]).stdout).map((u)=>u.label).filter((u)=>u.startsWith(r)),a=[];try{a=ur(lr(this.#r,"Library","LaunchAgents")).filter((u)=>u.startsWith(r)&&u.endsWith(".plist")).map((u)=>u.slice(0,-6))}catch{}return[...new Set([...o,...a])].sort()}followUp(){return[]}caution(){return}#n(r,o={}){let a=this.#t("launchctl",r);if(a.code===0||o.tolerate===!0)return a;throw new t({code:"daemon_launchctl_failed",message:`launchctl ${r.join(" ")} failed (${a.code}): ${a.stderr.trim()||"no output"}`,hint:`Code 5 usually means the service is already loaded — try \`daemon restart\`. Code 37 means an operation is still in progress; wait a moment. Code 125 or 112 means the ${this.#e} domain is unavailable, which happens over SSH with no GUI session: a LaunchAgent needs a logged-in desktop session, and the exit timeout is ${Ge}s.`})}}var vr=["install","uninstall","start","stop","restart","status","logs"];async function Ze(r){if(!vr.includes(r.action))throw new t({code:"cli_daemon_unknown_action",message:`daemon takes one of ${vr.join(", ")}, not "${r.action}".`,hint:`Usage: ${e.slug} daemon <action> <agent>. Run \`${e.slug} daemon --help\` for what each one does.`});let o=r.action;if(r.manifestPath!==void 0&&o!=="status"&&o!=="logs")throw new t({code:"daemon_per_agent_retired",message:`daemon ${o} no longer takes an agent — one service hosts every agent.`,hint:`\`${e.slug} daemon ${o}\` acts on that one service. Per-agent on/off is \`${e.slug} stop <agent>\` and \`${e.slug} start <agent>\`, which persist in the store rather than as a unit — so an agent you switch off stays off across a restart without the host going down with it.`});let a=r.platform??process.platform,u=Qo();if(a!=="darwin"&&a!=="linux"&&o!=="status")throw Vn(a,ei(u,r.manifestPath??"<manifest>"));let i=a==="darwin"||a==="linux"?Ue(a,{home:Yn(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec},...r.env===void 0?{}:{env:r.env}}):void 0;switch(o){case"status":return await oi(r,i);case"install":return await Yo(r,u,i);case"uninstall":return ri(r,i);case"start":case"stop":case"restart":return si(o,i);case"logs":return await di(r)}}async function Yo(r,o,a){let u=Ke(e.slug),i=Xt(r.env),f=(a?.labels(`${e.slug}.agent.`)??[]).filter((y)=>y!==u),h=[...Vt({binary:o,retiring:f,servedElsewhere:(await St(r.store)).map((y)=>({agentId:y.agentId,pid:y.pid,mode:y.mode}))}),...K(r.env).flatMap((y)=>{let S=ti(y.dir);return qt({agentId:y.id??y.ref,agentDir:y.dir,...y.problem===void 0?{}:{problem:y.problem},...S===void 0?{}:{envFileMode:S}})})],g={label:u,programArguments:[o.execPath,o.scriptPath,"serve","--store",w()],workingDirectory:ee(r.env),stdoutPath:i.out,stderrPath:i.err,environment:ni(u),provenance:[`Generated by \`${e.slug} daemon install\`. One service hosts every agent.`,"Rewritten on every install — it names no agent, so there is nothing here to edit","when you add one. Switch an agent off with `stop <agent>`, which persists.","There are no secrets here and there never will be: a service manager echoes a","unit's environment in plaintext to anything running as this user. Each agent","reads its own credentials from the .env beside its manifest."]};if(r.dryRun===!0){if(process.stdout.write(a?.id==="systemd"?bn(g,e.envPrefix):wn(g,e.envPrefix)),h.length>0)process.stderr.write(Er(h));return n}for(let y of f)a?.uninstall(y);if(h.length>0)process.stdout.write(Er(h));Go(kn(i.out),{recursive:!0}),a?.install(g);let v=a?.followUp(u)??[];if(process.stdout.write(`${u} — ${v.length===0?"service installed":"unit written"}
|
|
86
|
+
${l([{label:"runs",value:`${Ve(o.execPath)} … serve`},{label:"hosts",value:"every agent in the sandbox that is not stopped"},{label:"logs",value:Ve(i.err)},{label:"restarts",value:`on crash only, at most one per ${Be}s`}])}
|
|
87
87
|
`),v.length>0)process.stdout.write(`
|
|
88
88
|
Not started yet — run these:
|
|
89
89
|
${v.map((y,S)=>` ${S+1}. ${y}`).join(`
|
|
@@ -92,18 +92,18 @@ ${v.map((y,S)=>` ${S+1}. ${y}`).join(`
|
|
|
92
92
|
${k}
|
|
93
93
|
`);return process.stdout.write(`
|
|
94
94
|
A configuration error stops it once rather than looping — \`${e.slug} daemon status\` says why.
|
|
95
|
-
`),n}function
|
|
95
|
+
`),n}function Qo(){let r=Jn(process.execPath),o=Jn(process.argv[1]??""),a=Zo(kn(o));return{execPath:r,scriptPath:o,...a===void 0?{}:{gitRoot:a}}}function Jn(r){try{return Mt("node:fs").realpathSync(r)}catch{return r}}function Zo(r){let o=r;for(let a=0;a<40;a+=1){if(Tr(Or(o,".git")))return o;let u=kn(o);if(u===o)return;o=u}return}function ei(r,o){return`ExecStart=${r.execPath} ${r.scriptPath} serve ${o} --store ${w()}`}function ni(r){let o=Yn(),u=[kn(Jn(process.execPath)),"/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"].filter((h,g,v)=>v.indexOf(h)===g).join(":"),i={HOME:o,PATH:u,[`${e.envPrefix}SERVICE`]:r},f=process.env[`${e.envPrefix}HOME`];if(f!==void 0&&f!=="")i[`${e.envPrefix}HOME`]=f;return i}function ti(r){try{return Ar(Or(r,".env")).mode}catch{return}}function Er(r){return`${r.map((o)=>`${o.severity==="block"?"refused":"warning"}: ${o.message}
|
|
96
96
|
hint: ${o.hint}`).join(`
|
|
97
97
|
|
|
98
98
|
`)}
|
|
99
|
-
`}function
|
|
99
|
+
`}function ri(r,o){let a=Ke(e.slug),u=Xt(r.env);for(let i of(o?.labels(`${e.slug}.agent.`)??[]).filter((f)=>f!==a))o?.uninstall(i),process.stdout.write(` also removed ${i}
|
|
100
100
|
`);return o?.uninstall(a),process.stdout.write(`${a} — service removed
|
|
101
|
-
${l([{label:"logs kept",value:
|
|
102
|
-
`),n}function
|
|
103
|
-
`),n}async function
|
|
101
|
+
${l([{label:"logs kept",value:Ve(u.err)},{label:"agents",value:"unchanged — nothing was switched off"}])}
|
|
102
|
+
`),n}function si(r,o){let a=Ke(e.slug);if(o===void 0)return s;if(r==="start")o.start(a);if(r==="stop")o.stop(a);if(r==="restart")o.restart(a);let u=r==="stop"?" — the whole host. It stays stopped across a login until you start it again, and no"+" agent was switched off":"";return process.stdout.write(`${a} — ${r}${r==="stop"?"ped":"ed"}${u}
|
|
103
|
+
`),n}async function oi(r,o){let a=Ke(e.slug),u=await St(r.store);if(r.manifestPath===void 0){if(o?.state(a).installed!==!0&&u.length===0)return process.stdout.write(`no server is installed and nothing is running
|
|
104
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]:[
|
|
106
|
-
`);else{for(let v of f){process.stdout.write(`${
|
|
105
|
+
`),s}let i=r.manifestPath===void 0?[a]:[_r(r.manifestPath)],f=await Promise.all(i.map((v)=>ai(v,o,{...v===a?{label:a}:{},logs:v===a?Xt(r.env):Jt(v),...r.store===void 0?{}:{store:r.store},...v===a&&u[0]!==void 0?{leaseOf:u[0].agentId}:{}}))),h=r.manifestPath===void 0&&u.length>0?u.map((v)=>v.agentId).sort():[],g=(await ii()).filter((v)=>r.manifestPath===void 0||i.includes(v.agentId));if(r.json===!0)process.stdout.write(`${JSON.stringify({agents:f,hosting:h,disabled:g},null,2)}
|
|
106
|
+
`);else{for(let v of f){process.stdout.write(`${Qt(v.report)}
|
|
107
107
|
`);for(let k of v.attention)process.stdout.write(`
|
|
108
108
|
needs you ${k.summary}
|
|
109
109
|
${k.fix}
|
|
@@ -118,41 +118,41 @@ ${c(v.tail,4)}
|
|
|
118
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
119
|
`);process.stdout.write(` \`${e.slug} start <agent>\` switches one back on — a restart alone will not.
|
|
120
120
|
|
|
121
|
-
`)}}return f.every((v)=>v.report.healthy)?n:s}async function
|
|
122
|
-
`),n}let i=
|
|
121
|
+
`)}}return f.every((v)=>v.report.healthy)?n:s}async function ii(){try{let r=await M.open({path:w()});try{return(await r.agentState.list()).filter((o)=>!o.enabled).map((o)=>({agentId:o.agentId,...o.reason===void 0?{}:{reason:o.reason},...o.disabledAt===void 0?{}:{disabledAt:o.disabledAt}}))}finally{await r.close()}}catch{return[]}}async function ai(r,o,a){let u=a.label,i=u===void 0?void 0:o?.unitPath(u),f=u===void 0?void 0:o?.state(u),h=a.logs,g;try{let U=await M.open({path:a.store??w()});g=await U.leases.get(a.leaseOf??r),await U.close()}catch{g=void 0}if(g!==void 0&&!_(g.pid))g=void 0;let v=f?.print?.stderrPath??h.err,k=$n(v),y={installed:i!==void 0&&Tr(i)||f?.installed===!0,disabled:f?.disabled??!1,...f?.pid===void 0?{}:{pid:f.pid},...f?.print?.runs===void 0?{}:{runs:f.print.runs},...f?.print?.lastExitCode===void 0?{}:{lastExitCode:f.print.lastExitCode},stderrPath:Ve(v),...k===void 0?{}:{stderrBytes:k},...g===void 0?{}:{leasePid:g.pid,leaseMode:g.mode,leaseStartedAt:g.startedAt,uptimeMs:Date.now()-Date.parse(g.startedAt)}},S=Yt(r,y),P=zt(zn(h.out,200));return{agentId:r,report:S,tail:S.wantsStderrTail?zn(v,20):"",attention:P}}async function di(r){let o=r.manifestPath===void 0?void 0:_r(r.manifestPath),a=o??Ke(e.slug),u=o===void 0?Xt(r.env):Jt(o);if(r.truncate===!0){for(let f of[u.out,u.err])try{Mt("node:fs").writeFileSync(f,"")}catch{}return process.stdout.write(`${a} — logs truncated
|
|
122
|
+
`),n}let i=zn(u.err,r.lines??40);if(process.stdout.write(i===""?`${Ve(u.err)} is empty
|
|
123
123
|
`:`${i}
|
|
124
|
-
`),r.follow!==!0)return n;return await
|
|
124
|
+
`),r.follow!==!0)return n;return await sr([{path:u.err,label:"stderr"},{path:u.out,label:"stdout"}],li(),{offsets:{[u.err]:$n(u.err)??0,[u.out]:$n(u.out)??0},intervalMs:us}),n}function li(){let r=!1,o,a=()=>{r=!0,o?.()};return process.on("SIGINT",a),b(()=>{process.off("SIGINT",a)}),{sizeOf:(u)=>$n(u),read:(u,i,f)=>{try{let h=qo(u,"r");try{let g=Buffer.alloc(f-i),v=Xo(h,g,0,g.length,i);return g.subarray(0,v).toString("utf8")}finally{Wo(h)}}catch{return""}},write:(u)=>void process.stdout.write(u),wait:(u)=>new Promise((i)=>{if(r){i();return}let f=setTimeout(i,u);o=()=>{clearTimeout(f),i()}}),stopped:()=>r}}function _r(r){let o=T(r);if(o.id===void 0||o.id==="")throw new t({code:"cli_daemon_agent_id_missing",message:`${r} declares no id, so there is no stable name to install a service under.`,hint:"A service label is derived from the manifest id and has to survive a rename of the directory. Add `id: <name>` to the manifest."});return o.id}function Ve(r){return vt(zo(r),Yn())}function $n(r){try{return Ar(r).size}catch{return}}function zn(r,o){try{let a=Vo(r,"utf8").trimEnd();if(a==="")return"";return a.split(`
|
|
125
125
|
`).slice(-o).join(`
|
|
126
|
-
`)}catch{return""}}var
|
|
126
|
+
`)}catch{return""}}var ll=dn(e.envPrefix);import{basename as Si,dirname as xi,join as xe,resolve as Pi}from"node:path";import{rmSync as ci}from"node:fs";import{isAbsolute as Cr,join as ui,resolve as Nr}from"node:path";var fi=3;async function Mr(r){if(r.answers.skills!=="find")return;let o=r.answers.skillsSearch?.trim()??"";if(o===""){process.stdout.write("\nno words to search for, so no skill was installed — `sources search <words>` when you know what you want\n");return}let a=G(r.env);if(a.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
|
|
127
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
|
|
128
|
+
`);let u=[],i=[];for(let y of a){if(!ce(y.name,r.env))try{await tt(y,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}})}catch(S){i.push(`${y.name} — ${S instanceof t?S.message:String(S)}`);continue}u.push(...ke(y,r.env))}for(let y of i)process.stdout.write(c(`could not fetch ${y}
|
|
129
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
130
|
${c("`sources update` reports why; `sources search <words>` when it works",4)}
|
|
131
|
-
`);return}let f=
|
|
131
|
+
`);return}let f=mi(o,u);if(f.length===0){process.stdout.write(`${c(`nothing in ${u.length} skills matches those words, so none was installed`)}
|
|
132
132
|
${c("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
|
|
133
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+
|
|
134
|
+
`),f.length>1)process.stdout.write(`${c(`also matched: ${f.slice(1,1+fi).map((y)=>`${y.source}/${y.skill}`).join(", ")}`,4)}
|
|
135
135
|
`);if(process.stdout.write(`
|
|
136
|
-
`),
|
|
136
|
+
`),Se({action:"install",manifestPath:r.manifestPath,name:g,...r.env===void 0?{}:{sandboxEnv:r.env},...r.envOverlay===void 0?{}:{envOverlay:r.envOverlay}})!==n)return;let k=pi(r.manifestPath,r.envOverlay);if(k!==void 0)hi(r.manifestPath,h.skill,r.envOverlay),process.stdout.write(`
|
|
137
137
|
${d(`${g} was removed again: it does not load on this machine`)}
|
|
138
138
|
${c(k,4)}
|
|
139
139
|
${c("everything else is fine; `sources search` for one that needs no extra runtime",4)}
|
|
140
|
-
`)}function
|
|
141
|
-
`),n;return o.kind==="failed"?o.code:n}async function
|
|
142
|
-
`);let v=
|
|
143
|
-
${
|
|
144
|
-
`),{kind:"failed",code:s};throw
|
|
145
|
-
`),f.skills==="find"){let
|
|
146
|
-
`);try{
|
|
147
|
-
`)}}return process.stdout.write(
|
|
140
|
+
`)}function mi(r,o){let a=new Map,u=o.filter((i)=>i.problem===void 0).map((i)=>{let f=`${i.source}/${i.skill}`;return a.set(f,i),{name:f,dir:i.dir,tokens:i.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:f,description:i.description,metadata:{}}}});return wt(r,u).filter((i)=>i.score>0).map((i)=>a.get(i.skill.name)).filter((i)=>i!==void 0)}function pi(r,o){try{let a=x(r,{knownProviders:Y,knownChannels:X,...o===void 0?{}:{env:{...process.env,...o}}}),u=a.manifest.skills;if(u===void 0)return;let i=H(a.manifest.model.main.id,a.manifest.model.main.capabilities);He({dir:Cr(u.dir)?u.dir:Nr(a.dir,u.dir),maxActive:u.maxActive,threshold:u.threshold,style:i.promptStyle,agentDir:a.dir,runner:O()});return}catch(a){return a instanceof t?a.message:String(a)}}function hi(r,o,a){try{let u=x(r,{knownProviders:Y,knownChannels:X,...a===void 0?{}:{env:{...process.env,...a}}}),i=u.manifest.skills;if(i===void 0)return;let f=Cr(i.dir)?i.dir:Nr(u.dir,i.dir);ci(ui(f,o),{recursive:!0,force:!0}),Ln(f,o)}catch{}}import{existsSync as gi,mkdirSync as yi,writeFileSync as wi}from"node:fs";import{dirname as bi,join as Zn,resolve as vi}from"node:path";var Sn={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function rt(r,o,a){let u=[];for(;;){let i=Fe(r,a);if(i===void 0)break;if(i.optional===!0){r[i.step]="";continue}if(i.fallback===""){u.push(i.step),r[i.step]="(missing)";continue}let f=Te(i.step,i.fallback);if(f.ok)r[i.step]=f.value}if(u.length>0){let i=u.map((f)=>Sn[f]).join(", ");throw new t({code:"cli_init_missing_answers",message:`Not interactive (${o}), and ${u.join(", ")} ${u.length===1?"has":"have"} no default.`,hint:`Pass ${i} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function st(r,o){let a=r,u=ct(a.preset),i=a.apiKeyEnv??u?.apiKeyEnv,f=a.server??"local",h=a.dir??ut(a.dirChoice,a.name,o);if(h===void 0)throw new t({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(a.dirChoice)}, which resolves to no path.`,hint:"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it."});return{user:a.user,name:a.name,purpose:a.purpose,preset:a.preset,model:a.model,baseUrl:a.baseUrl,system:a.system,web:a.web,...a.webBackend===void 0?{}:{webBackend:a.webBackend},...a.webKey===void 0||a.webKey===""?{}:{webKey:a.webKey},composio:a.composio,...a.composioKey===void 0||a.composioKey===""?{}:{composioKey:a.composioKey},telegram:a.telegram,...a.telegramToken===void 0||a.telegramToken===""?{}:{telegramToken:a.telegramToken},...a.telegramAllow===void 0||a.telegramAllow===""?{}:{telegramAllow:a.telegramAllow},schedules:a.schedules??"none",server:f,skills:a.skills,...a.skillsSearch===void 0||a.skillsSearch===""?{}:{skillsSearch:a.skillsSearch},...a.skillsPick===void 0||a.skillsPick===""?{}:{skillsPick:a.skillsPick},daemon:a.daemon,...f==="local"?{serverToken:$i()}:{},...i===void 0?{}:{apiKeyEnv:i},...a.apiKey===void 0||a.apiKey===""?{}:{apiKey:a.apiKey},...a.dirChoice===void 0?{}:{dirChoice:a.dirChoice},dir:h}}function $i(){let r=new Uint8Array(32);return crypto.getRandomValues(r),[...r].map((o)=>o.toString(16).padStart(2,"0")).join("")}function ot(r,o){let a=o.map((u)=>Zn(r,u.relPath)).filter((u)=>gi(u));if(a.length>0)throw new t({code:"cli_init_target_exists",message:`${a.length} of the files init would write already exist: ${a.join(", ")}`,hint:"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable."});for(let u of o){let i=Zn(r,u.relPath);yi(bi(i),{recursive:!0}),wi(i,u.contents,{encoding:"utf8",...u.relPath===".env"?{mode:384}:{}})}}var Jr=new Map([["dir",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["dirChoice",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["daemon",{code:"provision_daemon_refused",hint:"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process."}]]),it=new Map([["skills",new Map([["find",{code:"provision_skills_search_refused",hint:"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists."}]])]]);function Qr(r){let o=Te(r.step,r.fallback);return o.ok?o.value:r.fallback}function ki(r,o){let a=it.get(r.step);return{step:r.step,prompt:r.prompt,fallback:Qr(r),optional:r.optional===!0,secret:Ct.has(r.step),...o===void 0?{}:{requires:o},...r.options===void 0?{}:{choices:r.options.filter((u)=>a?.has(u.value)!==!0).map((u)=>({value:u.value,label:u.label,...u.hint===void 0?{}:{hint:u.hint}}))}}}var Xr=64;function es(r){let o=new Map,a=new Set,u=(f,h)=>{let g={...f},v=[];for(let k=0;k<Xr;k+=1){let y=Fe(g,r);if(y===void 0)break;let S=Qr(y);if(!Jr.has(y.step)&&!o.has(y.step))o.set(y.step,ki(y,h));for(let P of y.options??[]){if(P.value===S)continue;if(it.get(y.step)?.has(P.value)===!0)continue;v.push({seed:{...g,[y.step]:P.value},opened:{step:y.step,value:P.value}})}g[y.step]=S}return v},i=[...u({})];for(let f=0;f<Xr&&i.length>0;f+=1){let h=i.splice(0,i.length);for(let g of h){let v=`${g.opened.step}=${g.opened.value}`;if(a.has(v))continue;a.add(v),i.push(...u(g.seed,g.opened))}}return[...o.values()].sort((f,h)=>Qn.indexOf(f.step)-Qn.indexOf(h.step))}function ns(r){let o={};for(let[g,v]of Object.entries(r.answers)){let k=g;if(!(k in Sn))throw new t({code:"provision_unknown_answer",message:`"${g}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:g});let y=Jr.get(k);if(y!==void 0)throw new t({code:y.code,message:`"${g}" cannot be set over the API.`,hint:y.hint,field:g});let S=it.get(k)?.get(v.trim().toLowerCase());if(S!==void 0)throw new t({code:S.code,message:`${g} is ${JSON.stringify(v)}, which this runtime cannot do over the API.`,hint:S.hint,field:g});let P=Te(k,v);if(!P.ok)throw new t({code:"provision_answer_invalid",message:`${g} is ${JSON.stringify(v)}, which ${P.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:g});o[k]=P.value}rt(o,"this is the provisioning API",r.defaults);let a=st(o,r.defaults),u=Pt(a.name),i=ut("sandbox",a.name,r.defaults);if(i===void 0)throw new t({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(a.name)}.`,hint:'This is a bug in the CLI: `dirFor("sandbox", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',field:"name"});let f=vi(i),h=er({...a,dir:f});return ot(f,h),{agentId:u,dir:f,manifestPath:Zn(f,"agent.yaml"),files:h.map((g)=>g.relPath)}}function Ei(r){if(r.web!=="search")return;return cn(r.webBackend??"tavily")?.apiKeyEnv}async function ts(r){let o=await rs(r);if(o.kind==="aborted")return process.stdout.write(`nothing written
|
|
141
|
+
`),n;return o.kind==="failed"?o.code:n}async function at(r){return rs(r)}async function rs(r){let o=Ii(r),a=ie({json:!1,plain:r.plain===!0,oneShot:!1}),u=a.mode==="rich"&&r.yes!==!0,i={agentDirBase:B()};if(u){let F=await Ti(o,i);if(F===void 0)return{kind:"aborted"};Object.assign(o,F)}else rt(o,r.yes===!0?"--yes was passed":a.because,i);let f=st(o,i),h=Pi(process.cwd(),f.dir),g=ao(h);if(g!==void 0)process.stderr.write(`${g}
|
|
142
|
+
`);let v=xe(h,"agent.yaml"),k=er(f);ot(h,k);let y=f.apiKeyEnv,S=y!==void 0&&f.apiKey===void 0&&(process.env[y]===void 0||process.env[y]===""),P=S&&y!==void 0?{[y]:"(pending)"}:void 0,U=!1;try{let F=x(xe(h,"agent.yaml"),{knownProviders:Y,knownChannels:X,...S?{env:{...process.env,[y]:"(pending)"}}:{}}),I=H(F.manifest.model.main.id,F.manifest.model.main.capabilities),{workspace:de,warnings:oe}=We(F,I.promptStyle),ge=Ie(de,F.manifest.context.rules);if(ge!==void 0&&F.manifest.context.rules.onExceed==="fail")throw ge;U=oe.some((z)=>z.code==="soul_distilled")}catch(F){if(F instanceof t)return process.stderr.write(`init wrote ${k.length} files to ${h}, but the result does not load:
|
|
143
|
+
${F.format()}
|
|
144
|
+
`),{kind:"failed",code:s};throw F}if(process.stdout.write(`wrote ${k.length} files to ${h} — validated ok
|
|
145
|
+
`),f.skills==="find"){let F=(f.skillsPick??"").split(",").map((I)=>I.trim()).filter((I)=>I!=="");if(F.length>0)qr(F,v,{...P===void 0?{}:{envOverlay:P}});else if(!u)await Mr({answers:f,manifestPath:v,...P===void 0?{}:{envOverlay:P}})}let W=!1;if(f.daemon==="service"){process.stdout.write(`
|
|
146
|
+
`);try{W=await Ze({action:"install",manifestPath:v})===n}catch(F){process.stderr.write(`the background service was not installed: ${F instanceof t?F.message:String(F)}
|
|
147
|
+
`)}}return process.stdout.write(Ai(f,h,U,W)),{kind:"ok",manifestPath:xe(h,"agent.yaml")}}function Ri(r){if(r===void 0)return[];if(ft.some((o)=>o.value===r))return[["skills",r]];return[["skills","find"],["skillsSearch",r]]}function Ii(r){let o={},a=[["user",r.user],["name",r.name],["purpose",r.purpose],["preset",r.preset],["model",r.model],["baseUrl",r.baseUrl],["apiKeyEnv",r.apiKeyEnv],["system",r.system],["web",r.web],["webBackend",r.webBackend],["composio",r.composio],["telegram",r.telegram],["telegramAllow",r.telegramAllow],["server",r.server],["schedules",r.schedules],...Ri(r.skills),["daemon",r.daemon],["dir",r.dir]];for(let[u,i]of a){if(i===void 0)continue;let f=Te(u,i);if(!f.ok)throw new t({code:"cli_init_flag_invalid",message:`${Sn[u]} is ${JSON.stringify(i)}, which ${f.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});o[u]=f.value}return o}async function Ti(r,o){let[{render:a},{createElement:u},{WizardApp:i}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-vzpbydy3.js")]),f;Wt();let h=a(u(i,{title:`${e.name} ${R}`,given:r,defaults:o,onDone:(g)=>{f=g}}),{exitOnCtrlC:!1,...Z()});return b(()=>h.unmount()),await h.waitUntilExit(),h.unmount(),f}function Ai(r,o,a,u=!1){let f=xi(o)===B()?Si(o):xe(o,"agent.yaml"),h=xe(o,"agent.yaml"),g=[];if(r.apiKeyEnv!==void 0&&r.apiKey===void 0)g.push(`Add your key: edit ${xe(o,".env")} and set ${r.apiKeyEnv}=`);let v=Ei(r);if(v!==void 0&&r.webKey===void 0)g.push(`Add your search key: edit ${xe(o,".env")} and set ${v}= — web_fetch works without it, web_search does not`);if(ht(r)&&r.composioKey===void 0)g.push(`Add your Composio key: edit ${xe(o,".env")} and set ${Nt}=`);if(r.telegram==="connected"&&r.telegramToken===void 0)g.push(`Add your bot token: message @BotFather with /newbot, then edit ${xe(o,".env")} and set ${un}=`);let k=r.telegram==="connected"||r.server==="local",y=r.telegram==="connected"&&r.server==="local"?"the Telegram bot and the HTTP API":r.telegram==="connected"?"the Telegram bot":"the HTTP API";if(k&&u)g.push(`${e.slug} run ${f} — talks to it right here. It starts no channel and binds `+`no port; ${y} belongs to the service, which is already up.`);else g.push(`${e.slug} run ${f}`);if(k){if(!u)g.push(`${e.slug} serve ${f} — starts ${y}; \`run\` starts neither`);if(r.daemon==="service"&&!u)g.push(`${e.slug} daemon install ${f} — the same thing, supervised: starts at `+"login and survives a reboot. Do this once the key and token above are in .env; the install checks them and refuses without them, on purpose.")}if(r.telegram==="connected"&&r.telegramAllow===void 0)g.push("Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print "+"the exact line to paste into agent.yaml.");if(ht(r))g.push('Ask it for an app — "connect my Gmail" — and it finds the tools, gives you the '+"sign-in link, and pins what you need. New tools go live on the next restart.");g.push(r.skills==="find"?`Add more skills: \`${e.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${e.slug} skills install ${f} <source>/<skill>\`.`:r.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${e.slug} sources search <what it should do>\` searches 440+ from two catalogues.`:`Skills are off but the directory is there — \`${e.slug} sources search <what it should do>\` finds one, \`${e.slug} skills new ${f} <name>\` writes one.`),g.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${e.slug} workspace ${h}\` shows exactly what still reads as a template.`);let S=u?`
|
|
148
148
|
it is running in the background now — \`${e.slug} daemon status ${f}\` at any time,
|
|
149
149
|
and \`${e.slug} stop\` turns everything off.
|
|
150
150
|
`:"";return`${a?`
|
|
151
151
|
this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
|
|
152
152
|
frontier-class model, and activates automatically if you upgrade.
|
|
153
153
|
`:""}${S}
|
|
154
|
-
`+g.map((
|
|
155
|
-
`).join("")}var
|
|
154
|
+
`+g.map((U,W)=>` ${W+1}. ${U}
|
|
155
|
+
`).join("")}var xn=16;function En(r=process.stdin){let o=[],a=[],u=(i)=>{let f=typeof i==="string"?i:i.toString("utf8");if(a.push(f),a.length>xn)a.splice(0,a.length-xn);if(o.push(...jo(f)),o.length>xn)o.splice(0,o.length-xn)};return r.on("data",u),{correct:(i,f)=>Bo(i,f,o),takeRaw:()=>a.shift(),close:()=>{r.off("data",u)}}}var ss=[{id:"vscode",name:"VS Code's integrated terminal",how:"write",configPath:"Library/Application Support/Code/User/keybindings.json",line:'{ "key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\\u001b[13;2u" } }',marker:"workbench.action.terminal.sendSequence"},{id:"ghostty",name:"Ghostty",how:"write",configPath:".config/ghostty/config",line:"keybind = shift+enter=text:\\x1b[13;2u",marker:"shift+enter=text:"},{id:"kitty",name:"kitty",how:"write",configPath:".config/kitty/kitty.conf",line:"map shift+enter send_text all \\x1b[13;2u",marker:"map shift+enter send_text"},{id:"wezterm",name:"WezTerm",how:"write",configPath:".wezterm.lua",line:"-- shift+enter: { key = 'Enter', mods = 'SHIFT', action = wezterm.action.SendString '\\x1b[13;2u' },",marker:"mods = 'SHIFT', action = wezterm.action.SendString"},{id:"warp",name:"Warp",how:"explain",reason:"Option is resolved to a character before the keyboard protocol sees it, so ⌥ plus a letter arrives as text like `®` unless Warp is told otherwise",steps:["Settings → Features → Keys → tick “Left and Right Option Key is Meta”","That is only needed for ⌥ plus a *letter*. ⌥ and cmd with arrows already work, and so does shift+⏎",`Every letter chord here has a control-key twin that needs none of this — \`${e.slug} keys\` shows exactly what your terminal sends`]},{id:"iterm2",name:"iTerm2",how:"explain",reason:"its preferences are a binary plist it rewrites on quit, so an edit made underneath it is discarded",steps:["Settings → Profiles → Keys → Key Mappings","Press +, then press shift and return together to capture the key","Set Action to “Send Hex Codes”","Enter: 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75"]},{id:"apple",name:"Terminal.app",how:"explain",reason:"its key bindings live in the same binary preferences file, and it caches them while running",steps:["Settings → Profiles → Keyboard","Press +, choose Return as the key and tick Shift","Set Action to “Send Text” and enter: \\033[13;2u"]}];function Rn(r){let o=r.TERM_PROGRAM??"";if(o==="vscode")return"vscode";if(o==="ghostty"||r.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(r.KITTY_WINDOW_ID!==void 0||r.TERM==="xterm-kitty")return"kitty";if(r.WEZTERM_PANE!==void 0)return"wezterm";if(o==="WarpTerminal")return"warp";if(o==="iTerm.app")return"iterm2";if(o==="Apple_Terminal")return"apple";return"unknown"}function In(r){return ss.find((o)=>o.id===r)}function os(){return ss}function is(r,o){return o.marker!==void 0&&r.includes(o.marker)}function as(r,o){let a=o.line;if(a===void 0)return;if(o.id!=="vscode"){let g=r.trimEnd();return g===""?`${a}
|
|
156
156
|
`:`${g}
|
|
157
157
|
${a}
|
|
158
158
|
`}let u=r.trim();if(u===""||u==="[]")return`[
|
|
@@ -160,49 +160,49 @@ ${a}
|
|
|
160
160
|
]
|
|
161
161
|
`;let i=u.indexOf("[");if(i===-1)return;let h=u.slice(i+1).trimStart().startsWith("]")?"":",";return`${u.slice(0,i+1)}
|
|
162
162
|
${a}${h}
|
|
163
|
-
${u.slice(i+1)}`}async function
|
|
163
|
+
${u.slice(i+1)}`}async function ds(r={}){let o=ie({plain:!1,json:!1,oneShot:!1});if(o.mode!=="rich")throw new t({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${o.because}). Run it in the terminal whose keys you want to inspect; there is no scripted form, because the answer is a property of that terminal.`});let a=Z(r.noEnhancedKeys),u=a.kittyKeyboard!==void 0,i=Rn(process.env),f=In(i)?.name??i,[{render:h},{createElement:g},{KeyProbe:v}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-9jjeze5r.js")]),k=()=>{},y=new Promise((U)=>{k=U}),S=En();b(()=>{S.close()}),pe(),process.stdout.write(ve);let P=h(g(v,{columns:q(process.stdout.columns,j),asked:u,terminal:f,takeRaw:S.takeRaw,correctKeys:S.correct,onDone:k}),{exitOnCtrlC:!1,...a});return b(()=>P.unmount()),await y,P.unmount(),S.close(),J(),await ue(),n}import{existsSync as Oi}from"node:fs";function dt(r=process.env){return Oi("/.dockerenv")||r.container!==void 0}function _i(r){let o=r.env??process.env;if(!r.needsServer)return"command-needs-no-server";if(r.disabled===!0)return"disabled-by-flag";if(o[`${e.envPrefix}SERVICE`]!==void 0)return"is-the-service";if(o[`${e.envPrefix}NO_BOOTSTRAP`]!==void 0)return"disabled-by-env";if(dt(o))return"in-container";if(o.CI!==void 0)return"in-ci";return}async function ls(r){let o=_i(r);if(o!==void 0)return{kind:"skipped",reason:o};if((await St(r.store)).length>0)return{kind:"already"};let u=r.platform??process.platform;if(!yr(u))return{kind:"manual",lines:[`${e.slug} daemon install`]};let i=r.install;if(i===void 0)return{kind:"failed",message:"no installer was supplied",hint:"This is a wiring mistake rather than a configuration one: `ensureServer` is called with an `install` callback by `index.ts`."};try{return await i()}catch(f){return{kind:"failed",message:f instanceof Error?f.message:String(f),hint:`The command ran anyway. \`${e.slug} daemon install\` reports the same failure with more detail — on macOS over SSH it is usually that a LaunchAgent needs a logged-in desktop session.`}}}function cs(r){switch(r.kind){case"started":return`started the background server · \`${e.slug} daemon uninstall\` to undo
|
|
164
164
|
`;case"manual":return`no server is running · ${r.lines.join(", then ")}
|
|
165
165
|
`;case"failed":return`could not start a background server: ${r.message}
|
|
166
166
|
hint: ${r.hint}
|
|
167
|
-
`;default:return}}var
|
|
168
|
-
delivery reads the channel back out of the key.`;function
|
|
167
|
+
`;default:return}}var Ci=24,gt=22;function kt(r){let o=r.args.map((a)=>{let u=a.variadic===!0?`${a.name}...`:a.name;return a.required?`<${u}>`:`[${u}]`}).join(" ");return`${e.slug} ${r.name}${o===""?"":` ${o}`}`}function fs(r){let o=r.placeholder===void 0?`--${r.name}`:`--${r.name} <${r.placeholder}>`,a=r.short===void 0?o:`-${r.short}, ${o}`,u=r.defaultHelp===void 0?"":` (default ${r.defaultHelp})`;return` ${a.padEnd(Ci)}${r.help}${u}`}var ms=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
|
|
168
|
+
delivery reads the channel back out of the key.`;function Ni(r){let o=[];for(let a of r.args){if(a.choices===void 0||a.choices.length===0)continue;let u=Math.max(...a.choices.map((i)=>i.value.length))+2;o.push("",`${a.name}:`);for(let i of a.choices)o.push(` ${i.value.padEnd(u)}${i.help}`)}return o}function It(r){if(r!==void 0){let a=[r.summary,"","usage:",` ${kt(r)} [flags]`,...Ni(r),"","flags:",...Ot(r).map(fs)];if(r.flags.some((u)=>u.name==="session"))a.push("",ms);return`${a.join(`
|
|
169
169
|
`)}
|
|
170
|
-
`}let o=Math.max(...le.map((a)=>
|
|
170
|
+
`}let o=Math.max(...le.map((a)=>kt(a).length))+2;return`${[`${e.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...le.map((a)=>` ${kt(a).padEnd(o)}${a.summary}`),` ${e.slug} --version`,` ${e.slug} --help`,"",`Per-command flags: ${e.slug} <command> --help`,"","global flags:",...Rt.map(fs),"",ms,"","environment:",` ${`${e.envPrefix}BRAND`.padEnd(gt)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(gt)}set to anything to force plain output`,` ${"DEBUG".padEnd(gt)}print stack traces on failure`].join(`
|
|
171
171
|
`)}
|
|
172
|
-
`}var
|
|
172
|
+
`}var Fi=[{name:"ExperimentalWarning",contains:"SQLite is an experimental feature",because:"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run."}];function Li(r,o){return Fi.some((a)=>a.name===r&&o.includes(a.contains))}function ji(r){return r.execArgv.includes("--trace-warnings")||(r.nodeOptions??"").includes("--trace-warnings")}var ps;function hs(r={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(ps)return;if(ji(r))return;let o=process.emitWarning;ps=o,process.emitWarning=(a,...u)=>{let i=typeof a==="string"?Mi(u):a.name,f=typeof a==="string"?a:a.message;if(Li(i,f))return;Reflect.apply(o,process,[a,...u])}}function Mi(r){let o=r[0];return typeof o==="string"?o:"Warning"}var gs=96;async function ws(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath])});try{let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");if(r.action==="rebuild"){let v=await a.rebuildMemory();if(r.json===!0)return process.stdout.write(`${JSON.stringify(v,null,2)}
|
|
173
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
174
|
Read: ${[...v.indexed,...v.sessions].join(", ")}
|
|
175
175
|
`),n}let u=r.query??"";if(u.trim()==="")return process.stderr.write(`memory search needs something to search for.
|
|
176
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
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
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)=>
|
|
179
|
+
`),n;let g=Math.max(6,...h.map((v)=>ys(v,i.carried).length));process.stdout.write(`
|
|
180
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(
|
|
181
|
+
`);for(let v of h){let k=v.score>=i.threshold?" ":"·";process.stdout.write(`${$e(v.score.toFixed(3),6)} ${$e(v.lexical.toFixed(3),7)} ${$e(v.coverage.toFixed(2),5)} ${$e(ys(v,i.carried),g)} ${$e(v.passage.at.slice(0,10),10)} ${k}${Ki(v.passage.text)}
|
|
182
182
|
`)}if(r.all===!0&&f.length<h.length)process.stdout.write(`
|
|
183
183
|
${h.length-f.length} shown below the threshold; a turn would not inject those.
|
|
184
184
|
`);if(i.carried!==void 0&&h.some((v)=>v.passage.source===i.carried))process.stdout.write(`
|
|
185
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
|
|
187
|
-
`)}function
|
|
188
|
-
Reply with the single character x.`;try{let i=await
|
|
186
|
+
`);return n}finally{await o.stop("cli-exit")}}function Ki(r){let o=r.replace(/\s+/g," ").trim();return o.length<=gs?o:`${o.slice(0,gs-1)}…`}function $e(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function ys(r,o){return r.passage.source===o?`${r.passage.source} *`:r.passage.source}var Ui=["context_length","context_window","max_context_length","max_model_len"],Di=[["prompt_cache_hit_tokens",(r)=>r.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(r)=>{let o=r.prompt_tokens_details;return Tn(o)?o.cached_tokens:void 0}],["cache_read_input_tokens",(r)=>r.cache_read_input_tokens]];function Tn(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}function Tt(r){if(typeof r!=="number"||!Number.isFinite(r))return;if(!Number.isInteger(r)||r<=0)return;return r}function bs(r,o){let a=Tn(r)?r.data:void 0,u=Array.isArray(a)?a:Array.isArray(r)?r:void 0;if(u===void 0)return;let i=o.toLowerCase();for(let f of u){if(!Tn(f))continue;let h=typeof f.id==="string"?f.id.toLowerCase():void 0;if(h===void 0)continue;if(!(h===i||h.endsWith(`/${i}`)||i.endsWith(`/${h}`)))continue;for(let v of Ui){let k=Tt(f[v]);if(k!==void 0)return{technique:"metadata",tokens:k,bound:"ceiling",detail:`GET /models published ${v}: ${k}`}}return}return}function At(r){let o=[/(?:max_?tokens|context[\s_]?(?:length|window))[^[\]]{0,40}\[\s*\d[\d_,]*\s*,\s*(\d[\d_,]*)\s*\]/i,/maximum context length is (\d[\d_,]*)/i,/max_?tokens[^.\d]{0,40}?(\d[\d_,]*)/i,/context (?:length|window)(?: of)? (?:is )?(\d[\d_,]*)/i,/maximum (?:sequence|model) length (?:is )?(\d[\d_,]*)/i],a=[];for(let u of o){let i=u.exec(r);if(i?.[1]===void 0)continue;let f=Tt(Number(i[1].replaceAll(/[,_]/g,"")));if(f!==void 0)a.push(f)}if(a.length===0)return;return Math.max(...a)}function vs(r){if(!Tn(r))return;let o=Tt(r.prompt_tokens)??0;for(let[a,u]of Di){let i=u(r);if(typeof i==="number"&&Number.isFinite(i))return{cached:i,promptTokens:o,field:a}}return{cached:void 0,promptTokens:o,field:void 0}}function $s(r,o,a){if(r===void 0||o===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(o.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let u=o.cached??0;if(u>0)return{supported:!0,detail:`the second identical call reported ${u} cached of ${o.promptTokens} prompt tokens, via ${o.field}`};return{supported:!1,detail:`${o.field} came back 0 on an identical repeat of a ${a}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function en(r){let o=r.filter((u)=>u.bound==="ceiling");return(o.length>0?o:r).reduce((u,i)=>u===void 0||i.tokens>u.tokens?i:u,void 0)}function ks(r,o,a){return[" {",` pattern: "${`${r.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${o.toLocaleString("en-US").replaceAll(",","_")},`,...a===void 0?[]:[` maxOutput: ${a.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
|
|
187
|
+
`)}function Ss(r,o,a){return`measured ${o} against ${r} — ${a}`}function xs(r,o){let a=Math.max(1,r),u=0,i=0;while(a<o)u+=a,i+=1,a*=2;return u+=o,i+=1,{requests:i,tokens:u}}var Hi=2000000000,Ps=1024,Rs=8192,Is=2097152;function Ts(r){return"context ".repeat(Math.max(1,r))}async function nn(r){let o=await r.text();try{return{text:o,json:JSON.parse(o)}}catch{return{text:o,json:void 0}}}function As(r,o){if(typeof r==="object"&&r!==null){let a=r,u=a.error;if(typeof u==="string")return u;if(typeof u==="object"&&u!==null){let i=u.message;if(typeof i==="string")return i}if(typeof a.message==="string")return a.message}return o}async function Bi(r,o,a){try{let u=await o(r.models,{headers:r.headers});if(!u.ok){a.push(`GET /models answered ${u.status}`);return}let{json:i}=await nn(u),f=bs(i,r.modelId);if(f===void 0)a.push("GET /models published no context length");return f}catch(u){a.push(`GET /models failed: ${u instanceof Error?u.message:String(u)}`);return}}async function Wi(r,o,a){try{let u=await o(r.chat,{method:"POST",headers:{"content-type":"application/json",...r.headers},body:JSON.stringify({model:r.modelId,messages:[{role:"user",content:"hi"}],max_tokens:Hi})}),{text:i,json:f}=await nn(u);if(u.ok)return a.push("the endpoint accepted an impossible max_tokens rather than refusing it — it clamps silently, so this technique cannot measure it"),{window:void 0,outputCeiling:void 0};let h=As(f,i.slice(0,400)),g=At(h);if(g===void 0)return a.push(`the refusal named no number: ${h.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let v=/max_?tokens/i.test(h);return{window:v?void 0:{technique:"refusal",tokens:g,bound:"ceiling",detail:`refused an over-range request naming ${g}`},outputCeiling:v?g:void 0}}catch(u){return a.push(`the over-range request failed: ${u instanceof Error?u.message:String(u)}`),{window:void 0,outputCeiling:void 0}}}async function Es(r,o,a){let u=await o(r.chat,{method:"POST",headers:{"content-type":"application/json",...r.headers},body:JSON.stringify({model:r.modelId,messages:[{role:"user",content:a}],max_tokens:1})});if(!u.ok)return;let{json:i}=await nn(u),f=typeof i==="object"&&i!==null?i.usage:void 0;return vs(f)}async function Gi(r,o,a){let u=`${Ts(Ps)}
|
|
188
|
+
Reply with the single character x.`;try{let i=await Es(r,o,u),f=await Es(r,o,u);return $s(i,f,Ps)}catch(i){return a.push(`the caching probe failed: ${i instanceof Error?i.message:String(i)}`),{supported:void 0,detail:"the probe did not complete"}}}async function qi(r,o,a){let u=Rs,i=0;while(u<=Is){let f;try{f=await o(r.chat,{method:"POST",headers:{"content-type":"application/json",...r.headers},body:JSON.stringify({model:r.modelId,messages:[{role:"user",content:Ts(u)}],max_tokens:1})})}catch(k){a.push(`the search stopped at ${u}: ${k instanceof Error?k.message:String(k)}`);break}if(f.ok){let{json:k}=await nn(f),y=typeof k==="object"&&k!==null?k.usage:void 0,S=typeof y==="object"&&y!==null?y.prompt_tokens:void 0;i=typeof S==="number"&&Number.isFinite(S)?S:i,u*=2;continue}let{text:h,json:g}=await nn(f),v=At(As(g,h.slice(0,400)));if(v!==void 0)return{technique:"search",tokens:v,bound:"ceiling",detail:`refused a ${u}-token prompt and named ${v}`};break}if(i===0)return;return{technique:"search",tokens:i,bound:"floor",detail:`accepted a prompt the endpoint counted at ${i} tokens; nothing above it named a number`}}function Vi(r,o){let a=en(r.findings),u=a===void 0?"nothing measured — every technique came back empty":`${a.tokens} (${a.bound}) · ${a.detail}`,i=a===void 0?"":a.tokens===r.declared?"matches what is configured":a.bound==="ceiling"&&a.tokens>r.declared?`configured value is ${r.declared}, which is ${(a.tokens-r.declared).toLocaleString("en-US")} tokens short`:`configured value is ${r.declared}`,f=r.cache.supported===void 0?`unknown — ${r.cache.detail}`:r.cache.supported?`yes — ${r.cache.detail}`:`no — ${r.cache.detail}`;return[p(` ${r.role} · ${r.modelId}`),l([{label:"endpoint",value:r.baseUrl},{label:"configured",value:`${r.declared} (${r.declaredSource})`},{label:"measured",value:u},{label:"agreement",value:i},{label:"output cap",value:r.outputCeiling===void 0?"":String(r.outputCeiling)},{label:"prompt cache",value:f},...o===void 0?[]:[{label:"price",value:`$${o}/Mtok input, as given`}]]),...r.failures.length===0?[]:[" what did not answer:",...r.failures.map((h)=>` · ${h}`)],...a===void 0||a.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",ks(r.modelId,a.tokens,r.outputCeiling).split(`
|
|
189
189
|
`).map((h)=>` ${h}`).join(`
|
|
190
190
|
`)]].join(`
|
|
191
|
-
`)}async function
|
|
191
|
+
`)}async function Os(r){let o=r.fetch??globalThis.fetch;try{let a=x(r.manifestPath,{knownProviders:Y,knownChannels:X,env:m([r.manifestPath])}),{manifest:u}=a,i=ye(u).filter((v)=>v.role===v.configuredAs),f=!1;if(r.window){let v=xs(Rs,Is),k=v.tokens*i.length,y=r.price===void 0?"":` ≈ $${(k/1e6*r.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${v.requests} requests per role, about ${k.toLocaleString("en-US")} input tokens in total${y}.
|
|
192
192
|
That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
|
|
193
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
|
|
194
|
+
`),f=r.yes||await Ye("spend it?"),process.stdout.write(f?`
|
|
195
195
|
`:`
|
|
196
196
|
Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
|
|
197
197
|
|
|
198
|
-
`)}let h=[];for(let v of i){let k=u.model[v.role]??u.model.main,y={chat:
|
|
199
|
-
`),n;let g=r.write?await
|
|
198
|
+
`)}let h=[];for(let v of i){let k=u.model[v.role]??u.model.main,y={chat:hn(k.baseUrl),models:kr(k.baseUrl),headers:Sr(k.apiKeyEnv,a.env,`model.${v.role}`),modelId:k.id},S=[],P=[],U=await Bi(y,o,S);if(U!==void 0)P.push(U);let W=await Wi(y,o,S);if(W.window!==void 0)P.push(W.window);let F=await Gi(y,o,S);if(f){let I=await qi(y,o,S);if(I!==void 0)P.push(I)}h.push({role:v.role,modelId:k.id,baseUrl:k.baseUrl,declared:v.window.contextWindow,declaredSource:v.window.source,findings:P,cache:F,outputCeiling:W.outputCeiling,failures:S})}if(r.json)return process.stdout.write(`${JSON.stringify({agent:u.id,probes:h},null,2)}
|
|
199
|
+
`),n;let g=r.write?await Xi(a.path,h):{written:[],refused:[]};return process.stdout.write([`probed ${u.id} · ${h.length} role${h.length===1?"":"s"}`,...h.map((v)=>Vi(v,r.price)),"",...r.write?[...g.written.length===0?[]:[" written to the manifest:",...g.written.map((v)=>` ${v}`)],...g.refused.length===0?[]:[" not written:",...g.refused.map((v)=>` ${v}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[Ji(h)],""].join(`
|
|
200
200
|
`)),n}catch(a){if(a instanceof t)return process.stderr.write(`${a.format()}
|
|
201
|
-
`),s;throw a}}async function
|
|
202
|
-
`)}async function
|
|
201
|
+
`),s;throw a}}async function Xi(r,o){let a=[],u=[];for(let i of o){let f=en(i.findings);if(f===void 0){u.push(`${i.role}: nothing measured`);continue}if(f.bound!=="ceiling"){u.push(`${i.role}: ${f.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(f.tokens===i.declared){u.push(`${i.role}: already ${f.tokens}, nothing to change`);continue}await pt({file:r,path:["model",i.role,"capabilities","contextWindow"],value:f.tokens}),a.push(`${i.role}: ${i.declared} → ${f.tokens}`)}return{written:a,refused:u}}function Ji(r){let o=r.filter((f)=>en(f.findings)?.bound==="ceiling");if(o.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let a=o[0],u=a===void 0?void 0:en(a.findings);if(a===void 0||u===void 0)return"";let i=new URL(a.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${u.tokens}`,` # ${Ss(i,new Date().toISOString().slice(0,10),u.detail)}`].join(`
|
|
202
|
+
`)}async function _s(r){let o=await L.create({agents:[r.manifestPath],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath]),store:w(),lease:!1});b(()=>o.stop("cli-exit"));let a=[...o.plugins.values()].flat();if(r.json===!0)return process.stdout.write(`${JSON.stringify({plugins:a,available:fr},null,2)}
|
|
203
203
|
`),n;if(a.length===0)return process.stdout.write(`No plugins. This binary can resolve these by name:
|
|
204
204
|
|
|
205
|
-
${
|
|
205
|
+
${fr.map((f)=>` - "${f}"`).join(`
|
|
206
206
|
`)}
|
|
207
207
|
|
|
208
208
|
Add a \`plugins:\` block to agent.yaml naming the ones you want.
|
|
@@ -210,19 +210,19 @@ Add a \`plugins:\` block to agent.yaml naming the ones you want.
|
|
|
210
210
|
`);let i=a.filter((f)=>f.permissions.length>0);if(i.length>0){process.stdout.write(`
|
|
211
211
|
Declared access — advisory in v1, recorded and not enforced:
|
|
212
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
|
|
214
|
-
`)}function
|
|
213
|
+
`)}}return n}import{existsSync as sa,readdirSync as Ms,rmSync as _t,statSync as Ks}from"node:fs";import{homedir as oa}from"node:os";import{join as Us}from"node:path";function Cs(r){if(r.filesOnly||r.sharesIdWith.length===0)return[];let o=r.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${r.ref}" has the manifest id "${r.agentId}", which is also used by ${o} — removing its data would take that agent's sessions and memory too.`,hint:`Change one manifest's id and run \`memory rebuild\` for it, or pass --files-only to delete just the ${r.ref} directory and leave the store alone.`}]}function Ns(r){let o=[];if(r.running!==void 0)o.push({kind:"stop",detail:`stop pid ${r.running.pid} (${r.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!r.filesOnly&&r.service!==void 0)o.push({kind:"service",detail:`disable and unload ${r.service}`});if(!r.filesOnly){let a=r.footprint;if(o.push({kind:"store",detail:`delete ${ae(a.sessions,"conversation")}, ${ae(a.messages,"message")}, ${ae(a.passages,"memory passage")}`}),r.logs.length>0)o.push({kind:"logs",detail:`delete ${ae(r.logs.length,"log file")}`})}return o.push({kind:"directory",detail:`delete ${r.dir}`}),o}function Fs(r){let o=r.footprint,a=[{label:"directory",value:`${r.dir}`,note:`${ae(r.files.count,"file")}, ${bt(r.files.bytes)}`}];if(r.agentId!==r.ref)a.push({label:"manifest id",value:r.agentId,note:"keys the store, logs and service"});if(r.filesOnly)a.push({label:"keeping",value:`${ae(o.sessions,"conversation")}, ${ae(o.passages,"memory passage")}, and the logs`,note:"--files-only"});else a.push({label:"sessions",value:`${ae(o.sessions,"conversation")}, ${ae(o.messages,"message")}, ${ae(o.turns,"turn")}`},{label:"memory",value:`${ae(o.passages,"passage")} from ${ae(o.memorySources,"source")}`},{label:"outbox",value:o.outbox===0?"nothing queued":`${ae(o.outbox,"delivery")}${o.outboxPending===0?"":`, ${o.outboxPending} not yet sent`}`,...o.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:o.schedules===0?"none":ae(o.schedules,"schedule"),...o.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:r.logs.length===0?"none":`${ae(r.logs.length,"file")}, ${bt(r.logs.reduce((u,i)=>u+i.bytes,0))}`},{label:"service",value:r.service??"not installed"});return a.push({label:"running",value:r.running===void 0?"no":`pid ${r.running.pid} (${r.running.mode})`}),l(a)}function Ls(r){if(r.length===0)return"";return r.map((o)=>{let a=o.footprint,u=[];if(a.sessions>0)u.push(`${ae(a.sessions,"conversation")}, ${ae(a.messages,"message")}`);if(a.passages>0)u.push(`${ae(a.passages,"memory passage")}`);if(a.outbox>0)u.push(`${ae(a.outbox,"queued delivery")}`);if(a.schedules>0)u.push(`${ae(a.schedules,"schedule")}`);if(a.lease)u.push("a stale lease");if(o.logs.length>0)u.push(`${ae(o.logs.length,"log file")}, ${bt(o.logs.reduce((i,f)=>i+f.bytes,0))}`);return` ${o.agentId} ${u.length===0?"rows with no detail":u.join(" · ")}`}).join(`
|
|
214
|
+
`)}function ae(r,o){return`${r} ${o}${r===1?"":"s"}`}import{homedir as zi}from"node:os";var js=12000,Yi=250;async function Nn(r){if(r.manifestPath!==void 0)return await Qi(r,r.manifestPath);return await Zi(r)}async function Qi(r,o){let a=ra(o),u=[];if(r.dryRun===!0){let g=await Ce(a,r.store);return process.stdout.write(`would stop 1 agent:
|
|
215
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
|
|
216
|
+
`),n}await Pn(a,!1,r.reason,r.store),u.push("switched off for the next start");let i=await Ce(a,r.store),f=!0;if(i===void 0)u.push("nothing was running");else if(i.baseUrl===void 0){let g=await On(i.pid,"SIGTERM");f=g||await On(i.pid,"SIGKILL",!0),u.push(g?`pid ${i.pid} stopped cleanly`:f?`pid ${i.pid} had to be killed`:`pid ${i.pid} would not stop — check it by hand`)}else{let g=await Qe(i,`/v1/agents/${encodeURIComponent(a)}/stop`,r.reason===void 0?{}:{reason:r.reason},o);if(g.ok)u.push(`pid ${i.pid} dropped it and kept serving`);else if(g.status===409)f=!1,u.push(g.detail??"a turn is running");else if(g.status===401)f=!1,u.push(`pid ${i.pid} refused the request — set ${e.envPrefix}API_TOKEN to the server's token`);else f=!1,u.push(`pid ${i.pid} at ${i.baseUrl} could not be reached${g.detail===void 0?"":`: ${g.detail}`}`)}let h={agentId:a,service:!1,...i===void 0?{}:{pid:i.pid,mode:i.mode},stopped:f,note:u.join(" · ")};if(r.json===!0)process.stdout.write(`${JSON.stringify({stopped:[h]},null,2)}
|
|
217
217
|
`);else process.stdout.write(`${l([{label:a,value:f?"stopped":"NOT FULLY STOPPED",note:h.note}])}
|
|
218
218
|
`),process.stdout.write(`
|
|
219
219
|
Stays off across restarts. \`${e.slug} start ${a}\` switches it back on.
|
|
220
|
-
`);return f?n:s}async function
|
|
220
|
+
`);return f?n:s}async function Zi(r){let o=r.platform??process.platform,a=o==="darwin"?Ue(o,{home:zi(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec}}):void 0,u=await ea(a,r.store);if(u.length===0)return process.stdout.write(r.json===!0?`${JSON.stringify({stopped:[]})}
|
|
221
221
|
`:`Nothing is running — no service is installed and no process holds an agent.
|
|
222
222
|
`),n;if(r.dryRun===!0)return process.stdout.write(`would stop ${u.length} ${u.length===1?"agent":"agents"}:
|
|
223
|
-
${u.map((f)=>d(
|
|
223
|
+
${u.map((f)=>d(ta(f))).join(`
|
|
224
224
|
`)}
|
|
225
|
-
`),n;let i=[];for(let f of u)i.push(await
|
|
225
|
+
`),n;let i=[];for(let f of u)i.push(await na(f,a));if(r.json===!0)process.stdout.write(`${JSON.stringify({stopped:i},null,2)}
|
|
226
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
227
|
`),i.some((h)=>h.service&&h.stopped))process.stdout.write(`
|
|
228
228
|
Services are disabled as well as unloaded, so they stay stopped across a reboot.
|
|
@@ -231,97 +231,97 @@ Start one again with \`${e.slug} daemon start <agent>\`.
|
|
|
231
231
|
Something had to be killed rather than asked. A forced stop skips the runtime's own
|
|
232
232
|
cleanup, so a command the agent had left running in the background may still be alive —
|
|
233
233
|
\`ps\` will show it if so.
|
|
234
|
-
`)}return i.every((f)=>f.stopped)?n:s}async function
|
|
235
|
-
${
|
|
234
|
+
`)}return i.every((f)=>f.stopped)?n:s}async function ea(r,o){let a=`${e.slug}.agent.`,u=new Map;for(let i of r?.labels(a)??[]){let f=i.slice(a.length);u.set(f,{agentId:f,service:!0})}try{let i=await M.open({path:o??w()});for(let f of await i.leases.all()){if(f.pid===process.pid||!_(f.pid))continue;u.set(f.agentId,{agentId:f.agentId,service:u.get(f.agentId)?.service===!0,pid:f.pid,mode:f.mode})}await i.close()}catch{}return[...u.values()].sort((i,f)=>i.agentId.localeCompare(f.agentId))}async function na(r,o){let a=[];if(r.service&&o!==void 0)try{o.stop(pn(e.slug,r.agentId)),a.push("service disabled and unloaded")}catch(f){a.push(`service could not be unloaded: ${f instanceof Error?f.message:String(f)}`)}if(r.pid===void 0)return{...r,stopped:!0,note:a.join(" · ")||"no process was running"};if(!_(r.pid))return{...r,stopped:!0,note:a.join(" · ")||`pid ${r.pid} exited`};if(await On(r.pid,"SIGTERM"))return a.push(`pid ${r.pid} stopped cleanly`),{...r,stopped:!0,note:a.join(" · ")};let i=await On(r.pid,"SIGKILL",!0);return a.push(i?`pid ${r.pid} did not stop in ${Math.round(js/1000)}s and was killed`:`pid ${r.pid} would not stop, even killed — check it by hand`),{...r,stopped:i,forced:!0,note:a.join(" · ")}}async function On(r,o,a=!1){try{process.kill(a?-r:r,o)}catch(i){if(i.code==="ESRCH")return!0;if(a)try{process.kill(r,o)}catch{return!_(r)}}let u=Date.now()+(o==="SIGKILL"?3000:js);while(Date.now()<u){if(!_(r))return!0;await new Promise((i)=>setTimeout(i,Yi))}return!_(r)}function ta(r){let o=[];if(r.service)o.push("background service");if(r.pid!==void 0)o.push(`pid ${r.pid}${r.mode===void 0?"":` (${r.mode})`}`);return`${r.agentId} — ${o.join(", ")}`}function ra(r){let o=T(r);if(o.id===void 0||o.id==="")throw new t({code:"cli_stop_agent_id_missing",message:`${r} declares no id, so there is nothing to match a running agent against.`,hint:`Add \`id: <name>\` to the manifest, or run \`${e.slug} stop\` with no argument to stop everything.`});return o.id}async function Ds(r){let o=await M.open({path:r.store??w()});try{if(r.prune===!0)return await da(r,o);if(r.all===!0)return await aa(r,o);if(r.ref===void 0)throw new t({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${e.slug} remove <name>\` takes a sandbox agent's name — the ones \`${e.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await ia(r.ref,r,o)}finally{await o.close()}}async function ia(r,o,a){let u=await Bs(r,o,a),i=Cs(u);if(i.length>0){let g=i[0];throw new t({code:g.code,message:g.message,hint:g.hint})}let f=Ns(u),h=`${p(`removing ${r} will:`,!0)}
|
|
235
|
+
${Fs(u)}
|
|
236
236
|
|
|
237
237
|
${f.map((g)=>d(g.detail)).join(`
|
|
238
238
|
`)}
|
|
239
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
240
|
`:`${h}
|
|
241
241
|
Nothing was deleted — this was --dry-run.
|
|
242
|
-
`),n;if(process.stdout.write(h),!await
|
|
242
|
+
`),n;if(process.stdout.write(h),!await Ft(o,r,"type the agent's name to confirm:"))return process.stdout.write(`
|
|
243
243
|
Nothing was deleted.
|
|
244
|
-
`),n;return await
|
|
244
|
+
`),n;return await Hs(u,o,a)}async function Hs(r,o,a){let u=[];if(r.running!==void 0||!r.filesOnly&&r.service!==void 0){if(await Nn({manifestPath:r.manifestPath,...o.exec===void 0?{}:{exec:o.exec},...o.platform===void 0?{}:{platform:o.platform}})!==n)return process.stderr.write(`
|
|
245
245
|
Stopping ${r.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
|
|
246
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=
|
|
247
|
+
`),s;u.push({label:"stopped",value:r.ref})}if(!r.filesOnly&&r.service!==void 0){let i=Ws(o);try{i?.uninstall(r.service),u.push({label:"service",value:`${r.service} removed`})}catch(f){u.push({label:"service",value:`${r.service} could NOT be removed`,note:f instanceof Error?f.message:String(f)})}}if(!r.filesOnly){let i=await a.purgeAgent(r.agentId);u.push({label:"store",value:`${i.sessions} conversation(s), ${i.messages} message(s), ${i.passages} passage(s)`});for(let f of r.logs)_t(f.path,{force:!0});if(r.logs.length>0)u.push({label:"logs",value:`${r.logs.length} file(s)`})}if(_t(r.dir,{recursive:!0,force:!0}),u.push({label:"directory",value:r.dir}),o.json===!0)return process.stdout.write(`${JSON.stringify({removed:r.ref,agentId:r.agentId,filesOnly:r.filesOnly},null,2)}
|
|
248
248
|
`),n;if(process.stdout.write(`
|
|
249
249
|
${r.ref} removed.
|
|
250
250
|
${l(u)}
|
|
251
251
|
`),r.filesOnly)process.stdout.write(`
|
|
252
252
|
Its sessions and memory are still in the store under the id "${r.agentId}", which another agent shares.
|
|
253
|
-
`);return n}async function
|
|
254
|
-
`),n;if(process.stdout.write(`${
|
|
253
|
+
`);return n}async function aa(r,o){let a=K();if(a.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
|
|
254
|
+
`),n;if(process.stdout.write(`${p(`removing every agent in ${B()}:`,!0)}
|
|
255
255
|
${a.map((i)=>d(`${i.ref}${i.id===void 0||i.id===i.ref?"":` (id ${i.id})`}`)).join(`
|
|
256
256
|
`)}
|
|
257
257
|
`),r.dryRun===!0)return process.stdout.write(`
|
|
258
258
|
Nothing was deleted — this was --dry-run.
|
|
259
|
-
`),n;if(!await
|
|
259
|
+
`),n;if(!await Ft(r,"all",`type \`all\` to remove all ${a.length}:`))return process.stdout.write(`
|
|
260
260
|
Nothing was deleted.
|
|
261
|
-
`),n;let u=n;for(let i of a){let f=await
|
|
262
|
-
`:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${
|
|
263
|
-
`),n;if(process.stdout.write(`${
|
|
264
|
-
${
|
|
261
|
+
`),n;let u=n;for(let i of a){let f=await Bs(i.ref,r,o),h=await Hs({...f,sharesIdWith:[]},r,o);if(h!==n)u=h}return u}async function da(r,o){let a=new Set(K().map((h)=>h.id??h.ref).filter((h)=>h!=="")),u=new Set((await o.agentIds()).filter((h)=>!a.has(h)));for(let h of ca())if(!a.has(h))u.add(h);let i=[];for(let h of[...u].sort())i.push({agentId:h,footprint:await o.agentFootprint(h),logs:Gs(h)});if(i.length===0)return process.stdout.write(r.json===!0?`${JSON.stringify({pruned:[]})}
|
|
262
|
+
`:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${B()}.
|
|
263
|
+
`),n;if(process.stdout.write(`${p("no sandbox directory claims these:",!0)}
|
|
264
|
+
${Ls(i)}
|
|
265
265
|
`),r.dryRun===!0)return process.stdout.write(`
|
|
266
266
|
Nothing was deleted — this was --dry-run.
|
|
267
|
-
`),n;if(!await
|
|
267
|
+
`),n;if(!await Ft(r,"prune","type `prune` to delete them:"))return process.stdout.write(`
|
|
268
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)
|
|
269
|
+
`),n;let f=[];for(let h of i){let g=await o.purgeAgent(h.agentId);for(let v of h.logs)_t(v.path,{force:!0});f.push({label:h.agentId,value:`${g.sessions} conversation(s), ${g.passages} passage(s), ${h.logs.length} log file(s)`})}return process.stdout.write(r.json===!0?`${JSON.stringify({pruned:i.map((h)=>h.agentId)},null,2)}
|
|
270
270
|
`:`
|
|
271
271
|
pruned ${i.length} agent id(s).
|
|
272
272
|
${l(f)}
|
|
273
|
-
`),n}async function
|
|
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
|
|
275
|
-
${
|
|
276
|
-
${a}${
|
|
277
|
-
`}function
|
|
278
|
-
${
|
|
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
|
|
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,
|
|
273
|
+
`),n}async function Bs(r,o,a){if(r.includes("/")||r.endsWith(".yaml")||r.endsWith(".yml"))throw new t({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${r}" is a path.`,hint:`An agent outside ${B()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${e.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let u=K(),i=u.find((P)=>P.ref===r);if(i===void 0){let P=u.map((U)=>U.ref);throw new t({code:"cli_agent_unknown",message:`No agent named "${r}" in the sandbox${P.length===0?", which is empty":""}.`,hint:P.length===0?`Nothing to remove. \`${e.slug} init\` creates one.`:`Known agents: ${P.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let f=i.id;if(f===void 0)try{f=T(i.manifestPath).id}catch{}let h=o.filesOnly===!0||f===void 0,g=f??r,v=await a.agentFootprint(g),k=v.lease?await a.leases.get(g):void 0,y=Ws(o),S=pn(e.slug,g);return{ref:r,agentId:g,manifestPath:i.manifestPath,dir:i.dir,files:la(i.dir),footprint:v,logs:Gs(g),sharesIdWith:u.filter((P)=>P.ref!==r&&(P.id??"")===g).map((P)=>P.ref),...k!==void 0&&_(k.pid)?{running:{pid:k.pid,mode:k.mode}}:{},...y?.state(S).installed===!0?{service:S}:{},filesOnly:h}}function Ws(r){let o=r.platform??process.platform;if(o!=="darwin")return;return Ue(o,{home:oa(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec}})}function la(r){let o=0,a=0,u=(i)=>{let f;try{f=Ms(i)}catch{return}for(let h of f){let g=Us(i,h);try{let v=Ks(g);if(v.isDirectory()){u(g);continue}o+=1,a+=v.size}catch{}}};return u(r),{count:o,bytes:a}}function Gs(r){let o=Jt(r),a=[];for(let u of[o.out,o.err])try{if(!sa(u))continue;a.push({path:u,bytes:Ks(u).size})}catch{}return a}function ca(){let r;try{r=Ms(Us(ee(),"logs"))}catch{return[]}let o=new Set;for(let a of r)for(let u of[".out.log",".err.log"])if(a.endsWith(u))o.add(a.slice(0,-u.length));return[...o]}async function Ft(r,o,a){if(r.yes===!0)return!0;let u=r.confirm;if(u===void 0)return!1;return await u(a,o)}import{randomBytes as jt}from"node:crypto";import{existsSync as wa}from"node:fs";import{createInterface as Zs}from"node:readline";class Oe extends Error{code;hint;field;status;request;constructor(r,o={}){super(r.hint===void 0?r.message:`${r.message}
|
|
274
|
+
hint: ${r.hint}`);if(this.name="DispachError",this.code=r.code,this.hint=r.hint??"",this.field=r.field,this.status=o.status,this.request=o.method===void 0||o.path===void 0?void 0:{method:o.method,path:o.path},o.cause!==void 0)this.cause=o.cause}}function ua(r,o){let a=r instanceof Error?r.message:String(r);return new Oe({code:"transport_failed",message:`${o.method} ${o.path} did not reach ${o.baseUrl}: ${a}`,hint:"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe."},{...o,cause:r})}async function fa(r,o){let a;try{let u=await r.json();if(typeof u.error?.code==="string"&&typeof u.error.message==="string")a={code:u.error.code,message:u.error.message,...u.error.hint===void 0?{}:{hint:u.error.hint},...u.error.field===void 0?{}:{field:u.error.field}}}catch{}return new Oe(a??{code:`http_${r.status}`,message:`${o.method} ${o.path} returned ${r.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:r.status,...o})}var qs=new Set(Me);async function*Vs(r){for await(let o of Fn(ma(r))){if(o.event===void 0||o.data==="")continue;let a;try{a=JSON.parse(o.data)}catch{continue}yield{name:o.event,data:a}}}async function*ma(r){let o=r.getReader();try{while(!0){let{done:a,value:u}=await o.read();if(a)return;if(u!==void 0)yield u}}finally{o.releaseLock()}}async function*pa(r){for await(let{name:o,data:a}of Vs(r)){if(qs.has(o)){yield{kind:"event",event:a};continue}let u=a??{};switch(o){case"turn.accepted":yield{kind:"accepted",turnId:String(u.turnId??""),sessionKey:String(u.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:u.state==="ended"?"ended":"running",events:Number(u.events??0),truncated:u.truncated===!0,dropped:Number(u.dropped??0),chunks:u.chunks==="start"||u.chunks==="partial"?u.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(u.turnId??""),status:String(u.status??"unknown"),steps:typeof u.steps==="number"?u.steps:void 0,errorCode:typeof u.errorCode==="string"?u.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(u.turnId??""),reason:String(u.reason??"not observable from this process")};break;default:break}}}async function*ha(r){for await(let{name:o,data:a}of Vs(r)){if(qs.has(o)){yield{kind:"event",event:a};continue}if(o==="stream.subscribed"){let u=a??{};yield{kind:"subscribed",report:{agentId:typeof u.agentId==="string"?u.agentId:null,types:Array.isArray(u.types)?u.types:null,chunks:u.chunks===!0,implied:typeof u.implied==="string"?u.implied:void 0}}}}}async function*ga(r,o={}){for await(let a of r){if(a.kind==="replay"&&a.report.truncated&&o.allowTruncated!==!0)throw new Oe({code:"replay_truncated",message:`This turn's replay is missing its oldest ${a.report.dropped} event(s), so the text reconstructed from it would be incomplete.`,hint:"Read the finished text from GET /v1/agents/:id/turns/:turnId, or pass { allowTruncated: true } to accept a fragment. Streaming from the start of a turn is never truncated — this only happens when reattaching to one that has already produced more events than the buffer holds."});if(a.kind==="unavailable")throw new Oe({code:"turn_not_observable",message:`Turn ${a.turnId} is recorded as running but is not observable here: ${a.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(a.kind!=="event")continue;if(a.event.type!=="model.chunk")continue;let u=a.event.data;if(u.kind==="reasoning")continue;if(typeof u.delta==="string")yield u.delta}}function Xs(r){let o=r.baseUrl.replace(/\/+$/,""),a=r.fetch??fetch,u=(k={})=>({...r.token===void 0?{}:{authorization:`Bearer ${r.token}`},...k});async function i(k,y,S={}){let P;try{P=await a(`${o}${y}`,{method:k,headers:u({...S.body===void 0?{}:{"content-type":"application/json"},...S.accept===void 0?{}:{accept:S.accept},...S.headers}),...S.body===void 0?{}:{body:JSON.stringify(S.body)},...S.signal===void 0?{}:{signal:S.signal}})}catch(U){throw ua(U,{method:k,path:y,baseUrl:o})}if(!P.ok)throw await fa(P,{method:k,path:y});return P}async function f(k,y,S){return await(await i(k,y,S??{})).json()}async function h(k,y){let S=await i("GET",k,{accept:"text/event-stream",...y===void 0?{}:{signal:y}});if(S.body===null)throw new Oe({code:"no_response_body",message:`GET ${k} returned ${S.status} with no body to read.`,hint:"An SSE route always has a body. A missing one means something between you and the server buffered the response — commonly a proxy without streaming enabled."},{status:S.status,method:"GET",path:k});return S.body}function g(k,y,S,P={}){let U=(F)=>F?.chunks===!0?"?chunks=true":"",W={turnId:y,sessionKey:S,replayed:P.replayed===!0,async*stream(F){let I=await h(`/v1/agents/${encodeURIComponent(k)}/turns/${encodeURIComponent(y)}/stream${U(F)}`,F?.signal);yield*pa(I)},async*tokens(F){yield*ga(W.stream({chunks:!0,...F}),{...F?.allowTruncated===void 0?{}:{allowTruncated:F.allowTruncated}})},async text(){for await(let F of W.stream()){if(F.kind==="ended")break;if(F.kind==="unavailable")break;if(F.kind==="event"&&F.event.type==="turn.end")break}return(await W.get()).text},get:()=>f("GET",`/v1/agents/${encodeURIComponent(k)}/turns/${encodeURIComponent(y)}`),async stop(){await i("POST",`/v1/agents/${encodeURIComponent(k)}/turns/${encodeURIComponent(y)}/stop`)}};return W}function v(k){let y=(S)=>`/v1/agents/${encodeURIComponent(k)}${S}`;return{id:k,async send(S,P){let U=await f("POST",y("/messages"),{body:{text:S,...P?.sessionKey===void 0?{}:{sessionKey:P.sessionKey},...P?.deliver===void 0?{}:{deliver:P.deliver},...P?.from===void 0?{}:{from:P.from}},...P?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":P.idempotencyKey}},...P?.signal===void 0?{}:{signal:P.signal}});return g(k,U.turnId,U.sessionKey,{replayed:U.replayed===!0})},turn:(S)=>g(k,S,""),describe:()=>f("GET",y("")),tools:()=>f("GET",y("/tools")),skills:()=>f("GET",y("/skills")),sessions:()=>f("GET",y("/sessions")),messages:(S,P)=>{let U=new URLSearchParams;if(P?.before!==void 0)U.set("before",String(P.before));if(P?.limit!==void 0)U.set("limit",String(P.limit));let W=U.size===0?"":`?${U.toString()}`;return f("GET",y(`/sessions/${encodeURIComponent(S)}/messages${W}`))},clearSession:(S)=>f("DELETE",y(`/sessions/${encodeURIComponent(S)}`)),reload:()=>f("POST",y("/reload"),{body:{}}),schedules:async()=>(await f("GET",y("/schedules"))).schedules,approvals:async()=>(await f("GET",y("/approvals"))).approvals,createSchedule:(S)=>f("POST",y("/schedules"),{body:S}),updateSchedule:(S,P)=>f("PATCH",y(`/schedules/${encodeURIComponent(S)}`),{body:P}),deleteSchedule:async(S)=>{await f("DELETE",y(`/schedules/${encodeURIComponent(S)}`))},runSchedule:(S)=>f("POST",y(`/schedules/${encodeURIComponent(S)}/run`),{body:{}}),config:()=>f("GET",y("/config")),setConfig:(S,P,U)=>f("PATCH",y("/config"),{body:{path:S,value:P,...U?.confirm===void 0?{}:{confirm:U.confirm}}}),session:(S)=>f("GET",y(`/sessions/${encodeURIComponent(S)}`)),setPhase:(S,P)=>f("POST",y(`/sessions/${encodeURIComponent(S)}/phase`),{body:{phase:P}}),approve:async(S,P)=>{await f("POST",y(`/approvals/${encodeURIComponent(S)}`),{body:{granted:P}})},stop:(S)=>f("POST",y("/stop"),{body:S===void 0?{}:{reason:S}}),start:()=>f("POST",y("/start"),{body:{}}),context:(S)=>{let P=new URLSearchParams;if(S?.sessionKey!==void 0)P.set("sessionKey",S.sessionKey);if(S?.input!==void 0)P.set("input",S.input);let U=P.size===0?"":`?${P.toString()}`;return f("GET",y(`/context${U}`))}}}return{agent:v,agents:()=>f("GET","/v1/agents"),health:()=>f("GET","/v1/health"),async ready(){try{return await i("GET","/v1/ready"),!0}catch(k){if(k instanceof Oe&&k.status===503)return!1;throw k}},provision:()=>f("GET","/v1/provision"),keys:()=>f("GET","/v1/keys"),createKey:(k)=>f("POST","/v1/keys",{body:k}),revokeKey:(k)=>f("DELETE",`/v1/keys/${encodeURIComponent(k)}`),createAgent:(k)=>f("POST","/v1/agents",{body:{answers:k}}),async*events(k){let y=new URLSearchParams;if(k?.agentId!==void 0)y.set("agentId",k.agentId);if(k?.types!==void 0&&k.types.length>0)y.set("types",k.types.join(","));if(k?.chunks===!0)y.set("chunks","true");let S=y.size===0?"":`?${y.toString()}`,P=await h(`/v1/events${S}`,k?.signal);yield*ha(P)}}}function tn(r,o){let a=[];for(let u of r){if(u.origin!==void 0&&u.origin!=="call")continue;if(u.role!=="user"&&u.role!=="assistant")continue;let i=Rr(u,o);if(i==="")continue;a.push({role:u.role,text:i})}return a}function Js(r){let o=r.ref??"<your agent>",a=`${e.slug} run ${o} --session ${r.sessionKey}`;return`
|
|
275
|
+
${Jo}Resume this session with:
|
|
276
|
+
${a}${_n}
|
|
277
|
+
`}function Lt(r,o){switch(r){case"first":return;case"restart":return"restarted — the configuration on disk is now the one in force; the conversation continues from the store.";case"switch":return"switched conversation — the one you left is still in the store, under its own key.";case"new":return o===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${o}, still in the store. /sessions goes back to it.`}}function ya(r){return r==="nlt"?jn():Un()}function zs(r){return{kind:"embedded",agentId:r.agent.id,describe:()=>r.description,subscribe:(o)=>r.bus.on("*",o,{chunks:!0}),send:(o,a)=>r.send(o,{...a,source:"repl"}),streamFilter:r.streamFilter,history:r.history,sessions:r.sessions,clearSession:r.clearSession,tools:async()=>Xn(r.agent),context:r.context,close:async()=>{}}}function Ys(r){let o=r.client.agent(r.agentId),a=new Set,u=new AbortController,i,f=()=>{if(i!==void 0)return;i=(async()=>{for await(let h of r.client.events({agentId:r.agentId,chunks:!0,signal:u.signal})){if(h.kind!=="event"||h.event===void 0)continue;for(let g of a)g(h.event)}})().catch(()=>{})};return{kind:"attached",agentId:r.agentId,host:r.host,describe:()=>r.description,subscribe:(h)=>(a.add(h),f(),()=>a.delete(h)),send:async(h,g)=>{let v=!1,k,y=()=>{if(v=!0,k!==void 0)o.turn(k).stop().catch(()=>{})};g.signal.addEventListener("abort",y,{once:!0});let S,P=new Promise((U)=>{let W=(F)=>{if(k!==void 0&&F.turnId!==void 0&&F.turnId!==k)return;if(F.type==="error"){S=F.data;return}if(F.type!=="turn.end")return;a.delete(W),U({text:"",reason:F.data.reason,steps:F.data.steps,durationMs:F.data.durationMs,tokens:F.data.tokens,...S===void 0?{}:{error:S}})};a.add(W),f()});try{if(k=(await o.send(h,{sessionKey:g.sessionKey})).turnId,v)o.turn(k).stop().catch(()=>{});return await P}finally{g.signal.removeEventListener("abort",y)}},streamFilter:()=>ya(r.description.dialect),history:async(h)=>{let g=await o.messages(h);return tn([...g.messages].reverse().map((v)=>({role:v.role,content:v.content,...v.origin===void 0?{}:{origin:v.origin}})),r.description.dialect)},sessions:()=>o.sessions(),clearSession:async(h)=>{await o.clearSession(h)},tools:async()=>{let h=await o.tools();return{dialect:r.description.dialect,catalogueTokens:r.description.catalogueTokens,tools:h.map((g)=>({slug:g.slug,mutating:g.mutating,trust:g.trust,...g.trustReason===void 0?{}:{trustReason:g.trustReason},summary:g.summary}))}},context:async(h)=>{let g=await o.context({sessionKey:h});return{...g,windowSource:"as the host resolved it",...g.lastCompaction===void 0&&g.compactions!==void 0?{lastCompaction:g.compactions===0?void 0:`${g.compactions} stage${g.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await o.reload()).adopted,close:async()=>{u.abort(),a.clear()}}}function Qs(r){if(r?.baseUrl===void 0||r.baseUrl==="")return;return{baseUrl:r.baseUrl,pid:r.pid}}async function ba(r,o,a,u,i,f=[],h){let g=r.describe(),[v,k]=await Promise.all([r.turns(o,1),r.store.messages.count(r.id,o)]),y=[`${e.name} ${R} · ${g.id} · ${g.model}`,`session ${o} · ${k} message(s) · window ${g.window} · store ${a}`,`ready in ${u.toFixed(0)} ms · /help for commands and keys · /exit to leave`],S=Lt(i,h);if(S!==void 0)y.push(S);if(v[0]?.errorCode==="turn_abandoned")y.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let P of[...r.warnings,...r.tools.warnings])y.push(`note: ${P.message}
|
|
278
|
+
${P.hint}`);if(f.length>0)y.push(`note: ${f.join(", ")} in the .env here ${f.length===1?"was":"were"} ignored — this agent's own .env sets ${f.length===1?"it":"them"}.
|
|
279
|
+
A .env in the directory you launched from configures that project, not an agent living somewhere else. Export the variable to override the agent's own file.`);return y}async function Ut(r){let o=r.once!==void 0,a=ie({json:!1,plain:r.plain===!0,oneShot:o}),{mode:u}=a;if(r.manifestPath===void 0){let F=await $a(u,a.because,r);if(typeof F==="number")return F;return Ut({...r,manifestPath:F})}let i=$r();if(r.store===void 0&&r.ephemeral!==!0&&wa(i))process.stdout.write(`note: a session store exists at ${i} from an earlier version — pass --store ${i} to keep using it; the default is now ${w()}
|
|
280
|
+
`);let f;b(()=>f?.stop("cli-exit"));let h={current:void 0},g={current:""},v={current:r.sessionKey},k={current:!1},y={current:void 0},S=r.quiet===!0,P="first",U={current:void 0},W=r.ephemeral===!0?void 0:Qs(await Ce(xt(r.manifestPath),r.store));if(W!==void 0)return await Pa({...r,host:W,mode:u==="rich"?"rich":"plain",quiet:S,oneShot:o,reader:h,draft:g,session:v,random:jt});for(;;){let F=await L.create({agents:[r.manifestPath],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath]),store:r.ephemeral===!0?":memory:":r.store??w()});f=F;let I=F.list()[0];if(I===void 0)throw Error("The manifest produced no agent.");if(v.current===void 0||v.current===""){let fe=await eo({list:()=>Q.sessions(),mode:u,asked:v.current,wantsContinue:r.continueSession===!0,random:jt});if(typeof fe==="number")return await F.stop("cli-exit"),fe;v.current=fe.sessionKey,k.current=fe.fresh}let de=v.current,oe=I.roles.main.capabilities.thinking!=="none",ge=r.noReasoning===!0?!1:oe,z=S||o?[]:await ba(I,de,F.store.location,P==="first"?F.boot.processMs:F.boot.bootMs,P,Co([r.manifestPath]),y.current),V=u==="rich"&&!S&&!o?tn(await I.history(de),I.describe().dialect):[],Q=zs({agent:I,bus:F.bus,send:(fe,Ae)=>I.send(fe,Ae),history:async(fe)=>tn(await I.history(fe),I.describe().dialect),sessions:async()=>await I.store.sessions.list(I.id),clearSession:async(fe)=>{await I.clearSession(fe)},context:async(fe)=>Ea(I,fe),streamFilter:()=>I.streamFilter(),description:{agentId:I.id,name:I.describe().name,model:I.describe().model,dialect:I.describe().dialect,window:I.describe().window,catalogueTokens:I.describe().catalogueTokens,thinking:I.roles.main.capabilities.thinking,warnings:[...I.warnings,...I.tools.warnings]}}),re={...r,source:Q,embedded:{agent:I,runtime:F},sessionKey:de,banner:z,prior:V,quiet:S,reader:h,draft:g,showReasoning:ge,freshSession:k.current,switchTo:U,random:jt},he=u==="rich"?await no(re):await to(re);if(await F.stop(he===Ne?"restart":"cli-exit"),he!==Ne)return he;if(U.current===void 0)P="restart";else P=U.current.reason,y.current=de,v.current=U.current.key,U.current=void 0;k.current=!1}}function va(r,o){let a=[];for(let u of r)Se({action:"install",manifestPath:o,name:`${u.source}/${u.skill}`,quiet:!0,collect:a});return a}var Ne=Symbol("restart");async function $a(r,o,a){let u=K();if(u.length===0){if(r==="rich"){let y=await at({plain:a.plain===!0});if(y.kind==="aborted")return process.stdout.write(`nothing to run
|
|
281
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
282
|
`),u[0].manifestPath;if(r!=="rich"){for(let y of u)process.stdout.write(`${y.ref} ${y.problem??y.modelId??"?"} ${y.dir}
|
|
283
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-
|
|
285
|
-
`),n;if(k.kind==="create"){let y=await
|
|
286
|
-
`),n;if(y.kind==="failed")return y.code;return y.manifestPath}return k.manifestPath}async function
|
|
284
|
+
`),s}let[{render:i},{createElement:f},{Picker:h}]=await Promise.all([import("ink"),import("react"),import("./Picker-hfeh1g6m.js")]),g={kind:"quit"};Wt();let v=i(f(h,{title:`${e.name} ${R}`,agents:u,onDone:(y)=>{g=y}}),{exitOnCtrlC:!1,...Z(a.noEnhancedKeys)});b(()=>v.unmount()),await v.waitUntilExit(),v.unmount();let k=g;if(k.kind==="quit")return process.stdout.write(`nothing run
|
|
285
|
+
`),n;if(k.kind==="create"){let y=await at({plain:a.plain===!0});if(y.kind==="aborted")return process.stdout.write(`nothing to run
|
|
286
|
+
`),n;if(y.kind==="failed")return y.code;return y.manifestPath}return k.manifestPath}async function eo(r){let o=()=>({sessionKey:Hn(r.random),fresh:!0});if(r.wantsContinue&&r.asked==="")throw new t({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(r.wantsContinue){let a=await r.list(),u=ka(a);if(u===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
|
|
287
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(
|
|
288
|
+
`),o();if(r.mode!=="rich"){for(let i of[...a].sort(Kn))process.stdout.write(`${i.sessionKey} ${i.messages} ${i.turns} ${i.lastActivityAt}
|
|
289
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
|
|
291
|
-
`)},h=(
|
|
292
|
-
`);f(`${
|
|
290
|
+
`),s}let u=await Sa([...a].sort(Kn));return u===void 0?o():{sessionKey:u,fresh:!1}}return r.asked===void 0?o():{sessionKey:r.asked,fresh:!1}}function Kn(r,o){return Date.parse(o.lastActivityAt)-Date.parse(r.lastActivityAt)}function ka(r){return[...r].sort(Kn)[0]}async function Sa(r){let[{render:o},{createElement:a},{SessionPicker:u}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-zyqkg4dn.js")]),i;Wt();let f=o(a(u,{sessions:r.map((h)=>({sessionKey:h.sessionKey,messages:h.messages,turns:h.turns,lastActivityAt:h.lastActivityAt,phase:h.phase})),now:Date.now(),columns:q(process.stdout.columns,j),maxRows:Bt,onDone:(h)=>{i=h,f.unmount()}}),{exitOnCtrlC:!1,...Z()});return b(()=>f.unmount()),await f.waitUntilExit(),i}function xa(r,o,a,u,i){let f=r.describe(),h=[`${e.name} ${R} · ${f.agentId} · ${f.model}`,`session ${o} · window ${f.window} · attached to ${a.baseUrl} (pid ${a.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],g=Lt(u,i);if(g!==void 0)h.push(g);for(let v of f.warnings)h.push(`warning: ${v.message}`);return h}async function Pa(r){let o=r.manifestPath??"",a=xt(o),u=Je(o),i=Xs({baseUrl:r.host.baseUrl,...u===void 0?{}:{token:u}}),f=await i.agent(a).describe(),h=Ys({client:i,agentId:a,host:r.host,description:{agentId:a,name:f.name,model:f.model??"unknown",dialect:f.dialect??"nlt",window:f.window??0,catalogueTokens:f.catalogueTokens??0,thinking:"unknown",warnings:f.warnings??[]}}),g={current:void 0},v="first",k={current:void 0},y={current:!1};for(;;){if(r.session.current===void 0||r.session.current===""){let I=await eo({list:()=>h.sessions(),mode:r.mode,asked:r.session.current,wantsContinue:r.continueSession===!0,random:r.random});if(typeof I==="number")return I;r.session.current=I.sessionKey,y.current=I.fresh}let S=r.session.current??"",P=r.quiet||r.oneShot?[]:xa(h,S,r.host,v,k.current),U=r.mode==="rich"&&!r.quiet&&!r.oneShot?await h.history(S):[],W={...r,source:h,sessionKey:S,banner:P,prior:U,quiet:r.quiet,reader:r.reader,draft:r.draft,showReasoning:r.noReasoning!==!0,freshSession:y.current,switchTo:g,random:r.random},F=r.mode==="rich"?await no(W):await to(W);if(F!==Ne)return await h.close(),F;if(g.current===void 0)v="restart";else v=g.current.reason,k.current=S,r.session.current=g.current.key,g.current=void 0;y.current=!1}}async function no(r){let[{render:o},{createElement:a},{App:u}]=await Promise.all([import("ink"),import("react"),import("./App-b1yrwrcq.js")]),i=En();b(()=>{i.close()}),pe(),Zr(),process.stdout.write(`${ve}${Ko}`);let f=!1,h=o(a(u,{source:r.source,onSwitch:(g,v)=>{f=!0,r.switchTo.current={key:g,reason:"switch"},r.draft.current=v},onNew:(g)=>{f=!0,r.switchTo.current={key:Hn(r.random),reason:"new"},r.draft.current=g},sessions:async()=>[...await r.source.sessions()].sort(Kn).map((v)=>({sessionKey:v.sessionKey,messages:v.messages,turns:v.turns,lastActivityAt:v.lastActivityAt,phase:v.phase})),onRestart:(g)=>{f=!0,r.draft.current=g},sessionKey:r.sessionKey,model:r.source.describe().model,agentName:r.source.describe().agentId,freshSession:r.freshSession,warnings:r.source.describe().warnings.map((g)=>g.message),initial:So(ko(r.banner.slice(1)),r.prior),correctKeys:i.correct,showReasoning:r.showReasoning,quiet:r.quiet,...r.manifestPath===void 0?{}:{manifestPath:r.manifestPath},catalogue:{load:(g)=>nt({onStatus:g}),install:async(g,v)=>Et(va(g,v))},status:()=>r.embedded===void 0?so(r.source):ro(r.embedded),contextView:()=>oo(r,r.sessionKey),...r.draft.current===""?{}:{initialDraft:r.draft.current}}),{exitOnCtrlC:!1,...Z(r.noEnhancedKeys)});if(b(()=>h.unmount()),await h.waitUntilExit(),J(),!f)process.stdout.write(Js({ref:r.source.describe().agentId,sessionKey:r.sessionKey}));return f?Ne:n}async function to(r){let{source:o,sessionKey:a,quiet:u}=r,i=!0,f=(z)=>{if(z==="")return;process.stdout.write(z),i=z.endsWith(`
|
|
291
|
+
`)},h=(z)=>{if(!i)f(`
|
|
292
|
+
`);f(`${z}
|
|
293
293
|
`)};if(r.banner.length>0)f(`${r.banner.join(`
|
|
294
294
|
`)}
|
|
295
295
|
|
|
296
|
-
`);let g=!u&&r.once===void 0,v=!1,k,y=o.streamFilter(),S=(
|
|
296
|
+
`);let g=!u&&r.once===void 0,v=!1,k,y=o.streamFilter(),S=(z)=>{if(z==="")return;f(z),v=!0},P=r.source.subscribe((z)=>{switch(z.type){case"model.result":S(y.endStep());return;case"model.chunk":{let{delta:V,kind:Q}=z.data;if(Q==="reasoning"&&r.showReasoning!==!0)return;if(Q!==k){if(k!==void 0)f(`
|
|
297
297
|
|
|
298
298
|
`);if(r.showReasoning===!0)f(Q==="reasoning"?`· reasoning ·
|
|
299
299
|
`:`· reply ·
|
|
300
|
-
`);k=Q}if(Q==="reasoning"){f(
|
|
301
|
-
${
|
|
302
|
-
`)},
|
|
303
|
-
`);else if(!v&&
|
|
304
|
-
`);let Q=
|
|
300
|
+
`);k=Q}if(Q==="reasoning"){f(V),v=!0;return}S(y.push(V));return}case"tool.result":{if(!g)return;let{slug:V,ok:Q,latencyMs:re,truncated:he}=z.data;h(` · ${V} — ${Q?"ok":"failed"} · ${re} ms${he?" · observation trimmed":""}`);return}case"agent.warning":h(` · ${z.data.message}
|
|
301
|
+
${z.data.hint}`);return;case"tool.repair":if(g)h(` · ${z.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":h(` · ${z.data.slug} — blocked: ${z.data.reason}`);return;case"context.dropped":h(` · context: ${z.data.messages} older message(s) did not fit the ${z.data.budget}-token budget and were left out`);return;default:return}}),U=async(z)=>{let V=on(z);if(V===void 0)return"prompt";switch(V.kind){case"exit":return"exit";case"restart":{let Q=o.reload;if(Q===void 0)return"restart";try{let re=await Q();h(`reloaded ${re.join(", ")} — this conversation continues`)}catch(re){h(`could not reload: ${re instanceof Error?re.message:String(re)}`)}return"handled"}case"new":return r.switchTo.current={key:Hn(r.random),reason:"new"},"restart";case"help":return h(sn()),"handled";case"tools":return h(lt(await o.tools())),"handled";case"status":return h(r.embedded===void 0?await so(o):await ro(r.embedded)),"handled";case"context":return h(await oo(r,a)),"handled";case"reset":return await o.clearSession(a),h("session cleared — memory files on disk are untouched"),"handled";case"unknown":return h($t(V)),"handled";case"command":return h(`${V.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${e.slug} ${V.name}${V.rest===""?"":` ${V.rest}`}\``),"handled"}},W,F=0,I=n,de=(z=r.reader.current)=>{if(W!==void 0&&!W.signal.aborted){F=performance.now(),W.abort();return}z?.close(),f(`
|
|
302
|
+
`)},oe=async(z)=>{W=new AbortController,v=!1,k=void 0,y=o.streamFilter();let V=await o.send(z,{sessionKey:a,signal:W.signal});if(W=void 0,S(y.end()),v&&!i)f(`
|
|
303
|
+
`);else if(!v&&V.text!=="")f(`${V.text}
|
|
304
|
+
`);let Q=ze(V.reason,{steps:V.steps,durationMs:V.durationMs,...F===0?{}:{cancelledAfterMs:performance.now()-F}});if(Q!==void 0)f(`
|
|
305
305
|
(${Q})
|
|
306
|
-
`);if(
|
|
307
|
-
${
|
|
308
|
-
hint: ${
|
|
309
|
-
`);if(
|
|
306
|
+
`);if(V.reason==="error"&&V.error!==void 0)process.stderr.write(`
|
|
307
|
+
${V.error.code}: ${V.error.message}
|
|
308
|
+
hint: ${V.error.hint}
|
|
309
|
+
`);if(xr(V.reason))I=s;if(!u&&V.reason==="final")f(` ${V.tokens.prompt} prompt · ${V.tokens.output} output · ${V.durationMs} ms
|
|
310
310
|
|
|
311
|
-
`);await ue()},
|
|
312
|
-
`);for(let f of r)process.stdout.write(`${
|
|
311
|
+
`);await ue()},ge=()=>de();process.on("SIGINT",ge);try{if(r.once!==void 0)return await oe(r.once),I;if(process.stdin.isTTY!==!0){let V=r.reader.current??Zs({input:process.stdin});r.reader.current=V;for await(let Q of V){let re=Q.trim();if(re==="")continue;let he=await U(re);if(he==="exit")break;if(he==="restart"){I=Ne;break}if(he==="handled")continue;await oe(re)}return I}let z=r.reader.current??Zs({input:process.stdin,output:process.stdout,prompt:An,terminal:!1});r.reader.current=z,z.prompt();for await(let V of z){let Q=V.trim();if(Q===""){z.prompt();continue}let re=await U(Q);if(re==="exit")break;if(re==="restart"){I=Ne;break}if(re==="handled"){z.prompt();continue}await oe(Q),z.prompt()}if(I!==Ne)z.close(),r.reader.current=void 0;return I}finally{process.off("SIGINT",ge),P()}}async function ro(r){let{agent:o,runtime:a}=r,u=o.describe(),i=o.manifest,f=i.channels.filter((y)=>y.enabled).map((y)=>`${y.id} (${y.type})`).join(", "),h=f===""?"none — reached through this session and the HTTP API only":a.channels.started?`${f} — connected in this session`:`${f} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,g=!i.server.enabled?"off":`enabled on ${i.server.host}:${i.server.port}, NOT bound here — \`serve\` binds it`,v=ye(i),k=v.filter((y)=>y.role!=="main"&&y.role===y.configuredAs);return l([{label:"agent",value:`${u.id} (${u.name})`},{label:"model",value:`${u.model} · ${i.tools.dialect} · ${u.window} token window (${je(v[0]?.window)})`},...k.map((y)=>({label:y.role,value:`${y.modelId} · ${y.window.contextWindow} token window (${je(y.window)})`})),{label:"channels",value:h},{label:"http api",value:g},{label:"store",value:a.store.location},{label:"background",value:await Ra(a,u.id)}])}async function so(r){let o=r.describe(),a=r.host,[u,i]=await Promise.all([r.tools(),r.sessions()]);return l([{label:"agent",value:`${o.agentId} (${o.name})`},{label:"attached to",value:a===void 0?"a host":`${a.baseUrl} · pid ${a.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${o.model} · ${o.window} token window`},{label:"dialect",value:o.dialect},{label:"tools",value:`${u.tools.length} pinned · ${u.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${i.length} on this agent`},{label:"warnings",value:o.warnings.length===0?"none":o.warnings.map((f)=>f.message).join("; ")}])}async function Ea(r,o){let a=await r.previewContext({sessionKey:o}),[u]=ye(r.manifest);return{slots:a.slots,history:a.history,cache:a.cache,total:a.total,window:a.window,windowSource:je(u?.window),wireTokens:a.wireTokens,reserveOutput:a.reserveOutput,calibration:a.calibration,lastCompaction:a.compactions===0?void 0:`${a.compactions} stage${a.compactions===1?"":"s"} run this session`}}async function oo(r,o){return bo(await r.source.context(o))}async function Ra(r,o){if(r.owned.includes(o))return"this session is serving this agent";let a=await r.store.leases.get(o);if(a!==void 0&&_(a.pid))return a.mode==="daemon"?`running as a background service · pid ${a.pid} · \`${e.slug} daemon status ${o}\``:`served by another session · pid ${a.pid} (${a.mode})`;return`not supervised — \`${e.slug} daemon install ${o}\` keeps it running without a terminal`}function be(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function Ia(r,o){if(!r.enabled)return"off";if(r.nextRunAt===void 0)return"done";let a=Date.parse(r.nextRunAt)-o;if(a<=0)return"due";let u=Math.round(a/60000);if(u<60)return`in ${u}m`;let i=Math.round(a/3600000);return i<48?`in ${i}h`:`in ${Math.round(i/24)}d`}function Ta(r,o){if(r.lastFiredAt===void 0)return"never run";let a=qe(r.lastFiredAt,o);if(r.lastStatus==="error")return`FAILED ${a}`;return`ok ${a}`}function Aa(r,o){if(r.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let a=Math.max(8,...r.map((f)=>f.id.length)),u=Math.max(4,...r.map((f)=>`${f.kind} ${f.expr}`.length));process.stdout.write(`${be("SCHEDULE",a)} ${be("WHEN",u)} ${be("NEXT",7)} LAST
|
|
312
|
+
`);for(let f of r)process.stdout.write(`${be(f.id,a)} ${be(`${f.kind} ${f.expr}`,u)} ${be(Ia(f,o),7)} ${Ta(f,o)}
|
|
313
313
|
`);let i=r.filter((f)=>f.lastStatus==="error");if(i.length>0)process.stdout.write(`
|
|
314
314
|
${i.length} failing — \`schedules --id ${i[0]?.id}\` for the error
|
|
315
|
-
`)}function
|
|
316
|
-
`);for(let[u,i]of o)process.stdout.write(` ${
|
|
317
|
-
`)}function
|
|
315
|
+
`)}function Oa(r){let o=[["kind",`${r.kind} ${r.expr}`],["timezone",r.timezone??"(host)"],["task",r.task],["deliver",r.deliverChannel===void 0?"none — the reply reaches the event stream only":`${r.deliverChannel} → ${r.deliverTo}`],["session",r.sessionMode],["model role",r.role??"main"],["enabled",r.enabled?"yes":"no"],["declared in",r.origin==="manifest"?"agent.yaml":"the API"],["next run",r.nextRunAt??"(never again)"],["runs",String(r.runs)],["last run",r.lastFiredAt??"never"],["last status",r.lastStatus??"-"]];if(r.lastError!==void 0)o.push(["last error",r.lastError]);let a=Math.max(...o.map(([u])=>u.length));process.stdout.write(`${r.id}
|
|
316
|
+
`);for(let[u,i]of o)process.stdout.write(` ${be(u,a)} ${i}
|
|
317
|
+
`)}function _a(r,o){let a=new Set(o),u=new Map;for(let i of r){if(!a.has(i.channel))continue;let f=`${i.channel}\x00${i.peerId}`,h=u.get(f);if(h!==void 0&&h.lastSeen>=i.lastActivityAt)continue;u.set(f,{channelId:i.channel,address:i.peerId,lastSeen:i.lastActivityAt})}return[...u.values()].sort((i,f)=>i.channelId===f.channelId?f.lastSeen.localeCompare(i.lastSeen):i.channelId.localeCompare(f.channelId))}function Ca(r,o){if(r.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
|
|
318
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(`${
|
|
320
|
-
`);for(let i of r)process.stdout.write(`${
|
|
319
|
+
`);return}let a=Math.max(7,...r.map((i)=>i.channelId.length)),u=Math.max(7,...r.map((i)=>i.address.length));process.stdout.write(`${be("CHANNEL",a)} ${be("ADDRESS",u)} LAST SEEN
|
|
320
|
+
`);for(let i of r)process.stdout.write(`${be(i.channelId,a)} ${be(i.address,u)} ${qe(i.lastSeen,o)}
|
|
321
321
|
`);process.stdout.write(`
|
|
322
322
|
Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
|
|
323
323
|
`+`never a person — a private chat is reached by the numeric id above.
|
|
324
|
-
`)}async function
|
|
324
|
+
`)}async function io(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath]),lease:!1});b(()=>o.stop("cli-exit"));let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");let u=Date.now();for(let[f,h]of[[r.enable,!0],[r.disable,!1]]){if(f===void 0)continue;let g=await a.store.schedules.get(a.id,f);if(g===void 0)return process.stderr.write(`no schedule "${f}" on ${a.id}
|
|
325
325
|
hint: run \`schedules\` with no flags to see what this agent has.
|
|
326
326
|
`),s;if(g.origin==="manifest")return process.stderr.write(`${f} is declared in agent.yaml, so the manifest decides whether it runs.
|
|
327
327
|
`+` Writing it here would last until the next start — reconciliation restores every
|
|
@@ -331,124 +331,128 @@ Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
|
|
|
331
331
|
${r.manifestPath}
|
|
332
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
333
|
`:`${f} disabled — still listed, and it keeps its place in the sequence
|
|
334
|
-
`)}if(r.recipients===!0){let f=
|
|
335
|
-
`),n;return
|
|
334
|
+
`)}if(r.recipients===!0){let f=_a(await a.store.sessions.list(a.id),a.manifest.channels.map((h)=>h.id));if(r.json===!0)return process.stdout.write(`${JSON.stringify({recipients:f},null,2)}
|
|
335
|
+
`),n;return Ca(f,u),n}let i=await a.store.schedules.list(a.id);if(r.json)return process.stdout.write(`${JSON.stringify({schedules:i},null,2)}
|
|
336
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
|
|
338
|
-
`)}),
|
|
337
|
+
`),s;return Oa(f),n}if(r.enable===void 0&&r.disable===void 0)Aa(i,u);return n}import{dirname as lo,resolve as Dt}from"node:path";function Na(){return mt.shape.server.parse({})}async function co(r){let o=m(r.manifestPaths),a=r.store??w(),u=await zr(r.manifestPaths,o,a),i=u.filter((D)=>!D.enabled),f=u.filter((D)=>D.enabled),h=r.manifestPaths.length===0,g=[],v=[];for(let D of f)try{let ne=T(D.manifestPath),se=await yt({refs:ne.plugins??[],agentId:ne.id??D.manifestPath,paths:{workspace:lo(Dt(D.manifestPath)),state:lo(Dt(D.manifestPath)),manifest:Dt(D.manifestPath)},env:o,bus:new _e({runtimeId:"serve-preload"}),builtIn:C,base:{toolProviders:A,channels:N}});g.push({path:D.manifestPath,loaded:x(D.manifestPath,{knownProviders:Object.keys(se.toolProviders),knownChannels:Object.keys(se.channels),env:o})})}catch(ne){if(!h)throw ne;v.push({path:D.manifestPath,detail:tr(ne)?ne.message:String(ne),...tr(ne)&&ne.hint!==void 0?{hint:ne.hint}:{}})}let k=g[0],y=k?.loaded,S=y?.manifest.server??Na();for(let D of g.slice(1)){let ne=D.loaded.manifest.server;for(let[se,De,rn,Le]of[["server.port",S.port,ne.port,r.port!==void 0],["server.host",S.host,ne.host,r.host!==void 0],["server.tokenEnv",S.tokenEnv,ne.tokenEnv,!1]]){if(Le||De===rn)continue;throw new t({code:"serve_bind_conflict",message:`${k?.path??"the first manifest"} sets ${se} to ${String(De)} and ${D.path} sets it to ${String(rn)}.`,hint:"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.",field:se})}}let P=r.port??S.port,U=r.host??S.host,W=y===void 0?o[S.tokenEnv]:y.env[S.tokenEnv],F=o[`${e.envPrefix}SERVICE`]!==void 0,I=new _e({runtimeId:`rt_${Date.now().toString(36)}`});if(r.json!==!0)I.on("agent.channel.status",(D)=>{let ne=D.data,se=ne.input===void 0?"":` (${ne.input.kind}${ne.input.expiresAt===void 0?"":`, expires ${ne.input.expiresAt}`} — GET /v1/agents/${D.agentId??""} carries it)`;process.stdout.write(` ${ne.channelId}: ${ne.status}${ne.detail===void 0?"":` — ${ne.detail}`}${se}
|
|
338
|
+
`)}),I.on("agent.channel.error",(D)=>{let ne=D.data;process.stderr.write(` ${ne.channelId}: ${ne.message}
|
|
339
339
|
hint: ${ne.hint}
|
|
340
|
-
`)}),
|
|
341
|
-
`)});let
|
|
342
|
-
`);else{process.stdout.write(`${e.name} serving on ${D
|
|
343
|
-
`)
|
|
344
|
-
`)
|
|
345
|
-
`)
|
|
346
|
-
`);if(
|
|
347
|
-
`)
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
`)
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
`)
|
|
354
|
-
`)
|
|
355
|
-
`)
|
|
356
|
-
`)
|
|
357
|
-
`);
|
|
358
|
-
`);
|
|
359
|
-
`)}
|
|
340
|
+
`)}),I.on("agent.channel.rejected",(D)=>{let ne=D.data;process.stdout.write(` ${ne.channelId}: ${ne.reason} — ${ne.detail}
|
|
341
|
+
`)});let de=cr(),oe=await L.create({agents:g.map((D)=>D.path),approve:de.approver,env:o,bus:I,toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,startChannels:!0,startSchedules:!0,store:a,mode:F?"daemon":"terminal"});Vr();let ge=Fa(),z=await oe.store.operatorKeys.liveCount(),V=z===0||r.claim===!0?Lr():void 0,Q;try{Q=await Ur({runtime:oe,host:U,port:P,approvals:de,allowedOrigins:S.allowedOrigins,allowedHosts:S.allowedHosts,resolveAgent:(D)=>Kt(D,o),provision:{steps:()=>es({agentDirBase:B(o)}),create:(D)=>ns({answers:D,defaults:{agentDirBase:B(o)}})},...V===void 0?{}:{claim:V},...W===void 0||W===""?{}:{token:W}})}catch(D){if(await oe.stop("server failed to bind"),D instanceof t)throw D;throw new t({code:"server_bind_failed",message:`Could not bind ${U}:${P}: ${D instanceof Error?D.message:String(D)}`,hint:"Another process is probably on that port. Pass --port, or set server.port in the manifest.",cause:D})}await oe.publishAddress(Q.url);let re=oe.list(),he=re[0];if(he!==void 0)process.title=re.length===1?`${e.slug} ${he.id}`:`${e.slug} ${re.length} agents`;for(let D of re)D.reportRuntimeState({serverListening:!0});if(r.json===!0)process.stdout.write(`${JSON.stringify({url:Q.url,websocket:Q.websocket,authenticated:W!==void 0&&W!=="",keys:z,...V===void 0?{}:{claim:V.token},agents:re.map((D)=>({id:D.id,channels:oe.channels.statusOf(D.id)})),declined:oe.declined.map((D)=>({agentId:D.agentId,pid:D.pid,mode:D.mode,since:D.startedAt})),disabled:i.map((D)=>({agentId:D.agentId,...D.reason===void 0?{}:{reason:D.reason}})),broken:v.map((D)=>({path:D.path,detail:D.detail,...D.hint===void 0?{}:{hint:D.hint}}))})}
|
|
342
|
+
`);else{let D=`http://${Xe(U)}:${Q.port}`,ne=D===Q.url?"":` (bound ${U} — every interface)`;process.stdout.write(`${e.name} serving on ${D}${ne}
|
|
343
|
+
`),process.stdout.write(` web UI ${D}/ · API reference ${D}/docs
|
|
344
|
+
`);for(let se of re){let De=oe.channels.statusOf(se.id),rn=De.length===0?"no channels":De.map((an)=>`${an.id} (${an.type})`).join(", "),Le=se.manifest.schedules.filter((an)=>an.enabled),Po=se.manifest.schedules.length===0?"":`, ${Le.length} schedule${Le.length===1?"":"s"}${se.manifest.schedules.length>Le.length?` (+${se.manifest.schedules.length-Le.length} disabled)`:""}`;process.stdout.write(` ${se.id} — ${rn}${Po}
|
|
345
|
+
`)}for(let se of i)process.stdout.write(` ${se.agentId} — stopped${se.reason===void 0?"":` (${se.reason})`}, \`${e.slug} start ${se.agentId}\`
|
|
346
|
+
`);for(let se of v)if(process.stdout.write(` ${se.path} — NOT served: ${se.detail}
|
|
347
|
+
`),se.hint!==void 0)process.stdout.write(` hint: ${se.hint}
|
|
348
|
+
`);for(let se of oe.declined)process.stdout.write(` ${se.agentId} — NOT served here: pid ${se.pid} (${se.mode}) already has it
|
|
349
|
+
`);if(oe.declined.length>0)process.stdout.write(` \`${e.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
|
|
350
|
+
`);if(V!==void 0){if(process.stdout.write(` open once to claim this server:
|
|
351
|
+
${Dr(U,Q.port,V.token)}
|
|
352
|
+
without a browser: ${Fr(U,Q.port,V.token)}
|
|
353
|
+
`),W===void 0||W==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
|
|
354
|
+
`)}if(W===void 0||W==="")process.stdout.write(` unauthenticated — loopback only. Set ${S.tokenEnv} to bind a public host.
|
|
355
|
+
`);if(!Q.websocket)process.stdout.write(` /v1/ws unavailable under Node — SSE and HTTP are unaffected.
|
|
356
|
+
`);if(F)process.stdout.write(` running as a background service · ${e.slug} daemon status ${re[0]?.id??""}
|
|
357
|
+
`);else if(dt())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
|
|
358
|
+
`);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${e.slug} daemon install${re[0]?.id===void 0?"":` ${re[0].id}`}\` keeps it running.
|
|
359
|
+
`)}let fe=!1,Ae=async()=>{if(fe)return;fe=!0,await Q.stop(),await oe.stop("interrupted")};return b(Ae),await ge,process.stdout.write(`stopping
|
|
360
|
+
`),await Ae(),n}function Fa(){return new Promise((r)=>{let o=()=>{process.off("SIGINT",o),process.off("SIGTERM",o),r()};process.once("SIGINT",o),process.once("SIGTERM",o)})}function me(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function La(r){let o=new Map,a=[];for(let u of r){let i=u.sessionKey.split(":"),f={sessionKey:u.sessionKey,phase:u.phase,messages:u.messages,turns:u.turns,lastActivityAt:u.lastActivityAt};if(i.length!==3||i[0]!=="schedule"){a.push(f);continue}let h=`schedule:${i[1]}`,g=o.get(h);if(g===void 0){let v={...f,sessionKey:`${h}:*`,runs:1};o.set(h,v),a.push(v);continue}if(g.runs=(g.runs??1)+1,g.messages+=u.messages,g.turns+=u.turns,u.lastActivityAt>g.lastActivityAt)g.lastActivityAt=u.lastActivityAt}return a}function ja(r){if(r.length===0){process.stdout.write(`no sessions yet
|
|
361
|
+
`);return}let o=La(r),a=Math.max(7,...o.map((u)=>u.sessionKey.length));process.stdout.write(`${me("SESSION",a)} ${me("MSGS",5)} ${me("TURNS",5)} ${me("PHASE",8)} LAST
|
|
362
|
+
`);for(let u of o){let i=u.runs===void 0?"":` (${u.runs} run${u.runs===1?"":"s"})`;process.stdout.write(`${me(u.sessionKey,a)} ${me(String(u.messages),5)} ${me(String(u.turns),5)} ${me(u.phase??"-",8)} ${qe(u.lastActivityAt,Date.now())}${i}
|
|
363
|
+
`)}}async function Ma(r,o,a){let u=await r.store.messages.page(r.id,o,{limit:a});if(u.messages.length===0){process.stdout.write(`no messages in ${o}
|
|
360
364
|
`);return}for(let i of[...u.messages].reverse())process.stdout.write(`${i.role}: ${i.content}
|
|
361
365
|
`);if(u.nextBefore!==void 0)process.stdout.write(`
|
|
362
366
|
… older messages exist; raise --limit
|
|
363
|
-
`)}async function
|
|
364
|
-
`);return}process.stdout.write(`${
|
|
365
|
-
`);for(let i of u)if(process.stdout.write(`${
|
|
367
|
+
`)}async function Ka(r,o,a){let u=await r.turns(o,a);if(u.length===0){process.stdout.write(`no turns in ${o}
|
|
368
|
+
`);return}process.stdout.write(`${me("TURN",22)} ${me("STATUS",9)} ${me("STEPS",5)} ${me("TOKENS",13)} ${me("MS",6)} SOURCE
|
|
369
|
+
`);for(let i of u)if(process.stdout.write(`${me(i.turnId,22)} ${me(i.status,9)} ${me(String(i.steps),5)} ${me(`${i.promptTokens}/${i.outputTokens}`,13)} ${me(String(i.durationMs??"-"),6)} ${i.source}
|
|
366
370
|
`),i.errorCode!==void 0){if(process.stdout.write(` ${i.errorCode}: ${i.errorMessage}
|
|
367
371
|
`),i.errorHint!==void 0)process.stdout.write(` hint: ${i.errorHint}
|
|
368
|
-
`)}}async function
|
|
372
|
+
`)}}async function uo(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath])});b(()=>o.stop("cli-exit"));let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");let u=r.limit??Cn;if(r.clear===!0){if(r.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let f=await a.store.messages.count(a.id,r.sessionKey);return await a.clearSession(r.sessionKey),process.stdout.write(`cleared ${r.sessionKey}: ${f} message(s) removed, memory files untouched
|
|
369
373
|
`),n}if(r.json===!0){let f=r.sessionKey===void 0?{store:o.store.location,sessions:await a.sessions()}:{store:o.store.location,session:await a.store.sessions.get(a.id,r.sessionKey),messages:(await a.store.messages.page(a.id,r.sessionKey,{limit:u})).messages,turns:await a.turns(r.sessionKey,u)};return process.stdout.write(`${JSON.stringify(f,null,2)}
|
|
370
374
|
`),n}if(process.stdout.write(`store: ${o.store.location}
|
|
371
375
|
|
|
372
|
-
`),r.sessionKey===void 0)return
|
|
376
|
+
`),r.sessionKey===void 0)return ja(await a.sessions()),n;if(await a.store.sessions.get(a.id,r.sessionKey)===void 0)return process.stderr.write(`no session "${r.sessionKey}" for agent ${a.id}
|
|
373
377
|
hint: run \`sessions ${r.manifestPath}\` to list the keys that exist
|
|
374
|
-
`),s;if(r.turns===!0)await
|
|
378
|
+
`),s;if(r.turns===!0)await Ka(a,r.sessionKey,u);else await Ma(a,r.sessionKey,u);return n}import{existsSync as Ua,readFileSync as Da,writeFileSync as Ha}from"node:fs";import{basename as Ba,dirname as Wa,join as Ga}from"node:path";var qa=/^(#{1,6})\s+(.*)$/,Va=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Xa=/^[ \t]*<\/rules>[ \t]*$/,Ja=/^\s*(?:```|~~~)/;function fo(r){if(r.action!=="distill")throw new t({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${r.action}".`,hint:"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled."});let o;try{o=Da(r.file,"utf8")}catch{throw new t({code:"cli_soul_file_missing",message:`${r.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let a=Ba(r.file),u=r.out??Ga(Wa(r.file),`${a.replace(/\.md$/i,"")}.compact.md`);if(Ua(u))throw new t({code:"cli_soul_out_exists",message:`${u} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:i}=fn(a,o),f=za(a,i);return Ha(u,f,"utf8"),process.stdout.write(`wrote ${u}
|
|
375
379
|
|
|
376
380
|
The scaffold copies ${a}'s headings and its <rules> blocks verbatim, and leaves a
|
|
377
381
|
{{PLACEHOLDER}} under each heading. Now:
|
|
378
382
|
`+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
|
|
379
383
|
`+` document's own voice. The workspace command warns until none are left.
|
|
380
384
|
2. Name the file in context.soul.distilled.
|
|
381
|
-
`),n}function
|
|
382
|
-
`)){if(
|
|
385
|
+
`),n}function za(r,o){let a=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${r}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],u=!1,i=!1,f=0,h=!1;for(let g of o.split(`
|
|
386
|
+
`)){if(Ja.test(g)){if(u=!u,i)a.push(g);continue}if(u){if(i)a.push(g);continue}if(Va.test(g)){i=!0,a.push(g);continue}if(i){if(a.push(g),Xa.test(g))i=!1,a.push("");continue}if(qa.exec(g)!==null)h=!0,f+=1,a.push(g),a.push(""),a.push(`{{SECTION_${f}}}`),a.push("")}if(!h)a.push("{{ESSENCE}}"),a.push("");return`${a.join(`
|
|
383
387
|
`).replace(/\n{3,}/g,`
|
|
384
388
|
|
|
385
389
|
`).trimEnd()}
|
|
386
|
-
`}var
|
|
390
|
+
`}var Ya=["list","add","remove","update","search"],Qa=12;async function mo(r){try{switch(r.action){case"list":return Za(r);case"add":return ed(r);case"remove":return td(r);case"update":return await rd(r);case"search":return await sd(r);default:throw new t({code:"sources_action_unknown",message:`${r.action} is not a sources action`,hint:`One of: ${Ya.join(", ")}.`})}}catch(o){if(o instanceof t)return process.stdout.write(`${o.message}
|
|
387
391
|
|
|
388
392
|
${o.hint}
|
|
389
|
-
`),s;throw o}}function
|
|
393
|
+
`),s;throw o}}function Za(r){let a=G(r.env).map((u)=>{let i=Mn(u.name,r.env);return{...u,cached:ce(u.name,r.env),commit:i.commit,fetchedAt:i.fetchedAt,skills:i.skills}});if(r.json===!0)return process.stdout.write(`${JSON.stringify({registry:Ht(r.env),sources:a},null,2)}
|
|
390
394
|
`),n;if(a.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
|
|
391
395
|
|
|
392
|
-
\`sources add <name> <url>\` to add one, or \`sources add ${
|
|
393
|
-
`),n;process.stdout.write(
|
|
396
|
+
\`sources add <name> <url>\` to add one, or \`sources add ${et[0]?.name??"anthropic"} ${et[0]?.url??""}\` to put a built-in back.
|
|
397
|
+
`),n;process.stdout.write(p("sources",!0));for(let u of a)process.stdout.write(`
|
|
394
398
|
${d(`${u.name}${u.builtin===!0?" (built-in)":""}`)}
|
|
395
399
|
`),process.stdout.write(c(l([{label:"url",value:u.url},...u.path===void 0?[]:[{label:"path",value:u.path}],...u.ref===void 0?[]:[{label:"branch",value:u.ref}],{label:"cached",value:u.cached?`${u.skills??"?"} skills at ${u.commit??"?"}, fetched ${u.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
|
|
396
|
-
${
|
|
397
|
-
${c(
|
|
398
|
-
`),n}function
|
|
400
|
+
${p("registry")}
|
|
401
|
+
${c(Ht(r.env))}
|
|
402
|
+
`),n}function ed(r){let[o,a]=r.rest;if(o===void 0)throw new t({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let u=a!==void 0,i=u?a:o,f=Wr(i),h=u?o:nd(f.url);if(!hr(h))throw new t({code:"sources_name_invalid",message:`${JSON.stringify(h)} is not usable as a source name`,hint:"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`."});let g=G(r.env).find((S)=>S.name===h);if(g!==void 0&&!u)throw new t({code:"sources_name_taken",message:`${h} is already a source, pointing at ${g.url}`,hint:`Give this one its own name: \`sources add <name> ${i}\`.`});let v=r.path??f.path,k=r.ref??f.ref,y={name:h,url:f.url,...v===void 0?{}:{path:v},...k===void 0?{}:{ref:k}};if(Kr(y,r.env),r.json===!0)return process.stdout.write(`${JSON.stringify({added:y},null,2)}
|
|
399
403
|
`),n;return process.stdout.write(`${l([{label:g===void 0?"added":"replaced",value:h},{label:"url",value:y.url},...y.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:y.path}],...y.ref===void 0?[]:[{label:"branch",value:y.ref}]])}
|
|
400
|
-
`),process.stdout.write(`${
|
|
404
|
+
`),process.stdout.write(`${p("next")}
|
|
401
405
|
${d(`sources update ${h}`)}
|
|
402
406
|
${d("sources search <what you need>")}
|
|
403
|
-
`),n}function
|
|
407
|
+
`),n}function nd(r){let o=r.replace(/\.git$/,"").split(/[:/]/).filter((u)=>u.length>0);return(o[o.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function td(r){let o=r.rest[0];if(o===void 0)throw new t({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let a=G(r.env).map((i)=>i.name);if(!Hr(o,r.env)){let i=E(o,a);throw new t({code:"sources_unknown",message:`no source called ${o}`,hint:i===void 0?`Configured: ${a.join(", ")||"none"}.`:`Did you mean ${i}?`})}let u=et.some((i)=>i.name===o);return process.stdout.write(`removed ${o}${u?" — a built-in, so it stays out until `sources add` puts it back":""}
|
|
404
408
|
`),process.stdout.write(`
|
|
405
409
|
The cached copy is left on disk; nothing already installed into an agent is touched.
|
|
406
|
-
`),n}async function
|
|
410
|
+
`),n}async function rd(r){let o=G(r.env),a=r.rest.length===0?o:r.rest.map((f)=>{let h=o.find((g)=>g.name===f);if(h===void 0){let g=E(f,o.map((v)=>v.name));throw new t({code:"sources_unknown",message:`no source called ${f}`,hint:g===void 0?`Configured: ${o.map((v)=>v.name).join(", ")||"none"}.`:`Did you mean ${g}?`})}return h});if(a.length===0)return process.stdout.write(`no sources configured
|
|
407
411
|
|
|
408
412
|
\`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
|
|
413
|
+
`),n;let u=[],i=[];for(let f of a){if(r.json!==!0)process.stdout.write(`fetching ${f.name} … `);try{let h=await tt(f,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}});if(u.push({name:f.name,commit:h.commit,skills:h.skills}),r.json!==!0)process.stdout.write(`${h.skills} skills at ${h.commit}${h.unfiltered&&f.path!==void 0?" (full clone — the server refused a partial one)":""}
|
|
410
414
|
`)}catch(h){let g=h instanceof Error?h.message:String(h);if(i.push({name:f.name,reason:g}),r.json!==!0)process.stdout.write(`failed
|
|
411
415
|
`);if(r.json!==!0&&h instanceof t)process.stdout.write(`${c(h.message)}
|
|
412
416
|
${c(h.hint,4)}
|
|
413
417
|
`)}}if(r.json===!0)process.stdout.write(`${JSON.stringify({updated:u,failed:i},null,2)}
|
|
414
|
-
`);return u.length===0?s:n}async function
|
|
418
|
+
`);return u.length===0?s:n}async function sd(r){let o=r.rest.join(" ").trim(),a=G(r.env);if(a.length===0)return process.stdout.write(`no sources configured
|
|
415
419
|
|
|
416
420
|
\`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
|
|
421
|
+
`),s;let u=a.filter((g)=>!ce(g.name,r.env));for(let g of u){if(r.json!==!0)process.stdout.write(`fetching ${g.name} for the first time … `);try{let v=await tt(g,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}});if(r.json!==!0)process.stdout.write(`${v.skills} skills
|
|
418
422
|
`)}catch(v){if(r.json!==!0){if(process.stdout.write(`failed
|
|
419
423
|
`),v instanceof t)process.stdout.write(`${c(v.message)}
|
|
420
|
-
`)}}}let i=a.flatMap((g)=>
|
|
424
|
+
`)}}}let i=a.flatMap((g)=>ke(g,r.env));if(i.length===0)return process.stdout.write(`
|
|
421
425
|
nothing to search — no source has been fetched successfully
|
|
422
426
|
|
|
423
427
|
\`sources update\` reports why.
|
|
424
|
-
`),s;let f=o.length===0?i:
|
|
428
|
+
`),s;let f=o.length===0?i:od(o,i);if(f.length===0)return process.stdout.write(`
|
|
425
429
|
nothing in ${i.length} skills across ${a.length} sources matches ${JSON.stringify(o)}
|
|
426
430
|
|
|
427
431
|
Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
|
|
428
432
|
`),n;if(r.json===!0)return process.stdout.write(`${JSON.stringify({query:o,searched:i.length,results:f.map((g)=>({source:g.source,skill:g.skill,description:g.description,tokens:g.tokens,scripts:g.scripts.length,repoPath:g.repoPath,...g.problem===void 0?{}:{problem:g.problem}}))},null,2)}
|
|
429
|
-
`),n;let h=f.slice(0,
|
|
430
|
-
${
|
|
433
|
+
`),n;let h=f.slice(0,Qa);process.stdout.write(`
|
|
434
|
+
${p(o.length===0?`${i.length} skills`:`${f.length} of ${i.length} skills match ${JSON.stringify(o)}`,!0)}
|
|
431
435
|
`);for(let g of h){process.stdout.write(`${d(`${g.source}/${g.skill}`)} ${g.tokens} tokens${g.scripts.length===0?"":`, ${g.scripts.length} runnable file${g.scripts.length===1?"":"s"}`}${g.problem===void 0?"":" — will not load"}
|
|
432
436
|
`);let v=g.problem??g.description;process.stdout.write(`${c(v.length>160?`${v.slice(0,157)}…`:v,4)}
|
|
433
437
|
`)}if(f.length>h.length)process.stdout.write(`
|
|
434
438
|
${c(`… and ${f.length-h.length} more; narrow the query or use --json`)}
|
|
435
439
|
`);return process.stdout.write(`
|
|
436
|
-
${
|
|
440
|
+
${p("install")}
|
|
437
441
|
${c(`skills install <agent> ${h[0]?.source}/${h[0]?.skill}`)}
|
|
438
|
-
`),n}function
|
|
442
|
+
`),n}function od(r,o){let a=new Map,u=o.map((i)=>{let f=`${i.source}/${i.skill}`;return a.set(f,i),{name:f,dir:i.dir,tokens:i.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:f,description:i.description,metadata:{}}}});return wt(r,u).filter((i)=>i.score>0).map((i)=>a.get(i.skill.name)).filter((i)=>i!==void 0)}async function po(r){let o=id(r.manifestPath),a=await Br(o,r.store),u=[];if(a?.enabled===!0)u.push("was already switched on");await Pn(o,!0,void 0,r.store);let i=await Pe(r.store),f=!1;if(i===void 0)u.push("nothing is serving yet — it will be hosted at the next start");else if(i.baseUrl===void 0)u.push(`pid ${i.pid} is a ${i.mode} session, which serves no HTTP to adopt into`);else{let h=await Qe(i,`/v1/agents/${encodeURIComponent(o)}/start`,{},r.manifestPath);if(h.ok)f=!0,u.push(`adopted by pid ${i.pid}, live now`);else if(h.status===501)u.push(`pid ${i.pid} cannot look up manifests — restart it to pick this up`);else if(h.status===401)u.push(`pid ${i.pid} refused the request — set ${e.envPrefix}API_TOKEN to the server's token`);else u.push(`pid ${i.pid} could not adopt it${h.detail===void 0?"":`: ${h.detail}`}`)}if(r.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:o,enabled:!0,running:f,...i===void 0?{}:{pid:i.pid,mode:i.mode},note:u.join(" · ")}]},null,2)}
|
|
439
443
|
`);else if(process.stdout.write(`${l([{label:o,value:f?"running":"switched on",note:u.join(" · ")}])}
|
|
440
444
|
`),!f&&i!==void 0&&i.baseUrl!==void 0)process.stdout.write(`
|
|
441
445
|
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
|
|
443
|
-
`),i===void 0?s:n;if(process.stdout.write(`${
|
|
446
|
+
`);return i!==void 0&&i.baseUrl!==void 0&&!f?s:n}function id(r){let o=T(r);if(o.id===void 0||o.id==="")throw new t({code:"cli_start_agent_id_missing",message:`${r} declares no id, so there is nothing to switch on.`,hint:"Add `id: <name>` to the manifest. The id is what the switch, the sessions and the API paths are all keyed by."});return o.id}import{copyFileSync as ad,existsSync as dd,mkdirSync as ld,readFileSync as cd,writeFileSync as ud}from"node:fs";import{dirname as fd,join as ho}from"node:path";async function go(r){let o=r.env??m([]),a=r.home??o.HOME??"",u=Rn(o),i=In(u);if(r.json===!0)return process.stdout.write(`${JSON.stringify({terminal:u,how:i?.how??"unknown",configPath:i?.configPath===void 0?void 0:ho(a,i.configPath),line:i?.line,steps:i?.steps},null,2)}
|
|
447
|
+
`),i===void 0?s:n;if(process.stdout.write(`${p("shift+enter",!0)}
|
|
444
448
|
${c("⌥ or ⇧ ⏎ already puts a new line in a message, everywhere, with no setup. This command is for shift+⏎, which a terminal can only send once it has been given a key binding.")}
|
|
445
449
|
`),i===void 0)return process.stdout.write(`
|
|
446
|
-
${
|
|
450
|
+
${p("this terminal was not recognised")}
|
|
447
451
|
${c(`TERM_PROGRAM=${o.TERM_PROGRAM??"(unset)"} TERM=${o.TERM??"(unset)"}`)}
|
|
448
|
-
${c(`known: ${
|
|
452
|
+
${c(`known: ${os().map((f)=>f.name).join(", ")}`)}
|
|
449
453
|
${d("⌥⏎ works here regardless — nothing needs configuring for it")}
|
|
450
454
|
`),s;if(process.stdout.write(`
|
|
451
|
-
${
|
|
455
|
+
${p(i.name)}
|
|
452
456
|
`),i.how!=="write"){process.stdout.write(`${c(i.how==="unverified"?`no verified recipe for this one — ${i.reason??"nobody has checked it"}`:`this one has to be done by hand — ${i.reason??"its settings are not a text file"}`)}
|
|
453
457
|
|
|
454
458
|
`);for(let[f,h]of(i.steps??[]).entries())process.stdout.write(`${c(`${f+1}. ${h}`)}
|
|
@@ -456,54 +460,54 @@ ${m(i.name)}
|
|
|
456
460
|
${d("⌥⏎ works here today — nothing has to be configured for it")}
|
|
457
461
|
`:`
|
|
458
462
|
${d("then restart the terminal and press shift+⏎ in a session to check it")}
|
|
459
|
-
`),n}return await
|
|
460
|
-
${c(
|
|
461
|
-
`),n;let i=
|
|
462
|
-
${c(
|
|
463
|
+
`),n}return await md(i,{...r,env:o,home:a})}async function md(r,o){let a=ho(o.home,r.configPath??""),u=dd(a)?cd(a,"utf8"):"";if(is(u,r))return process.stdout.write(`${c("already configured — a binding for shift+enter is present")}
|
|
464
|
+
${c(vt(a,o.home),4)}
|
|
465
|
+
`),n;let i=as(u,r);if(i===void 0)return process.stdout.write(`${c("this file is not in a shape this command can edit safely:")}
|
|
466
|
+
${c(vt(a,o.home),4)}
|
|
463
467
|
${d("add the line below by hand:")}
|
|
464
468
|
${c(r.line??"",4)}
|
|
465
|
-
`),s;if(process.stdout.write(`${l([{label:"file",value:
|
|
469
|
+
`),s;if(process.stdout.write(`${l([{label:"file",value:vt(a,o.home)},{label:"exists",value:u===""?"no — it will be created":"yes"},{label:"add",value:r.line??""}])}
|
|
466
470
|
`),o.dryRun===!0)return process.stdout.write(`
|
|
467
471
|
${d("--dry-run: nothing was written")}
|
|
468
472
|
`),n;if(o.yes!==!0){if(!(o.confirm===void 0?!1:await o.confirm("write this change?")))return process.stdout.write(`
|
|
469
473
|
${d("nothing was written")}
|
|
470
|
-
`),n}try{if(
|
|
474
|
+
`),n}try{if(ld(fd(a),{recursive:!0}),u!=="")ad(a,`${a}.${e.slug}-backup`);ud(a,i,"utf8")}catch(f){return process.stderr.write(`could not write ${a}: ${f instanceof Error?f.message:String(f)}
|
|
471
475
|
`),s}return process.stdout.write(`
|
|
472
|
-
${
|
|
473
|
-
${u===""?"":`${c(`a copy of the old file is at ${
|
|
476
|
+
${p("done")}
|
|
477
|
+
${u===""?"":`${c(`a copy of the old file is at ${vt(`${a}.${e.slug}-backup`,o.home)}`)}
|
|
474
478
|
`}${d("restart the terminal, then press shift+⏎ in a session to check it")}
|
|
475
|
-
`),n}async function
|
|
479
|
+
`),n}async function yo(r){return r.warm===!0?await pd(r):await hd(r)}async function pd(r){let o=x(r.manifestPath,{knownProviders:Y,knownChannels:X,env:m([r.manifestPath])}),a=we(o.manifest.tools).selections,u=o.manifest.tools.pinned;if(a.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
|
|
476
480
|
`),n;if(u.length===0)return process.stdout.write(`nothing to warm — ${a.map((g)=>g.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
|
|
477
|
-
`),n;let i=[],f=new Set;for(let g of a){let v=
|
|
481
|
+
`),n;let i=[],f=new Set;for(let g of a){let v=A[g.id];if(v===void 0)return s;let k=v({dir:o.dir,env:o.env,config:g.config,agentId:o.manifest.id});if(k.refresh===void 0){for(let S of await k.resolve(u))f.add(S.spec.slug);if(r.json!==!0)process.stdout.write(`${g.id}: nothing to warm — it resolves without a cache.
|
|
478
482
|
`);continue}let y=await k.refresh(u);for(let S of u)if(!y.missing.includes(S))f.add(S);i.push({provider:g.id,fetched:y.fetched,changed:[...y.changed],missing:[...y.missing],cachePath:"cachePath"in y&&typeof y.cachePath==="string"?y.cachePath:""})}if(r.json===!0)process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
479
483
|
`);else for(let g of i){if(process.stdout.write(`${g.fetched} of ${u.length} pinned tools fetched from ${g.provider}
|
|
480
484
|
`),g.changed.length>0)process.stdout.write(` changed: ${g.changed.join(", ")}
|
|
481
485
|
`);if(g.cachePath!=="")process.stdout.write(` cache: ${g.cachePath}
|
|
482
486
|
`)}let h=u.filter((g)=>!f.has(g));for(let g of h)process.stdout.write(` missing: ${g} — no configured provider has a tool with that slug
|
|
483
|
-
`);return h.length>0?s:n}async function
|
|
484
|
-
`:`${
|
|
485
|
-
`),n}finally{await o.stop("cli-exit")}}import{dirname as
|
|
486
|
-
`),n;let
|
|
487
|
+
`);return h.length>0?s:n}async function hd(r){let o=await L.create({agents:[r.manifestPath],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath])});try{let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");let u=Xn(a);return process.stdout.write(r.json===!0?`${JSON.stringify(u,null,2)}
|
|
488
|
+
`:`${lt(u)}
|
|
489
|
+
`),n}finally{await o.stop("cli-exit")}}import{dirname as wo,isAbsolute as gd,resolve as Bn}from"node:path";async function vo(r){try{let o=T(r.manifestPath),a=await yt({refs:o.plugins??[],agentId:o.id??r.manifestPath,paths:{workspace:wo(Bn(r.manifestPath)),state:wo(Bn(r.manifestPath)),manifest:Bn(r.manifestPath)},env:m([r.manifestPath]),bus:new _e({runtimeId:"validate"}),builtIn:C,base:{toolProviders:A,channels:N}}),u=x(r.manifestPath,{knownProviders:Object.keys(a.toolProviders),knownChannels:Object.keys(a.channels),env:m([r.manifestPath])}),{manifest:i}=u,f=H(i.model.main.id,i.model.main.capabilities),{workspace:h,warnings:g}=We(u,f.promptStyle);yn(u,{channels:a.channels});let v=Ie(h,i.context.rules);if(v!==void 0&&i.context.rules.onExceed==="fail")throw v;let k=[...g,...mn(i),...v===void 0?[]:[v.toDetail()]],y=i.knowledge===void 0?void 0:gn({dir:gd(i.knowledge.dir)?i.knowledge.dir:Bn(u.dir,i.knowledge.dir),maxActive:i.knowledge.maxActive,budget:i.knowledge.budget,style:f.promptStyle}),S=["static","volatile","reminder"].map((I)=>{let de=h.files.filter((oe)=>oe.tier===I).map((oe)=>oe.name);if(de.length===0)return;return`${I}=${de.join(",")} (${h.tokens[I]}/${i.context.budgets[I]})`}).filter((I)=>I!==void 0).join(" ");if(r.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:u.path,id:i.id,model:i.model.main.id,window:u.window,capabilities:f,workspace:{files:h.files.map((I)=>({name:I.name,tier:I.tier,editable:I.editable,tokens:I.tokens,budget:I.budget})),tokens:h.tokens},knowledge:y===void 0?[]:y.entries.map((I)=>({name:I.name,keywords:I.keywords,tokens:I.tokens})),warnings:k},null,2)}
|
|
490
|
+
`),n;let P=ye(i),U=P.map((I)=>I.role===I.configuredAs?`${I.role}=${I.modelId}`:`${I.role}=→main`).join(" "),W=P.filter((I)=>I.role===I.configuredAs),F=$o({manifestPath:r.manifestPath,rawModelId:o.modelId,apiKeyEnv:i.model.main.apiKeyEnv}).flatMap((I)=>{let de=_o(I.origin);return de===void 0?[]:[` env ${I.variable} — ${de}
|
|
487
491
|
`]}).join("");return process.stdout.write(`ok ${u.path}
|
|
488
492
|
id ${i.id}${i.name===void 0?"":` (${i.name})`}
|
|
489
|
-
models ${
|
|
490
|
-
`+
|
|
491
|
-
`+(
|
|
493
|
+
models ${U}
|
|
494
|
+
`+F+` window ${u.window} ${je(P[0]?.window)} (reserveOutput ${i.context.reserveOutput}, maxOutput ${f.maxOutput})
|
|
495
|
+
`+(W.length<2?"":`${W.slice(1).map((I)=>` ${I.role.padEnd(12)} ${I.modelId} · window ${I.window.contextWindow} ${je(I.window)}
|
|
492
496
|
`).join("")}`)+` capabilities thinking=${f.thinking} promptCache=${f.promptCache} nativeTools=${f.nativeTools} strictSchema=${f.strictSchema}
|
|
493
|
-
`+
|
|
497
|
+
`+yd(f.promptCache,i.model.main.id)+` dialect ${i.tools.dialect}
|
|
494
498
|
workspace ${S===""?"(none)":S}
|
|
495
499
|
`+(y===void 0?"":` knowledge ${y.entries.length} entries, maxActive=${y.maxActive}, budget=${y.budget}
|
|
496
500
|
`)+` memory ${i.memory===void 0?"none — nothing is retrieved across sessions":`${i.memory.retriever} at ${i.memory.dir}, maxActive=${i.memory.maxActive}, threshold=${i.memory.threshold}, budget=${i.memory.budget}, history=${i.memory.includeHistory}`}
|
|
497
|
-
schedules ${i.schedules.length===0?"none":i.schedules.map((
|
|
498
|
-
team ${i.team===void 0?"none — no delegation; `handoff` is not registered":`${i.team.members.map((
|
|
501
|
+
schedules ${i.schedules.length===0?"none":i.schedules.map((I)=>`${I.id} (${I.kind} ${I.expr}${I.timezone===void 0?"":` ${I.timezone}`}${I.role===void 0?"":` role=${I.role}`}${I.enabled?"":", disabled"})`).join(" ")}
|
|
502
|
+
team ${i.team===void 0?"none — no delegation; `handoff` is not registered":`${i.team.members.map((I)=>`${I.id} (${I.manifest})`).join(" ")} — run one at a time`}
|
|
499
503
|
limits maxSteps=${i.limits.maxSteps} turnTimeoutMs=${i.limits.turnTimeoutMs}
|
|
500
|
-
`+k.map((
|
|
504
|
+
`+k.map((I)=>` warning ${I.message}
|
|
501
505
|
`).join("")),n}catch(o){if(r.json===!0&&o instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:o.toDetail(),details:o.details},null,2)}
|
|
502
|
-
`),s;throw o}}function
|
|
506
|
+
`),s;throw o}}function yd(r,o){if(r!=="none")return"";return/(^|\/)claude-/i.test(o)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
|
|
503
507
|
`+` caching at all, so no request field reaches it. Caching lives on the native
|
|
504
508
|
Messages API, which this runtime does not speak.
|
|
505
509
|
`:` promptCache none — this runtime sends no cache directives. Many endpoints cache
|
|
506
|
-
`+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function
|
|
510
|
+
`+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function xo(r){try{let o=x(r.manifestPath,{knownProviders:Y,knownChannels:X,env:m([r.manifestPath])}),{manifest:a}=o,u=H(a.model.main.id,a.model.main.capabilities),{workspace:i,warnings:f}=We(o,u.promptStyle),h=[...f,...Ir(i.files.map((k)=>({name:k.name,authored:k.authored,tier:k.tier,field:k.field})))],g=Ie(i,a.context.rules);if(g!==void 0)h.push(g.toDetail());if(r.json===!0)return process.stdout.write(`${JSON.stringify({ok:h.length===0,path:o.path,promptStyle:u.promptStyle,files:i.files.map((k)=>({name:k.name,tier:k.tier,editable:k.editable,tokens:k.tokens,budget:k.budget})),tokens:i.tokens,findings:h},null,2)}
|
|
507
511
|
`),r.strict===!0&&h.length>0?s:n;let v=u.promptStyle;process.stdout.write(`${o.path}
|
|
508
512
|
rendering delimiters=${v.delimiters} intensity=${v.intensity} examplesIn=${v.examplesIn}
|
|
509
513
|
total ${i.tokens.total} tokens (static ${i.tokens.static}, volatile ${i.tokens.volatile}, reminder ${i.tokens.reminder})
|
|
@@ -516,12 +520,12 @@ no findings
|
|
|
516
520
|
`);return process.stdout.write(`
|
|
517
521
|
${h.length} finding(s)
|
|
518
522
|
`),r.strict===!0?s:n}catch(o){if(r.json===!0&&o instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:o.toDetail(),details:o.details},null,2)}
|
|
519
|
-
`),s;throw o}}function
|
|
523
|
+
`),s;throw o}}function wd(r){if(r instanceof t)process.stderr.write(`${r.format()}
|
|
520
524
|
`);else if(r instanceof Error){if(process.stderr.write(`${r.message}
|
|
521
|
-
`),
|
|
525
|
+
`),Ee().debug&&r.stack!==void 0)process.stderr.write(`${r.stack}
|
|
522
526
|
`)}else process.stderr.write(`${String(r)}
|
|
523
|
-
`);return s}async function
|
|
524
|
-
`),n;case"help":return process.stdout.write(
|
|
527
|
+
`);return s}async function bd(){let r=process.stdout.write.bind(process.stdout);process.stdout.write=()=>!0;try{let o=await Ze({action:"install"});if(o!==n)return{kind:"failed",message:`daemon install exited ${o}`,hint:`Run \`${e.slug} daemon install\` to see what it said.`};return{kind:"started",label:`${e.slug}.server`}}finally{process.stdout.write=r}}async function vd(r){let o=jr(r);switch(o.kind){case"version":return process.stdout.write(`${R}
|
|
528
|
+
`),n;case"help":return process.stdout.write(It(o.command)),n;case"usage":return process.stdout.write(It()),s;case"command":break}let{command:a,positionals:u,flags:i}=o.parsed,f=u[0],h=()=>te(f),g=a.flags.some((y)=>y.name==="store")?i.str("store"):void 0,v=await ls({needsServer:a.needsServer,disabled:i.bool("no-bootstrap"),install:()=>bd(),...g===void 0?{}:{store:g}}),k=cs(v);if(k!==void 0)process.stderr.write(k);switch(a.name){case"init":{let y=i.str("dir"),S=i.str("user"),P=i.str("name"),U=i.str("purpose"),W=i.str("preset"),F=i.str("model"),I=i.str("base-url"),de=i.str("api-key-env"),oe=i.str("system"),ge=i.str("web"),z=i.str("web-backend"),V=i.str("composio"),Q=i.str("telegram"),re=i.str("telegram-allow"),he=i.str("server"),fe=i.str("schedules"),Ae=i.str("skills"),D=i.str("daemon");return await ts({...y===void 0?{}:{dir:y},...S===void 0?{}:{user:S},...P===void 0?{}:{name:P},...U===void 0?{}:{purpose:U},...W===void 0?{}:{preset:W},...F===void 0?{}:{model:F},...I===void 0?{}:{baseUrl:I},...de===void 0?{}:{apiKeyEnv:de},...oe===void 0?{}:{system:oe},...ge===void 0?{}:{web:ge},...z===void 0?{}:{webBackend:z},...V===void 0?{}:{composio:V},...Q===void 0?{}:{telegram:Q},...fe===void 0?{}:{schedules:fe},...re===void 0?{}:{telegramAllow:re},...he===void 0?{}:{server:he},...Ae===void 0?{}:{skills:Ae},...D===void 0?{}:{daemon:D},yes:i.bool("yes"),plain:i.bool("plain")})}case"run":{let y=i.str("session"),S=i.str("input"),P=i.str("store");return await Ut({...u[0]===void 0?{}:{manifestPath:h()},...y===void 0?{}:{sessionKey:y},continueSession:i.bool("continue"),...S===void 0?{}:{once:S},...P===void 0?{}:{store:P},ephemeral:i.bool("ephemeral"),quiet:i.bool("quiet"),showReasoning:i.bool("show-reasoning"),noReasoning:i.bool("no-reasoning"),...i.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:i.bool("plain")})}case"schedules":{let y=i.str("store"),S=i.str("id"),P=i.str("enable"),U=i.str("disable");return await io({manifestPath:h(),...y===void 0?{}:{store:y},...S===void 0?{}:{id:S},...P===void 0?{}:{enable:P},...U===void 0?{}:{disable:U},recipients:i.bool("recipients"),json:i.bool("json")})}case"sessions":{let y=i.str("session"),S=i.str("store"),P=i.num("limit");return await uo({manifestPath:h(),...y===void 0?{}:{sessionKey:y},...S===void 0?{}:{store:S},...P===void 0?{}:{limit:P},json:i.bool("json"),clear:i.bool("clear"),turns:i.bool("turns")})}case"memory":{let y=i.num("limit"),S=i.str("store");return await ws({action:f,manifestPath:te(u[1]??""),...u[2]===void 0?{}:{query:u[2]},...y===void 0?{}:{limit:y},...S===void 0?{}:{store:S},all:i.bool("all"),json:i.bool("json")})}case"config":{let{configCommand:y,readAction:S}=await import("./config-g7za9x13.js"),P=S(f,u[1]);return await y({action:P.action,...P.ref===void 0?{}:{ref:P.ref},...u[2]===void 0?{}:{name:u[2]},...u[3]===void 0?{}:{value:u[3]},...i.str("channel")===void 0?{}:{channel:i.str("channel")},remove:i.bool("remove"),yes:i.bool("yes"),...i.str("store")===void 0?{}:{store:i.str("store")}})}case"validate":return await vo({manifestPath:h(),json:i.bool("json")});case"workspace":return xo({manifestPath:h(),json:i.bool("json"),strict:i.bool("strict")});case"soul":{let y=i.str("out");return fo({action:f,file:u[1],...y===void 0?{}:{out:y}})}case"skills":{if(u.length===0)return await Gr({plain:i.bool("plain"),json:i.bool("json")});let y=u[2];return Se({action:f,manifestPath:te(u[1]??""),...y===void 0?{}:{name:y},json:i.bool("json"),strict:i.bool("strict")})}case"sources":{let y=i.str("path"),S=i.str("ref");return await mo({action:f,rest:u.slice(1),...y===void 0?{}:{path:y},...S===void 0?{}:{ref:S},json:i.bool("json")})}case"plugins":return await _s({manifestPath:te(u[0]??""),json:i.bool("json")});case"agents":return await Gt({manifestPaths:u.map((y)=>te(y)),json:i.bool("json")});case"serve":{let y=i.num("port"),S=i.str("host"),P=i.str("store");return await co({manifestPaths:u.map((U)=>te(U)),...y===void 0?{}:{port:y},...S===void 0?{}:{host:S},...P===void 0?{}:{store:P},claim:i.bool("claim"),json:i.bool("json")})}case"keys":return await ds({noEnhancedKeys:i.bool("no-enhanced-keys")});case"terminal-setup":return await go({dryRun:i.bool("dry-run"),yes:i.bool("yes"),json:i.bool("json"),confirm:Ye});case"remove":return await Ds({...f===void 0?{}:{ref:f},dryRun:i.bool("dry-run"),filesOnly:i.bool("files-only"),prune:i.bool("prune"),all:i.bool("all"),yes:i.bool("yes"),json:i.bool("json"),...i.str("store")===void 0?{}:{store:i.str("store")},confirm:Pr});case"stop":{let y=i.str("reason");return await Nn({...f===void 0?{}:{manifestPath:h()},dryRun:i.bool("dry-run"),...y===void 0?{}:{reason:y},...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"start":return await po({manifestPath:h(),...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")});case"web":{let{webCommand:y}=await import("./web-vkb16r62.js");return await y({action:f,...u[1]===void 0?{}:{manifestPath:te(u[1])},noOpen:i.bool("no-open"),...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"credential":{let{credentialCommand:y}=await import("./credential-npr6z8c8.js");return await y({action:f??"",...u[1]===void 0?{}:{keyId:u[1]},...i.str("label")===void 0?{}:{label:i.str("label")},...i.str("agents")===void 0?{}:{agents:i.str("agents")},...i.str("sessions")===void 0?{}:{sessions:i.str("sessions")},...i.str("can")===void 0?{}:{can:i.str("can")},...i.str("expires")===void 0?{}:{expires:i.str("expires")},...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"daemon":{let y=i.num("lines");return await Ze({action:f,...u[1]===void 0?{}:{manifestPath:te(u[1])},...y===void 0?{}:{lines:y},follow:i.bool("follow"),truncate:i.bool("truncate"),dryRun:i.bool("dry-run"),...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"model":{let y=i.num("price");return await Os({manifestPath:te(u[1]),window:i.bool("window"),...y===void 0?{}:{price:y},write:i.bool("write"),yes:i.bool("yes"),json:i.bool("json")})}case"tools":return await yo({manifestPath:h(),warm:i.bool("warm"),json:i.bool("json")});default:throw new t({code:"cli_command_unwired",message:`Command "${a.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}hs();Yr();await vd(process.argv.slice(2)).catch(wd).then((r)=>Dn(r));
|
|
525
529
|
|
|
526
|
-
//# debugId=
|
|
530
|
+
//# debugId=92EA07B9DCA0055664756E2164756E21
|
|
527
531
|
//# sourceMappingURL=index.js.map
|