dispach 0.2.3 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -43
- package/dist/APEv2Parser-rt8hyadd.js +5 -0
- package/dist/{AiffParser-9hj6fpmy.js → AiffParser-gvpmtb2e.js} +3 -3
- package/dist/{AiffParser-9hj6fpmy.js.map → AiffParser-gvpmtb2e.js.map} +1 -1
- package/dist/App-18dvbyev.js +11 -0
- package/dist/{App-2f72vhjv.js.map → App-18dvbyev.js.map} +1 -1
- package/dist/AsfParser-h9zyh6cx.js +5 -0
- package/dist/{AsfParser-7emspn04.js.map → AsfParser-h9zyh6cx.js.map} +1 -1
- package/dist/ConfigEditor-444m13ta.js +6 -0
- package/dist/{ConfigEditor-vk7vxaa6.js.map → ConfigEditor-444m13ta.js.map} +1 -1
- package/dist/DsdiffParser-gxqv4gn1.js +5 -0
- package/dist/{DsdiffParser-dz88pnnr.js.map → DsdiffParser-gxqv4gn1.js.map} +1 -1
- package/dist/{DsfParser-qgh63tbs.js → DsfParser-sndt4jbk.js} +3 -3
- package/dist/{DsfParser-qgh63tbs.js.map → DsfParser-sndt4jbk.js.map} +1 -1
- package/dist/FlacParser-rmkpvf9e.js +5 -0
- package/dist/{KeyProbe-5anphmb7.js → KeyProbe-6t531sy6.js} +3 -3
- package/dist/{KeyProbe-5anphmb7.js.map → KeyProbe-6t531sy6.js.map} +1 -1
- package/dist/MP4Parser-87xfsck4.js +5 -0
- package/dist/{MP4Parser-yr7p3z12.js.map → MP4Parser-87xfsck4.js.map} +2 -2
- package/dist/{MatroskaParser-jkbsbsk3.js → MatroskaParser-7krspfgx.js} +3 -3
- package/dist/{MatroskaParser-jkbsbsk3.js.map → MatroskaParser-7krspfgx.js.map} +1 -1
- package/dist/{MpegParser-t93vwnew.js → MpegParser-jcs35q0h.js} +3 -3
- package/dist/{MpegParser-t93vwnew.js.map → MpegParser-jcs35q0h.js.map} +1 -1
- package/dist/MusepackParser-d4zfnzk3.js +5 -0
- package/dist/{MusepackParser-6e8kbh2d.js.map → MusepackParser-d4zfnzk3.js.map} +2 -2
- package/dist/OggParser-fbspjs7v.js +5 -0
- package/dist/{OggParser-ggcypmag.js.map → OggParser-fbspjs7v.js.map} +1 -1
- package/dist/Picker-x6aj42tc.js +5 -0
- package/dist/{Picker-j7txnm7w.js.map → Picker-x6aj42tc.js.map} +1 -1
- package/dist/SessionPicker-pngdv97x.js +5 -0
- package/dist/{SessionPicker-hpv2ncsb.js.map → SessionPicker-pngdv97x.js.map} +1 -1
- package/dist/SkillBrowser-3mnzkakr.js +5 -0
- package/dist/{SkillBrowser-qc542n71.js.map → SkillBrowser-3mnzkakr.js.map} +1 -1
- package/dist/WavPackParser-0x9z4466.js +5 -0
- package/dist/{WavPackParser-jw9stzqp.js.map → WavPackParser-0x9z4466.js.map} +1 -1
- package/dist/WaveParser-31b6qtef.js +5 -0
- package/dist/{WaveParser-epmncs9w.js.map → WaveParser-31b6qtef.js.map} +1 -1
- package/dist/WizardApp-c42wc116.js +5 -0
- package/dist/{WizardApp-pgzcz9zq.js.map → WizardApp-c42wc116.js.map} +1 -1
- package/dist/channels-nf6d8fvx.js +31 -0
- package/dist/{channels-m8nambmm.js.map → channels-nf6d8fvx.js.map} +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +11 -11
- package/dist/client.js.map +4 -4
- package/dist/config-sx40rg8m.js +24 -0
- package/dist/{config-hmgrqgf2.js.map → config-sx40rg8m.js.map} +2 -2
- package/dist/credential-vdbkfk65.js +19 -0
- package/dist/{credential-nkb2ya59.js.map → credential-vdbkfk65.js.map} +1 -1
- package/dist/daemon.d.ts.map +1 -1
- package/dist/{index-51x0n5z0.js → index-0dcpsfet.js} +4 -4
- package/dist/{index-51x0n5z0.js.map → index-0dcpsfet.js.map} +1 -1
- package/dist/{index-yw3fby4n.js → index-1h8s50d9.js} +3 -3
- package/dist/{index-yw3fby4n.js.map → index-1h8s50d9.js.map} +1 -1
- package/dist/index-1hbvhrsj.js +6 -0
- package/dist/{index-dzy19wtf.js.map → index-1hbvhrsj.js.map} +1 -1
- package/dist/index-1hfece7s.js +10 -0
- package/dist/{index-22fzzn7z.js.map → index-1hfece7s.js.map} +2 -2
- package/dist/index-2h566rtg.js +6 -0
- package/dist/{index-jc4kmfwa.js.map → index-2h566rtg.js.map} +1 -1
- package/dist/index-4g4smpkk.js +11 -0
- package/dist/{index-sh44ymqz.js.map → index-4g4smpkk.js.map} +1 -1
- package/dist/index-4gfsf9n8.js +6 -0
- package/dist/{index-8tmv33mr.js.map → index-4gfsf9n8.js.map} +1 -1
- package/dist/{index-dv9pdjy4.js → index-5ptbytze.js} +10 -10
- package/dist/{index-dv9pdjy4.js.map → index-5ptbytze.js.map} +1 -1
- package/dist/index-5s1cq8np.js +8 -0
- package/dist/{index-9t4dz145.js.map → index-5s1cq8np.js.map} +1 -1
- package/dist/{index-2zjh5zd5.js → index-659ggfbf.js} +2 -2
- package/dist/index-6ebppx3t.js +6 -0
- package/dist/{index-1x8mzvz7.js.map → index-6ebppx3t.js.map} +1 -1
- package/dist/index-6pym9p8h.js +9 -0
- package/dist/{index-38gs9anh.js.map → index-6pym9p8h.js.map} +1 -1
- package/dist/index-9ejax6hp.js +6 -0
- package/dist/{index-8edck2pr.js.map → index-9ejax6hp.js.map} +1 -1
- package/dist/{index-zw6wyas6.js → index-9hw9j1qg.js} +4 -4
- package/dist/{index-zw6wyas6.js.map → index-9hw9j1qg.js.map} +1 -1
- package/dist/{index-bqdkm3de.js → index-9xhresrg.js} +4 -4
- package/dist/{index-bqdkm3de.js.map → index-9xhresrg.js.map} +1 -1
- package/dist/{index-hgm2gchq.js → index-abm0zyc0.js} +12 -12
- package/dist/{index-hgm2gchq.js.map → index-abm0zyc0.js.map} +1 -1
- package/dist/index-ar5c9d2f.js +7 -0
- package/dist/{index-3826kf9t.js.map → index-ar5c9d2f.js.map} +1 -1
- package/dist/index-bhj4pmrx.js +74 -0
- package/dist/index-bhj4pmrx.js.map +13 -0
- package/dist/index-brt17yfr.js +6 -0
- package/dist/{index-hrwakb11.js.map → index-brt17yfr.js.map} +2 -2
- package/dist/index-bysnsdkd.js +6 -0
- package/dist/{index-nxhqf597.js.map → index-bysnsdkd.js.map} +1 -1
- package/dist/index-c74wx9pv.js +6 -0
- package/dist/{index-323jvr1g.js.map → index-c74wx9pv.js.map} +1 -1
- package/dist/index-cm3g4t3r.js +14 -0
- package/dist/{index-y7dxq4a4.js.map → index-cm3g4t3r.js.map} +2 -2
- package/dist/index-dzp6mc5h.js +6 -0
- package/dist/{index-42e29zs4.js.map → index-dzp6mc5h.js.map} +1 -1
- package/dist/index-fad09b8c.js +6 -0
- package/dist/{index-836hc2h1.js.map → index-fad09b8c.js.map} +2 -2
- package/dist/{index-0444sh6x.js → index-fvb2dxzn.js} +4 -4
- package/dist/{index-0444sh6x.js.map → index-fvb2dxzn.js.map} +1 -1
- package/dist/{index-2bsardvh.js → index-gpq4agva.js} +3 -3
- package/dist/{index-2bsardvh.js.map → index-gpq4agva.js.map} +1 -1
- package/dist/{index-qgsdgbk8.js → index-hcpvk5de.js} +3 -3
- package/dist/{index-qgsdgbk8.js.map → index-hcpvk5de.js.map} +1 -1
- package/dist/{index-pqw1n1pv.js → index-jv5t63tp.js} +4 -4
- package/dist/{index-pqw1n1pv.js.map → index-jv5t63tp.js.map} +1 -1
- package/dist/index-kyz4t0j0.js +126 -0
- package/dist/{index-ry6a4bqh.js.map → index-kyz4t0j0.js.map} +2 -2
- package/dist/{index-ytxbw8py.js → index-m6r2sxcw.js} +33 -33
- package/dist/{index-ytxbw8py.js.map → index-m6r2sxcw.js.map} +1 -1
- package/dist/{index-snz49ndn.js → index-mhw3d7af.js} +3 -3
- package/dist/{index-snz49ndn.js.map → index-mhw3d7af.js.map} +1 -1
- package/dist/{index-1mbdz3f7.js → index-mk7hrzq7.js} +9 -9
- package/dist/{index-1mbdz3f7.js.map → index-mk7hrzq7.js.map} +1 -1
- package/dist/index-n0hqgwad.js +6 -0
- package/dist/{index-xg7s813b.js.map → index-n0hqgwad.js.map} +2 -2
- package/dist/index-ncb840sk.js +6 -0
- package/dist/{index-mjfv7k5w.js.map → index-ncb840sk.js.map} +1 -1
- package/dist/{index-fbsrhcga.js → index-ntczmwnf.js} +4 -4
- package/dist/{index-fbsrhcga.js.map → index-ntczmwnf.js.map} +1 -1
- package/dist/{index-095hrkyr.js → index-p5gy5s7p.js} +4 -4
- package/dist/{index-095hrkyr.js.map → index-p5gy5s7p.js.map} +1 -1
- package/dist/{index-3c5jt6by.js → index-p86w0qjw.js} +3 -3
- package/dist/{index-3c5jt6by.js.map → index-p86w0qjw.js.map} +1 -1
- package/dist/index-qhh30m9p.js +6 -0
- package/dist/{index-nvc24414.js.map → index-qhh30m9p.js.map} +1 -1
- package/dist/{index-p6ya59m6.js → index-rerdsr3d.js} +4 -4
- package/dist/{index-p6ya59m6.js.map → index-rerdsr3d.js.map} +1 -1
- package/dist/{index-k8e9f466.js → index-s0mfq8t7.js} +19 -19
- package/dist/index-s0mfq8t7.js.map +11 -0
- package/dist/{index-3vzf253k.js → index-s9ybp2r1.js} +7 -7
- package/dist/{index-3vzf253k.js.map → index-s9ybp2r1.js.map} +1 -1
- package/dist/index-ss77hvwy.js +1246 -0
- package/dist/{index-hpvfqq6r.js.map → index-ss77hvwy.js.map} +32 -31
- package/dist/{index-jff5q27j.js → index-t9bnt6a1.js} +4 -4
- package/dist/{index-jff5q27j.js.map → index-t9bnt6a1.js.map} +1 -1
- package/dist/index-w2ss9hn5.js +9 -0
- package/dist/{index-eztfverw.js.map → index-w2ss9hn5.js.map} +1 -1
- package/dist/{index-pszmnhgq.js → index-w80shmpv.js} +9 -9
- package/dist/{index-pszmnhgq.js.map → index-w80shmpv.js.map} +1 -1
- package/dist/index-w8e8qxd4.js +337 -0
- package/dist/index-w8e8qxd4.js.map +21 -0
- package/dist/{index-308y9xt0.js → index-z9r4e0yq.js} +4 -4
- package/dist/{index-308y9xt0.js.map → index-z9r4e0yq.js.map} +1 -1
- package/dist/index-zj87j4j2.js +6 -0
- package/dist/index-zj87j4j2.js.map +10 -0
- package/dist/{index-m6fqx0ch.js → index-zmerx9rc.js} +6 -6
- package/dist/{index-m6fqx0ch.js.map → index-zmerx9rc.js.map} +1 -1
- package/dist/index-zqjtjs7c.js +153 -0
- package/dist/{index-dpcm1j62.js.map → index-zqjtjs7c.js.map} +2 -2
- package/dist/index.js +381 -368
- package/dist/index.js.map +7 -6
- package/dist/lib/launchd.d.ts.map +1 -1
- package/dist/lib/service-env.d.ts.map +1 -1
- package/dist/lib/templates.d.ts.map +1 -1
- package/dist/lib/theme.d.ts.map +1 -1
- package/dist/lib/watchdog.d.ts +20 -0
- package/dist/lib/watchdog.d.ts.map +1 -0
- package/dist/serve.d.ts.map +1 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/sources.d.ts.map +1 -1
- package/dist/web-zvf80ns1.js +14 -0
- package/dist/{web-gfv0mzgs.js.map → web-zvf80ns1.js.map} +1 -1
- package/dist/wire.js +11 -11
- package/dist/wire.js.map +4 -4
- package/dist/wrapper-5zhcdmnk.js +5 -0
- package/package.json +4 -4
- package/dist/APEv2Parser-ysjr6adv.js +0 -5
- package/dist/App-2f72vhjv.js +0 -11
- package/dist/AsfParser-7emspn04.js +0 -5
- package/dist/ConfigEditor-vk7vxaa6.js +0 -6
- package/dist/DsdiffParser-dz88pnnr.js +0 -5
- package/dist/FlacParser-drm5wq0p.js +0 -5
- package/dist/MP4Parser-yr7p3z12.js +0 -5
- package/dist/MusepackParser-6e8kbh2d.js +0 -5
- package/dist/OggParser-ggcypmag.js +0 -5
- package/dist/Picker-j7txnm7w.js +0 -5
- package/dist/SessionPicker-hpv2ncsb.js +0 -5
- package/dist/SkillBrowser-qc542n71.js +0 -5
- package/dist/WavPackParser-jw9stzqp.js +0 -5
- package/dist/WaveParser-epmncs9w.js +0 -5
- package/dist/WizardApp-pgzcz9zq.js +0 -5
- package/dist/channels-m8nambmm.js +0 -31
- package/dist/config-hmgrqgf2.js +0 -24
- package/dist/credential-nkb2ya59.js +0 -19
- package/dist/index-1x8mzvz7.js +0 -6
- package/dist/index-22fzzn7z.js +0 -10
- package/dist/index-323jvr1g.js +0 -6
- package/dist/index-3826kf9t.js +0 -7
- package/dist/index-38gs9anh.js +0 -9
- package/dist/index-42e29zs4.js +0 -6
- package/dist/index-836hc2h1.js +0 -6
- package/dist/index-8edck2pr.js +0 -6
- package/dist/index-8tmv33mr.js +0 -6
- package/dist/index-9t4dz145.js +0 -8
- package/dist/index-djeqvfms.js +0 -74
- package/dist/index-djeqvfms.js.map +0 -13
- package/dist/index-dpcm1j62.js +0 -153
- package/dist/index-dzy19wtf.js +0 -6
- package/dist/index-eztfverw.js +0 -9
- package/dist/index-fxpmx6cr.js +0 -308
- package/dist/index-fxpmx6cr.js.map +0 -21
- package/dist/index-hpvfqq6r.js +0 -1252
- package/dist/index-hrwakb11.js +0 -6
- package/dist/index-jc4kmfwa.js +0 -6
- package/dist/index-k8e9f466.js.map +0 -13
- package/dist/index-mjfv7k5w.js +0 -6
- package/dist/index-nvc24414.js +0 -6
- package/dist/index-nxhqf597.js +0 -6
- package/dist/index-qv6ktepc.js +0 -6
- package/dist/index-qv6ktepc.js.map +0 -10
- package/dist/index-ry6a4bqh.js +0 -126
- package/dist/index-sh44ymqz.js +0 -11
- package/dist/index-xg7s813b.js +0 -6
- package/dist/index-y7dxq4a4.js +0 -14
- package/dist/web-gfv0mzgs.js +0 -14
- package/dist/wrapper-f662ny3r.js +0 -5
- /package/dist/{APEv2Parser-ysjr6adv.js.map → APEv2Parser-rt8hyadd.js.map} +0 -0
- /package/dist/{FlacParser-drm5wq0p.js.map → FlacParser-rmkpvf9e.js.map} +0 -0
- /package/dist/{index-2zjh5zd5.js.map → index-659ggfbf.js.map} +0 -0
- /package/dist/{wrapper-f662ny3r.js.map → wrapper-5zhcdmnk.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,489 +1,502 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`);else process.stdout.write(`${
|
|
4
|
-
`);return o}let
|
|
5
|
-
`),o;let s
|
|
6
|
-
`),o}import{basename as
|
|
7
|
-
searching ${
|
|
8
|
-
`);let i=[],
|
|
9
|
-
`));if(i.length===0){process.stdout.write(`${
|
|
10
|
-
${
|
|
11
|
-
`);return}let a=
|
|
12
|
-
${
|
|
13
|
-
`);return}let
|
|
14
|
-
`),a.length>1)process.stdout.write(`${
|
|
2
|
+
import{A,J,h,n,fo,si,bt,HA,Xt,KA,gA,Se,Co,ai,gi,cA,ho,Nt,Bo,Mt,YA,Bt,yo,Qo,Fe,Re,U,z,Ii,Or,jA,q,wo,Do,dA,JA,bo,uA,ee,re,fi,pe,yn,Oo,No,pi,Ci,hi,v,Js}from"./index-ss77hvwy.js";import{Ir,Ye,dr,ur,Jt,Er,fr,pr}from"./index-bhj4pmrx.js";import{ae,be,Ee,fe,Ie,Qe,Jr}from"./index-w8e8qxd4.js";import{oa}from"./index-1hbvhrsj.js";import{mn}from"./index-659ggfbf.js";import{_A,kA,to,He,cs,ls,sr,jr,ar,pt,gr,vA,Ht,cr,Kt,LA,Is,ds}from"./index-kyz4t0j0.js";import{tr,rn,Ft,xr,Ar,bA,nr,jn,OA,NA,sn,Jn,qn,Xi,Vn,Wn,zn}from"./index-zqjtjs7c.js";import{Wt,FA,Io,En,uo,UA,Sr,fn,ct,aA,zt,xA,wr}from"./index-5ptbytze.js";import{Yr,ts,an,As,ns,os,nA}from"./index-s0mfq8t7.js";import{gn,st,cn,ss}from"./index-zj87j4j2.js";import{Hn,Kn,nn,Xo,DA,Yi,Yn,qi,Vi}from"./index-mk7hrzq7.js";import"./index-rerdsr3d.js";import{$o}from"./index-9xhresrg.js";import{Gt,on,Zi,$i}from"./index-ncb840sk.js";import{MA,es}from"./index-p5gy5s7p.js";import{Ve}from"./index-4g4smpkk.js";import{rs}from"./index-t9bnt6a1.js";import{as,rr,ir,We,ze,Ut,gs,xt,De,RA,ft,eo}from"./index-fad09b8c.js";import{Ke,at}from"./index-z9r4e0yq.js";import{oo,wt,Es,H,ps,Ze,Ct,lr,Cs}from"./index-6pym9p8h.js";import{p,L,D,w,oA,dn,rA,iA}from"./index-s9ybp2r1.js";import{Zt,Oe,W,Dr,G,ge,br,pn,Cn,ii,Hs,$t,Ks,oe,Ge}from"./index-5s1cq8np.js";import{Ue}from"./index-2h566rtg.js";import{Xs,ta}from"./index-4fj1k64j.js";import{ko,Ia,Rt,Me,Po,Ho,o,E,Sn}from"./index-4gfsf9n8.js";async function In(e){let t=await xt(e),s=[];for(let i of oe()){let r=i.id??i.ref,a=await ir(r,e)??{enabled:!0},d=t.find((u)=>u.agentId===r),l=d===void 0?Number.NaN:Date.now()-Date.parse(d.startedAt);s.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...d===void 0?{}:{pid:d.pid,serving:`serving · ${d.mode} · pid ${d.pid}${Number.isFinite(l)?` · up ${dn(l)}`:""}`}})}return s}function On(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((t)=>({label:t.ref,value:t.problem!==void 0?"broken":t.enabled?"on":"off",note:t.problem??t.serving??(t.enabled?`not hosted${t.modelId===void 0?"":` · ${t.modelId}`}`:`switched off${t.reason===void 0?"":` — ${t.reason}`}`)}))}async function Pt(e){if(e.manifestPaths.length===0){let a=await In(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
|
|
3
|
+
`);else process.stdout.write(`${p(On(a))}
|
|
4
|
+
`);return o}let t=await pe.create({agents:[...e.manifestPaths],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v(e.manifestPaths),store:e.store??G(),lease:!1});H(()=>t.stop("cli-exit"));let s=t.list().map((a)=>a.describe()),i=new Map;for(let a of await t.store.leases.all()){if(a.runtimeId===t.runtimeId||!ee(a.pid))continue;let d=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(d)?` · up ${dn(d)}`:""}`)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:s.map((a)=>({...a,serving:i.get(a.id)??null}))},null,2)}
|
|
5
|
+
`),o;let r=s.map((a)=>({label:a.id,value:`${a.model} ${String(a.window).padStart(7)} window`,note:i.get(a.id)??a.name}));return process.stdout.write(`${p(r)}
|
|
6
|
+
`),o}import{basename as tn,dirname as Mi,join as de,resolve as Di}from"node:path";import{rmSync as yi}from"node:fs";import{isAbsolute as Et,join as wi,resolve as Tt}from"node:path";var bi=3;async function It(e){if(e.answers.skills!=="find")return;let t=e.answers.skillsSearch?.trim()??"";if(t===""){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 s=He(e.env);if(s.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
|
|
7
|
+
searching ${s.length} skill source(s) for ${JSON.stringify(t)}
|
|
8
|
+
`);let i=[],r=[];for(let c of s){if(!pt(c.name,e.env))try{await vA(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(f){r.push(`${c.name} — ${h(f)?f.message:String(f)}`);continue}i.push(...Ht(c,e.env))}for(let c of r)process.stdout.write(w(`could not fetch ${c}
|
|
9
|
+
`));if(i.length===0){process.stdout.write(`${w("no source could be read, so no skill was installed — the directory is there and empty")}
|
|
10
|
+
${w("`sources update` reports why; `sources search <words>` when it works",4)}
|
|
11
|
+
`);return}let a=vi(t,i);if(a.length===0){process.stdout.write(`${w(`nothing in ${i.length} skills matches those words, so none was installed`)}
|
|
12
|
+
${w("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
|
|
13
|
+
`);return}let d=a[0],l=`${d.source}/${d.skill}`;if(process.stdout.write(`${w(`best of ${i.length}: ${l}`)}
|
|
14
|
+
`),a.length>1)process.stdout.write(`${w(`also matched: ${a.slice(1,1+bi).map((c)=>`${c.source}/${c.skill}`).join(", ")}`,4)}
|
|
15
15
|
`);if(process.stdout.write(`
|
|
16
|
-
`),Kt({action:"install",manifestPath:e.manifestPath,name:
|
|
17
|
-
${
|
|
18
|
-
${
|
|
19
|
-
${
|
|
20
|
-
`)}function
|
|
21
|
-
`,{encoding:"utf8",mode:384}),
|
|
22
|
-
`),o;return
|
|
23
|
-
`);let
|
|
24
|
-
${
|
|
25
|
-
`),{kind:"failed",code:
|
|
26
|
-
`),
|
|
27
|
-
`);let{outcome:
|
|
28
|
-
`)}}let
|
|
29
|
-
${
|
|
30
|
-
To make it yours across every surface: ${
|
|
31
|
-
`);return}let
|
|
32
|
-
hint: run \`${
|
|
33
|
-
`)}finally{await
|
|
34
|
-
it is running in the background now — \`${
|
|
35
|
-
\`${
|
|
36
|
-
`:"";return`${
|
|
16
|
+
`),Kt({action:"install",manifestPath:e.manifestPath,name:l,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let g=Si(e.manifestPath,e.envOverlay);if(g!==void 0)ki(e.manifestPath,d.skill,e.envOverlay),process.stdout.write(`
|
|
17
|
+
${D(`${l} was removed again: it does not load on this machine`)}
|
|
18
|
+
${w(g,4)}
|
|
19
|
+
${w("everything else is fine; `sources search` for one that needs no extra runtime",4)}
|
|
20
|
+
`)}function vi(e,t){let s=new Map,i=t.filter((r)=>r.problem===void 0).map((r)=>{let a=`${r.source}/${r.skill}`;return s.set(a,r),{name:a,dir:r.dir,tokens:r.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:r.description,metadata:{}}}});return JA(e,i).filter((r)=>r.score>0).map((r)=>s.get(r.skill.name)).filter((r)=>r!==void 0)}function Si(e,t){try{let s=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=s.manifest.skills;if(i===void 0)return;let r=Se(s.manifest.model.main.id,s.manifest.model.main.capabilities);dA({dir:Et(i.dir)?i.dir:Tt(s.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:r.promptStyle,agentDir:s.dir,runner:fe()});return}catch(s){return h(s)?s.message:String(s)}}function ki(e,t,s){try{let i=z(e,{...s===void 0?{}:{env:{...process.env,...s}}}),r=i.manifest.skills;if(r===void 0)return;let a=Et(r.dir)?r.dir:Tt(i.dir,r.dir);yi(wi(a,t),{recursive:!0,force:!0}),cr(a,t)}catch{}}var An=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function Ot(e,t,s={}){let i=s.fetch??fetch,r=e.replace(/\/+$/,""),a=s.apiKey===void 0?{}:{authorization:`Bearer ${s.apiKey}`},d=async(y)=>{try{let R=await i(y,{headers:a,signal:AbortSignal.timeout(3000)});if(!R.ok)return;let T=await R.json();return T!==null&&typeof T==="object"?T:void 0}catch{return}},g=((await d(`${r}/models/${t}/endpoints`))?.data?.endpoints??[]).map((y)=>An(y.context_length)).filter((y)=>y!==void 0);if(g.length>0)return{tokens:Math.min(...g),source:`the smallest of ${g.length} published endpoint${g.length===1?"":"s"} at ${r}`};let f=((await d(`${r}/models`))?.data??[]).find((y)=>y.id===t),m=An(f?.context_length)??An(f?.max_model_len);return m===void 0?void 0:{tokens:m,source:`${r}/models`}}import{randomBytes as Pi}from"node:crypto";import{mkdirSync as Ei,readFileSync as At,writeFileSync as Ri}from"node:fs";import{join as Ti}from"node:path";function Je(e){return Ti(e,".owner")}function xi(e,t=Pi){try{let i=At(Je(e),"utf8").trim();if(i!=="")return i}catch{}let s=`me:${fo(t(6))}`;return Ei(e,{recursive:!0}),Ri(Je(e),`${s}
|
|
21
|
+
`,{encoding:"utf8",mode:384}),s}function Oi(e){return e.flatMap((t)=>(t.allowFrom??[]).filter((s)=>s!=="*").map((s)=>`${t.type}:${s}`))}async function Ai(e,t){let s=e.conversations,i=(t.now??new Date).toISOString(),r=await s.assignment(t.agentId);if(r!==void 0&&r.participantId!==t.owner)throw new n({code:"owner_assigned_elsewhere",message:`Agent "${t.agentId}" is assigned to ${r.participantId}, not to ${t.owner}.`,hint:`Somebody else is this agent's owner, and taking it over would make it answer the wrong person as its owner. If it really is yours, unassign it first (DELETE /v1/agents/${t.agentId}/assignee) and run \`${A.slug} owner adopt ${t.agentId}\` again.`});if(await s.participant(t.owner)===void 0)await s.upsertParticipant({id:t.owner,kind:"human",role:"admin",createdAt:i});let a=[...new Set([...r?.channelIds??[],...t.channelIds])];return await s.assign({agentId:t.agentId,participantId:t.owner,...a.length===0?{}:{channelIds:a},assignedAt:i}),{channelIds:a}}async function ve(e,t,s){let i=At(t,"utf8"),r=String(Re(i,["id"])??""),a=Re(i,["channels"]),d=xi(s),{channelIds:l}=await Ai(e,{agentId:r,owner:d,channelIds:Oi(Array.isArray(a)?a.filter((u)=>typeof u?.type==="string"):[])});return{agentId:r,owner:d,channelIds:l}}import{existsSync as _i,mkdirSync as Ni,writeFileSync as ji}from"node:fs";import{dirname as Fi,join as _n,resolve as Nn,sep as Li}from"node:path";var Xe={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",region:"--region",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",whatsapp:"--whatsapp",whatsappNumber:"--whatsapp-number",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function Fn(e,t,s,i){let r=[];for(;;){let a=aA(e,s);if(a===void 0)break;if(a.optional===!0){e[a.step]="";continue}if(a.fallback===""){r.push(a.step),e[a.step]="(missing)";continue}let d=zt(a.step,a.fallback);if(d.ok)e[a.step]=d.value}if(r.length>0){if(i?.naming==="answers"){let d=r.map((l)=>`answers.${l}`).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${r.join(", ")} ${r.length===1?"has":"have"} no default.`,hint:`Provide ${d} in the request body. GET /v1/provision lists every question with its prompt, its default and its choices.`})}let a=r.map((d)=>Xe[d]).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${r.join(", ")} ${r.length===1?"has":"have"} no default.`,hint:`Pass ${a} — 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 Ln(e,t){let s=e,i=Wt(s.preset),r=s.apiKeyEnv??i?.apiKeyEnv,a=s.server??"local",d=s.dir??FA(s.dirChoice,s.name,t);if(d===void 0)throw new n({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(s.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:s.user,name:s.name,purpose:s.purpose,preset:s.preset,model:s.model,baseUrl:s.baseUrl??"",...s.region===void 0?{}:{region:s.region},system:s.system,web:s.web,...s.webBackend===void 0?{}:{webBackend:s.webBackend},...s.webKey===void 0||s.webKey===""?{}:{webKey:s.webKey},composio:s.composio,...s.composioKey===void 0||s.composioKey===""?{}:{composioKey:s.composioKey},telegram:s.telegram,...s.telegramToken===void 0||s.telegramToken===""?{}:{telegramToken:s.telegramToken},...s.telegramAllow===void 0||s.telegramAllow===""?{}:{telegramAllow:s.telegramAllow},whatsapp:s.whatsapp??"none",...s.whatsappNumber===void 0||s.whatsappNumber===""?{}:{whatsappNumber:s.whatsappNumber},schedules:s.schedules??"none",server:a,skills:s.skills,...s.skillsSearch===void 0||s.skillsSearch===""?{}:{skillsSearch:s.skillsSearch},...s.skillsPick===void 0||s.skillsPick===""?{}:{skillsPick:s.skillsPick},daemon:s.daemon,...a==="local"?{serverToken:Ki(d,t.agentDirBase)?Hs(t.agentDirBase,_t):_t()}:{},...r===void 0?{}:{apiKeyEnv:r},...s.apiKey===void 0||s.apiKey===""?{}:{apiKey:s.apiKey},...s.dirChoice===void 0?{}:{dirChoice:s.dirChoice},dir:d}}function Ki(e,t){let s=Nn(e),i=Nn(t);return s===i||s.startsWith(i+Li)}function _t(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Te(e,t){let s=t.map((i)=>_n(e,i.relPath)).filter((i)=>_i(i));if(s.length>0)throw new n({code:"cli_init_target_exists",message:`${s.length} of the files init would write already exist: ${s.join(", ")}`,hint:"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable."});for(let i of t){let r=_n(e,i.relPath);Ni(Fi(r),{recursive:!0}),ji(r,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function en(e,t){let s=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=Se(s.manifest.model.main.id,s.manifest.model.main.capabilities),{workspace:r,warnings:a}=uA(s,i.promptStyle),d=Xt(r,s.manifest.context.rules);if(d!==void 0&&s.manifest.context.rules.onExceed==="fail")throw d;return{distilled:a.some((l)=>l.code==="soul_distilled")}}var Lt=new Map([["dir",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["dirChoice",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["daemon",{code:"provision_daemon_refused",hint:"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process."}]]),Un=new Map([["skills",new Map([["find",{code:"provision_skills_search_refused",hint:"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists."}]])]]);function Dt(e){let t=zt(e.step,e.fallback);return t.ok?t.value:e.fallback}function Ui(e,t){let s=Un.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Dt(e),optional:e.optional===!0,secret:fn.has(e.step),...t===void 0?{}:{requires:t},...e.options===void 0?{}:{choices:e.options.filter((i)=>s?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var jt=64;function qt(e){let t=new Map,s=new Set,i=(a,d)=>{let l={...a},u=[];for(let g=0;g<jt;g+=1){let c=aA(l,e);if(c===void 0)break;let f=Dt(c);if(!Lt.has(c.step)&&!t.has(c.step))t.set(c.step,Ui(c,d));for(let m of c.options??[]){if(m.value===f)continue;if(Un.get(c.step)?.has(m.value)===!0)continue;u.push({seed:{...l,[c.step]:m.value},opened:{step:c.step,value:m.value}})}l[c.step]=f}return u},r=[...i({})];for(let a=0;a<jt&&r.length>0;a+=1){let d=r.splice(0,r.length);for(let l of d){let u=`${l.opened.step}=${l.opened.value}`;if(s.has(u))continue;s.add(u),r.push(...i(l.seed,l.opened))}}return[...t.values()].sort((a,d)=>Sr.indexOf(a.step)-Sr.indexOf(d.step))}function Vt(e){let t={};for(let[l,u]of Object.entries(e.answers)){let g=l;if(!(g in Xe))throw new n({code:"provision_unknown_answer",message:`"${l}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:l});let c=Lt.get(g);if(c!==void 0)throw new n({code:c.code,message:`"${l}" cannot be set over the API.`,hint:c.hint,field:l});let f=Un.get(g)?.get(u.trim().toLowerCase());if(f!==void 0)throw new n({code:f.code,message:`${l} is ${JSON.stringify(u)}, which this runtime cannot do over the API.`,hint:f.hint,field:l});let m=zt(g,u);if(!m.ok)throw new n({code:"provision_answer_invalid",message:`${l} is ${JSON.stringify(u)}, which ${m.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:l});t[g]=m.value}Fn(t,"this is the provisioning API",e.defaults,{naming:"answers"});let s=Ln(t,e.defaults),i=ct(s.name),r=FA("sandbox",s.name,e.defaults);if(r===void 0)throw new n({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(s.name)}.`,hint:'This is a bug in the CLI: `dirFor("sandbox", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',field:"name"});let a=Nn(r),d=wr({...s,dir:a});return Te(a,d),{agentId:i,dir:a,manifestPath:_n(a,"agent.yaml"),files:d.map((l)=>l.relPath)}}function Hi(e){if(e.web!=="search")return;return Io(e.webBackend??"tavily")?.apiKeyEnv}async function Yt(e){let t=await Qt(e);if(t.kind==="aborted")return process.stdout.write(`nothing written
|
|
22
|
+
`),o;return t.kind==="failed"?t.code:o}async function Mn(e){return Qt(e)}async function Qt(e){let t=Bi(e),s=at({json:!1,plain:e.plain===!0,oneShot:!1}),i=s.mode==="rich"&&e.yes!==!0,r={agentDirBase:W()};if(i){let S=await Ji(t,r);if(S===void 0)return{kind:"aborted"};Object.assign(t,S)}else Fn(t,e.yes===!0?"--yes was passed":s.because,r);let a=Ln(t,r),d=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),l=(i||e.measureWindow===!0)&&a.baseUrl!==""?await Ot(a.baseUrl,a.model,{...d===void 0||d===""?{}:{apiKey:d}}):void 0,u=a,g=Di(process.cwd(),u.dir),c=Ks(g);if(c!==void 0)process.stderr.write(`${c}
|
|
23
|
+
`);let f=de(g,"agent.yaml"),m=wr(u,l);Te(g,m);let y=u.apiKeyEnv,T=y!==void 0&&u.apiKey===void 0&&(process.env[y]===void 0||process.env[y]==="")&&y!==void 0?{[y]:"(pending)"}:void 0,b=!1;try{b=en(de(g,"agent.yaml"),T).distilled}catch(S){if(h(S))return process.stderr.write(`init wrote ${m.length} files to ${g}, but the result does not load:
|
|
24
|
+
${S.format()}
|
|
25
|
+
`),{kind:"failed",code:E};throw S}if(process.stdout.write(`wrote ${m.length} files to ${g} — validated ok
|
|
26
|
+
`),u.skills==="find"){let S=(u.skillsPick??"").split(",").map((P)=>P.trim()).filter((P)=>P!=="");if(S.length>0)Is(S,f,{...T===void 0?{}:{envOverlay:T}});else if(!i)await It({answers:u,manifestPath:f,...T===void 0?{}:{envOverlay:T}})}await Wi(f,g,r.agentDirBase);let N;if(u.daemon==="service"){process.stdout.write(`
|
|
27
|
+
`);let{outcome:S,host:P}=await jn({...e.installServer===void 0?{}:{install:e.installServer}}),I=bA(S);if(I!==void 0)process.stderr.write(I);if(P?.baseUrl!==void 0){let O=await OA(P,f);if(O.ok)N=P.baseUrl;else process.stderr.write(`pid ${P.pid} did not adopt ${ct(u.name)}${O.detail===void 0?"":`: ${O.detail}`}
|
|
28
|
+
`)}}let M;if(u.whatsapp==="connected"&&(u.whatsappNumber??"")!==""&&i)M=N!==void 0?await Jn({manifestPath:f,channelId:"wa"}):await qn({manifestPath:f,dir:g,number:u.whatsappNumber??"",channelId:"wa"});if(u.whatsapp==="connected"&&M!=="paired")process.stdout.write(`
|
|
29
|
+
${Xi(ct(u.name))}`);return process.stdout.write(zi(u,g,b,N)),{kind:"ok",manifestPath:de(g,"agent.yaml")}}async function Wi(e,t,s){let i=tn(t);if(!$t(t)){process.stdout.write(`
|
|
30
|
+
To make it yours across every surface: ${A.slug} owner adopt ${e}
|
|
31
|
+
`);return}let r;try{r=await re.open({path:G()}),await ve(r,e,s)}catch(a){let d=a instanceof Error?a.message:String(a);process.stderr.write(`could not record you as ${i}'s owner: ${d}
|
|
32
|
+
hint: run \`${A.slug} owner adopt ${i}\` once the store is reachable.
|
|
33
|
+
`)}finally{await r?.close()}}function Gi(e){if(e===void 0)return[];if(UA.some((t)=>t.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function Bi(e){let t={},s=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["region",e.region],["apiKeyEnv",e.apiKeyEnv],["system",e.system],["web",e.web],["webBackend",e.webBackend],["composio",e.composio],["telegram",e.telegram],["telegramAllow",e.telegramAllow],["whatsapp",e.whatsapp],["whatsappNumber",e.whatsappNumber],["server",e.server],["schedules",e.schedules],...Gi(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,r]of s){if(r===void 0)continue;let a=zt(i,r);if(!a.ok)throw new n({code:"cli_init_flag_invalid",message:`${Xe[i]} is ${JSON.stringify(r)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});t[i]=a.value}return t}async function Ji(e,t){let[{render:s},{createElement:i},{WizardApp:r}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-c42wc116.js")]),a;oo();let d=s(i(r,{title:`${A.name} ${q}`,given:e,defaults:t,onDone:(l)=>{a=l}}),{exitOnCtrlC:!1,...Ke()});return H(()=>d.unmount()),await d.waitUntilExit(),d.unmount(),a}function zi(e,t,s,i){let r=i!==void 0,d=Mi(t)===W()?tn(t):de(t,"agent.yaml"),l=de(t,"agent.yaml"),u=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)u.push(`Add your key: edit ${de(t,".env")} and set ${e.apiKeyEnv}=`);let g=Hi(e);if(g!==void 0&&e.webKey===void 0)u.push(`Add your search key: edit ${de(t,".env")} and set ${g}= — web_fetch works without it, web_search does not`);if(xA(e)&&e.composioKey===void 0)u.push(`Add your Composio key: edit ${de(t,".env")} and set ${En}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)u.push(`Add your bot token: message @BotFather with /newbot, then edit ${de(t,".env")} and set ${uo}=`);let c=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],f=c.length>0||e.server==="local",m=[...c,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(r)u.push(`open ${nA(i,tn(t))} — the web UI. The service is serving `+`${tn(t)} now; ${m} ${c.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),u.push(`${A.slug} run ${d} — talks to it here, attached to that same service.`);else u.push(`${A.slug} run ${d}`);if(f&&!r){if(u.push(`${A.slug} serve ${d} — starts ${m}; \`run\` starts neither`),e.daemon==="service")u.push(`${A.slug} daemon install — the same thing, supervised: one service hosts `+"every agent, starts at login and survives a reboot.")}if(e.telegram==="connected"&&e.telegramAllow===void 0)u.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(xA(e))u.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.");u.push(e.skills==="find"?`Add more skills: \`${A.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${A.slug} skills install ${d} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${A.slug} sources search <what it should do>\` searches the configured catalogues.`:`Skills are off but the directory is there — \`${A.slug} sources search <what it should do>\` finds one, \`${A.slug} skills new ${d} <name>\` writes one.`),u.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${l}\` shows exactly what still reads as a template.`);let y=r?`
|
|
34
|
+
it is running in the background now — \`${A.slug} status\` at any time,
|
|
35
|
+
\`${A.slug} restart ${d}\` after editing it, and \`${A.slug} stop\` turns everything off.
|
|
36
|
+
`:"";return`${s?`
|
|
37
37
|
this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
|
|
38
38
|
frontier-class model, and activates automatically if you upgrade.
|
|
39
|
-
`:""}${
|
|
40
|
-
`+
|
|
41
|
-
`).join("")}var
|
|
42
|
-
`:`${
|
|
43
|
-
${
|
|
39
|
+
`:""}${y}
|
|
40
|
+
`+u.map((T,b)=>` ${b+1}. ${T}
|
|
41
|
+
`).join("")}var ln=16;function un(e=process.stdin){let t=[],s=[],i=(r)=>{let a=typeof r==="string"?r:r.toString("utf8");if(s.push(a),s.length>ln)s.splice(0,s.length-ln);if(t.push(...Xs(a)),t.length>ln)t.splice(0,t.length-ln)};return e.on("data",i),{correct:(r,a)=>ta(r,a,t),takeRaw:()=>s.shift(),close:()=>{e.off("data",i)}}}var er=[{id:"vscode",name:"VS Code's integrated terminal",how:"write",configPath:"Library/Application Support/Code/User/keybindings.json",line:'{ "key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\\u001b[13;2u" } }',marker:"workbench.action.terminal.sendSequence"},{id:"ghostty",name:"Ghostty",how:"write",configPath:".config/ghostty/config",line:"keybind = shift+enter=text:\\x1b[13;2u",marker:"shift+enter=text:"},{id:"kitty",name:"kitty",how:"write",configPath:".config/kitty/kitty.conf",line:"map shift+enter send_text all \\x1b[13;2u",marker:"map shift+enter send_text"},{id:"wezterm",name:"WezTerm",how:"write",configPath:".wezterm.lua",line:"-- shift+enter: { key = 'Enter', mods = 'SHIFT', action = wezterm.action.SendString '\\x1b[13;2u' },",marker:"mods = 'SHIFT', action = wezterm.action.SendString"},{id:"warp",name:"Warp",how:"explain",reason:"Option is resolved to a character before the keyboard protocol sees it, so ⌥ plus a letter arrives as text like `®` unless Warp is told otherwise",steps:["Settings → Features → Keys → tick “Left and Right Option Key is Meta”","That is only needed for ⌥ plus a *letter*. ⌥ and cmd with arrows already work, and so does shift+⏎",`Every letter chord here has a control-key twin that needs none of this — \`${A.slug} keys\` shows exactly what your terminal sends`]},{id:"iterm2",name:"iTerm2",how:"explain",reason:"its preferences are a binary plist it rewrites on quit, so an edit made underneath it is discarded",steps:["Settings → Profiles → Keys → Key Mappings","Press +, then press shift and return together to capture the key","Set Action to “Send Hex Codes”","Enter: 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75"]},{id:"apple",name:"Terminal.app",how:"explain",reason:"its key bindings live in the same binary preferences file, and it caches them while running",steps:["Settings → Profiles → Keyboard","Press +, choose Return as the key and tick Shift","Set Action to “Send Text” and enter: \\033[13;2u"]}];function hn(e){let t=e.TERM_PROGRAM??"";if(t==="vscode")return"vscode";if(t==="ghostty"||e.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(e.KITTY_WINDOW_ID!==void 0||e.TERM==="xterm-kitty")return"kitty";if(e.WEZTERM_PANE!==void 0)return"wezterm";if(t==="WarpTerminal")return"warp";if(t==="iTerm.app")return"iterm2";if(t==="Apple_Terminal")return"apple";return"unknown"}function wn(e){return er.find((t)=>t.id===e)}function or(){return er}function mr(e,t){return t.marker!==void 0&&e.includes(t.marker)}function hr(e,t){let s=t.line;if(s===void 0)return;if(t.id!=="vscode"){let l=e.trimEnd();return l===""?`${s}
|
|
42
|
+
`:`${l}
|
|
43
|
+
${s}
|
|
44
44
|
`}let i=e.trim();if(i===""||i==="[]")return`[
|
|
45
|
-
${
|
|
45
|
+
${s}
|
|
46
46
|
]
|
|
47
|
-
`;let
|
|
48
|
-
${
|
|
49
|
-
${i.slice(
|
|
50
|
-
delivery reads the channel back out of the key.`;function
|
|
47
|
+
`;let r=i.indexOf("[");if(r===-1)return;let d=i.slice(r+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,r+1)}
|
|
48
|
+
${s}${d}
|
|
49
|
+
${i.slice(r+1)}`}async function yr(e={}){let t=at({plain:!1,json:!1,oneShot:!1});if(t.mode!=="rich")throw new n({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${t.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 s=Ke(e.noEnhancedKeys),i=s.kittyKeyboard!==void 0,r=hn(process.env),a=wn(r)?.name??r,[{render:d},{createElement:l},{KeyProbe:u}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-6t531sy6.js")]),g=()=>{},c=new Promise((y)=>{g=y}),f=un();H(()=>{f.close()}),wt(),process.stdout.write(Rt);let m=d(l(u,{columns:Ue(process.stdout.columns,Me),asked:i,terminal:a,takeRaw:f.takeRaw,correctKeys:f.correct,onDone:g}),{exitOnCtrlC:!1,...s});return H(()=>m.unmount()),await c,m.unmount(),f.close(),Ze(),await Ct(),o}var Qi=24,Dn=22;function Gn(e){let t=e.args.map((s)=>{let i=s.variadic===!0?`${s.name}...`:s.name;return s.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${t===""?"":` ${t}`}`}function $r(e){let t=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,s=e.short===void 0?t:`-${e.short}, ${t}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${s.padEnd(Qi-1)} ${e.help}${i}`}var vr=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
|
|
50
|
+
delivery reads the channel back out of the key.`;function ea(e){let t=[];for(let s of e.args){if(s.choices===void 0||s.choices.length===0)continue;let i=Math.max(...s.choices.map((r)=>r.value.length))+2;t.push("",`${s.name}:`);for(let r of s.choices)t.push(` ${r.value.padEnd(i)}${r.help}`)}return t}function Bn(e){if(e!==void 0){let s=[e.summary,"","usage:",` ${Gn(e)} [flags]`,...ea(e),"","flags:",...cn(e).map($r)];if(e.flags.some((i)=>i.name==="session"))s.push("",vr);return`${s.join(`
|
|
51
51
|
`)}
|
|
52
|
-
`}let
|
|
52
|
+
`}let t=Math.max(...st.map((s)=>Gn(s).length))+2;return`${[`${A.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...st.map((s)=>` ${Gn(s).padEnd(t)}${s.summary}`),` ${A.slug} --version`,` ${A.slug} --help`,"",`Per-command flags: ${A.slug} <command> --help`,"","global flags:",...gn.map($r),"",vr,"","environment:",` ${`${A.envPrefix}BRAND`.padEnd(Dn)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Dn)}set to anything to force plain output`,` ${"DEBUG".padEnd(Dn)}print stack traces on failure`].join(`
|
|
53
53
|
`)}
|
|
54
|
-
`}function
|
|
55
|
-
`)){let
|
|
56
|
-
`),o;return process.stdout.write(
|
|
57
|
-
Read: ${[...
|
|
54
|
+
`}function kr(e){if(!(e instanceof Error))return;let t=e.code;if(t!=="ERR_MODULE_NOT_FOUND"&&t!=="MODULE_NOT_FOUND")return;let s=/['"](ink|react)(?:\/[^'"]*)?['"]/.exec(e.message);return s?.[1]==="ink"||s?.[1]==="react"?s[1]:void 0}import{readFileSync as na,statSync as ra}from"node:fs";var sa=65536;function Pr(e=process.env,t=(s)=>process.stderr.write(`${s}
|
|
55
|
+
`)){let s=[];for(let[i,r]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||r===void 0||r==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(ra(r).size>sa)continue;e[a]=na(r,"utf8").replace(/\r?\n$/,""),s.push(a)}catch(d){t(`${i} names ${r}, which could not be read (${d instanceof Error?d.message:String(d)}); ${a} is not set from it.`)}}return s}var ia=[{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 aa(e,t){return ia.some((s)=>s.name===e&&t.includes(s.contains))}function da(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var Rr;function Tr(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(Rr)return;if(da(e))return;let t=process.emitWarning;Rr=t,process.emitWarning=(s,...i)=>{let r=typeof s==="string"?la(i):s.name,a=typeof s==="string"?s:s.message;if(aa(r,a))return;Reflect.apply(t,process,[s,...i])}}function la(e){let t=e[0];return typeof t==="string"?t:"Warning"}var _r=96;async function Nr(e){let t=await pe.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath])});try{let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let u=await s.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(u,null,2)}
|
|
56
|
+
`),o;return process.stdout.write(p([{label:"passages",value:String(u.passages)},{label:"files read",value:String(u.indexed.length)},{label:"conversations",value:u.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(u.sessions.length)},{label:"shared scopes",value:u.scopes.length===0?"none":u.scopes.join(", ")},{label:"dropped",value:u.dropped.length===0?"":u.dropped.join(", ")}])),process.stdout.write(u.indexed.length===0&&u.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":`
|
|
57
|
+
Read: ${[...u.indexed,...u.sessions].join(", ")}
|
|
58
58
|
`),o}let i=e.query??"";if(i.trim()==="")return process.stderr.write(`memory search needs something to search for.
|
|
59
|
-
`+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),
|
|
60
|
-
`),o;if(process.stdout.write(
|
|
61
|
-
Nothing ${e.all===!0?"matched":`scored above ${
|
|
62
|
-
`),o;let
|
|
63
|
-
${
|
|
64
|
-
`);for(let
|
|
65
|
-
`)}if(e.all===!0&&a.length<
|
|
66
|
-
${
|
|
67
|
-
`);if(
|
|
68
|
-
${
|
|
69
|
-
`);return o}finally{await
|
|
70
|
-
`)}function
|
|
71
|
-
Reply with the single character x.`;try{let
|
|
72
|
-
`).map((
|
|
59
|
+
`+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),E;let r=await s.searchMemory({query:i,limit:e.limit??10}),a=r.hits.filter((u)=>u.score>=r.threshold),d=e.all===!0?r.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:r.corpus,threshold:r.threshold,carried:r.carried??null,hits:d.map((u)=>({source:u.passage.source,at:u.passage.at,score:u.score,lexical:u.lexical,coverage:u.coverage,tokens:u.tokens,wouldInject:u.score>=r.threshold,carried:u.passage.source===r.carried,text:u.passage.text}))},null,2)}
|
|
60
|
+
`),o;if(process.stdout.write(p([{label:"corpus",value:`${r.corpus} passage${r.corpus===1?"":"s"}`},{label:"threshold",value:r.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),r.corpus===0)return process.stdout.write("\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\n"),o;if(d.length===0)return process.stdout.write(`
|
|
61
|
+
Nothing ${e.all===!0?"matched":`scored above ${r.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
|
|
62
|
+
`),o;let l=Math.max(6,...d.map((u)=>Cr(u,r.carried).length));process.stdout.write(`
|
|
63
|
+
${se("SCORE",6)} ${se("LEXICAL",7)} ${se("COVER",5)} ${se("SOURCE",l)} ${se("LEARNED",10)} PASSAGE
|
|
64
|
+
`);for(let u of d){let g=u.score>=r.threshold?" ":"·";process.stdout.write(`${se(u.score.toFixed(3),6)} ${se(u.lexical.toFixed(3),7)} ${se(u.coverage.toFixed(2),5)} ${se(Cr(u,r.carried),l)} ${se(u.passage.at.slice(0,10),10)} ${g}${ca(u.passage.text)}
|
|
65
|
+
`)}if(e.all===!0&&a.length<d.length)process.stdout.write(`
|
|
66
|
+
${d.length-a.length} shown below the threshold; a turn would not inject those.
|
|
67
|
+
`);if(r.carried!==void 0&&d.some((u)=>u.passage.source===r.carried))process.stdout.write(`
|
|
68
|
+
${r.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
|
|
69
|
+
`);return o}finally{await t.stop("cli-exit")}}function ca(e){let t=e.replace(/\s+/g," ").trim();return t.length<=_r?t:`${t.slice(0,_r-1)}…`}function se(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Cr(e,t){return e.passage.source===t?`${e.passage.source} *`:e.passage.source}var ua=["context_length","context_window","max_context_length","max_model_len"],fa=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let t=e.prompt_tokens_details;return bn(t)?t.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function bn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Xn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function Fr(e,t){let s=bn(e)?e.data:void 0,i=Array.isArray(s)?s:Array.isArray(e)?e:void 0;if(i===void 0)return;let r=t.toLowerCase();for(let a of i){if(!bn(a))continue;let d=typeof a.id==="string"?a.id.toLowerCase():void 0;if(d===void 0)continue;if(!(d===r||d.endsWith(`/${r}`)||r.endsWith(`/${d}`)))continue;for(let u of ua){let g=Xn(a[u]);if(g!==void 0)return{technique:"metadata",tokens:g,bound:"ceiling",detail:`GET /models published ${u}: ${g}`}}return}return}function Qn(e){let t=[/(?: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],s=[];for(let i of t){let r=i.exec(e);if(r?.[1]===void 0)continue;let a=Xn(Number(r[1].replaceAll(/[,_]/g,"")));if(a!==void 0)s.push(a)}if(s.length===0)return;return Math.max(...s)}function Lr(e){if(!bn(e))return;let t=Xn(e.prompt_tokens)??0;for(let[s,i]of fa){let r=i(e);if(typeof r==="number"&&Number.isFinite(r))return{cached:r,promptTokens:t,field:s}}return{cached:void 0,promptTokens:t,field:void 0}}function Kr(e,t,s){if(e===void 0||t===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(t.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=t.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${t.promptTokens} prompt tokens, via ${t.field}`};return{supported:!1,detail:`${t.field} came back 0 on an identical repeat of a ${s}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function xe(e){let t=e.filter((i)=>i.bound==="ceiling");return(t.length>0?t:e).reduce((i,r)=>i===void 0||r.tokens>i.tokens?r:i,void 0)}function Ur(e,t,s){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${t.toLocaleString("en-US").replaceAll(",","_")},`,...s===void 0?[]:[` maxOutput: ${s.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
|
|
70
|
+
`)}function Mr(e,t,s){return`measured ${t} against ${e} — ${s}`}function Hr(e,t){let s=Math.max(1,e),i=0,r=0;while(s<t)i+=s,r+=1,s*=2;return i+=t,r+=1,{requests:r,tokens:i}}var ma=2000000000,Wr=1024,Br=8192,qr=2097152;function Vr(e){return"context ".repeat(Math.max(1,e))}async function Ae(e){let t=await e.text();try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function Xr(e,t){if(typeof e==="object"&&e!==null){let s=e,i=s.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let r=i.message;if(typeof r==="string")return r}if(typeof s.message==="string")return s.message}return t}async function pa(e,t,s){try{let i=await t(e.models,{headers:e.headers});if(!i.ok){s.push(`GET /models answered ${i.status}`);return}let{json:r}=await Ae(i),a=Fr(r,e.modelId);if(a===void 0)s.push("GET /models published no context length");return a}catch(i){s.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function ha(e,t,s){try{let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:ma})}),{text:r,json:a}=await Ae(i);if(i.ok)return s.push("the endpoint accepted an impossible max_tokens rather than refusing it — it clamps silently, so this technique cannot measure it"),{window:void 0,outputCeiling:void 0};let d=Xr(a,r.slice(0,400)),l=Qn(d);if(l===void 0)return s.push(`the refusal named no number: ${d.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let u=/max_?tokens/i.test(d);return{window:u?void 0:{technique:"refusal",tokens:l,bound:"ceiling",detail:`refused an over-range request naming ${l}`},outputCeiling:u?l:void 0}}catch(i){return s.push(`the over-range request failed: ${i instanceof Error?i.message:String(i)}`),{window:void 0,outputCeiling:void 0}}}async function Gr(e,t,s){let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:s}],max_tokens:1})});if(!i.ok)return;let{json:r}=await Ae(i),a=typeof r==="object"&&r!==null?r.usage:void 0;return Lr(a)}async function ga(e,t,s){let i=`${Vr(Wr)}
|
|
71
|
+
Reply with the single character x.`;try{let r=await Gr(e,t,i),a=await Gr(e,t,i);return Kr(r,a,Wr)}catch(r){return s.push(`the caching probe failed: ${r instanceof Error?r.message:String(r)}`),{supported:void 0,detail:"the probe did not complete"}}}async function ya(e,t,s){let i=Br,r=0;while(i<=qr){let a;try{a=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Vr(i)}],max_tokens:1})})}catch(g){s.push(`the search stopped at ${i}: ${g instanceof Error?g.message:String(g)}`);break}if(a.ok){let{json:g}=await Ae(a),c=typeof g==="object"&&g!==null?g.usage:void 0,f=typeof c==="object"&&c!==null?c.prompt_tokens:void 0;r=typeof f==="number"&&Number.isFinite(f)?f:r,i*=2;continue}let{text:d,json:l}=await Ae(a),u=Qn(Xr(l,d.slice(0,400)));if(u!==void 0)return{technique:"search",tokens:u,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${u}`};break}if(r===0)return;return{technique:"search",tokens:r,bound:"floor",detail:`accepted a prompt the endpoint counted at ${r} tokens; nothing above it named a number`}}function wa(e,t){let s=xe(e.findings),i=s===void 0?"nothing measured — every technique came back empty":`${s.tokens} (${s.bound}) · ${s.detail}`,r=s===void 0?"":s.tokens===e.declared?"matches what is configured":s.bound==="ceiling"&&s.tokens>e.declared?`configured value is ${e.declared}, which is ${(s.tokens-e.declared).toLocaleString("en-US")} tokens short`:`configured value is ${e.declared}`,a=e.cache.supported===void 0?`unknown — ${e.cache.detail}`:e.cache.supported?`yes — ${e.cache.detail}`:`no — ${e.cache.detail}`;return[L(` ${e.role} · ${e.modelId}`),p([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:r},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...t===void 0?[]:[{label:"price",value:`$${t}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((d)=>` · ${d}`)],...s===void 0||s.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",Ur(e.modelId,s.tokens,e.outputCeiling).split(`
|
|
72
|
+
`).map((d)=>` ${d}`).join(`
|
|
73
73
|
`)]].join(`
|
|
74
|
-
`)}async function
|
|
74
|
+
`)}async function zr(e){let t=e.fetch??globalThis.fetch;try{let s=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:i}=s,r=Nt(i).filter((u)=>u.role===u.configuredAs),a=!1;if(e.window){let u=Hr(Br,qr),g=u.tokens*r.length,c=e.price===void 0?"":` ≈ $${(g/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${u.requests} requests per role, about ${g.toLocaleString("en-US")} input tokens in total${c}.
|
|
75
75
|
That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
|
|
76
76
|
Tokens rather than dollars unless --price says otherwise: a price table in this repo would be wrong within a quarter.
|
|
77
77
|
`),a=e.yes||await MA("spend it?"),process.stdout.write(a?`
|
|
78
78
|
`:`
|
|
79
79
|
Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
|
|
80
80
|
|
|
81
|
-
`)}let
|
|
82
|
-
`);continue}let
|
|
83
|
-
`),o;let
|
|
84
|
-
`)),o}catch(
|
|
85
|
-
`),
|
|
86
|
-
`)}import{readFileSync as
|
|
87
|
-
`);else process.stdout.write(
|
|
88
|
-
`:`${
|
|
89
|
-
`);return o}let
|
|
81
|
+
`)}let d=[];for(let u of r){let g=i.model[u.role]??i.model.main;if(g.baseUrl===void 0){process.stdout.write(`model.${u.role} uses the ${g.api??"chat-completions"} transport, which this probe does not speak. Its window comes from the capability registry: ${u.window.contextWindow.toLocaleString("en-US")} tokens (${u.window.source}).
|
|
82
|
+
`);continue}let c={chat:Co(g.baseUrl),models:ai(g.baseUrl),headers:gi(g.apiKeyEnv,s.env,`model.${u.role}`),modelId:g.id},f=[],m=[],y=await pa(c,t,f);if(y!==void 0)m.push(y);let R=await ha(c,t,f);if(R.window!==void 0)m.push(R.window);let T=await ga(c,t,f);if(a){let b=await ya(c,t,f);if(b!==void 0)m.push(b)}d.push({role:u.role,modelId:g.id,baseUrl:g.baseUrl,declared:u.window.contextWindow,declaredSource:u.window.source,findings:m,cache:T,outputCeiling:R.outputCeiling,failures:f})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:d},null,2)}
|
|
83
|
+
`),o;let l=e.write?await ba(s.path,d):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${d.length} role${d.length===1?"":"s"}`,...d.map((u)=>wa(u,e.price)),"",...e.write?[...l.written.length===0?[]:[" written to the manifest:",...l.written.map((u)=>` ${u}`)],...l.refused.length===0?[]:[" not written:",...l.refused.map((u)=>` ${u}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[$a(d)],""].join(`
|
|
84
|
+
`)),o}catch(s){if(h(s))return process.stderr.write(`${s.format()}
|
|
85
|
+
`),E;throw s}}async function ba(e,t){let s=[],i=[];for(let r of t){let a=xe(r.findings);if(a===void 0){i.push(`${r.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${r.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===r.declared){i.push(`${r.role}: already ${a.tokens}, nothing to change`);continue}await Fe({file:e,path:["model",r.role,"capabilities","contextWindow"],value:a.tokens}),s.push(`${r.role}: ${r.declared} → ${a.tokens}`)}return{written:s,refused:i}}function $a(e){let t=e.filter((a)=>xe(a.findings)?.bound==="ceiling");if(t.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let s=t[0],i=s===void 0?void 0:xe(s.findings);if(s===void 0||i===void 0)return"";let r=new URL(s.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${Mr(r,new Date().toISOString().slice(0,10),i.detail)}`].join(`
|
|
86
|
+
`)}import{readFileSync as va}from"node:fs";async function Qr(e){let t=W();if(e.action==="show"){let g;try{g=va(Je(t),"utf8").trim()||void 0}catch{g=void 0}if(e.json)process.stdout.write(`${JSON.stringify({owner:g??null})}
|
|
87
|
+
`);else process.stdout.write(g===void 0?`No owner yet. \`${A.slug} init\` or \`${A.slug} owner adopt <agent>\` makes you one.
|
|
88
|
+
`:`${g}
|
|
89
|
+
`);return o}let s=e.manifestPath;if(s===void 0||s==="")throw new n({code:"owner_agent_required",message:"owner adopt needs an agent.",hint:`Name one: \`${A.slug} owner adopt milo\`, or a path to its agent.yaml.`});let i=U(s).id??"",r=await re.open({path:e.store??G()}),a;try{a=await ve(r,s,t)}finally{await r.close()}let d=await Fe({file:s,path:["sessions","scope"],value:"owner",fallback:(g)=>/^sessions:/m.test(g)?void 0:`${g.replace(/\n*$/,`
|
|
90
90
|
`)}
|
|
91
91
|
# One conversation with you across the web, the terminal and every channel.
|
|
92
92
|
sessions:
|
|
93
93
|
scope: owner
|
|
94
|
-
`}),
|
|
95
|
-
`),o;return process.stdout.write([`owner ${a.owner}`,`agent ${i} sessions.scope: owner${
|
|
96
|
-
`)),o}import{existsSync as
|
|
97
|
-
`),{dir:i,commit:
|
|
98
|
-
`).slice(-3).join(" ");if(
|
|
99
|
-
`),o;if(
|
|
94
|
+
`}),l=await NA(s,e.store),u=l.kind==="reloaded"||l.kind==="pending"?`reloaded by pid ${l.pid}`:l.kind==="no-host"?"not running here; takes effect when it next starts":`pid ${l.pid} did not reload it (${l.kind}); restart it to take effect`;if(e.json)return process.stdout.write(`${JSON.stringify({agent:i,owner:a.owner,channelIds:a.channelIds,scopeChanged:d.changed,reload:l.kind})}
|
|
95
|
+
`),o;return process.stdout.write([`owner ${a.owner}`,`agent ${i} sessions.scope: owner${d.changed?"":" (already)"}`,`you on ${a.channelIds.length===0?"the web and the terminal only — no allowFrom entries to recognise you by on a channel":a.channelIds.join(", ")}`,`host ${u}`,""].join(`
|
|
96
|
+
`)),o}import{existsSync as bs,rmSync as xa}from"node:fs";import{resolve as Oa}from"node:path";var Sa={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function Zr(e){if(e===null||typeof e!=="object")return!1;let t=e.kind;return t==="network"||t==="env"||t==="fs"||t==="exec"||t==="store"}async function is(e,t={}){let s=[],i=[],r=t.hostVersion??Ye,a=(m,y,R)=>{s.push({level:"error",check:m,message:y,hint:R})},d=(m,y,R)=>{s.push({level:"warning",check:m,message:y,hint:R})};if(typeof e.name!=="string"||e.name==="")a("name","The plugin has no name.","`name` is how events, errors and `plugins` output refer to this plugin. It must be unique within a runtime.");if(dr(e.version,"*")===void 0)a("version",`\`version\` is ${JSON.stringify(e.version)}, which is not a plain semver triple.`,"Write it as `major.minor.patch`. It is reported verbatim in `plugin.loaded`, and a version nobody can compare is a version nobody can act on.");let l=dr(r,e.dispachApi);if(l===void 0)a("dispachApi",`\`dispachApi\` is ${JSON.stringify(e.dispachApi)}, which the host cannot check.`,"Supported: `*`, an exact version, `^`, `~`, space-separated comparators, and `||`. A range the host cannot parse is refused rather than assumed satisfied, so this plugin would not load.");else if(!l)d("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${r}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")d("dispachApi","`dispachApi` is `*`, which accepts every host version including ones that do not exist yet.","Narrow it to the range you have actually tested. A plugin that never refuses to load is a plugin that fails at runtime instead, somewhere else, with nothing pointing back at the skew.");for(let[m,y]of(e.permissions??[]).entries())if(!Zr(y))a("permissions",`\`permissions[${m}]\` is not one of the declared kinds.`,"Kinds are network, env, fs, exec and store. Advisory in v1 — but authors who declare accurately before enforcement lands are the ones who will not have to scramble afterwards.");let u=t.config??{};if(e.configSchema!==void 0){let m=e.configSchema.safeParse(u);if(m.success)u=m.data;else d("configSchema","The schema refused the config this suite passed.","Pass a valid `config` through `conformance(plugin, { config })`. The default is `{}`, which a schema with required fields correctly rejects.")}let g={defineChannel:(m)=>i.push(`channel:${m}`),defineToolProvider:(m)=>i.push(`toolProvider:${m}`),defineModelTransport:(m)=>i.push(`modelTransport:${m}`),defineMediaProvider:(m)=>i.push(`mediaProvider:${m}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(m)=>i.push(`middleware:${m.name}`),defineRoute:(m)=>i.push(`route:${m.method} ${m.path}`),config:u,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Sa,events:new Ir({runtimeId:"conformance"})},c=performance.now();try{await e.setup(g)}catch(m){a("setup",`\`setup\` threw: ${m instanceof Error?m.message:String(m)}`,"`setup` registers capabilities and does no work, so it must succeed with an empty environment and a workspace that does not exist. Read a token in the factory you register, not here — that runs only when an agent actually uses the capability.")}let f=Math.round((performance.now()-c)*100)/100;if(f>ur)a("setup budget",`\`setup\` took ${f} ms against a ${ur} ms budget.`,"Move the work into the factory you register. A channel connects in `start()`, which runs after readiness; a provider resolves from its cache at boot and refreshes afterwards. Hard rule 4: no network I/O before `runtime.ready`.");if(i.length===0)d("setup","`setup` registered nothing.","A plugin that registers no channel, tool provider, script runner or middleware extends nothing. Every `define*` and `use` call is recorded, so registering something and still seeing this means the registration did not run — check for a branch in `setup` that skipped it.");return{ok:s.every((m)=>m.level!=="error"),findings:s,registered:i,setupMs:f,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(Zr)}}}import{existsSync as ue,mkdirSync as ka,readdirSync as Pa,readFileSync as Zn,renameSync as us,rmSync as ce,writeFileSync as Ea}from"node:fs";import{join as Q}from"node:path";var fs=".origin.json";function Ra(e){let t=Q(e,fs);if(!ue(t))return;try{return JSON.parse(Zn(t,"utf8"))}catch{return}}function et(e){let t=ge(e),s;try{s=Pa(t)}catch{return[]}let i=[];for(let r of s.sort()){if(r.startsWith(".")||r.endsWith(".partial"))continue;let a=Q(t,r);if(!ue(Q(a,"package.json"))&&!ue(Q(a,"index.js")))continue;let d=Ra(a);i.push({name:r,dir:a,...d===void 0?{}:{origin:d}})}return i}function ms(e){let t=Q(e,"package.json");if(!ue(t))return Q(e,"index.js");try{let s=JSON.parse(Zn(t,"utf8"));if(typeof s.main==="string"&&s.main!=="")return Q(e,s.main)}catch{}return Q(e,"index.js")}function hs(e){let t=Q(e,"package.json");if(!ue(t))return;let s;try{s=JSON.parse(Zn(t,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(s.dependencies??{});if(i.length===0)return;if(ue(Q(e,"node_modules")))return;let r=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${r}${i.length>4?", …":""}) and ships no node_modules`}function ys(e,t){let i=((t??e).split("/").filter((r)=>r.length>0).pop()??"").replace(/\.git$/,"");if(!kA(i))throw new n({code:"plugin_name_invalid",message:`${JSON.stringify(i||e)} is not a usable plugin directory name`,hint:"A plugin is installed into one lowercase path segment — letters, digits and single hyphens — because that segment is what the manifest's `plugins:` entry names. Pass `--name <name>` to choose it."});return i}async function ws(e,t={}){let s=t.git??jr,i=br(e.name,t.env),r=`${i}.partial`;ka(ge(t.env),{recursive:!0}),ce(r,{recursive:!0,force:!0});let a=await s(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,r]);if(a.code!==0)throw ce(r,{recursive:!0,force:!0}),Ta(e,a.stderr,a.timedOut===!0);let d=await s(["rev-parse","--short","HEAD"],r),l=d.code===0?d.stdout.trim():"unknown",u=e.path===void 0?r:Q(r,e.path);if(!ue(u))throw ce(r,{recursive:!0,force:!0}),new n({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${l}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});ce(Q(u,".git"),{recursive:!0,force:!0});try{await t.inspect?.(u)}catch(c){throw ce(r,{recursive:!0,force:!0}),c}if(ce(i,{recursive:!0,force:!0}),u===r)us(r,i);else us(u,i),ce(r,{recursive:!0,force:!0});let g={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:l,fetchedAt:new Date().toISOString()};return Ea(Q(i,fs),`${JSON.stringify(g,null,4)}
|
|
97
|
+
`),{dir:i,commit:l}}function Ta(e,t,s){let i=t.trim().split(`
|
|
98
|
+
`).slice(-3).join(" ");if(s)return new n({code:"plugin_fetch_timeout",message:`${e.name}: git did not finish in time`,hint:`Check the network and try again — the partial fetch was discarded, so whatever was installed as ${e.name} is untouched.`});return new n({code:"plugin_fetch_failed",message:`${e.name}: could not clone ${e.url}${i.length===0?"":` — ${i}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the --ref; nothing was written."})}async function $s(e){switch(e.action){case"list":return await Aa(e);case"add":return await Ca(e);case"remove":return await La(e);default:throw new n({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(e.action)} is not an action`,hint:`Actions are list, add and remove — \`${A.slug} plugins list <agent>\`.`})}}async function Aa(e){let t=await pe.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(e.env),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath]),store:G(e.env),lease:!1});H(()=>t.stop("cli-exit"));let s=[...t.plugins.values()].flat(),i=et(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:s,installed:i,available:Jr},null,2)}
|
|
99
|
+
`),o;if(s.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
|
|
100
100
|
|
|
101
|
-
${Jr.map((
|
|
101
|
+
${Jr.map((l)=>` - "${l}"`).join(`
|
|
102
102
|
`)}
|
|
103
103
|
|
|
104
|
-
Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${
|
|
104
|
+
Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${A.slug} plugins add <agent> <repo>\`.
|
|
105
105
|
`),i.length>0)process.stdout.write(`
|
|
106
|
-
Installed in ${
|
|
107
|
-
${i.map((
|
|
106
|
+
Installed in ${ge(e.env)} and named by no agent:
|
|
107
|
+
${i.map((l)=>` - "${l.name}"`).join(`
|
|
108
108
|
`)}
|
|
109
|
-
`);return o}let s
|
|
110
|
-
`);let a=
|
|
109
|
+
`);return o}let r=s.map((l)=>({label:l.name,value:`${l.version} ${`${l.setupMs} ms`.padStart(9)}`,note:`${_a(l.spec,l.lookup,i)} — ${l.registered.length===0?"registered nothing":l.registered.join(", ")}`}));process.stdout.write(`${p(r)}
|
|
110
|
+
`);let a=s.filter((l)=>l.permissions.length>0);if(a.length>0){process.stdout.write(`
|
|
111
111
|
Declared access — advisory in v1, recorded and not enforced:
|
|
112
|
-
`);for(let
|
|
113
|
-
`)}let
|
|
114
|
-
Also installed, named by no agent: ${
|
|
115
|
-
`);return o}function
|
|
116
|
-
`);let l
|
|
117
|
-
${
|
|
118
|
-
`)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${
|
|
119
|
-
${
|
|
120
|
-
from ${
|
|
121
|
-
installed ${
|
|
122
|
-
host range ${
|
|
123
|
-
registers ${
|
|
124
|
-
`),
|
|
112
|
+
`);for(let l of a)for(let u of l.permissions)process.stdout.write(` ${l.name} ${u.kind} ${vs(u)}
|
|
113
|
+
`)}let d=i.filter((l)=>!s.some((u)=>u.spec===l.name));if(d.length>0)process.stdout.write(`
|
|
114
|
+
Also installed, named by no agent: ${d.map((l)=>l.name).join(", ")}
|
|
115
|
+
`);return o}function _a(e,t,s){if(t!=="installed")return t==="registry"?"built in":"imported";let i=s.find((r)=>r.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function vs(e){switch(e.kind){case"network":return e.hosts.join(", ");case"env":return e.vars.join(", ");case"fs":return`${e.paths.join(", ")} (${e.mode})`;case"exec":return e.commands.join(", ");default:return e.tables.join(", ")}}async function Ca(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${A.slug} plugins add <agent> <owner/repo> [--ref v1.0.0]\`. A plugin is fetched with git — an owner/repo shorthand, a clone URL, the page URL you were reading (whose .../tree/<branch>/<subdir> is understood), or a local repository while you are writing one.`});let s=gr(t)?{url:Oa(t.replace(/^file:\/\//,""))}:sr(t),i=e.ref??s.ref,r=e.name===void 0?ys(s.url,s.path):Na(e.name),a=et(e.env).find((f)=>f.name===r);if(a?.origin!==void 0&&a.origin.url!==s.url)throw new n({code:"plugin_name_taken",message:`A different plugin is already installed as "${r}" — from ${a.origin.url}`,hint:`Two repositories cannot share one directory, and the directory name is what a manifest's \`plugins:\` entry means. Pass \`--name <name>\`, or \`${A.slug} plugins remove <agent> ${r}\` first.`});process.stdout.write(`Fetching ${s.url}${i===void 0?"":` at ${i}`} as "${r}"…
|
|
116
|
+
`);let d,l=await ws({name:r,url:s.url,...i===void 0?{}:{ref:i},...s.path===void 0?{}:{path:s.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(f)=>{let m=hs(f);if(m!==void 0)throw new n({code:"plugin_not_self_contained",message:`${r} cannot be loaded as fetched: ${m}`,hint:"A plugin is distributed as one self-contained bundle. Nothing is installed while this runtime runs (hard rule 5), so a declared dependency would simply be missing at boot. Ask the author to bundle their dependencies, or commit node_modules in the distribution repository."});let y=ms(f);if(!bs(y))throw new n({code:"plugin_entry_missing",message:`${r} has no entry file — ${y.slice(f.length+1)} is not in the repository`,hint:"A plugin directory is entered through the `main` its package.json names, defaulting to index.js. A distribution repository commits its built entry file; a source checkout does not, which is usually what this means."});let R=await ja(r,y);if(d=await is(R),!d.ok)throw new n({code:"plugin_not_conformant",message:`${d.declared.name} does not meet the plugin contract:
|
|
117
|
+
${d.findings.filter((T)=>T.level==="error").map((T)=>` ${T.check}: ${T.message}`).join(`
|
|
118
|
+
`)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${A.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(wo(q,d.declared.apiRange)!==!0)throw new n({code:"plugin_api_mismatch",message:`${d.declared.name} ${d.declared.version} supports host ${d.declared.apiRange}, and this host is ${q}`,hint:"The loader refuses this at boot, so installing it would write an entry that stops the agent starting. Look for a newer release of the plugin, or a `--ref` that matches this host."})}}),u=d?.declared;if(process.stdout.write(`
|
|
119
|
+
${u?.name??r} ${u?.version??"?"} (${l.commit})
|
|
120
|
+
from ${s.url}${i===void 0?"":` at ${i}`}
|
|
121
|
+
installed ${l.dir}
|
|
122
|
+
host range ${u?.apiRange??"?"} — this host is ${q}
|
|
123
|
+
registers ${d===void 0||d.registered.length===0?"nothing":d.registered.join(", ")}
|
|
124
|
+
`),u!==void 0&&u.permissions.length>0)process.stdout.write(`
|
|
125
125
|
It declares access to:
|
|
126
|
-
${
|
|
126
|
+
${u.permissions.map((f)=>` ${f.kind} ${vs(f)}`).join(`
|
|
127
127
|
`)}
|
|
128
128
|
`+"\nAdvisory only. `permissions` is recorded and enforced by nothing in v1 (decision 7.5) —\n"+`a plugin is trusted in-process code, so this list is what the author says it needs, not a
|
|
129
129
|
boundary. Install plugins you trust.
|
|
130
130
|
`);else process.stdout.write(`
|
|
131
131
|
It declares no access. That is not a guarantee: \`permissions\` is advisory in v1, so a
|
|
132
132
|
plugin that declares nothing can still do anything this process can. Install plugins you trust.
|
|
133
|
-
`);let
|
|
134
|
-
note: ${
|
|
135
|
-
`);if(
|
|
136
|
-
note: it calls itself "${
|
|
137
|
-
`);let
|
|
138
|
-
${e.manifestPath} already names "${
|
|
133
|
+
`);let g=d?.findings.filter((f)=>f.level==="warning")??[];for(let f of g)process.stdout.write(`
|
|
134
|
+
note: ${f.check} — ${f.message}
|
|
135
|
+
`);if(u!==void 0&&u.name!==r)process.stdout.write(`
|
|
136
|
+
note: it calls itself "${u.name}"; the \`plugins:\` entry is the directory, "${r}".
|
|
137
|
+
`);let c=await Fa(e.manifestPath,r);return process.stdout.write(c==="already"?`
|
|
138
|
+
${e.manifestPath} already names "${r}".
|
|
139
139
|
`:`
|
|
140
|
-
Added "${
|
|
140
|
+
Added "${r}" to the plugins: block in ${e.manifestPath}.
|
|
141
141
|
It loads at the next start — an agent's plugins are fixed for its lifetime, so restart a running one.
|
|
142
|
-
`),o}function
|
|
143
|
-
Run \`${
|
|
144
|
-
`);else process.stdout.write(`${e.manifestPath} does not name "${
|
|
145
|
-
`);let
|
|
146
|
-
`),o;let a=
|
|
142
|
+
`),o}function Na(e){if(kA(e))return e;throw new n({code:"plugin_name_invalid",message:`--name ${JSON.stringify(e)} is not a usable plugin directory name`,hint:"Lowercase letters, digits and single hyphens. That segment is what the manifest's `plugins:` entry names, so it has to be a directory name and a YAML scalar at once."})}async function ja(e,t){let s;try{s=await import(t)}catch(r){throw new n({code:"plugin_import_failed",message:`${e}: ${t} could not be imported — ${r instanceof Error?r.message:String(r)}`,hint:"A plugin is one self-contained ES module. A bare `require` or an unresolved import is what this usually means, and neither can be fixed by installing anything: nothing is installed while this runtime runs. Nothing was installed.",cause:r})}let i=s.default;if(i===null||typeof i!=="object")throw new n({code:"plugin_malformed",message:`${e}: ${t} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${A.slug}Api\` host range and \`setup\`. A named export is not searched for and a factory function is not called, because a wrong guess produces a plugin that registers nothing and reports success.`});if(typeof i.setup!=="function")throw new n({code:"plugin_malformed",message:`${e}: the default export of ${t} has no \`setup\` function`,hint:"`setup(context)` is the whole extension surface — it registers channels, tool providers, a script runner or middleware, and does no work."});return i}async function Fa(e,t){let i=U(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===t))return"already";return await Fe({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),t]}),"written"}async function La(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${A.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let i=(U(e.manifestPath).plugins??[]).map((d)=>typeof d==="string"?d:d.spec);if(i.includes(t))await Fe({file:e.manifestPath,path:["plugins"],value:i.filter((d)=>d!==t)}),process.stdout.write(`Dropped "${t}" from ${e.manifestPath}.
|
|
143
|
+
Run \`${A.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
|
|
144
|
+
`);else process.stdout.write(`${e.manifestPath} does not name "${t}".
|
|
145
|
+
`);let r=br(t,e.env);if(!bs(r))return process.stdout.write(`Nothing installed at ${r}.
|
|
146
|
+
`),o;let a=Ka(t,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${r} — still named by ${a.join(", ")}.
|
|
147
147
|
Remove it from those agents first, or delete the directory by hand.
|
|
148
|
-
`),o;return
|
|
149
|
-
`),o}function
|
|
150
|
-
`)}function
|
|
151
|
-
${
|
|
152
|
-
`),o}await rr(
|
|
153
|
-
`);else process.stdout.write(`${
|
|
148
|
+
`),o;return xa(r,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${r}.
|
|
149
|
+
`),o}function Ka(e,t,s){let i=[];for(let r of oe(s)){if(r.manifestPath===t)continue;try{if((U(r.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec).includes(e))i.push(r.ref)}catch{}}return i}import{existsSync as Va,readdirSync as Os,rmSync as nt,statSync as _s}from"node:fs";import{homedir as Ja}from"node:os";import{join as Ns}from"node:path";function Ss(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let t=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${t} — removing its data would take that agent's sessions and memory too.`,hint:`Change one manifest's id and run \`memory rebuild\` for it, or pass --files-only to delete just the ${e.ref} directory and leave the store alone.`}]}function ks(e){let t=[];if(e.running!==void 0)t.push({kind:"stop",detail:`stop pid ${e.running.pid} (${e.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!e.filesOnly&&e.service!==void 0)t.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let s=e.footprint;if(t.push({kind:"store",detail:`delete ${K(s.sessions,"conversation")}, ${K(s.messages,"message")}, ${K(s.passages,"memory passage")}`}),e.logs.length>0)t.push({kind:"logs",detail:`delete ${K(e.logs.length,"log file")}`})}return t.push({kind:"directory",detail:`delete ${e.dir}`}),t}function Ps(e){let t=e.footprint,s=[{label:"directory",value:`${e.dir}`,note:`${K(e.files.count,"file")}, ${oA(e.files.bytes)}`}];if(e.agentId!==e.ref)s.push({label:"manifest id",value:e.agentId,note:"keys the store, logs and service"});if(e.filesOnly)s.push({label:"keeping",value:`${K(t.sessions,"conversation")}, ${K(t.passages,"memory passage")}, and the logs`,note:"--files-only"});else s.push({label:"sessions",value:`${K(t.sessions,"conversation")}, ${K(t.messages,"message")}, ${K(t.turns,"turn")}`},{label:"memory",value:`${K(t.passages,"passage")} from ${K(t.memorySources,"source")}`},{label:"outbox",value:t.outbox===0?"nothing queued":`${K(t.outbox,"delivery")}${t.outboxPending===0?"":`, ${t.outboxPending} not yet sent`}`,...t.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:t.schedules===0?"none":K(t.schedules,"schedule"),...t.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${K(e.logs.length,"file")}, ${oA(e.logs.reduce((i,r)=>i+r.bytes,0))}`},{label:"service",value:e.service??"not installed"});return s.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),p(s)}function Rs(e){if(e.length===0)return"";return e.map((t)=>{let s=t.footprint,i=[];if(s.sessions>0)i.push(`${K(s.sessions,"conversation")}, ${K(s.messages,"message")}`);if(s.passages>0)i.push(`${K(s.passages,"memory passage")}`);if(s.outbox>0)i.push(`${K(s.outbox,"queued delivery")}`);if(s.schedules>0)i.push(`${K(s.schedules,"schedule")}`);if(s.lease)i.push("a stale lease");if(t.logs.length>0)i.push(`${K(t.logs.length,"log file")}, ${oA(t.logs.reduce((r,a)=>r+a.bytes,0))}`);return` ${t.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
|
|
150
|
+
`)}function K(e,t){return`${e} ${t}${e===1?"":"s"}`}import{homedir as Ua}from"node:os";var Ts=12000,Ma=250;async function vn(e){if(e.manifestPath!==void 0)return await Da(e,e.manifestPath);return await Ha(e)}async function Da(e,t){let s=qa(t),i=[];if(e.dryRun===!0){let l=await We(s,e.store);return process.stdout.write(`would stop 1 agent:
|
|
151
|
+
${D(`${s} — ${l===void 0?"not running; would be switched off for the next start":l.baseUrl===void 0?`pid ${l.pid} (${l.mode}), which serves no HTTP — would be signalled`:`pid ${l.pid} (${l.mode}) at ${l.baseUrl}, which would drop it and keep serving`}`)}
|
|
152
|
+
`),o}await rr(s,!1,e.reason,e.store),i.push("switched off for the next start");let r=await We(s,e.store),a=!0;if(r===void 0)i.push("nothing was running");else if(r.baseUrl===void 0){let l=await $n(r.pid,"SIGTERM");a=l||await $n(r.pid,"SIGKILL",!0),i.push(l?`pid ${r.pid} stopped cleanly`:a?`pid ${r.pid} had to be killed`:`pid ${r.pid} would not stop — check it by hand`)}else{let l=await ft(r,`/v1/agents/${encodeURIComponent(s)}/stop`,e.reason===void 0?{}:{reason:e.reason},t);if(l.ok)i.push(`pid ${r.pid} dropped it and kept serving`);else if(l.status===409)a=!1,i.push(l.detail??"a turn is running");else if(l.status===401)a=!1,i.push(`pid ${r.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${r.pid} at ${r.baseUrl} could not be reached${l.detail===void 0?"":`: ${l.detail}`}`)}let d={agentId:s,service:!1,...r===void 0?{}:{pid:r.pid,mode:r.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[d]},null,2)}
|
|
153
|
+
`);else process.stdout.write(`${p([{label:s,value:a?"stopped":"NOT FULLY STOPPED",note:d.note}])}
|
|
154
154
|
`),process.stdout.write(`
|
|
155
|
-
Stays off across restarts. \`${
|
|
156
|
-
`);return a?o:
|
|
155
|
+
Stays off across restarts. \`${A.slug} start ${s}\` switches it back on.
|
|
156
|
+
`);return a?o:E}async function Ha(e){let t=e.platform??process.platform,s=t==="darwin"?rn(t,{home:Ua(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await Wa(s,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
|
|
157
157
|
`:`Nothing is running — no service is installed and no process holds an agent.
|
|
158
158
|
`),o;if(e.dryRun===!0)return process.stdout.write(`would stop ${i.length} ${i.length===1?"agent":"agents"}:
|
|
159
|
-
${i.map((a)=>
|
|
159
|
+
${i.map((a)=>D(Ba(a))).join(`
|
|
160
160
|
`)}
|
|
161
|
-
`),o;let
|
|
162
|
-
`);else{let a=
|
|
163
|
-
`),
|
|
161
|
+
`),o;let r=[];for(let a of i)r.push(await Ga(a,s));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:r},null,2)}
|
|
162
|
+
`);else{let a=r.map((d)=>({label:xs(d.agentId),value:d.stopped?"stopped":"STILL RUNNING",note:d.note}));if(process.stdout.write(`${p(a)}
|
|
163
|
+
`),r.some((d)=>d.service&&d.stopped))process.stdout.write(`
|
|
164
164
|
Services are disabled as well as unloaded, so they stay stopped across a reboot.
|
|
165
|
-
Start one again with \`${
|
|
166
|
-
`);if(
|
|
165
|
+
Start one again with \`${A.slug} daemon start <agent>\`.
|
|
166
|
+
`);if(r.some((d)=>d.forced===!0))process.stdout.write(`
|
|
167
167
|
Something had to be killed rather than asked. A forced stop skips the runtime's own
|
|
168
168
|
cleanup, so a command the agent had left running in the background may still be alive —
|
|
169
169
|
\`ps\` will show it if so.
|
|
170
|
-
`)}return
|
|
171
|
-
${
|
|
170
|
+
`)}return r.every((a)=>a.stopped)?o:E}async function Wa(e,t){let s=`${A.slug}.agent.`,i=new Map;for(let r of e?.labels(s)??[]){let a=r.slice(s.length);i.set(a,{agentId:a,service:!0})}try{let r=await re.open({path:t??G()});for(let a of await r.leases.all()){if(a.pid===process.pid||!ee(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await r.close()}catch{}return[...i.values()].sort((r,a)=>r.agentId.localeCompare(a.agentId))}async function Ga(e,t){let s=[];if(e.service&&t!==void 0)try{t.stop(tr(A.slug,e.agentId)),s.push("service disabled and unloaded")}catch(a){s.push(`service could not be unloaded: ${a instanceof Error?a.message:String(a)}`)}if(e.pid===void 0)return{...e,stopped:!0,note:s.join(" · ")||"no process was running"};if(!ee(e.pid))return{...e,stopped:!0,note:s.join(" · ")||`pid ${e.pid} exited`};if(await $n(e.pid,"SIGTERM"))return s.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:s.join(" · ")};let r=await $n(e.pid,"SIGKILL",!0);return s.push(r?`pid ${e.pid} did not stop in ${Math.round(Ts/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:r,forced:!0,note:s.join(" · ")}}async function $n(e,t,s=!1){try{process.kill(s?-e:e,t)}catch(r){if(r.code==="ESRCH")return!0;if(s)try{process.kill(e,t)}catch{return!ee(e)}}let i=Date.now()+(t==="SIGKILL"?3000:Ts);while(Date.now()<i){if(!ee(e))return!0;await new Promise((r)=>setTimeout(r,Ma))}return!ee(e)}function Ba(e){let t=[];if(e.service)t.push("background service");if(e.pid!==void 0)t.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${xs(e.agentId)} — ${t.join(", ")}`}function xs(e){return e===Ut?"(host, no agents)":e}function qa(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_stop_agent_id_missing",message:`${e} declares no id, so there is nothing to match a running agent against.`,hint:`Add \`id: <name>\` to the manifest, or run \`${A.slug} stop\` with no argument to stop everything.`});return t.id}async function js(e){let t=await re.open({path:e.store??G()});try{if(e.prune===!0)return await Ya(e,t);if(e.all===!0)return await za(e,t);if(e.ref===void 0)throw new n({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${A.slug} remove <name>\` takes a sandbox agent's name — the ones \`${A.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await Xa(e.ref,e,t)}finally{await t.close()}}async function Xa(e,t,s){let i=await Ls(e,t,s),r=Ss(i);if(r.length>0){let l=r[0];throw new n({code:l.code,message:l.message,hint:l.hint})}let a=ks(i),d=`${L(`removing ${e} will:`,!0)}
|
|
171
|
+
${Ps(i)}
|
|
172
172
|
|
|
173
|
-
${a.map((
|
|
173
|
+
${a.map((l)=>D(l.detail)).join(`
|
|
174
174
|
`)}
|
|
175
|
-
`;if(
|
|
176
|
-
`:`${
|
|
175
|
+
`;if(t.dryRun===!0)return process.stdout.write(t.json===!0?`${JSON.stringify({ref:e,agentId:i.agentId,steps:a,footprint:i.footprint},null,2)}
|
|
176
|
+
`:`${d}
|
|
177
177
|
Nothing was deleted — this was --dry-run.
|
|
178
|
-
`),o;if(process.stdout.write(
|
|
178
|
+
`),o;if(process.stdout.write(d),!await tt(t,e,"type the agent's name to confirm:"))return process.stdout.write(`
|
|
179
179
|
Nothing was deleted.
|
|
180
|
-
`),o;return await
|
|
180
|
+
`),o;return await Fs(i,t,s)}async function Fs(e,t,s){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await vn({manifestPath:e.manifestPath,...t.exec===void 0?{}:{exec:t.exec},...t.platform===void 0?{}:{platform:t.platform}})!==o)return process.stderr.write(`
|
|
181
181
|
Stopping ${e.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
|
|
182
|
-
hint: check what is still running with \`${
|
|
183
|
-
`),
|
|
182
|
+
hint: check what is still running with \`${A.slug} stop --dry-run\`, then run remove again.
|
|
183
|
+
`),E;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let r=Us(t);try{r?.uninstall(e.service),i.push({label:"service",value:`${e.service} removed`})}catch(a){i.push({label:"service",value:`${e.service} could NOT be removed`,note:a instanceof Error?a.message:String(a)})}}if(!e.filesOnly){let r=await s.purgeAgent(e.agentId);i.push({label:"store",value:`${r.sessions} conversation(s), ${r.messages} message(s), ${r.passages} passage(s)`});for(let a of e.logs)nt(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(nt(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),t.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
|
|
184
184
|
`),o;if(process.stdout.write(`
|
|
185
185
|
${e.ref} removed.
|
|
186
|
-
${
|
|
186
|
+
${p(i)}
|
|
187
187
|
`),e.filesOnly)process.stdout.write(`
|
|
188
188
|
Its sessions and memory are still in the store under the id "${e.agentId}", which another agent shares.
|
|
189
|
-
`);return o}async function
|
|
190
|
-
`),o;if(process.stdout.write(`${
|
|
191
|
-
${
|
|
189
|
+
`);return o}async function za(e,t){let s=oe();if(s.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
|
|
190
|
+
`),o;if(process.stdout.write(`${L(`removing every agent in ${W()}:`,!0)}
|
|
191
|
+
${s.map((r)=>D(`${r.ref}${r.id===void 0||r.id===r.ref?"":` (id ${r.id})`}`)).join(`
|
|
192
192
|
`)}
|
|
193
193
|
`),e.dryRun===!0)return process.stdout.write(`
|
|
194
194
|
Nothing was deleted — this was --dry-run.
|
|
195
|
-
`),o;if(!await
|
|
195
|
+
`),o;if(!await tt(e,"all",`type \`all\` to remove all ${s.length}:`))return process.stdout.write(`
|
|
196
196
|
Nothing was deleted.
|
|
197
|
-
`),o;let i=o;for(let
|
|
198
|
-
`:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${
|
|
199
|
-
`),o;if(process.stdout.write(`${
|
|
200
|
-
${
|
|
197
|
+
`),o;let i=o;for(let r of s){let a=await Ls(r.ref,e,t),d=await Fs({...a,sharesIdWith:[]},e,t);if(d!==o)i=d}return i}async function Ya(e,t){let s=new Set(oe().map((d)=>d.id??d.ref).filter((d)=>d!=="")),i=new Set((await t.agentIds()).filter((d)=>!s.has(d)));for(let d of Za())if(!s.has(d))i.add(d);let r=[];for(let d of[...i].sort())r.push({agentId:d,footprint:await t.agentFootprint(d),logs:Ms(d)});if(r.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
|
|
198
|
+
`:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${W()}.
|
|
199
|
+
`),o;if(process.stdout.write(`${L("no sandbox directory claims these:",!0)}
|
|
200
|
+
${Rs(r)}
|
|
201
201
|
`),e.dryRun===!0)return process.stdout.write(`
|
|
202
202
|
Nothing was deleted — this was --dry-run.
|
|
203
|
-
`),o;if(!await
|
|
203
|
+
`),o;if(!await tt(e,"prune","type `prune` to delete them:"))return process.stdout.write(`
|
|
204
204
|
Nothing was deleted.
|
|
205
|
-
`),o;let a=[];for(let
|
|
205
|
+
`),o;let a=[];for(let d of r){let l=await t.purgeAgent(d.agentId);for(let u of d.logs)nt(u.path,{force:!0});a.push({label:d.agentId,value:`${l.sessions} conversation(s), ${l.passages} passage(s), ${d.logs.length} log file(s)`})}return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:r.map((d)=>d.agentId)},null,2)}
|
|
206
206
|
`:`
|
|
207
|
-
pruned ${
|
|
208
|
-
${
|
|
209
|
-
`),o}async function
|
|
210
|
-
`);else process.stdout.write(`${
|
|
211
|
-
`);return a}import{randomBytes as
|
|
212
|
-
`));if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.details=e.details??[],this.status=n.status,this.request=n.method===void 0||n.path===void 0?void 0:{method:n.method,path:n.path},n.cause!==void 0)this.cause=n.cause}}function Xa(e,n){let r=e instanceof Error?e.message:String(e);return new ge({code:"transport_failed",message:`${n.method} ${n.path} did not reach ${n.baseUrl}: ${r}`,hint:"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe."},{...n,cause:e})}async function za(e,n){let r;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")r={code:i.error.code,message:i.error.message,...i.error.hint===void 0?{}:{hint:i.error.hint},...i.error.field===void 0?{}:{field:i.error.field}}}catch{}return new ge(r??{code:`http_${e.status}`,message:`${n.method} ${n.path} returned ${e.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:e.status,...n})}var Wr=new Set(Jt);async function*Br(e){for await(let n of Er(Ya(e))){if(n.event===void 0||n.data==="")continue;let r;try{r=JSON.parse(n.data)}catch{continue}yield{name:n.event,data:r}}}async function*Ya(e){let n=e.getReader();try{while(!0){let{done:r,value:i}=await n.read();if(r)return;if(i!==void 0)yield i}}finally{n.releaseLock()}}async function*Qa(e){for await(let{name:n,data:r}of Br(e)){if(Wr.has(n)){yield{kind:"event",event:r};continue}let i=r??{};switch(n){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*Za(e){for await(let{name:n,data:r}of Br(e)){if(Wr.has(n)){yield{kind:"event",event:r};continue}if(n==="stream.subscribed"){let i=r??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*ed(e,n={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&n.allowTruncated!==!0)throw new ge({code:"replay_truncated",message:`This turn's replay is missing its oldest ${r.report.dropped} event(s), so the text reconstructed from it would be incomplete.`,hint:"Read the finished text from GET /v1/agents/:id/turns/:turnId, or pass { allowTruncated: true } to accept a fragment. Streaming from the start of a turn is never truncated — this only happens when reattaching to one that has already produced more events than the buffer holds."});if(r.kind==="unavailable")throw new ge({code:"turn_not_observable",message:`Turn ${r.turnId} is recorded as running but is not observable here: ${r.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(r.kind!=="event")continue;if(r.event.type!=="model.chunk")continue;let i=r.event.data;if(i.kind==="reasoning")continue;if(typeof i.delta==="string")yield i.delta}}function qr(e){let n=e.baseUrl.length;while(n>0&&e.baseUrl[n-1]==="/")n-=1;let r=e.baseUrl.slice(0,n),i=e.fetch??fetch,s=(f={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...f});async function a(f,h,g={}){let b;try{b=await i(`${r}${h}`,{method:f,headers:s({...g.body===void 0?{}:{"content-type":"application/json"},...g.accept===void 0?{}:{accept:g.accept},...g.headers}),...g.body===void 0?{}:{body:JSON.stringify(g.body)},...g.signal===void 0?{}:{signal:g.signal}})}catch(T){throw Xa(T,{method:f,path:h,baseUrl:r})}if(!b.ok)throw await za(b,{method:f,path:h});return b}async function l(f,h,g){return await(await a(f,h,g??{})).json()}async function c(f,h){let g=await a("GET",f,{accept:"text/event-stream",...h===void 0?{}:{signal:h}});if(g.body===null)throw new ge({code:"no_response_body",message:`GET ${f} returned ${g.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:g.status,method:"GET",path:f});return g.body}function m(f,h,g,b={}){let T=(S)=>{let L=new URLSearchParams;if(S?.chunks===!0)L.set("chunks","true");if(S?.children===!0)L.set("children","true");let G=L.toString();return G===""?"":`?${G}`},x={turnId:h,sessionKey:g,replayed:b.replayed===!0,async*stream(S){let L=await c(`/v1/agents/${encodeURIComponent(f)}/turns/${encodeURIComponent(h)}/stream${T(S)}`,S?.signal);yield*Qa(L)},async*tokens(S){yield*ed(x.stream({chunks:!0,...S,children:!1}),{...S?.allowTruncated===void 0?{}:{allowTruncated:S.allowTruncated}})},async text(){for await(let S of x.stream()){if(S.kind==="ended")break;if(S.kind==="unavailable")break;if(S.kind==="event"&&S.event.type==="turn.end")break}return(await x.get()).text},get:()=>l("GET",`/v1/agents/${encodeURIComponent(f)}/turns/${encodeURIComponent(h)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(f)}/turns/${encodeURIComponent(h)}/stop`)}};return x}function w(f){let h=(g)=>`/v1/agents/${encodeURIComponent(f)}${g}`;return{id:f,async send(g,b){let T=await l("POST",h("/messages"),{body:{text:g,...b?.sessionKey===void 0?{}:{sessionKey:b.sessionKey},...b?.deliver===void 0?{}:{deliver:b.deliver},...b?.from===void 0?{}:{from:b.from},...b?.images===void 0?{}:{images:b.images},...b?.runtimeNote===void 0?{}:{runtimeNote:b.runtimeNote},...b?.chunks===!0?{chunks:!0}:{},...b?.role===void 0?{}:{role:b.role}},...b?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":b.idempotencyKey}},...b?.signal===void 0?{}:{signal:b.signal}});return m(f,T.turnId,T.sessionKey,{replayed:T.replayed===!0})},turn:(g)=>m(f,g,""),describe:()=>l("GET",h("")),tools:()=>l("GET",h("/tools")),skills:()=>l("GET",h("/skills")),sessions:()=>l("GET",h("/sessions")),messages:(g,b)=>{let T=new URLSearchParams;if(b?.before!==void 0)T.set("before",String(b.before));if(b?.limit!==void 0)T.set("limit",String(b.limit));let x=T.size===0?"":`?${T.toString()}`;return l("GET",h(`/sessions/${encodeURIComponent(g)}/messages${x}`))},clearSession:(g)=>l("DELETE",h(`/sessions/${encodeURIComponent(g)}`)),reload:()=>l("POST",h("/reload"),{body:{}}),usage:(g)=>l("GET",h(`/usage${Gr(g)}`)),turns:(g)=>{let b=new URLSearchParams;if(g?.limit!==void 0)b.set("limit",String(g.limit));if(g?.before!==void 0)b.set("before",String(g.before));let T=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/turns${T}`))},secrets:async()=>(await l("GET",h("/secrets"))).secrets,setSecrets:(g)=>l("PUT",h("/secrets"),{body:{values:g}}),schedules:async()=>(await l("GET",h("/schedules"))).schedules,approvals:async()=>(await l("GET",h("/approvals"))).approvals,createSchedule:(g)=>l("POST",h("/schedules"),{body:g}),updateSchedule:(g,b)=>l("PATCH",h(`/schedules/${encodeURIComponent(g)}`),{body:b}),deleteSchedule:async(g)=>{await l("DELETE",h(`/schedules/${encodeURIComponent(g)}`))},refreshTools:(g)=>l("POST",h("/tools/refresh"),{body:g?.providers===void 0?{}:{providers:g.providers}}),previewSchedule:(g)=>{let b=new URLSearchParams({kind:g.kind,expr:g.expr});if(g.timezone!==void 0)b.set("timezone",g.timezone);if(g.count!==void 0)b.set("count",String(g.count));return l("GET",h(`/schedules/preview?${b.toString()}`))},runSchedule:(g)=>l("POST",h(`/schedules/${encodeURIComponent(g)}/run`),{body:{}}),config:()=>l("GET",h("/config")),setConfig:(g,b,T)=>l("PATCH",h("/config"),{body:{path:g,value:b,...T?.confirm===void 0?{}:{confirm:T.confirm}}}),removeConfig:(g,b)=>l("PATCH",h("/config"),{body:{path:g,remove:!0,...b?.confirm===void 0?{}:{confirm:b.confirm}}}),setConfigs:(g)=>l("PATCH",h("/config"),{body:{changes:g.map((b)=>({...b}))}}),setChannel:(g,b)=>l("PATCH",h(`/channels/${encodeURIComponent(g)}`),{body:{...b}}),unpairChannel:(g)=>l("POST",h(`/channels/${encodeURIComponent(g)}/unpair`)),session:(g)=>l("GET",h(`/sessions/${encodeURIComponent(g)}`)),setPhase:(g,b)=>l("POST",h(`/sessions/${encodeURIComponent(g)}/phase`),{body:{phase:b}}),setRecall:(g,b)=>l("POST",h(`/sessions/${encodeURIComponent(g)}/recall`),{body:{recall:b}}),resolveSessionKey:async(g)=>(await l("POST",h("/sessions/resolve"),{body:{sessionKey:g}})).sessionKey,compactSession:(g,b)=>l("POST",h(`/sessions/${encodeURIComponent(g)}/compact`),{body:b?.keepTurns===void 0?{}:{keepTurns:b.keepTurns}}),rotateSession:(g)=>l("POST",h("/sessions/rotate"),{body:g?.from===void 0?{}:{from:g.from}}),approve:async(g,b)=>{await l("POST",h(`/approvals/${encodeURIComponent(g)}`),{body:{granted:b}})},stop:(g)=>l("POST",h("/stop"),{body:g===void 0?{}:{reason:g}}),start:()=>l("POST",h("/start"),{body:{}}),assign:(g)=>l("PUT",h("/assignee"),{body:{participantId:g}}),unassign:()=>l("DELETE",h("/assignee")),assignment:()=>l("GET",h("/assignee")),workspaceFiles:()=>l("GET",h("/workspace")),workspaceFile:(g)=>l("GET",h(`/workspace/${encodeURIComponent(g)}`)),putWorkspaceFile:(g,b)=>l("PUT",h(`/workspace/${encodeURIComponent(g)}`),{body:{content:b}}),exportBundle:(g)=>l("GET",h(`/export${g===void 0?"":`?paths=${encodeURIComponent(g.join(","))}`}`)),importBundle:(g,b)=>l("POST",h("/import"),{body:{bundle:g,...b===void 0?{}:{mode:b}}}),setVars:(g)=>l("PATCH",h("/vars"),{body:{vars:g}}),vars:()=>l("GET",h("/vars")),deliver:(g)=>l("POST",h("/deliveries"),{body:g}),context:(g)=>{let b=new URLSearchParams;if(g?.sessionKey!==void 0)b.set("sessionKey",g.sessionKey);if(g?.input!==void 0)b.set("input",g.input);let T=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/context${T}`))}}}return{agent:w,agents:()=>l("GET","/v1/agents"),health:()=>l("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(f){if(f instanceof ge&&f.status===503)return!1;throw f}},provision:()=>l("GET","/v1/provision"),keys:()=>l("GET","/v1/keys"),createKey:(f)=>l("POST","/v1/keys",{body:f}),revokeKey:(f)=>l("DELETE",`/v1/keys/${encodeURIComponent(f)}`),deleteAgent:(f,h)=>l("DELETE",`/v1/agents/${encodeURIComponent(f)}?confirm=${encodeURIComponent(h)}`),backup:async(f)=>(await a("GET",`/v1/backup${f===void 0||f.length===0?"":`?include=${f.join(",")}`}`,{accept:"application/gzip"})).blob(),deleteParticipant:(f)=>l("DELETE",`/v1/participants/${encodeURIComponent(f)}`),createAgent:(f)=>l("POST","/v1/agents",{body:{answers:f}}),usage:(f)=>l("GET",`/v1/usage${Gr(f)}`),activity:()=>l("GET","/v1/activity"),participants:async()=>(await l("GET","/v1/participants")).participants,registerParticipant:(f)=>l("POST","/v1/participants",{body:f}),conversations:async()=>(await l("GET","/v1/conversations")).conversations,createConversation:(f)=>l("POST","/v1/conversations",{body:f}),conversation:(f)=>l("GET",`/v1/conversations/${encodeURIComponent(f)}`),setMembers:(f,h)=>l("PATCH",`/v1/conversations/${encodeURIComponent(f)}/members`,{body:h}),postMessage:(f,h)=>l("POST",`/v1/conversations/${encodeURIComponent(f)}/messages`,{body:h}),conversationMessages:(f,h={})=>{let g=new URLSearchParams;if(h.after!==void 0)g.set("after",String(h.after));if(h.limit!==void 0)g.set("limit",String(h.limit));let b=g.size===0?"":`?${g}`;return l("GET",`/v1/conversations/${encodeURIComponent(f)}/messages${b}`)},setPresence:(f,h)=>l("PUT",`/v1/participants/${encodeURIComponent(f)}/presence`,{body:{presence:h}}),actions:async(f={})=>(await l("GET",`/v1/actions${f.status===void 0?"":`?status=${f.status}`}`)).actions,decideAction:(f,h)=>l("POST",`/v1/actions/${encodeURIComponent(f)}`,{body:{approve:h}}),addNote:(f)=>l("POST","/v1/memory/notes",{body:f}),notes:async(f)=>(await l("GET",`/v1/memory/notes?scope=${encodeURIComponent(f)}`)).notes,deleteNote:(f)=>l("DELETE",`/v1/memory/notes/${encodeURIComponent(f)}`),memoryReads:async(f)=>(await l("GET",`/v1/participants/${encodeURIComponent(f)}/memory/reads`)).reads,projects:async()=>(await l("GET","/v1/projects")).projects,putProject:(f,h)=>l("PUT",`/v1/projects/${encodeURIComponent(f)}`,{body:h}),deleteProject:(f)=>l("DELETE",`/v1/projects/${encodeURIComponent(f)}`),setSpaceWriter:(f)=>l("PUT","/v1/memory/space/writer",{body:{writer:f}}),webhooks:async()=>(await l("GET","/v1/webhooks")).webhooks,createWebhook:(f)=>l("POST","/v1/webhooks",{body:f}),deleteWebhook:(f)=>l("DELETE",`/v1/webhooks/${encodeURIComponent(f)}`),templates:async()=>(await l("GET","/v1/templates")).templates,createAgentFromTemplate:(f)=>l("POST","/v1/agents",{body:f}),async*events(f){let h=new URLSearchParams;if(f?.agentId!==void 0)h.set("agentId",f.agentId);if(f?.types!==void 0&&f.types.length>0)h.set("types",f.types.join(","));if(f?.chunks===!0)h.set("chunks","true");let g=h.size===0?"":`?${h.toString()}`,b=await c(`/v1/events${g}`,f?.signal);yield*Za(b)}}}function Gr(e){let n=new URLSearchParams;if(e?.by!==void 0)n.set("by",e.by.join(","));if(e?.from!==void 0)n.set("from",e.from);if(e?.to!==void 0)n.set("to",e.to);return n.size===0?"":`?${n.toString()}`}function Ke(e,n){let r=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let s=hi(i,n);if(s==="")continue;r.push({role:i.role,text:s})}return r}function Vr(e){let n=e.ref??"<your agent>",r=`${t.slug} run ${n} --session ${e.sessionKey}`;return`
|
|
207
|
+
pruned ${r.length} agent id(s).
|
|
208
|
+
${p(a)}
|
|
209
|
+
`),o}async function Ls(e,t,s){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new n({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${W()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${A.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let i=oe(),r=i.find((m)=>m.ref===e);if(r===void 0){let m=i.map((y)=>y.ref);throw new n({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${m.length===0?", which is empty":""}.`,hint:m.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${m.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=r.id;if(a===void 0)try{a=U(r.manifestPath).id}catch{}let d=t.filesOnly===!0||a===void 0,l=a??e,u=await s.agentFootprint(l),g=u.lease?await s.leases.get(l):void 0,c=Us(t),f=tr(A.slug,l);return{ref:e,agentId:l,manifestPath:r.manifestPath,dir:r.dir,files:Qa(r.dir),footprint:u,logs:Ms(l),sharesIdWith:i.filter((m)=>m.ref!==e&&(m.id??"")===l).map((m)=>m.ref),...g!==void 0&&ee(g.pid)?{running:{pid:g.pid,mode:g.mode}}:{},...c?.state(f).installed===!0?{service:f}:{},filesOnly:d}}function Us(e){let t=e.platform??process.platform;if(t!=="darwin")return;return rn(t,{home:Ja(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function Qa(e){let t=0,s=0,i=(r)=>{let a;try{a=Os(r)}catch{return}for(let d of a){let l=Ns(r,d);try{let u=_s(l);if(u.isDirectory()){i(l);continue}t+=1,s+=u.size}catch{}}};return i(e),{count:t,bytes:s}}function Ms(e){let t=pn(e),s=[];for(let i of[t.out,t.err])try{if(!Va(i))continue;s.push({path:i,bytes:_s(i).size})}catch{}return s}function Za(){let e;try{e=Os(Ns(Oe(),"logs"))}catch{return[]}let t=new Set;for(let s of e)for(let i of[".out.log",".err.log"])if(s.endsWith(i))t.add(s.slice(0,-i.length));return[...t]}async function tt(e,t,s){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(s,t)}async function Ds(e){if(e.manifestPath===void 0)return await Ft({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let t=De(e.manifestPath),s=await NA(e.manifestPath,e.store),i,r,a=o;switch(s.kind){case"reloaded":i="reloaded",r=`pid ${s.pid} rebuilt it from disk${s.adopted.length>0?` · adopted ${s.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",r=`pid ${s.pid} applies it when its ${s.running} running turn(s) finish`;break;case"busy":i="not reloaded",r=`pid ${s.pid} has a turn in flight — try again when it finishes`,a=E;break;case"failed":i="not reloaded",r=`pid ${s.pid} answered ${s.status}${s.detail===void 0?"":`: ${s.detail}`}${s.hint===void 0?"":` — ${s.hint}`}`,a=E;break;case"no-host":{let d=await ze(e.store);if(d===void 0)throw new n({code:"cli_restart_nothing_running",message:`Nothing is hosting ${t}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${t}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${t}\` reloads it in place.`});let l=await OA(d,e.manifestPath,e.store);if(l.ok)i="started",r=`nothing was hosting it — adopted by pid ${d.pid}`;else i="not started",r=`pid ${d.pid} did not adopt it${l.detail===void 0?"":`: ${l.detail}`}`,a=E;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:t,result:s,ok:a===o},null,2)}
|
|
210
|
+
`);else process.stdout.write(`${p([{label:t,value:i,note:r}])}
|
|
211
|
+
`);return a}import{randomBytes as ot}from"node:crypto";import{existsSync as ad}from"node:fs";import{resolve as Zs}from"node:path";import{createInterface as no}from"node:readline";class me extends Error{code;hint;field;details;status;request;constructor(e,t={}){super([e.message,...(e.details??[]).map((s)=>` - ${s.field===void 0?"":`${s.field}: `}${s.message}`),...e.hint===void 0?[]:[` hint: ${e.hint}`]].join(`
|
|
212
|
+
`));if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.details=e.details??[],this.status=t.status,this.request=t.method===void 0||t.path===void 0?void 0:{method:t.method,path:t.path},t.cause!==void 0)this.cause=t.cause}}function ed(e,t){let s=e instanceof Error?e.message:String(e);return new me({code:"transport_failed",message:`${t.method} ${t.path} did not reach ${t.baseUrl}: ${s}`,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."},{...t,cause:e})}async function nd(e,t){let s;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")s={code:i.error.code,message:i.error.message,...i.error.hint===void 0?{}:{hint:i.error.hint},...i.error.field===void 0?{}:{field:i.error.field}}}catch{}return new me(s??{code:`http_${e.status}`,message:`${t.method} ${t.path} returned ${e.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:e.status,...t})}var Gs=new Set(Jt);async function*Bs(e){for await(let t of Er(td(e))){if(t.event===void 0||t.data==="")continue;let s;try{s=JSON.parse(t.data)}catch{continue}yield{name:t.event,data:s}}}async function*td(e){let t=e.getReader();try{while(!0){let{done:s,value:i}=await t.read();if(s)return;if(i!==void 0)yield i}}finally{t.releaseLock()}}async function*rd(e){for await(let{name:t,data:s}of Bs(e)){if(Gs.has(t)){yield{kind:"event",event:s};continue}let i=s??{};switch(t){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*sd(e){for await(let{name:t,data:s}of Bs(e)){if(Gs.has(t)){yield{kind:"event",event:s};continue}if(t==="stream.subscribed"){let i=s??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*od(e,t={}){for await(let s of e){if(s.kind==="replay"&&s.report.truncated&&t.allowTruncated!==!0)throw new me({code:"replay_truncated",message:`This turn's replay is missing its oldest ${s.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(s.kind==="unavailable")throw new me({code:"turn_not_observable",message:`Turn ${s.turnId} is recorded as running but is not observable here: ${s.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(s.kind!=="event")continue;if(s.event.type!=="model.chunk")continue;let i=s.event.data;if(i.kind==="reasoning")continue;if(typeof i.delta==="string")yield i.delta}}function qs(e){let t=e.baseUrl.length;while(t>0&&e.baseUrl[t-1]==="/")t-=1;let s=e.baseUrl.slice(0,t),i=e.fetch??fetch,r=(c={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...c});async function a(c,f,m={}){let y;try{y=await i(`${s}${f}`,{method:c,headers:r({...m.body===void 0?{}:{"content-type":"application/json"},...m.accept===void 0?{}:{accept:m.accept},...m.headers}),...m.body===void 0?{}:{body:JSON.stringify(m.body)},...m.signal===void 0?{}:{signal:m.signal}})}catch(R){throw ed(R,{method:c,path:f,baseUrl:s})}if(!y.ok)throw await nd(y,{method:c,path:f});return y}async function d(c,f,m){return await(await a(c,f,m??{})).json()}async function l(c,f){let m=await a("GET",c,{accept:"text/event-stream",...f===void 0?{}:{signal:f}});if(m.body===null)throw new me({code:"no_response_body",message:`GET ${c} returned ${m.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:m.status,method:"GET",path:c});return m.body}function u(c,f,m,y={}){let R=(b)=>{let N=new URLSearchParams;if(b?.chunks===!0)N.set("chunks","true");if(b?.children===!0)N.set("children","true");let M=N.toString();return M===""?"":`?${M}`},T={turnId:f,sessionKey:m,replayed:y.replayed===!0,async*stream(b){let N=await l(`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stream${R(b)}`,b?.signal);yield*rd(N)},async*tokens(b){yield*od(T.stream({chunks:!0,...b,children:!1}),{...b?.allowTruncated===void 0?{}:{allowTruncated:b.allowTruncated}})},async text(){for await(let b of T.stream()){if(b.kind==="ended")break;if(b.kind==="unavailable")break;if(b.kind==="event"&&b.event.type==="turn.end")break}return(await T.get()).text},get:()=>d("GET",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stop`)}};return T}function g(c){let f=(m)=>`/v1/agents/${encodeURIComponent(c)}${m}`;return{id:c,async send(m,y){let R=await d("POST",f("/messages"),{body:{text:m,...y?.sessionKey===void 0?{}:{sessionKey:y.sessionKey},...y?.deliver===void 0?{}:{deliver:y.deliver},...y?.from===void 0?{}:{from:y.from},...y?.images===void 0?{}:{images:y.images},...y?.runtimeNote===void 0?{}:{runtimeNote:y.runtimeNote},...y?.chunks===!0?{chunks:!0}:{},...y?.role===void 0?{}:{role:y.role}},...y?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":y.idempotencyKey}},...y?.signal===void 0?{}:{signal:y.signal}});return u(c,R.turnId,R.sessionKey,{replayed:R.replayed===!0})},turn:(m)=>u(c,m,""),describe:()=>d("GET",f("")),tools:()=>d("GET",f("/tools")),skills:()=>d("GET",f("/skills")),sessions:()=>d("GET",f("/sessions")),messages:(m,y)=>{let R=new URLSearchParams;if(y?.before!==void 0)R.set("before",String(y.before));if(y?.limit!==void 0)R.set("limit",String(y.limit));let T=R.size===0?"":`?${R.toString()}`;return d("GET",f(`/sessions/${encodeURIComponent(m)}/messages${T}`))},clearSession:(m)=>d("DELETE",f(`/sessions/${encodeURIComponent(m)}`)),reload:()=>d("POST",f("/reload"),{body:{}}),usage:(m)=>d("GET",f(`/usage${Ws(m)}`)),turns:(m)=>{let y=new URLSearchParams;if(m?.limit!==void 0)y.set("limit",String(m.limit));if(m?.before!==void 0)y.set("before",String(m.before));let R=y.size===0?"":`?${y.toString()}`;return d("GET",f(`/turns${R}`))},secrets:async()=>(await d("GET",f("/secrets"))).secrets,setSecrets:(m)=>d("PUT",f("/secrets"),{body:{values:m}}),schedules:async()=>(await d("GET",f("/schedules"))).schedules,approvals:async()=>(await d("GET",f("/approvals"))).approvals,createSchedule:(m)=>d("POST",f("/schedules"),{body:m}),updateSchedule:(m,y)=>d("PATCH",f(`/schedules/${encodeURIComponent(m)}`),{body:y}),deleteSchedule:async(m)=>{await d("DELETE",f(`/schedules/${encodeURIComponent(m)}`))},refreshTools:(m)=>d("POST",f("/tools/refresh"),{body:m?.providers===void 0?{}:{providers:m.providers}}),previewSchedule:(m)=>{let y=new URLSearchParams({kind:m.kind,expr:m.expr});if(m.timezone!==void 0)y.set("timezone",m.timezone);if(m.count!==void 0)y.set("count",String(m.count));return d("GET",f(`/schedules/preview?${y.toString()}`))},runSchedule:(m)=>d("POST",f(`/schedules/${encodeURIComponent(m)}/run`),{body:{}}),config:()=>d("GET",f("/config")),setConfig:(m,y,R)=>d("PATCH",f("/config"),{body:{path:m,value:y,...R?.confirm===void 0?{}:{confirm:R.confirm}}}),removeConfig:(m,y)=>d("PATCH",f("/config"),{body:{path:m,remove:!0,...y?.confirm===void 0?{}:{confirm:y.confirm}}}),setConfigs:(m)=>d("PATCH",f("/config"),{body:{changes:m.map((y)=>({...y}))}}),setChannel:(m,y)=>d("PATCH",f(`/channels/${encodeURIComponent(m)}`),{body:{...y}}),unpairChannel:(m)=>d("POST",f(`/channels/${encodeURIComponent(m)}/unpair`)),session:(m)=>d("GET",f(`/sessions/${encodeURIComponent(m)}`)),setPhase:(m,y)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/phase`),{body:{phase:y}}),setRecall:(m,y)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/recall`),{body:{recall:y}}),resolveSessionKey:async(m)=>(await d("POST",f("/sessions/resolve"),{body:{sessionKey:m}})).sessionKey,compactSession:(m,y)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/compact`),{body:y?.keepTurns===void 0?{}:{keepTurns:y.keepTurns}}),rotateSession:(m)=>d("POST",f("/sessions/rotate"),{body:m?.from===void 0?{}:{from:m.from}}),approve:async(m,y)=>{await d("POST",f(`/approvals/${encodeURIComponent(m)}`),{body:{granted:y}})},stop:(m)=>d("POST",f("/stop"),{body:m===void 0?{}:{reason:m}}),start:()=>d("POST",f("/start"),{body:{}}),assign:(m)=>d("PUT",f("/assignee"),{body:{participantId:m}}),unassign:()=>d("DELETE",f("/assignee")),assignment:()=>d("GET",f("/assignee")),workspaceFiles:()=>d("GET",f("/workspace")),workspaceFile:(m)=>d("GET",f(`/workspace/${encodeURIComponent(m)}`)),putWorkspaceFile:(m,y)=>d("PUT",f(`/workspace/${encodeURIComponent(m)}`),{body:{content:y}}),exportBundle:(m)=>d("GET",f(`/export${m===void 0?"":`?paths=${encodeURIComponent(m.join(","))}`}`)),importBundle:(m,y)=>d("POST",f("/import"),{body:{bundle:m,...y===void 0?{}:{mode:y}}}),setVars:(m)=>d("PATCH",f("/vars"),{body:{vars:m}}),vars:()=>d("GET",f("/vars")),deliver:(m)=>d("POST",f("/deliveries"),{body:m}),context:(m)=>{let y=new URLSearchParams;if(m?.sessionKey!==void 0)y.set("sessionKey",m.sessionKey);if(m?.input!==void 0)y.set("input",m.input);let R=y.size===0?"":`?${y.toString()}`;return d("GET",f(`/context${R}`))}}}return{agent:g,agents:()=>d("GET","/v1/agents"),health:()=>d("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(c){if(c instanceof me&&c.status===503)return!1;throw c}},provision:()=>d("GET","/v1/provision"),keys:()=>d("GET","/v1/keys"),createKey:(c)=>d("POST","/v1/keys",{body:c}),revokeKey:(c)=>d("DELETE",`/v1/keys/${encodeURIComponent(c)}`),deleteAgent:(c,f)=>d("DELETE",`/v1/agents/${encodeURIComponent(c)}?confirm=${encodeURIComponent(f)}`),backup:async(c)=>(await a("GET",`/v1/backup${c===void 0||c.length===0?"":`?include=${c.join(",")}`}`,{accept:"application/gzip"})).blob(),deleteParticipant:(c)=>d("DELETE",`/v1/participants/${encodeURIComponent(c)}`),createAgent:(c)=>d("POST","/v1/agents",{body:{answers:c}}),usage:(c)=>d("GET",`/v1/usage${Ws(c)}`),activity:()=>d("GET","/v1/activity"),participants:async()=>(await d("GET","/v1/participants")).participants,registerParticipant:(c)=>d("POST","/v1/participants",{body:c}),conversations:async()=>(await d("GET","/v1/conversations")).conversations,createConversation:(c)=>d("POST","/v1/conversations",{body:c}),conversation:(c)=>d("GET",`/v1/conversations/${encodeURIComponent(c)}`),setMembers:(c,f)=>d("PATCH",`/v1/conversations/${encodeURIComponent(c)}/members`,{body:f}),postMessage:(c,f)=>d("POST",`/v1/conversations/${encodeURIComponent(c)}/messages`,{body:f}),conversationMessages:(c,f={})=>{let m=new URLSearchParams;if(f.after!==void 0)m.set("after",String(f.after));if(f.limit!==void 0)m.set("limit",String(f.limit));let y=m.size===0?"":`?${m}`;return d("GET",`/v1/conversations/${encodeURIComponent(c)}/messages${y}`)},setPresence:(c,f)=>d("PUT",`/v1/participants/${encodeURIComponent(c)}/presence`,{body:{presence:f}}),actions:async(c={})=>(await d("GET",`/v1/actions${c.status===void 0?"":`?status=${c.status}`}`)).actions,decideAction:(c,f)=>d("POST",`/v1/actions/${encodeURIComponent(c)}`,{body:{approve:f}}),addNote:(c)=>d("POST","/v1/memory/notes",{body:c}),notes:async(c)=>(await d("GET",`/v1/memory/notes?scope=${encodeURIComponent(c)}`)).notes,deleteNote:(c)=>d("DELETE",`/v1/memory/notes/${encodeURIComponent(c)}`),memoryReads:async(c)=>(await d("GET",`/v1/participants/${encodeURIComponent(c)}/memory/reads`)).reads,projects:async()=>(await d("GET","/v1/projects")).projects,putProject:(c,f)=>d("PUT",`/v1/projects/${encodeURIComponent(c)}`,{body:f}),deleteProject:(c)=>d("DELETE",`/v1/projects/${encodeURIComponent(c)}`),setSpaceWriter:(c)=>d("PUT","/v1/memory/space/writer",{body:{writer:c}}),webhooks:async()=>(await d("GET","/v1/webhooks")).webhooks,createWebhook:(c)=>d("POST","/v1/webhooks",{body:c}),deleteWebhook:(c)=>d("DELETE",`/v1/webhooks/${encodeURIComponent(c)}`),templates:async()=>(await d("GET","/v1/templates")).templates,createAgentFromTemplate:(c)=>d("POST","/v1/agents",{body:c}),async*events(c){let f=new URLSearchParams;if(c?.agentId!==void 0)f.set("agentId",c.agentId);if(c?.types!==void 0&&c.types.length>0)f.set("types",c.types.join(","));if(c?.chunks===!0)f.set("chunks","true");let m=f.size===0?"":`?${f.toString()}`,y=await l(`/v1/events${m}`,c?.signal);yield*sd(y)}}}function Ws(e){let t=new URLSearchParams;if(e?.by!==void 0)t.set("by",e.by.join(","));if(e?.from!==void 0)t.set("from",e.from);if(e?.to!==void 0)t.set("to",e.to);return t.size===0?"":`?${t.toString()}`}function _e(e,t){let s=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let r=Ci(i,t);if(r==="")continue;s.push({role:i.role,text:r})}return s}function Vs(e){let t=e.ref??"<your agent>",s=`${A.slug} run ${t} --session ${e.sessionKey}`;return`
|
|
213
213
|
${Ia}Resume this session with:
|
|
214
|
-
${
|
|
215
|
-
`}function
|
|
216
|
-
${
|
|
217
|
-
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
|
|
218
|
-
`);let a;
|
|
219
|
-
`),o;if(
|
|
220
|
-
`),i[0].manifestPath;if(e!=="rich"){for(let
|
|
221
|
-
`);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${
|
|
222
|
-
`),
|
|
223
|
-
`),o;if(
|
|
224
|
-
`),o;if(
|
|
225
|
-
`),
|
|
226
|
-
`),
|
|
214
|
+
${s}${ko}
|
|
215
|
+
`}function rt(e,t){switch(e){case"first":return;case"restart":return"restarted — the configuration on disk is now the one in force; the conversation continues from the store.";case"switch":return"switched conversation — the one you left is still in the store, under its own key.";case"new":return t===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${t}, still in the store. /sessions goes back to it.`}}function id(e){return e==="nlt"?pr():fr()}function zs(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(t)=>e.bus.on("*",t,{chunks:!0}),send:(t,s)=>e.send(t,{...s,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,ownConversation:e.ownConversation,resolveSessionKey:e.resolveSessionKey,rotateSession:e.rotateSession,tools:async()=>Xo(e.agent),context:e.context,close:async()=>{}}}function Ys(e){let t=e.client.agent(e.agentId),s=new Set,i=new AbortController,r,a=()=>{if(r!==void 0)return;r=(async()=>{for await(let d of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(d.kind!=="event"||d.event===void 0)continue;for(let l of s)l(d.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(d)=>(s.add(d),a(),()=>s.delete(d)),send:async(d,l)=>{let u=!1,g,c=()=>{if(u=!0,g!==void 0)t.turn(g).stop().catch(()=>{})};l.signal.addEventListener("abort",c,{once:!0});let f,m=new Promise((y)=>{let R=(T)=>{if(g!==void 0&&T.turnId!==void 0&&T.turnId!==g)return;if(T.type==="error"){f=T.data;return}if(T.type!=="turn.end")return;s.delete(R),y({text:"",reason:T.data.reason,steps:T.data.steps,durationMs:T.data.durationMs,tokens:T.data.tokens,...f===void 0?{}:{error:f}})};s.add(R),a()});try{if(g=(await t.send(d,{sessionKey:l.sessionKey})).turnId,u)t.turn(g).stop().catch(()=>{});return await m}finally{l.signal.removeEventListener("abort",c)}},streamFilter:()=>id(e.description.dialect),history:async(d)=>{let l=await t.messages(d);return _e([...l.messages].reverse().map((u)=>({role:u.role,content:u.content,...u.origin===void 0?{}:{origin:u.origin}})),e.description.dialect)},sessions:()=>t.sessions(),clearSession:async(d)=>{await t.clearSession(d)},ownConversation:async()=>(await t.sessions()).find((d)=>d.head!==!1&&d.sessionKey.startsWith("owner:"))?.sessionKey,resolveSessionKey:async(d)=>{try{return await t.resolveSessionKey(d)}catch{return d}},rotateSession:async()=>{try{return(await t.rotateSession()).sessionKey}catch{return}},tools:async()=>{let d=await t.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:d.map((l)=>({slug:l.slug,mutating:l.mutating,trust:l.trust,...l.trustReason===void 0?{}:{trustReason:l.trustReason},summary:l.summary}))}},context:async(d)=>{let l=await t.context({sessionKey:d});return{...l,windowSource:"as the host resolved it",...l.lastCompaction===void 0&&l.compactions!==void 0?{lastCompaction:l.compactions===0?void 0:`${l.compactions} stage${l.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await t.reload()).adopted,close:async()=>{i.abort(),s.clear()}}}function Qs(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function dd(e,t,s,i,r,a=[],d){let l=e.describe(),[u,g]=await Promise.all([e.turns(t,1),e.store.messages.count(e.id,t)]),c=[`${A.name} ${q} · ${l.id} · ${l.model}`,`session ${t} · ${g} message(s) · window ${l.window} · store ${s}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],f=rt(r,d);if(f!==void 0)c.push(f);if(u[0]?.errorCode==="turn_abandoned")c.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let m of[...e.warnings,...e.tools.warnings])c.push(`note: ${m.message}
|
|
216
|
+
${m.hint}`);if(a.length>0)c.push(`note: ${a.join(", ")} in the .env here ${a.length===1?"was":"were"} ignored — this agent's own .env sets ${a.length===1?"it":"them"}.
|
|
217
|
+
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 c}async function it(e){let t=e.once!==void 0,s=at({json:!1,plain:e.plain===!0,oneShot:t}),{mode:i}=s;if(e.manifestPath===void 0){let T=await cd(i,s.because,e);if(typeof T==="number")return T;return it({...e,manifestPath:T})}let r=fi();if(e.store===void 0&&e.ephemeral!==!0&&Zs(r)!==Zs(G())&&ad(r))process.stdout.write(`note: a session store exists at ${r} from an earlier version — pass --store ${r} to keep using it; the default is now ${G()}
|
|
218
|
+
`);let a;H(()=>a?.stop("cli-exit"));let d={current:void 0},l={current:""},u={current:e.sessionKey},g={current:!1},c={current:void 0},f=e.quiet===!0,m="first",y={current:void 0},R=e.ephemeral===!0?void 0:Qs(await We(De(e.manifestPath),e.store));if(R!==void 0)return await pd({...e,host:R,mode:i==="rich"?"rich":"plain",quiet:f,oneShot:t,reader:d,draft:l,session:u,random:ot});for(;;){let T=await pe.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??G()});a=T;let b=T.list()[0];if(b===void 0)throw Error("The manifest produced no agent.");if(u.current===void 0||u.current===""){let C=await so({list:async()=>co(await b.store.sessions.list(b.id)),mode:i,asked:u.current,wantsContinue:e.continueSession===!0,random:ot});if(typeof C==="number")return await T.stop("cli-exit"),C;if(u.current=C.sessionKey,g.current=C.fresh,C.fresh)u.current=await ro(b)??C.sessionKey}if(m==="new"){let C=await b.rotateSession({source:"repl"});if(C!==void 0)u.current=C.sessionKey}u.current=await b.resolveSessionKey(u.current??"",{source:"repl"});let N=u.current,M=b.roles.main.capabilities.thinking!=="none",S=e.noReasoning===!0?!1:M,P=f||t?[]:await dd(b,N,T.store.location,m==="first"?T.boot.processMs:T.boot.bootMs,m,Js([e.manifestPath]),c.current),I=i==="rich"&&!f&&!t?_e(await b.history(N),b.describe().dialect):[],O=zs({agent:b,bus:T.bus,send:(C,ne)=>b.send(C,ne),history:async(C)=>_e(await b.history(C),b.describe().dialect),sessions:async()=>{let C=await b.store.sessions.heads(b.id);return(await b.store.sessions.list(b.id)).map((ne)=>({...ne,head:si(ne.sessionKey,C)}))},clearSession:async(C)=>{await b.clearSession(C)},ownConversation:()=>ro(b),resolveSessionKey:(C)=>b.resolveSessionKey(C,{source:"repl"}),rotateSession:async()=>(await b.rotateSession({source:"repl"}))?.sessionKey,context:async(C)=>hd(b,C),streamFilter:()=>b.streamFilter(),description:{agentId:b.id,name:b.describe().name,model:b.describe().model,dialect:b.describe().dialect,window:b.describe().window,catalogueTokens:b.describe().catalogueTokens,thinking:b.roles.main.capabilities.thinking,warnings:[...b.warnings,...b.tools.warnings]}}),j={...e,source:O,embedded:{agent:b,runtime:T},sessionKey:N,banner:P,prior:I,quiet:f,reader:d,draft:l,showReasoning:S,freshSession:g.current,switchTo:y,random:ot},V=i==="rich"?await io(j):await ao(j);if(await T.stop(V===he?"restart":"cli-exit"),V!==he)return V;if(y.current===void 0)m="restart";else m=y.current.reason,c.current=N,u.current=y.current.key,y.current=void 0;g.current=!1}}function ld(e,t){let s=[];for(let i of e)Kt({action:"install",manifestPath:t,name:`${i.source}/${i.skill}`,quiet:!0,collect:s});return s}var he=Symbol("restart");async function cd(e,t,s){let i=oe();if(i.length===0){if(e==="rich"){let c=await Mn({plain:s.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
|
|
219
|
+
`),o;if(c.kind==="failed")return c.code;return c.manifestPath}throw new n({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${A.slug} init\`, or pass a path to an agent.yaml.`})}if(i.length===1&&i[0]!==void 0)return process.stdout.write(`running ${i[0].ref} — the only agent in the sandbox
|
|
220
|
+
`),i[0].manifestPath;if(e!=="rich"){for(let c of i)process.stdout.write(`${c.ref} ${c.problem??c.modelId??"?"} ${c.dir}
|
|
221
|
+
`);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${t})
|
|
222
|
+
`),E}let[{render:r},{createElement:a},{Picker:d}]=await Promise.all([import("ink"),import("react"),import("./Picker-x6aj42tc.js")]),l={kind:"quit"};oo();let u=r(a(d,{title:`${A.name} ${q}`,agents:i,onDone:(c)=>{l=c}}),{exitOnCtrlC:!1,...Ke(s.noEnhancedKeys)});H(()=>u.unmount()),await u.waitUntilExit(),u.unmount();let g=l;if(g.kind==="quit")return process.stdout.write(`nothing run
|
|
223
|
+
`),o;if(g.kind==="create"){let c=await Mn({plain:s.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
|
|
224
|
+
`),o;if(c.kind==="failed")return c.code;return c.manifestPath}return g.manifestPath}async function ro(e){let s=await e.resolveSessionKey("local:-",{source:"repl"});return s==="local:-"?void 0:s}async function so(e){let t=()=>({sessionKey:$o(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new n({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(e.wantsContinue){let s=await e.list(),i=ud(s);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
|
|
225
|
+
`),t();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let s=await e.list();if(s.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
|
|
226
|
+
`),t();if(e.mode!=="rich"){for(let r of[...s].sort(kn))process.stdout.write(`${r.sessionKey} ${r.messages} ${r.turns} ${r.lastActivityAt}
|
|
227
227
|
`);return process.stderr.write(`pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one
|
|
228
|
-
`),
|
|
229
|
-
`)},
|
|
230
|
-
`);a(`${
|
|
228
|
+
`),E}let i=await fd([...s].sort(kn));return i===void 0?t():{sessionKey:i,fresh:!1}}return e.asked===void 0?t():{sessionKey:e.asked,fresh:!1}}function kn(e,t){return Date.parse(t.lastActivityAt)-Date.parse(e.lastActivityAt)}function ud(e){return[...e].sort(kn)[0]}async function fd(e){let[{render:t},{createElement:s},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-pngdv97x.js")]),r;oo();let a=t(s(i,{sessions:e,now:Date.now(),columns:Ue(process.stdout.columns,Me),maxRows:Sn,onDone:(d)=>{r=d,a.unmount()}}),{exitOnCtrlC:!1,...Ke()});return H(()=>a.unmount()),await a.waitUntilExit(),r}function md(e,t,s,i,r){let a=e.describe(),d=[`${A.name} ${q} · ${a.agentId} · ${a.model}`,`session ${t} · window ${a.window} · attached to ${s.baseUrl} (pid ${s.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],l=rt(i,r);if(l!==void 0)d.push(l);for(let u of a.warnings)d.push(`warning: ${u.message}`);return d}async function pd(e){let t=e.manifestPath??"",s=De(t),i=RA(t),r=qs({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await r.agent(s).describe();if(a.status==="disabled")throw new n({code:"agent_disabled",message:`${s} was stopped while this run was attaching.`,hint:`Start it with \`${A.slug} start ${s}\`, then run again.`});let d=Ys({client:r,agentId:s,host:e.host,description:{agentId:s,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),l={current:void 0},u="first",g={current:void 0},c={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let b=await so({list:()=>mo(d),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof b==="number")return b;if(e.session.current=b.sessionKey,c.current=b.fresh,b.fresh)e.session.current=await d.ownConversation()??b.sessionKey}if(u==="new"){let b=await d.rotateSession();if(b!==void 0)e.session.current=b}e.session.current=await d.resolveSessionKey(e.session.current??"");let f=e.session.current??"",m=e.quiet||e.oneShot?[]:md(d,f,e.host,u,g.current),y=e.mode==="rich"&&!e.quiet&&!e.oneShot?await d.history(f):[],R={...e,source:d,sessionKey:f,banner:m,prior:y,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:c.current,switchTo:l,random:e.random},T=e.mode==="rich"?await io(R):await ao(R);if(T!==he)return await d.close(),T;if(l.current===void 0)u="restart";else u=l.current.reason,g.current=f,e.session.current=l.current.key,l.current=void 0;c.current=!1}}async function io(e){let[{render:t},{createElement:s},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-18dvbyev.js")]),r=un();H(()=>{r.close()}),wt(),Es(),process.stdout.write(`${Rt}${oa}`);let a=!1,d=t(s(i,{source:e.source,onSwitch:(l,u)=>{a=!0,e.switchTo.current={key:l,reason:"switch"},e.draft.current=u},onNew:(l)=>{a=!0,e.switchTo.current={key:$o(e.random),reason:"new"},e.draft.current=l},sessions:async()=>[...await mo(e.source)].sort(kn),onRestart:(l)=>{a=!0,e.draft.current=l},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((l)=>l.message),initial:Vi(qi(e.banner.slice(1)),e.prior),correctKeys:r.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(l)=>LA({onStatus:l}),install:async(l,u)=>mn(ld(l,u))},status:()=>e.embedded===void 0?po(e.source):lo(e.embedded),contextView:()=>go(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Ke(e.noEnhancedKeys)});if(H(()=>d.unmount()),await d.waitUntilExit(),Ze(),!a)process.stdout.write(Vs({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?he:o}async function ao(e){let{source:t,sessionKey:s,quiet:i}=e,r=!0,a=(P)=>{if(P==="")return;process.stdout.write(P),r=P.endsWith(`
|
|
229
|
+
`)},d=(P)=>{if(!r)a(`
|
|
230
|
+
`);a(`${P}
|
|
231
231
|
`)};if(e.banner.length>0)a(`${e.banner.join(`
|
|
232
232
|
`)}
|
|
233
233
|
|
|
234
|
-
`);let
|
|
234
|
+
`);let l=!i&&e.once===void 0,u=!1,g,c=t.streamFilter(),f=(P)=>{if(P==="")return;a(P),u=!0},m=e.source.subscribe((P)=>{if(P.sessionKey!==void 0&&P.sessionKey!==s)return;switch(P.type){case"model.result":f(c.endStep());return;case"model.chunk":{let{delta:I,kind:O}=P.data;if(O==="reasoning"&&e.showReasoning!==!0)return;if(O!==g){if(g!==void 0)a(`
|
|
235
235
|
|
|
236
|
-
`);if(e.showReasoning===!0)a(
|
|
236
|
+
`);if(e.showReasoning===!0)a(O==="reasoning"?`· reasoning ·
|
|
237
237
|
`:`· reply ·
|
|
238
|
-
`);
|
|
239
|
-
${
|
|
240
|
-
`)},
|
|
241
|
-
`);else if(!
|
|
242
|
-
`);let
|
|
243
|
-
(${
|
|
244
|
-
`);if(
|
|
245
|
-
${
|
|
246
|
-
hint: ${
|
|
247
|
-
`);if(Bo(
|
|
238
|
+
`);g=O}if(O==="reasoning"){a(I),u=!0;return}f(c.push(I));return}case"tool.result":{if(!l)return;let{slug:I,ok:O,latencyMs:j,truncated:V}=P.data;d(` · ${I} — ${O?"ok":"failed"} · ${j} ms${V?" · observation trimmed":""}`);return}case"agent.warning":d(` · ${P.data.message}
|
|
239
|
+
${P.data.hint}`);return;case"tool.repair":if(l)d(P.data.slugs.length===0?` · reply stopped short (${P.data.errors.join("; ")}), asking again`:` · ${P.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":d(` · ${P.data.slug} — blocked: ${P.data.reason}`);return;case"context.dropped":d(` · context: ${P.data.messages} older message(s) did not fit the ${P.data.budget}-token budget and were left out`);return;default:return}}),y=async(P)=>{let I=Hn(P,Yn());if(I===void 0)return"prompt";switch(I.kind){case"exit":return"exit";case"restart":{let O=t.reload;if(O===void 0)return"restart";try{let j=await O();d(`reloaded ${j.join(", ")} — this conversation continues`)}catch(j){d(`could not reload: ${j instanceof Error?j.message:String(j)}`)}return"handled"}case"new":return e.switchTo.current={key:$o(e.random),reason:"new"},"restart";case"help":return d(Kn()),"handled";case"tools":return d(DA(await t.tools())),"handled";case"status":return d(e.embedded===void 0?await po(t):await lo(e.embedded)),"handled";case"context":return d(await go(e,s)),"handled";case"reset":return await t.clearSession(s),d("session cleared — memory files on disk are untouched"),"handled";case"unknown":return d(nn(I)),"handled";case"command":return d(`${I.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${A.slug} ${I.name}${I.rest===""?"":` ${I.rest}`}\``),"handled"}},R,T=0,b=o,N=(P=e.reader.current)=>{if(R!==void 0&&!R.signal.aborted){T=performance.now(),R.abort();return}P?.close(),a(`
|
|
240
|
+
`)},M=async(P)=>{R=new AbortController,u=!1,g=void 0,c=t.streamFilter();let I=await t.send(P,{sessionKey:s,signal:R.signal});if(R=void 0,f(c.end()),u&&!r)a(`
|
|
241
|
+
`);else if(!u&&I.text!=="")a(`${I.text}
|
|
242
|
+
`);let O=Mt(I.reason,{steps:I.steps,durationMs:I.durationMs,...T===0?{}:{cancelledAfterMs:performance.now()-T}});if(O!==void 0)a(`
|
|
243
|
+
(${O})
|
|
244
|
+
`);if(I.reason==="error"&&I.error!==void 0)process.stderr.write(`
|
|
245
|
+
${I.error.code}: ${I.error.message}
|
|
246
|
+
hint: ${I.error.hint}
|
|
247
|
+
`);if(Bo(I.reason))b=E;if(!i&&I.reason==="final")a(` ${I.tokens.prompt} prompt · ${I.tokens.output} output · ${I.durationMs} ms
|
|
248
248
|
|
|
249
|
-
`);await Ct()},
|
|
250
|
-
`);for(let a of e)process.stdout.write(`${
|
|
251
|
-
`);let
|
|
252
|
-
${
|
|
253
|
-
`)}function
|
|
254
|
-
`);for(let[i,
|
|
255
|
-
`)}function
|
|
249
|
+
`);await Ct()},S=()=>N();process.on("SIGINT",S);try{if(e.once!==void 0)return await M(e.once),b;if(process.stdin.isTTY!==!0){let I=e.reader.current??no({input:process.stdin});e.reader.current=I;for await(let O of I){let j=O.trim();if(j==="")continue;let V=await y(j);if(V==="exit")break;if(V==="restart"){b=he;break}if(V==="handled")continue;await M(j)}return b}let P=e.reader.current??no({input:process.stdin,output:process.stdout,prompt:Po,terminal:!1});e.reader.current=P,P.prompt();for await(let I of P){let O=I.trim();if(O===""){P.prompt();continue}let j=await y(O);if(j==="exit")break;if(j==="restart"){b=he;break}if(j==="handled"){P.prompt();continue}await M(O),P.prompt()}if(b!==he)P.close(),e.reader.current=void 0;return b}finally{process.off("SIGINT",S),m()}}async function lo(e){let{agent:t,runtime:s}=e,i=t.describe(),r=t.manifest,a=r.channels.filter((c)=>c.enabled).map((c)=>`${c.id} (${c.type})`).join(", "),d=a===""?"none — reached through this session and the HTTP API only":s.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,l=!r.server.enabled?"off":`enabled on ${r.server.host}:${r.server.port}, NOT bound here — \`serve\` binds it`,u=Nt(r),g=u.filter((c)=>c.role!=="main"&&c.role===c.configuredAs);return p([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${r.tools.dialect} · ${i.window} token window (${gA(u[0]?.window)})`},...g.map((c)=>({label:c.role,value:`${c.modelId} · ${c.window.contextWindow} token window (${gA(c.window)})`})),{label:"channels",value:d},{label:"http api",value:l},{label:"store",value:s.store.location},{label:"background",value:await gd(s,i.id)}])}function co(e){return e.filter((t)=>!pi(t.sessionKey))}async function mo(e){return co(await e.sessions())}async function po(e){let t=e.describe(),s=e.host,[i,r]=await Promise.all([e.tools(),e.sessions()]);return p([{label:"agent",value:`${t.agentId} (${t.name})`},{label:"attached to",value:s===void 0?"a host":`${s.baseUrl} · pid ${s.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${t.model} · ${t.window} token window`},{label:"dialect",value:t.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${r.length} on this agent`},{label:"warnings",value:t.warnings.length===0?"none":t.warnings.map((a)=>a.message).join("; ")}])}async function hd(e,t){let s=await e.previewContext({sessionKey:t}),[i]=Nt(e.manifest);return{slots:s.slots,history:s.history,cache:s.cache,total:s.total,window:s.window,windowSource:gA(i?.window),wireTokens:s.wireTokens,reserveOutput:s.reserveOutput,calibration:s.calibration,lastCompaction:s.compactions===0?void 0:`${s.compactions} stage${s.compactions===1?"":"s"} run this session`}}async function go(e,t){return Yi(await e.source.context(t))}async function gd(e,t){if(e.owned.includes(t))return"this session is serving this agent";let s=await e.store.leases.get(t);if(s!==void 0&&ee(s.pid))return s.mode==="daemon"?`running as a background service · pid ${s.pid} · \`${A.slug} daemon status ${t}\``:`served by another session · pid ${s.pid} (${s.mode})`;return`not supervised — \`${A.slug} daemon install ${t}\` keeps it running without a terminal`}function Z(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function yd(e,t){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let s=Date.parse(e.nextRunAt)-t;if(s<=0)return"due";let i=Math.round(s/60000);if(i<60)return`in ${i}m`;let r=Math.round(s/3600000);return r<48?`in ${r}h`:`in ${Math.round(r/24)}d`}function wd(e,t){if(e.lastFiredAt===void 0)return"never run";let s=iA(e.lastFiredAt,t);if(e.lastStatus==="error")return`FAILED ${s}`;return`ok ${s}`}function bd(e,t){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let s=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${Z("SCHEDULE",s)} ${Z("WHEN",i)} ${Z("NEXT",7)} LAST
|
|
250
|
+
`);for(let a of e)process.stdout.write(`${Z(a.id,s)} ${Z(`${a.kind} ${a.expr}`,i)} ${Z(yd(a,t),7)} ${wd(a,t)}
|
|
251
|
+
`);let r=e.filter((a)=>a.lastStatus==="error");if(r.length>0)process.stdout.write(`
|
|
252
|
+
${r.length} failing — \`schedules --id ${r[0]?.id}\` for the error
|
|
253
|
+
`)}function $d(e){let t=[["kind",`${e.kind} ${e.expr}`],["timezone",e.timezone??"(host)"],["task",e.task],["deliver",e.deliverChannel===void 0?"none — the reply reaches the event stream only":`${e.deliverChannel} → ${e.deliverTo}`],["session",e.sessionMode],["model role",e.role??"main"],["enabled",e.enabled?"yes":"no"],["declared in",e.origin==="manifest"?"agent.yaml":"the API"],["next run",e.nextRunAt??"(never again)"],["runs",String(e.runs)],["last run",e.lastFiredAt??"never"],["last status",e.lastStatus??"-"]];if(e.lastError!==void 0)t.push(["last error",e.lastError]);let s=Math.max(...t.map(([i])=>i.length));process.stdout.write(`${e.id}
|
|
254
|
+
`);for(let[i,r]of t)process.stdout.write(` ${Z(i,s)} ${r}
|
|
255
|
+
`)}function vd(e,t){let s=new Set(t),i=new Map;for(let r of e){if(!s.has(r.channel))continue;let a=`${r.channel}\x00${r.peerId}`,d=i.get(a);if(d!==void 0&&d.lastSeen>=r.lastActivityAt)continue;i.set(a,{channelId:r.channel,address:r.peerId,lastSeen:r.lastActivityAt})}return[...i.values()].sort((r,a)=>r.channelId===a.channelId?a.lastSeen.localeCompare(r.lastSeen):r.channelId.localeCompare(a.channelId))}function Sd(e,t){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
|
|
256
256
|
`+` An address appears here once a first message arrives on one.
|
|
257
|
-
`);return}let
|
|
258
|
-
`);for(let
|
|
257
|
+
`);return}let s=Math.max(7,...e.map((r)=>r.channelId.length)),i=Math.max(7,...e.map((r)=>r.address.length));process.stdout.write(`${Z("CHANNEL",s)} ${Z("ADDRESS",i)} LAST SEEN
|
|
258
|
+
`);for(let r of e)process.stdout.write(`${Z(r.channelId,s)} ${Z(r.address,i)} ${iA(r.lastSeen,t)}
|
|
259
259
|
`);process.stdout.write(`
|
|
260
260
|
Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
|
|
261
261
|
`+`never a person — a private chat is reached by the numeric id above.
|
|
262
|
-
`)}async function vo(e){let
|
|
262
|
+
`)}async function vo(e){let t=await pe.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath]),lease:!1});H(()=>t.stop("cli-exit"));let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,d]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let l=await s.store.schedules.get(s.id,a);if(l===void 0)return process.stderr.write(`no schedule "${a}" on ${s.id}
|
|
263
263
|
hint: run \`schedules\` with no flags to see what this agent has.
|
|
264
|
-
`),
|
|
264
|
+
`),E;if(l.origin==="manifest")return process.stderr.write(`${a} is declared in agent.yaml, so the manifest decides whether it runs.
|
|
265
265
|
`+` Writing it here would last until the next start — reconciliation restores every
|
|
266
266
|
`+` field from the file, enabled included.
|
|
267
267
|
|
|
268
|
-
hint: set \`enabled: ${
|
|
268
|
+
hint: set \`enabled: ${d}\` on the "${a}" entry under schedules: in
|
|
269
269
|
${e.manifestPath}
|
|
270
|
-
`),
|
|
270
|
+
`),E;await s.store.schedules.setEnabled(s.id,a,d,new Date(i).toISOString()),process.stdout.write(d?`${a} enabled — it fires at its next occurrence, not now
|
|
271
271
|
`:`${a} disabled — still listed, and it keeps its place in the sequence
|
|
272
|
-
`)}if(e.recipients===!0){let a=
|
|
273
|
-
`),o;return
|
|
274
|
-
`),o;if(e.id!==void 0){let a=
|
|
275
|
-
`),
|
|
276
|
-
`,{mode:384})}function
|
|
277
|
-
`,{mode:384})}}}function Eo(e){for(let
|
|
278
|
-
`,{mode:384}),
|
|
272
|
+
`)}if(e.recipients===!0){let a=vd(await s.store.sessions.list(s.id),s.manifest.channels.map((d)=>d.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
|
|
273
|
+
`),o;return Sd(a,i),o}let r=await s.store.schedules.list(s.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:r},null,2)}
|
|
274
|
+
`),o;if(e.id!==void 0){let a=r.find((d)=>d.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${s.id}
|
|
275
|
+
`),E;return $d(a),o}if(e.enable===void 0&&e.disable===void 0)bd(r,i);return o}import{rmSync as Fd}from"node:fs";import{dirname as qo,join as Ld}from"node:path";import{readFileSync as kd}from"node:fs";var Pd="server.tokenEnv";function dt(e){let t=kd(e,"utf8"),s=Gt(e),i=new Map,r=new Set(jA(t).filter((a)=>a.path===Pd).map((a)=>a.name));for(let a of jA(t)){if(r.has(a.name))continue;let d=i.get(a.name)??[];d.push(a.path),i.set(a.name,d)}return[...i].map(([a,d])=>({name:a,set:on(s,a),usedBy:d}))}function So(e,t){let s=dt(e).map((d)=>d.name);for(let[d,l]of Object.entries(t)){if(!s.includes(d))throw new n({code:"secret_not_referenced",message:`"${d}" is not a variable this agent's manifest reads.`,hint:s.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${s.join(", ")}. A variable is settable when the manifest names it, as \${NAME} or through an *Env field; the server's own token never is. GET /v1/agents/:id/secrets lists them.`,field:`values.${d}`});if(l==="")throw new n({code:"secret_value_empty",message:`An empty value for ${d} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.",field:`values.${d}`})}let i=v([e]),r=[],a=[];for(let[d,l]of Object.entries(t))if(Ve(e,d,l),r.push(d),on(i,d))a.push(d);return{written:r,shadowed:a}}import{createHash as Ed}from"node:crypto";import{existsSync as ye,lstatSync as mt,mkdirSync as lt,readdirSync as Ro,readFileSync as je,renameSync as Rd,rmSync as To,writeFileSync as Ne}from"node:fs";import{basename as Le,dirname as xo,join as X}from"node:path";var Ce="template.yaml",Ao=/^[a-z0-9][a-z0-9-]*$/;function ht(e){let t;try{t=Ro(e)}catch{return[]}let s=[];for(let i of t.sort()){if(!Ao.test(i))continue;let r=X(e,i);if(!mt(r).isDirectory())continue;try{let a=Rn(r);s.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((d)=>({name:d.name,...d.description===void 0?{}:{description:d.description},required:d.required,...d.default===void 0?{}:{default:d.default},secret:d.secret!==void 0}))})}catch(a){if(!h(a))throw a;s.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return s}function Rn(e){let t=X(e,Ce);if(!ye(t))throw new n({code:"template_spec_missing",message:`${Le(e)} has no ${Ce}.`,hint:`A template is an agent directory with a ${Ce} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return Ii(je(t,"utf8"),`${Le(e)}/${Ce}`)}function gt(e,t=""){let s=[];for(let i of Ro(X(e,t)).sort()){let r=t===""?i:`${t}/${i}`;if(r===Ce)continue;let a=X(e,r),d=mt(a);if(d.isSymbolicLink())throw new n({code:"template_symlink",message:`${r} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:r});if(d.isDirectory()){s.push(...gt(e,r));continue}let l=je(a);if(l.includes(0))throw new n({code:"template_binary_file",message:`${r} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:r});s.push({relPath:r,contents:l.toString("utf8")})}return s}function _o(e){if(!Ao.test(e.template))throw ut(e.template,e.templatesDir);let t=X(e.templatesDir,e.template);if(!ye(t)||!mt(t).isDirectory())throw ut(e.template,e.templatesDir);let s=e.name.trim();if(s==="")throw new n({code:"provision_name_required",message:"An agent made from a template needs a name.",hint:'Send { "template": "…", "name": "Acme store", "vars": {…} }. The id every route keys on is derived from the name, and a template can use it as {{agent.name}} and {{agent.id}}.',field:"name"});let i=ct(s),r=X(e.agentDirBase,i);if(ye(r))throw new n({code:"provision_agent_exists",message:`An agent directory named "${i}" already exists.`,hint:"The id is derived from the name, so pick a different name. Nothing is overwritten: replacing an agent's workspace is exactly the loss provisioning exists to prevent.",field:"name"});let a=Or({spec:Rn(t),files:gt(t),id:i,name:s,vars:e.vars}),d=X(xo(e.agentDirBase),`.${Le(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);lt(d,{recursive:!0});try{Te(d,a.files),Fo(d,{template:e.template,name:s,vars:jo(Rn(t),e.vars),files:Td(a.files)});let l=X(d,"agent.yaml");for(let[c,f]of Object.entries(a.env))Ve(l,c,f);let u=a.files.find((c)=>c.relPath==="agent.yaml"),g={};for(let c of jA(u?.contents??""))if(a.env[c.name]===void 0&&!process.env[c.name])g[c.name]="(pending)";en(l,g),lt(e.agentDirBase,{recursive:!0}),Rd(d,r)}catch(l){throw To(d,{recursive:!0,force:!0}),l}return{agentId:i,dir:r,manifestPath:X(r,"agent.yaml"),files:[...a.files.map((l)=>l.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function ut(e,t){let s=ht(t).map((i)=>i.name);return new n({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:s.length===0?`This server has no templates. An operator adds one as a directory under ${t}.`:`Templates here: ${s.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var yt=".template.json";function Pn(e){return Ed("sha256").update(e).digest("hex")}function Td(e){return Object.fromEntries(e.map((t)=>[t.relPath,Pn(t.contents)]))}function jo(e,t){let s=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(t).filter(([i])=>!s.has(i)))}function Fo(e,t){Ne(X(e,yt),`${JSON.stringify({version:1,...t},null,2)}
|
|
276
|
+
`,{mode:384})}function Lo(e){let t=X(e,yt);if(!ye(t))return;let s=JSON.parse(je(t,"utf8"));return{template:s.template,vars:s.vars}}function Ko(e){let t=X(e.agentDir,yt);if(!ye(t))throw new n({code:"agent_not_from_template",message:"This agent has no record of the template it was made from.",hint:"Only an agent created with POST /v1/agents {template} on 0.2.0 or later carries one, because re-rendering needs the hash of every file as it was rendered. For an older agent, edit the files directly or create it again from the template."});let s=JSON.parse(je(t,"utf8")),i=X(e.templatesDir,s.template);if(!ye(i))throw ut(s.template,e.templatesDir);let r=Rn(i);for(let f of Object.keys(e.vars)){let m=r.vars.find((y)=>y.name===f);if(m?.secret!==void 0)throw new n({code:"template_var_secret",message:`"${f}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${m.secret}.`,field:`vars.${f}`})}let a={...s.vars,...e.vars},d=Or({spec:r,files:gt(i),id:Le(e.agentDir),name:s.name,vars:{...Object.fromEntries(r.vars.filter((f)=>f.secret!==void 0&&f.required).map((f)=>[f.name,"(in .env)"])),...a}}),l=[],u=[],g=[],c={...s.files};try{for(let f of d.files){let m=X(e.agentDir,f.relPath),y=s.files[f.relPath];if(!ye(m)){if(y!==void 0){g.push({file:f.relPath,reason:"removed"});continue}lt(xo(m),{recursive:!0}),Ne(m,f.contents),l.push({path:m,before:void 0}),c[f.relPath]=Pn(f.contents),u.push(f.relPath);continue}let R=je(m,"utf8");if(xd(f.relPath,R)){g.push({file:f.relPath,reason:"memory"});continue}if(y===void 0||Pn(R)!==y){g.push({file:f.relPath,reason:"edited"});continue}if(R===f.contents)continue;Ne(m,f.contents),l.push({path:m,before:R}),c[f.relPath]=Pn(f.contents),u.push(f.relPath)}Fo(e.agentDir,{template:s.template,name:s.name,vars:jo(r,a),files:c})}catch(f){throw Eo(l),f}return{rendered:u,skipped:g,undo:()=>{Eo(l),Ne(t,`${JSON.stringify(s,null,2)}
|
|
277
|
+
`,{mode:384})}}}function Eo(e){for(let t of e)if(t.before===void 0)To(t.path,{force:!0});else Ne(t.path,t.before)}function xd(e,t){if(Le(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return HA(e,t).frontmatter.eviction==="oldest"}catch{return!1}}import{readFileSync as Id,renameSync as Od,writeFileSync as Ad}from"node:fs";function _d(e){try{let t=JSON.parse(Id(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:{}}catch{return{}}}async function Cd(e,t){let i=(await e.json().catch(()=>({}))).error;return Error(i?.message===void 0?`the control plane answered ${e.status} to ${t}`:`${i.message}${i.hint===void 0?"":` ${i.hint}`}`)}function Uo(e){let t=e.fetch??globalThis.fetch,s=e.url.replace(/\/+$/,""),i={authorization:`Bearer ${e.token}`},r=_d(e.cacheFile);return{cachedPeers:(a)=>r[a]??[],async refreshPeers(a,d){let l=await t(`${s}/v1/relay/peers?participant=${encodeURIComponent(d)}`,{headers:i});if(!l.ok)throw await Cd(l,"the peer list");let{peers:u}=await l.json();r[a]=u;let g=`${e.cacheFile}.partial`;return Ad(g,`${JSON.stringify(r,null,2)}
|
|
278
|
+
`,{mode:384}),Od(g,e.cacheFile),u},async ask(a){let d=await t(`${s}/v1/relay/ask`,{method:"POST",headers:{...i,"content-type":"application/json"},body:JSON.stringify({participant:a.participantId,toSilo:a.silo,toAgent:a.agent,question:a.question,askedBy:a.fromAgent,sessionKey:a.sessionKey}),...a.signal===void 0?{}:{signal:a.signal}});if(!d.ok){let l=await d.json().catch(()=>({}));return{text:"",reason:"error",steps:0,tokens:{prompt:0,output:0},error:l.error??{code:"relay_unavailable",message:`The control plane answered ${d.status}.`,hint:"Check the control plane is reachable from this silo."}}}return await d.json()}}}import{Worker as Nd}from"node:worker_threads";var Mo=60;function Wo(e){let t=`${A.envPrefix}LOOP_STALL_S`,s=e[t];if(s===void 0||s==="")return Mo;if(!/^\d+$/.test(s))throw new n({code:"serve_loop_stall_invalid",message:`${t} is "${s}", which is not a whole number of seconds.`,hint:`Set it to the seconds a frozen server may stay frozen before it is killed and restarted (default ${Mo}), or 0 to switch the watchdog off.`,field:t});return Number(s)}var jd=`
|
|
279
|
+
const { workerData } = require("node:worker_threads")
|
|
280
|
+
const { writeSync } = require("node:fs")
|
|
281
|
+
const beat = new Float64Array(workerData.beat)
|
|
282
|
+
setInterval(() => {
|
|
283
|
+
const stalled = Date.now() - beat[0]
|
|
284
|
+
if (stalled < workerData.limitMs) return
|
|
285
|
+
try {
|
|
286
|
+
writeSync(2, workerData.prefix + "event loop stalled for " + Math.round(stalled / 1000) + "s; killing the process so its supervisor restarts it\\n")
|
|
287
|
+
} finally {
|
|
288
|
+
process.kill(workerData.pid, "SIGKILL")
|
|
289
|
+
}
|
|
290
|
+
}, 1000)
|
|
291
|
+
`;function Go(e,t=`${A.slug}: `){if(e<=0)return()=>{};let s=new Float64Array(new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT));s[0]=Date.now();let i=setInterval(()=>{s[0]=Date.now()},1000);i.unref();let r=new Nd(jd,{eval:!0,workerData:{beat:s.buffer,limitMs:e*1000,pid:process.pid,prefix:t}});return r.unref(),()=>{clearInterval(i),r.terminate()}}function Kd(){return KA.shape.server.parse({})}async function Vo(e){let t=v(e.manifestPaths),s=Ud(t),i=Wo(t),r=e.store??G(),a=await as(e.manifestPaths,t,r),d=a.filter((k)=>!k.enabled),l=a.filter((k)=>k.enabled),u=e.manifestPaths.length===0,g=[],c=[];for(let k of l)try{g.push({path:k.manifestPath,loaded:z(k.manifestPath,{env:t})})}catch(x){if(!u)throw x;c.push({path:k.manifestPath,detail:h(x)?x.message:String(x),...h(x)&&x.hint!==void 0?{hint:x.hint}:{}})}let f=g[0],m=f?.loaded,y=m?.manifest.server??Kd();for(let k of g.slice(1)){let x=k.loaded.manifest.server;for(let[_,Y,qe,$e]of[["server.port",y.port,x.port,e.port!==void 0],["server.host",y.host,x.host,e.host!==void 0],["server.tokenEnv",y.tokenEnv,x.tokenEnv,!1]]){if($e||Y===qe)continue;throw new n({code:"serve_bind_conflict",message:`${f?.path??"the first manifest"} sets ${_} to ${String(Y)} and ${k.path} sets it to ${String(qe)}.`,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:_})}}let R=e.port??y.port,T=e.port===void 0,b=e.host??y.host,N=m===void 0?t[y.tokenEnv]:m.env[y.tokenEnv],M=t[y.tokenEnv],S=g.every((k)=>$t(qo(k.path),t)),P=N;if(S&&(M===void 0||M==="")){let k=Cn(W(t));if(k!==void 0)P=k;else if(N!==void 0&&N!=="")ii(W(t),N)}let I=t[`${A.envPrefix}SERVICE`]!==void 0,O=new bt({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)O.on("agent.channel.status",(k)=>{let x=k.data,_=x.input===void 0?"":x.input.kind==="pairing_code"?`
|
|
279
292
|
|
|
280
|
-
${
|
|
281
|
-
${
|
|
282
|
-
expires ${
|
|
283
|
-
`)}),
|
|
284
|
-
hint: ${
|
|
285
|
-
`)}),
|
|
286
|
-
hint: ${
|
|
287
|
-
`)}),
|
|
288
|
-
`)});let
|
|
289
|
-
`);else{let
|
|
290
|
-
`),
|
|
291
|
-
`);process.stdout.write(` web UI ${
|
|
292
|
-
`);for(let
|
|
293
|
-
`)}for(let
|
|
294
|
-
`);for(let
|
|
295
|
-
`),
|
|
296
|
-
`);for(let
|
|
297
|
-
`);if(
|
|
298
|
-
`);if(
|
|
299
|
-
${
|
|
300
|
-
without a browser: ${
|
|
301
|
-
`),
|
|
302
|
-
`)}if(
|
|
303
|
-
`);if(I)process.stdout.write(` running as a background service · ${
|
|
293
|
+
${x.input.payload}
|
|
294
|
+
${x.input.expiresAt===void 0?"":`
|
|
295
|
+
expires ${x.input.expiresAt}`}`:` (${x.input.kind}${x.input.expiresAt===void 0?"":`, expires ${x.input.expiresAt}`} — GET /v1/agents/${k.agentId??""} carries it)`;process.stdout.write(` ${x.channelId}: ${x.status}${x.detail===void 0?"":` — ${x.detail}`}${_}
|
|
296
|
+
`)}),O.on("agent.channel.error",(k)=>{let x=k.data;process.stderr.write(` ${x.channelId}: ${x.message}
|
|
297
|
+
hint: ${x.hint}
|
|
298
|
+
`)}),O.on("error",(k)=>{let x=k.data,_=k.sessionKey===void 0?"":` [${k.sessionKey}]`;process.stderr.write(` turn failed${_}: ${x.code}: ${x.message}
|
|
299
|
+
hint: ${x.hint}
|
|
300
|
+
`)}),O.on("agent.channel.rejected",(k)=>{let x=k.data;process.stdout.write(` ${x.channelId}: ${x.reason} — ${x.detail}
|
|
301
|
+
`)});let j=Yr(),V=t[`${A.envPrefix}RELAY_URL`],C=t[`${A.envPrefix}RELAY_TOKEN`],ne=V===void 0||V===""||C===void 0||C===""?void 0:Uo({url:V,token:C,cacheFile:Ld(qo(r),"relay-peers.json")}),we=(k)=>({agents:k,...ne===void 0?{}:{relay:ne},approve:j.approver,env:t,bus:O,toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,startChannels:!0,startSchedules:!0,store:r,mode:I?"daemon":"terminal"}),F;try{F=await pe.create(we(g.map((k)=>k.path)))}catch(k){if(!u||g.length===0)throw k;let x=[];for(let _ of g)try{await(await pe.create({...we([_.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),x.push(_)}catch(Y){c.push({path:_.path,detail:h(Y)?Y.message:String(Y),...h(Y)&&Y.hint!==void 0?{hint:Y.hint}:{}})}if(x.length===g.length)throw k;g.splice(0,g.length,...x),F=await pe.create(we(x.map((_)=>_.path)))}ps();let Be=Md(),ke=await F.store.operatorKeys.liveCount(),le=ke===0||e.claim===!0?ts():void 0,te,xn=[];try{te=await Hd(R,T,(k)=>(xn.push(k),os({runtime:F,host:b,port:k,approvals:j,allowedOrigins:y.allowedOrigins,allowedHosts:y.allowedHosts,resolveAgent:(x)=>eo(x,t),provision:{steps:()=>qt({agentDirBase:W(t)}),create:(x)=>Vt({answers:x,defaults:{agentDirBase:W(t)}}),claim:async(x)=>{await ve(F.store,x,W(t))},templates:()=>ht(Dr(t)),createFromTemplate:(x)=>_o({...x,templatesDir:Dr(t),agentDirBase:W(t)}),rerender:(x)=>Ko({...x,templatesDir:Dr(t)}),templateOf:Lo},secrets:{status:dt,write:So},remover:Gd(t),home:Oe(t),channels:{setEnabled:Vn,setCredential:Wn,unpair:zn},...le===void 0?{}:{claim:le},...P===void 0||P===""?{}:{token:P}})))}catch(k){if(await F.stop("server failed to bind"),h(k))throw k;let x=xn.length>1?` — also tried ${xn.slice(1).join(", ")}`:"";throw new n({code:"server_bind_failed",message:`Could not bind ${b}:${R}${x}: ${k instanceof Error?k.message:String(k)}`,hint:T?`Every port in the range is taken. Pass --port to name a free one, or stop whatever is holding them — \`${A.slug} stop\` releases one this runtime started.`:"Another process is on that port, and --port was given explicitly so nothing else was tried. Drop the flag to let it walk to the next free port, or name a different one.",cause:k})}let ci=F.owned.length===0&&await gs(F.store.leases,{runtimeId:F.runtimeId,mode:I?"daemon":"terminal"});await F.publishAddress(te.url);let ie=F.list(),vt=ie[0];if(vt!==void 0)process.title=ie.length===1?`${A.slug} ${vt.id}`:`${A.slug} ${ie.length} agents`;for(let k of ie)k.reportRuntimeState({serverListening:!0});let ui=Go(i);if(e.json===!0)process.stdout.write(`${JSON.stringify({url:te.url,websocket:te.websocket,authenticated:P!==void 0&&P!=="",keys:ke,...le===void 0?{}:{claim:le.token},agents:ie.map((k)=>({id:k.id,channels:F.channels.statusOf(k.id)})),declined:F.declined.map((k)=>({agentId:k.agentId,pid:k.pid,mode:k.mode,since:k.startedAt})),disabled:d.map((k)=>({agentId:k.agentId,...k.reason===void 0?{}:{reason:k.reason}})),broken:c.map((k)=>({path:k.path,detail:k.detail,...k.hint===void 0?{}:{hint:k.hint}}))})}
|
|
302
|
+
`);else{let k=`http://${an(b)}:${te.port}`,x=k===te.url?"":` (bound ${b} — every interface)`;if(process.stdout.write(`${A.name} serving on ${k}${x}
|
|
303
|
+
`),te.port!==R)process.stdout.write(` moved from ${R} — something else is on it. \`--port ${R}\` would refuse instead of moving.
|
|
304
|
+
`);process.stdout.write(` web UI ${k}/ · API reference ${k}/docs
|
|
305
|
+
`);for(let _ of ie){let Y=F.channels.statusOf(_.id),qe=Y.length===0?"no channels":Y.map((Pe)=>`${Pe.id} (${Pe.type}${Pe.status==="error"?", BROKEN":""})`).join(", "),$e=_.manifest.schedules.filter((Pe)=>Pe.enabled),mi=_.manifest.schedules.length===0?"":`, ${$e.length} schedule${$e.length===1?"":"s"}${_.manifest.schedules.length>$e.length?` (+${_.manifest.schedules.length-$e.length} disabled)`:""}`;process.stdout.write(` ${_.id} — ${qe}${mi}
|
|
306
|
+
`)}for(let _ of d)process.stdout.write(` ${_.agentId} — stopped${_.reason===void 0?"":` (${_.reason})`}, \`${A.slug} start ${_.agentId}\`
|
|
307
|
+
`);for(let _ of c)if(process.stdout.write(` ${_.path} — NOT served: ${_.detail}
|
|
308
|
+
`),_.hint!==void 0)process.stdout.write(` hint: ${_.hint}
|
|
309
|
+
`);for(let _ of F.declined)process.stdout.write(` ${_.agentId} — NOT served here: pid ${_.pid} (${_.mode}) already has it
|
|
310
|
+
`);if(F.declined.length>0)process.stdout.write(` \`${A.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
|
|
311
|
+
`);if(le!==void 0){if(process.stdout.write(` open once to claim this server:
|
|
312
|
+
${As(b,te.port,le.token)}
|
|
313
|
+
without a browser: ${ns(b,te.port,le.token)}
|
|
314
|
+
`),P===void 0||P==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
|
|
315
|
+
`)}if(P===void 0||P==="")process.stdout.write(` unauthenticated — loopback only. Set ${y.tokenEnv} to bind a public host.
|
|
316
|
+
`);if(I)process.stdout.write(` running as a background service · ${A.slug} daemon status ${ie[0]?.id??""}
|
|
304
317
|
`);else if(xr())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
|
|
305
|
-
`);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${
|
|
306
|
-
`)}let
|
|
307
|
-
`);let
|
|
308
|
-
`:`${
|
|
309
|
-
`)}if(await
|
|
310
|
-
`),await
|
|
311
|
-
`);return}let
|
|
312
|
-
`);for(let i of
|
|
313
|
-
`)}}async function
|
|
314
|
-
`);return}for(let
|
|
318
|
+
`);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${A.slug} daemon install${ie[0]?.id===void 0?"":` ${ie[0].id}`}\` keeps it running.
|
|
319
|
+
`)}let St=!1,kt=async()=>{if(St)return;if(St=!0,ui(),s>0&&F.all().some((k)=>k.inFlight>0)){let k=Date.now();process.stdout.write(`draining — waiting up to ${s} ms for running turns
|
|
320
|
+
`);let x=await F.drain(s);process.stdout.write(x===0?`drained in ${Date.now()-k} ms
|
|
321
|
+
`:`${x} turn(s) still running after ${s} ms; the next start marks them interrupted
|
|
322
|
+
`)}if(await te.stop(),ci)await F.store.leases.release(Ut,F.runtimeId).catch(()=>{});await F.stop("interrupted")};return H(kt),await Be,process.stdout.write(`stopping
|
|
323
|
+
`),await kt(),o}function Ud(e){let t=`${A.envPrefix}DRAIN_MS`,s=e[t];if(s===void 0||s==="")return 0;if(!/^\d+$/.test(s))throw new n({code:"serve_drain_invalid",message:`${t} is "${s}", which is not a number of milliseconds.`,hint:"Set it to a whole number, a few seconds under the orchestrator's grace period — 25000 beside Kubernetes' default terminationGracePeriodSeconds of 30. Unset, a stop does not wait.",field:t});return Number(s)}function Md(){return new Promise((e)=>{let t=()=>{process.off("SIGINT",t),process.off("SIGTERM",t),e()};process.once("SIGINT",t),process.once("SIGTERM",t)})}var Dd=16;async function Hd(e,t,s){let i=t&&e!==0?e+Dd:e;for(let r=e;;r+=1)try{return await s(r)}catch(a){if(r>=i||!Wd(a))throw a}}function Wd(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let t=e instanceof Error?e.message:String(e);return t.includes("EADDRINUSE")||t.includes("in use")}function Gd(e){return{locate(t){let s=oe(e).filter((r)=>r.id===t),i=s[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${t}" in the sandbox, so there are no files here to delete.`,hint:"Only sandbox agents are deleted over the API. An agent elsewhere is removed by deleting its directory yourself."}};if(s.length>1)return{ok:!1,status:409,error:{code:"agent_remove_shared_id",message:`${s.length} sandbox directories declare id "${t}": ${s.map((r)=>r.dir).join(", ")}.`,hint:"They share one conversation history, so deleting either would delete the other's too. Give one a different id first."}};return{ok:!0,dir:i.dir}},async deleteDir(t){if(!$t(t,e))throw Error(`refusing to delete ${t}: it is outside the sandbox`);Fd(t,{recursive:!0,force:!0})}}}function B(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Bd(e){let t=new Map,s=[];for(let i of e){let r=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(r.length!==3||r[0]!=="schedule"){s.push(a);continue}let d=`schedule:${r[1]}`,l=t.get(d);if(l===void 0){let u={...a,sessionKey:`${d}:*`,runs:1};t.set(d,u),s.push(u);continue}if(l.runs=(l.runs??1)+1,l.messages+=i.messages,l.turns+=i.turns,i.lastActivityAt>l.lastActivityAt)l.lastActivityAt=i.lastActivityAt}return s}function qd(e){if(e.length===0){process.stdout.write(`no sessions yet
|
|
324
|
+
`);return}let t=Bd(e),s=Math.max(7,...t.map((i)=>i.sessionKey.length));process.stdout.write(`${B("SESSION",s)} ${B("MSGS",5)} ${B("TURNS",5)} ${B("PHASE",8)} LAST
|
|
325
|
+
`);for(let i of t){let r=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${B(i.sessionKey,s)} ${B(String(i.messages),5)} ${B(String(i.turns),5)} ${B(i.phase??"-",8)} ${iA(i.lastActivityAt,Date.now())}${r}
|
|
326
|
+
`)}}async function Vd(e,t,s){let i=await e.store.messages.page(e.id,t,{limit:s});if(i.messages.length===0){process.stdout.write(`no messages in ${t}
|
|
327
|
+
`);return}for(let r of[...i.messages].reverse())process.stdout.write(`${r.role}: ${r.content}
|
|
315
328
|
`);if(i.nextBefore!==void 0)process.stdout.write(`
|
|
316
329
|
… older messages exist; raise --limit
|
|
317
|
-
`)}async function
|
|
318
|
-
`);return}process.stdout.write(`${
|
|
319
|
-
`);for(let
|
|
320
|
-
`),
|
|
321
|
-
`),
|
|
322
|
-
`)}}async function
|
|
323
|
-
`),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:
|
|
324
|
-
`),o}if(process.stdout.write(`store: ${
|
|
330
|
+
`)}async function Jd(e,t,s){let i=await e.turns(t,s);if(i.length===0){process.stdout.write(`no turns in ${t}
|
|
331
|
+
`);return}process.stdout.write(`${B("TURN",22)} ${B("STATUS",9)} ${B("STEPS",5)} ${B("TOKENS",13)} ${B("MS",6)} SOURCE
|
|
332
|
+
`);for(let r of i)if(process.stdout.write(`${B(r.turnId,22)} ${B(r.status,9)} ${B(String(r.steps),5)} ${B(`${r.promptTokens}/${r.outputTokens}`,13)} ${B(String(r.durationMs??"-"),6)} ${r.source}
|
|
333
|
+
`),r.errorCode!==void 0){if(process.stdout.write(` ${r.errorCode}: ${r.errorMessage}
|
|
334
|
+
`),r.errorHint!==void 0)process.stdout.write(` hint: ${r.errorHint}
|
|
335
|
+
`)}}async function Jo(e){let t=await pe.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath])});H(()=>t.stop("cli-exit"));let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Ho;if(e.clear===!0){if(e.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let a=await s.store.messages.count(s.id,e.sessionKey);return await s.clearSession(e.sessionKey),process.stdout.write(`cleared ${e.sessionKey}: ${a} message(s) removed, memory files untouched
|
|
336
|
+
`),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:t.store.location,sessions:await s.sessions()}:{store:t.store.location,session:await s.store.sessions.get(s.id,e.sessionKey),messages:(await s.store.messages.page(s.id,e.sessionKey,{limit:i})).messages,turns:await s.turns(e.sessionKey,i)};return process.stdout.write(`${JSON.stringify(a,null,2)}
|
|
337
|
+
`),o}if(process.stdout.write(`store: ${t.store.location}
|
|
325
338
|
|
|
326
|
-
`),e.sessionKey===void 0)return
|
|
339
|
+
`),e.sessionKey===void 0)return qd(await s.sessions()),o;if(await s.store.sessions.get(s.id,e.sessionKey)===void 0)return process.stderr.write(`no session "${e.sessionKey}" for agent ${s.id}
|
|
327
340
|
hint: run \`sessions ${e.manifestPath}\` to list the keys that exist
|
|
328
|
-
`),
|
|
341
|
+
`),E;if(e.turns===!0)await Jd(s,e.sessionKey,i);else await Vd(s,e.sessionKey,i);return o}import{existsSync as Xd,readFileSync as zd,writeFileSync as Yd}from"node:fs";import{basename as Qd,dirname as Zd,join as el}from"node:path";var nl=/^(#{1,6})\s+(.*)$/,tl=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,rl=/^[ \t]*<\/rules>[ \t]*$/,sl=/^\s*(?:```|~~~)/;function zo(e){if(e.action!=="distill")throw new n({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${e.action}".`,hint:"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled."});let t;try{t=zd(e.file,"utf8")}catch{throw new n({code:"cli_soul_file_missing",message:`${e.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let s=Qd(e.file),i=e.out??el(Zd(e.file),`${s.replace(/\.md$/i,"")}.compact.md`);if(Xd(i))throw new n({code:"cli_soul_out_exists",message:`${i} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:r}=HA(s,t),a=ol(s,r);return Yd(i,a,"utf8"),process.stdout.write(`wrote ${i}
|
|
329
342
|
|
|
330
|
-
The scaffold copies ${
|
|
343
|
+
The scaffold copies ${s}'s headings and its <rules> blocks verbatim, and leaves a
|
|
331
344
|
{{PLACEHOLDER}} under each heading. Now:
|
|
332
345
|
`+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
|
|
333
346
|
`+` document's own voice. The workspace command warns until none are left.
|
|
334
347
|
2. Name the file in context.soul.distilled.
|
|
335
|
-
`),o}function
|
|
336
|
-
`)){if(
|
|
348
|
+
`),o}function ol(e,t){let s=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${e}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],i=!1,r=!1,a=0,d=!1;for(let l of t.split(`
|
|
349
|
+
`)){if(sl.test(l)){if(i=!i,r)s.push(l);continue}if(i){if(r)s.push(l);continue}if(tl.test(l)){r=!0,s.push(l);continue}if(r){if(s.push(l),rl.test(l))r=!1,s.push("");continue}if(nl.exec(l)!==null)d=!0,a+=1,s.push(l),s.push(""),s.push(`{{SECTION_${a}}}`),s.push("")}if(!d)s.push("{{ESSENCE}}"),s.push("");return`${s.join(`
|
|
337
350
|
`).replace(/\n{3,}/g,`
|
|
338
351
|
|
|
339
352
|
`).trimEnd()}
|
|
340
|
-
`}var
|
|
353
|
+
`}var il=["list","add","remove","update","search"],al=12;async function Yo(e){try{switch(e.action){case"list":return dl(e);case"add":return ll(e);case"remove":return ul(e);case"update":return await fl(e);case"search":return await ml(e);default:throw new n({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${il.join(", ")}.`})}}catch(t){if(h(t))return process.stdout.write(`${t.message}
|
|
341
354
|
|
|
342
|
-
${
|
|
343
|
-
`),
|
|
344
|
-
`),o;if(
|
|
355
|
+
${t.hint}
|
|
356
|
+
`),E;throw t}}function dl(e){let s=He(e.env).map((i)=>{let r=ar(i.name,e.env);return{...i,cached:pt(i.name,e.env),commit:r.commit,fetchedAt:r.fetchedAt,skills:r.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:to(e.env),sources:s},null,2)}
|
|
357
|
+
`),o;if(s.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
|
|
345
358
|
|
|
346
359
|
\`sources add <name> <url>\` to add one, or \`sources add ${_A[0]?.name??"anthropic"} ${_A[0]?.url??""}\` to put a built-in back.
|
|
347
|
-
`),o;process.stdout.write(
|
|
348
|
-
${
|
|
349
|
-
`),process.stdout.write(
|
|
350
|
-
${
|
|
351
|
-
${
|
|
352
|
-
`),o}function
|
|
353
|
-
`),o;return process.stdout.write(`${
|
|
354
|
-
`),process.stdout.write(`${
|
|
355
|
-
${
|
|
356
|
-
${
|
|
357
|
-
`),o}function
|
|
360
|
+
`),o;process.stdout.write(L("sources",!0));for(let i of s)process.stdout.write(`
|
|
361
|
+
${D(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
|
|
362
|
+
`),process.stdout.write(w(p([{label:"url",value:i.url},...i.path===void 0?[]:[{label:"path",value:i.path}],...i.ref===void 0?[]:[{label:"branch",value:i.ref}],{label:"cached",value:i.cached?`${i.skills??"?"} skills at ${i.commit??"?"}, fetched ${i.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
|
|
363
|
+
${L("registry")}
|
|
364
|
+
${w(to(e.env))}
|
|
365
|
+
`),o}function ll(e){let[t,s]=e.rest;if(t===void 0)throw new n({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let i=s!==void 0,r=i?s:t,a=sr(r),d=i?t:cl(a.url);if(!kA(d))throw new n({code:"sources_name_invalid",message:`${JSON.stringify(d)} is not usable as a source name`,hint:"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`."});let l=He(e.env).find((f)=>f.name===d);if(l!==void 0&&!i)throw new n({code:"sources_name_taken",message:`${d} is already a source, pointing at ${l.url}`,hint:`Give this one its own name: \`sources add <name> ${r}\`.`});let u=e.path??a.path,g=e.ref??a.ref,c={name:d,url:a.url,...u===void 0?{}:{path:u},...g===void 0?{}:{ref:g}};if(cs(c,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:c},null,2)}
|
|
366
|
+
`),o;return process.stdout.write(`${p([{label:l===void 0?"added":"replaced",value:d},{label:"url",value:c.url},...c.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:c.path}],...c.ref===void 0?[]:[{label:"branch",value:c.ref}]])}
|
|
367
|
+
`),process.stdout.write(`${L("next")}
|
|
368
|
+
${D(`sources update ${d}`)}
|
|
369
|
+
${D("sources search <what you need>")}
|
|
370
|
+
`),o}function cl(e){let t=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(t[t.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ul(e){let t=e.rest[0];if(t===void 0)throw new n({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let s=He(e.env).map((r)=>r.name);if(!ls(t,e.env)){let r=J(t,s);throw new n({code:"sources_unknown",message:`no source called ${t}`,hint:r===void 0?`Configured: ${s.join(", ")||"none"}.`:`Did you mean ${r}?`})}let i=_A.some((r)=>r.name===t);return process.stdout.write(`removed ${t}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
|
|
358
371
|
`),process.stdout.write(`
|
|
359
372
|
The cached copy is left on disk; nothing already installed into an agent is touched.
|
|
360
|
-
`),o}async function
|
|
373
|
+
`),o}async function fl(e){let t=He(e.env),s=e.rest.length===0?t:e.rest.map((a)=>{let d=t.find((l)=>l.name===a);if(d===void 0){let l=J(a,t.map((u)=>u.name));throw new n({code:"sources_unknown",message:`no source called ${a}`,hint:l===void 0?`Configured: ${t.map((u)=>u.name).join(", ")||"none"}.`:`Did you mean ${l}?`})}return d});if(s.length===0)return process.stdout.write(`no sources configured
|
|
361
374
|
|
|
362
375
|
\`sources add <url>\` to add one.
|
|
363
|
-
`),o;let i=[],
|
|
364
|
-
`)}catch(
|
|
365
|
-
`);if(e.json!==!0&&
|
|
366
|
-
${
|
|
367
|
-
`)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:
|
|
368
|
-
`);return i.length===0?
|
|
376
|
+
`),o;let i=[],r=[];for(let a of s){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let d=await vA(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:d.commit,skills:d.skills}),e.json!==!0)process.stdout.write(`${d.skills} skills at ${d.commit}${d.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
|
|
377
|
+
`)}catch(d){let l=d instanceof Error?d.message:String(d);if(r.push({name:a.name,reason:l}),e.json!==!0)process.stdout.write(`failed
|
|
378
|
+
`);if(e.json!==!0&&h(d))process.stdout.write(`${w(d.message)}
|
|
379
|
+
${w(d.hint,4)}
|
|
380
|
+
`)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:r},null,2)}
|
|
381
|
+
`);return i.length===0?E:o}async function ml(e){let t=e.rest.join(" ").trim(),s=He(e.env);if(s.length===0)return process.stdout.write(`no sources configured
|
|
369
382
|
|
|
370
383
|
\`sources add <url>\` to add one.
|
|
371
|
-
`),
|
|
372
|
-
`)}catch(
|
|
373
|
-
`),
|
|
374
|
-
`)}}}let s
|
|
384
|
+
`),E;let i=s.filter((l)=>!pt(l.name,e.env));for(let l of i){if(e.json!==!0)process.stdout.write(`fetching ${l.name} for the first time … `);try{let u=await vA(l,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${u.skills} skills
|
|
385
|
+
`)}catch(u){if(e.json!==!0){if(process.stdout.write(`failed
|
|
386
|
+
`),h(u))process.stdout.write(`${w(u.message)}
|
|
387
|
+
`)}}}let r=s.flatMap((l)=>Ht(l,e.env));if(r.length===0)return process.stdout.write(`
|
|
375
388
|
nothing to search — no source has been fetched successfully
|
|
376
389
|
|
|
377
390
|
\`sources update\` reports why.
|
|
378
|
-
`),
|
|
379
|
-
nothing in ${
|
|
391
|
+
`),E;let a=t.length===0?r:pl(t,r);if(a.length===0)return process.stdout.write(`
|
|
392
|
+
nothing in ${r.length} skills across ${s.length} sources matches ${JSON.stringify(t)}
|
|
380
393
|
|
|
381
394
|
Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
|
|
382
|
-
`),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:
|
|
383
|
-
`),o;let
|
|
384
|
-
${
|
|
385
|
-
`);for(let
|
|
386
|
-
`);let
|
|
387
|
-
`)}if(a.length>
|
|
388
|
-
${
|
|
395
|
+
`),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:t,searched:r.length,results:a.map((l)=>({source:l.source,skill:l.skill,description:l.description,tokens:l.tokens,scripts:l.scripts.length,repoPath:l.repoPath,...l.problem===void 0?{}:{problem:l.problem}}))},null,2)}
|
|
396
|
+
`),o;let d=a.slice(0,al);process.stdout.write(`
|
|
397
|
+
${L(t.length===0?`${r.length} skills`:`${a.length} of ${r.length} skills match ${JSON.stringify(t)}`,!0)}
|
|
398
|
+
`);for(let l of d){process.stdout.write(`${D(`${l.source}/${l.skill}`)} ${l.tokens} tokens${l.scripts.length===0?"":`, ${l.scripts.length} runnable file${l.scripts.length===1?"":"s"}`}${l.problem===void 0?"":" — will not load"}
|
|
399
|
+
`);let u=l.problem??l.description;process.stdout.write(`${w(u.length>160?`${u.slice(0,157)}…`:u,4)}
|
|
400
|
+
`)}if(a.length>d.length)process.stdout.write(`
|
|
401
|
+
${w(`… and ${a.length-d.length} more; narrow the query or use --json`)}
|
|
389
402
|
`);return process.stdout.write(`
|
|
390
|
-
${
|
|
391
|
-
${
|
|
392
|
-
`),o}function
|
|
393
|
-
`);else if(process.stdout.write(`${
|
|
394
|
-
`),!a&&
|
|
395
|
-
Switched on but not yet running. \`${
|
|
396
|
-
`);return
|
|
397
|
-
`),o;let i=await Ft({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${
|
|
398
|
-
`);let
|
|
399
|
-
${
|
|
400
|
-
`);return i}import{copyFileSync as
|
|
401
|
-
`),
|
|
402
|
-
${
|
|
403
|
-
`),
|
|
404
|
-
${
|
|
405
|
-
${
|
|
406
|
-
${
|
|
407
|
-
${
|
|
408
|
-
`),
|
|
409
|
-
${
|
|
410
|
-
`),
|
|
403
|
+
${L("install")}
|
|
404
|
+
${w(`skills install <agent> ${d[0]?.source}/${d[0]?.skill}`)}
|
|
405
|
+
`),o}function pl(e,t){let s=new Map,i=t.map((r)=>{let a=`${r.source}/${r.skill}`;return s.set(a,r),{name:a,dir:r.dir,tokens:r.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:r.description,metadata:{}}}});return JA(e,i).filter((r)=>r.score>0).map((r)=>s.get(r.skill.name)).filter((r)=>r!==void 0)}async function Zo(e){let t=hl(e.manifestPath),s=await ir(t,e.store),i=[];if(s?.enabled===!0)i.push("was already switched on");await rr(t,!0,void 0,e.store);let r=await ze(e.store),a=!1;if(r===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(r.baseUrl===void 0)i.push(`pid ${r.pid} is a ${r.mode} session, which serves no HTTP to adopt into`);else{let d=await ft(r,`/v1/agents/${encodeURIComponent(t)}/start`,{},e.manifestPath);if(d.ok)a=!0,i.push(`adopted by pid ${r.pid}, live now`);else if(d.status===501)i.push(`pid ${r.pid} cannot look up manifests — restart it to pick this up`);else if(d.status===401)i.push(`pid ${r.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${r.pid} could not adopt it${d.detail===void 0?"":`: ${d.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:t,enabled:!0,running:a,...r===void 0?{}:{pid:r.pid,mode:r.mode},note:i.join(" · ")}]},null,2)}
|
|
406
|
+
`);else if(process.stdout.write(`${p([{label:t,value:a?"running":"switched on",note:i.join(" · ")}])}
|
|
407
|
+
`),!a&&r!==void 0&&r.baseUrl!==void 0)process.stdout.write(`
|
|
408
|
+
Switched on but not yet running. \`${A.slug} daemon restart\` picks it up.
|
|
409
|
+
`);return r!==void 0&&r.baseUrl!==void 0&&!a?E:o}function hl(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_start_agent_id_missing",message:`${e} declares no id, so there is nothing to switch on.`,hint:"Add `id: <name>` to the manifest. The id is what the switch, the sessions and the API paths are all keyed by."});return t.id}async function ei(e){let t=await In(e.store),s=new Map;for(let a of t){if(a.serving===void 0)continue;let d=await sn(a.manifestPath,e.store);if(d!==void 0)s.set(a.ref,d)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:t.map((a)=>({...a,channels:[...s.get(a.ref)?.values()??[]]}))},null,2)}
|
|
410
|
+
`),o;let i=await Ft({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${p(On(t))}
|
|
411
|
+
`);let r=[];for(let[a,d]of s)for(let l of d.values())r.push({label:`${a} / ${l.id}`,value:l.status,note:l.input!==void 0?`${l.detail??"enter this code"}: ${l.input.payload}`:l.detail??""});if(r.length>0)process.stdout.write(`
|
|
412
|
+
${p(r)}
|
|
413
|
+
`);return i}import{copyFileSync as gl,existsSync as yl,mkdirSync as wl,readFileSync as bl,writeFileSync as $l}from"node:fs";import{dirname as vl,join as ni}from"node:path";async function ti(e){let t=e.env??v([]),s=e.home??t.HOME??"",i=hn(t),r=wn(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:r?.how??"unknown",configPath:r?.configPath===void 0?void 0:ni(s,r.configPath),line:r?.line,steps:r?.steps},null,2)}
|
|
414
|
+
`),r===void 0?E:o;if(process.stdout.write(`${L("shift+enter",!0)}
|
|
415
|
+
${w("⌥ 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.")}
|
|
416
|
+
`),r===void 0)return process.stdout.write(`
|
|
417
|
+
${L("this terminal was not recognised")}
|
|
418
|
+
${w(`TERM_PROGRAM=${t.TERM_PROGRAM??"(unset)"} TERM=${t.TERM??"(unset)"}`)}
|
|
419
|
+
${w(`known: ${or().map((a)=>a.name).join(", ")}`)}
|
|
420
|
+
${D("⌥⏎ works here regardless — nothing needs configuring for it")}
|
|
421
|
+
`),E;if(process.stdout.write(`
|
|
422
|
+
${L(r.name)}
|
|
423
|
+
`),r.how!=="write"){process.stdout.write(`${w(r.how==="unverified"?`no verified recipe for this one — ${r.reason??"nobody has checked it"}`:`this one has to be done by hand — ${r.reason??"its settings are not a text file"}`)}
|
|
411
424
|
|
|
412
|
-
`);for(let[a,
|
|
413
|
-
`);return process.stdout.write(
|
|
414
|
-
${
|
|
425
|
+
`);for(let[a,d]of(r.steps??[]).entries())process.stdout.write(`${w(`${a+1}. ${d}`)}
|
|
426
|
+
`);return process.stdout.write(r.how==="unverified"?`
|
|
427
|
+
${D("⌥⏎ works here today — nothing has to be configured for it")}
|
|
415
428
|
`:`
|
|
416
|
-
${
|
|
417
|
-
`),o}return await
|
|
418
|
-
${
|
|
419
|
-
`),o;let
|
|
420
|
-
${
|
|
421
|
-
${
|
|
422
|
-
${
|
|
423
|
-
`),
|
|
424
|
-
`),
|
|
425
|
-
${
|
|
426
|
-
`),o;if(
|
|
427
|
-
${
|
|
428
|
-
`),o}try{if(
|
|
429
|
-
`),
|
|
430
|
-
${
|
|
431
|
-
${i===""?"":`${
|
|
432
|
-
`}${
|
|
433
|
-
`),o}async function
|
|
434
|
-
`),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${
|
|
435
|
-
`),o;let
|
|
436
|
-
`);continue}
|
|
437
|
-
hint: ${
|
|
438
|
-
`);continue}for(let
|
|
439
|
-
`);else for(let
|
|
440
|
-
`),
|
|
441
|
-
`);if(
|
|
442
|
-
`)}let
|
|
443
|
-
`);return
|
|
429
|
+
${D("then restart the terminal and press shift+⏎ in a session to check it")}
|
|
430
|
+
`),o}return await Sl(r,{...e,env:t,home:s})}async function Sl(e,t){let s=ni(t.home,e.configPath??""),i=yl(s)?bl(s,"utf8"):"";if(mr(i,e))return process.stdout.write(`${w("already configured — a binding for shift+enter is present")}
|
|
431
|
+
${w(rA(s,t.home),4)}
|
|
432
|
+
`),o;let r=hr(i,e);if(r===void 0)return process.stdout.write(`${w("this file is not in a shape this command can edit safely:")}
|
|
433
|
+
${w(rA(s,t.home),4)}
|
|
434
|
+
${D("add the line below by hand:")}
|
|
435
|
+
${w(e.line??"",4)}
|
|
436
|
+
`),E;if(process.stdout.write(`${p([{label:"file",value:rA(s,t.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
|
|
437
|
+
`),t.dryRun===!0)return process.stdout.write(`
|
|
438
|
+
${D("--dry-run: nothing was written")}
|
|
439
|
+
`),o;if(t.yes!==!0){if(!(t.confirm===void 0?!1:await t.confirm("write this change?")))return process.stdout.write(`
|
|
440
|
+
${D("nothing was written")}
|
|
441
|
+
`),o}try{if(wl(vl(s),{recursive:!0}),i!=="")gl(s,`${s}.${A.slug}-backup`);$l(s,r,"utf8")}catch(a){return process.stderr.write(`could not write ${s}: ${a instanceof Error?a.message:String(a)}
|
|
442
|
+
`),E}return process.stdout.write(`
|
|
443
|
+
${L("done")}
|
|
444
|
+
${i===""?"":`${w(`a copy of the old file is at ${rA(`${s}.${A.slug}-backup`,t.home)}`)}
|
|
445
|
+
`}${D("restart the terminal, then press shift+⏎ in a session to check it")}
|
|
446
|
+
`),o}async function ri(e){return e.warm===!0?await kl(e):await Pl(e)}async function kl(e){let t=z(e.manifestPath,{env:v([e.manifestPath])}),s=Bt(t.manifest.tools).selections,i=t.manifest.tools.pinned;if(s.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
|
|
447
|
+
`),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${s.map((l)=>l.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
|
|
448
|
+
`),o;let r=[],a=new Set;for(let l of s){let u=ae[l.id];if(u===void 0)return E;let g;try{let c=u({dir:t.dir,env:t.env,config:l.config,agentId:t.manifest.id});if(c.refresh===void 0){for(let f of await c.resolve(i))a.add(f.spec.slug);if(e.json!==!0)process.stdout.write(`${l.id}: nothing to warm — it resolves without a cache.
|
|
449
|
+
`);continue}g=await c.refresh(i)}catch(c){let f=h(c)?`${c.message}
|
|
450
|
+
hint: ${c.hint}`:c instanceof Error?c.message:String(c);process.stdout.write(`${l.id}: not warmed — ${f}
|
|
451
|
+
`);continue}for(let c of i)if(!g.missing.includes(c))a.add(c);r.push({provider:l.id,fetched:g.fetched,changed:[...g.changed],missing:[...g.missing],cachePath:"cachePath"in g&&typeof g.cachePath==="string"?g.cachePath:""})}if(e.json===!0)process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
452
|
+
`);else for(let l of r){if(process.stdout.write(`${l.fetched} of ${i.length} pinned tools fetched from ${l.provider}
|
|
453
|
+
`),l.changed.length>0)process.stdout.write(` changed: ${l.changed.join(", ")}
|
|
454
|
+
`);if(l.cachePath!=="")process.stdout.write(` cache: ${l.cachePath}
|
|
455
|
+
`)}let d=i.filter((l)=>!a.has(l));for(let l of d)process.stdout.write(` missing: ${l} — no configured provider has a tool with that slug
|
|
456
|
+
`);return d.length>0?E:o}async function Pl(e){let t=await pe.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath])});try{let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");let i=Xo(s);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
|
|
444
457
|
`:`${DA(i)}
|
|
445
|
-
`),o}finally{await
|
|
446
|
-
`),o;let
|
|
458
|
+
`),o}finally{await t.stop("cli-exit")}}import{dirname as oi,isAbsolute as El,resolve as Tn}from"node:path";async function di(e){try{let t=U(e.manifestPath),s=await Do({refs:t.plugins??[],agentId:t.id??e.manifestPath,paths:{workspace:oi(Tn(e.manifestPath)),state:oi(Tn(e.manifestPath)),manifest:Tn(e.manifestPath)},env:v([e.manifestPath]),bus:new bt({runtimeId:"validate"}),builtIn:Qe,pluginRoot:ge(),base:{toolProviders:ae,modelTransports:be,mediaProviders:Ee,channels:Ie}}),i=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:r}=i,a=Se(r.model.main.id,r.model.main.capabilities),{workspace:d,warnings:l}=uA(i,a.promptStyle),u=No(Oo(i,{channels:s.channels})),g=await yn(i,{toolProviders:s.toolProviders,modelTransports:s.modelTransports,mediaProviders:s.mediaProviders,channels:s.channels,scriptRunner:s.scriptRunner,middleware:s.middleware});for(let S of g.providers)await S.stop?.();let c=ho(r,{env:i.env,transports:new Map([...cA,...Object.entries(s.modelTransports)])});YA(r,{env:i.env,providers:new Map(Object.entries(s.mediaProviders))});let f=Xt(d,r.context.rules);if(f!==void 0&&r.context.rules.onExceed==="fail")throw f;let m=[...l,...s.failed,...g.warnings,...g.registry.warnings,...u,...Qo(r),...yo(r),...f===void 0?[]:[f.toDetail()]],y=r.knowledge===void 0?void 0:bo({dir:El(r.knowledge.dir)?r.knowledge.dir:Tn(i.dir,r.knowledge.dir),maxActive:r.knowledge.maxActive,budget:r.knowledge.budget,style:a.promptStyle}),R=["static","volatile","reminder"].map((S)=>{let P=d.files.filter((I)=>I.tier===S).map((I)=>I.name);if(P.length===0)return;return`${S}=${P.join(",")} (${d.tokens[S]}/${r.context.budgets[S]})`}).filter((S)=>S!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:r.id,model:r.model.main.id,window:i.window,capabilities:a,workspace:{files:d.files.map((S)=>({name:S.name,tier:S.tier,editable:S.editable,tokens:S.tokens,budget:S.budget})),tokens:d.tokens},knowledge:y===void 0?[]:y.entries.map((S)=>({name:S.name,keywords:S.keywords,tokens:S.tokens})),warnings:m},null,2)}
|
|
459
|
+
`),o;let T=Nt(r),b=T.map((S)=>S.role===S.configuredAs?`${S.role}=${S.modelId}`:`${S.role}=→main`).join(" "),N=T.filter((S)=>S.role===S.configuredAs),M=$i({manifestPath:e.manifestPath,rawModelId:t.modelId,apiKeyEnv:r.model.main.apiKeyEnv}).flatMap((S)=>{let P=Zi(S.origin);return P===void 0?[]:[` env ${S.variable} — ${P}
|
|
447
460
|
`]}).join("");return process.stdout.write(`ok ${i.path}
|
|
448
|
-
id ${
|
|
449
|
-
models ${
|
|
450
|
-
`+
|
|
451
|
-
`+(
|
|
452
|
-
`).join("")}`)+` capabilities thinking=${
|
|
453
|
-
`+
|
|
454
|
-
workspace ${
|
|
455
|
-
`+(
|
|
456
|
-
`)+` memory ${
|
|
457
|
-
schedules ${
|
|
458
|
-
team ${
|
|
459
|
-
limits maxSteps=${
|
|
460
|
-
`+
|
|
461
|
-
`).join("")),o}catch(
|
|
462
|
-
`),
|
|
461
|
+
id ${r.id}${r.name===void 0?"":` (${r.name})`}
|
|
462
|
+
models ${b}
|
|
463
|
+
`+M+` window ${i.window} ${gA(T[0]?.window)} (reserveOutput ${r.context.reserveOutput}, maxOutput ${a.maxOutput})
|
|
464
|
+
`+(N.length<2?"":`${N.slice(1).map((S)=>` ${S.role.padEnd(12)} ${S.modelId} · window ${S.window.contextWindow} ${gA(S.window)}
|
|
465
|
+
`).join("")}`)+` capabilities thinking=${c.main.capabilities.thinking} promptCache=${c.main.capabilities.promptCache} nativeTools=${c.main.capabilities.nativeTools} strictSchema=${c.main.capabilities.strictSchema}
|
|
466
|
+
`+Rl(c.main.capabilities.promptCache,r.model.main.id)+` dialect ${r.tools.dialect}
|
|
467
|
+
workspace ${R===""?"(none)":R}
|
|
468
|
+
`+(y===void 0?"":` knowledge ${y.entries.length} entries, maxActive=${y.maxActive}, budget=${y.budget}
|
|
469
|
+
`)+` memory ${r.memory===void 0?"none — nothing is retrieved across sessions":`${r.memory.retriever} at ${r.memory.dir}, maxActive=${r.memory.maxActive}, threshold=${r.memory.threshold}, budget=${r.memory.budget}, history=${r.memory.includeHistory}`}
|
|
470
|
+
schedules ${r.schedules.length===0?"none":r.schedules.map((S)=>`${S.id} (${S.kind} ${S.expr}${S.timezone===void 0?"":` ${S.timezone}`}${S.role===void 0?"":` role=${S.role}`}${S.enabled?"":", disabled"})`).join(" ")}
|
|
471
|
+
team ${r.team===void 0?"none — no delegation; `handoff` is not registered":`${r.team.members.map((S)=>`${S.id} (${S.manifest})`).join(" ")} — run one at a time`}
|
|
472
|
+
limits maxSteps=${r.limits.maxSteps} turnTimeoutMs=${r.limits.turnTimeoutMs}
|
|
473
|
+
`+m.map((S)=>` warning ${S.message}
|
|
474
|
+
`).join("")),o}catch(t){if(e.json===!0&&h(t))return process.stdout.write(`${JSON.stringify({ok:!1,error:t.toDetail(),details:t.details},null,2)}
|
|
475
|
+
`),E;throw t}}function Rl(e,t){if(e!=="none")return"";return/(^|\/)claude-/i.test(t)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
|
|
463
476
|
`+` caching at all, so no request field reaches it. Caching lives on the native
|
|
464
477
|
Messages API, which this runtime does not speak.
|
|
465
478
|
`:` promptCache none — this runtime sends no cache directives. Many endpoints cache
|
|
466
|
-
`+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function
|
|
467
|
-
`),e.strict===!0&&
|
|
468
|
-
rendering delimiters=${
|
|
469
|
-
total ${
|
|
470
|
-
`);for(let
|
|
471
|
-
`);if(
|
|
479
|
+
`+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function li(e){try{let t=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:s}=t,i=Se(s.model.main.id,s.model.main.capabilities),{workspace:r,warnings:a}=uA(t,i.promptStyle),d=[...a,...hi(r.files.map((g)=>({name:g.name,authored:g.authored,tier:g.tier,field:g.field})))],l=Xt(r,s.context.rules);if(l!==void 0)d.push(l.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:d.length===0,path:t.path,promptStyle:i.promptStyle,files:r.files.map((g)=>({name:g.name,tier:g.tier,editable:g.editable,tokens:g.tokens,budget:g.budget})),tokens:r.tokens,findings:d},null,2)}
|
|
480
|
+
`),e.strict===!0&&d.length>0?E:o;let u=i.promptStyle;process.stdout.write(`${t.path}
|
|
481
|
+
rendering delimiters=${u.delimiters} intensity=${u.intensity} examplesIn=${u.examplesIn}
|
|
482
|
+
total ${r.tokens.total} tokens (static ${r.tokens.static}, volatile ${r.tokens.volatile}, reminder ${r.tokens.reminder})
|
|
483
|
+
`);for(let g of r.files)process.stdout.write(` ${g.name.padEnd(14)} ${g.tier.padEnd(9)} ${String(g.tokens).padStart(5)}/${g.budget} tokens, editable=${g.editable}
|
|
484
|
+
`);if(d.length===0)return process.stdout.write(`
|
|
472
485
|
no findings
|
|
473
|
-
`),o;for(let
|
|
474
|
-
${
|
|
475
|
-
`),process.stdout.write(` hint: ${
|
|
486
|
+
`),o;for(let g of d)process.stdout.write(`
|
|
487
|
+
${g.code}: ${g.message}
|
|
488
|
+
`),process.stdout.write(` hint: ${g.hint}
|
|
476
489
|
`);return process.stdout.write(`
|
|
477
|
-
${
|
|
478
|
-
`),e.strict===!0?
|
|
479
|
-
`),
|
|
480
|
-
hint: it is an optional dependency, left out by an install with --omit=optional. Reinstall without it (npm i -g ${
|
|
481
|
-
`),
|
|
490
|
+
${d.length} finding(s)
|
|
491
|
+
`),e.strict===!0?E:o}catch(t){if(e.json===!0&&h(t))return process.stdout.write(`${JSON.stringify({ok:!1,error:t.toDetail(),details:t.details},null,2)}
|
|
492
|
+
`),E;throw t}}function Tl(e){let t=kr(e);if(t!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${t} is not installed.
|
|
493
|
+
hint: it is an optional dependency, left out by an install with --omit=optional. Reinstall without it (npm i -g ${A.slug}), or pass --plain where the command has it.
|
|
494
|
+
`),E;if(h(e))process.stderr.write(`${e.format()}
|
|
482
495
|
`);else if(e instanceof Error){if(process.stderr.write(`${e.message}
|
|
483
|
-
`),
|
|
496
|
+
`),Zt().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
|
|
484
497
|
`)}else process.stderr.write(`${String(e)}
|
|
485
|
-
`);return
|
|
486
|
-
`),o;case"help":return process.stdout.write(
|
|
498
|
+
`);return E}async function xl(e){let t=rs(e);switch(t.kind){case"version":return process.stdout.write(`${q}
|
|
499
|
+
`),o;case"help":return process.stdout.write(Bn(t.command)),o;case"usage":return process.stdout.write(Bn()),E;case"command":break}let{command:s,positionals:i,flags:r}=t.parsed,a=i[0],d=()=>Ge(a),l=s.flags.some((c)=>c.name==="store")?r.str("store"):void 0,u=await Ar({needsServer:s.needsServer,disabled:r.bool("no-bootstrap"),install:()=>nr(),...l===void 0?{}:{store:l}}),g=bA(u);if(g!==void 0)process.stderr.write(g);switch(s.name){case"init":{let c=r.str("dir"),f=r.str("user"),m=r.str("name"),y=r.str("purpose"),R=r.str("preset"),T=r.str("model"),b=r.str("base-url"),N=r.str("region"),M=r.str("api-key-env"),S=r.str("system"),P=r.str("web"),I=r.str("web-backend"),O=r.str("composio"),j=r.str("telegram"),V=r.str("telegram-allow"),C=r.str("whatsapp"),ne=r.str("whatsapp-number"),we=r.str("server"),F=r.str("schedules"),Be=r.str("skills"),ke=r.str("daemon");return await Yt({...c===void 0?{}:{dir:c},...f===void 0?{}:{user:f},...m===void 0?{}:{name:m},...y===void 0?{}:{purpose:y},...R===void 0?{}:{preset:R},...T===void 0?{}:{model:T},...b===void 0?{}:{baseUrl:b},...N===void 0?{}:{region:N},...M===void 0?{}:{apiKeyEnv:M},...S===void 0?{}:{system:S},...P===void 0?{}:{web:P},...I===void 0?{}:{webBackend:I},...O===void 0?{}:{composio:O},...j===void 0?{}:{telegram:j},...F===void 0?{}:{schedules:F},...V===void 0?{}:{telegramAllow:V},...C===void 0?{}:{whatsapp:C},...ne===void 0?{}:{whatsappNumber:ne},...we===void 0?{}:{server:we},...Be===void 0?{}:{skills:Be},...ke===void 0?{}:{daemon:ke},yes:r.bool("yes"),plain:r.bool("plain"),measureWindow:r.bool("measure-window"),installServer:nr})}case"run":{let c=r.str("session"),f=r.str("input"),m=r.str("store");return await it({...i[0]===void 0?{}:{manifestPath:d()},...c===void 0?{}:{sessionKey:c},continueSession:r.bool("continue"),...f===void 0?{}:{once:f},...m===void 0?{}:{store:m},ephemeral:r.bool("ephemeral"),quiet:r.bool("quiet"),showReasoning:r.bool("show-reasoning"),noReasoning:r.bool("no-reasoning"),...r.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:r.bool("plain")})}case"schedules":{let c=r.str("store"),f=r.str("id"),m=r.str("enable"),y=r.str("disable");return await vo({manifestPath:d(),...c===void 0?{}:{store:c},...f===void 0?{}:{id:f},...m===void 0?{}:{enable:m},...y===void 0?{}:{disable:y},recipients:r.bool("recipients"),json:r.bool("json")})}case"sessions":{let c=r.str("session"),f=r.str("store"),m=r.num("limit");return await Jo({manifestPath:d(),...c===void 0?{}:{sessionKey:c},...f===void 0?{}:{store:f},...m===void 0?{}:{limit:m},json:r.bool("json"),clear:r.bool("clear"),turns:r.bool("turns")})}case"owner":{let c=r.str("store");return await Qr({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{store:c},json:r.bool("json")})}case"memory":{let c=r.num("limit"),f=r.str("store");return await Nr({action:a,manifestPath:Ge(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...c===void 0?{}:{limit:c},...f===void 0?{}:{store:f},all:r.bool("all"),json:r.bool("json")})}case"config":{let{configCommand:c,readAction:f}=await import("./config-sx40rg8m.js"),m=f(a,i[1]);return await c({action:m.action,...m.ref===void 0?{}:{ref:m.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...r.str("channel")===void 0?{}:{channel:r.str("channel")},remove:r.bool("remove"),yes:r.bool("yes"),...r.str("store")===void 0?{}:{store:r.str("store")}})}case"validate":return await di({manifestPath:d(),json:r.bool("json")});case"workspace":return li({manifestPath:d(),json:r.bool("json"),strict:r.bool("strict")});case"soul":{let c=r.str("out");return zo({action:a,file:i[1],...c===void 0?{}:{out:c}})}case"skills":{if(i.length===0)return await ds({plain:r.bool("plain"),json:r.bool("json")});let c=i[2];return Kt({action:a,manifestPath:Ge(i[1]??""),...c===void 0?{}:{name:c},json:r.bool("json"),strict:r.bool("strict")})}case"sources":{let c=r.str("path"),f=r.str("ref");return await Yo({action:a,rest:i.slice(1),...c===void 0?{}:{path:c},...f===void 0?{}:{ref:f},json:r.bool("json")})}case"channels":{let c=ss("channels",a),f=c.ref??i[1]??"",{channelsCommand:m}=await import("./channels-nf6d8fvx.js");return await m({...c.action===void 0?{}:{action:c.action},manifestPath:Ge(f),...i[2]===void 0?{}:{channelId:i[2]},json:r.bool("json"),installServer:nr})}case"plugins":{let c=r.str("ref"),f=r.str("name");return await $s({action:a,manifestPath:Ge(i[1]??""),rest:i.slice(2),...c===void 0?{}:{ref:c},...f===void 0?{}:{name:f},json:r.bool("json")})}case"agents":{let c=r.str("store");return await Pt({manifestPaths:i.map((f)=>Ge(f)),...c===void 0?{}:{store:c},json:r.bool("json")})}case"restart":{let c=r.str("store");return await Ds({...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{store:c},json:r.bool("json")})}case"status":{let c=r.str("store");return await ei({...c===void 0?{}:{store:c},json:r.bool("json")})}case"logs":{let c=r.num("lines"),f=r.str("store");return await Ft({action:"logs",...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{lines:c},follow:r.bool("follow"),truncate:r.bool("truncate"),...f===void 0?{}:{store:f},json:r.bool("json")})}case"serve":{let c=r.num("port"),f=r.str("host"),m=r.str("store");return await Vo({manifestPaths:i.map((y)=>Ge(y)),...c===void 0?{}:{port:c},...f===void 0?{}:{host:f},...m===void 0?{}:{store:m},claim:r.bool("claim"),json:r.bool("json")})}case"keys":return await yr({noEnhancedKeys:r.bool("no-enhanced-keys")});case"terminal-setup":return await ti({dryRun:r.bool("dry-run"),yes:r.bool("yes"),json:r.bool("json"),confirm:MA});case"remove":return await js({...a===void 0?{}:{ref:a},dryRun:r.bool("dry-run"),filesOnly:r.bool("files-only"),prune:r.bool("prune"),all:r.bool("all"),yes:r.bool("yes"),json:r.bool("json"),...r.str("store")===void 0?{}:{store:r.str("store")},confirm:es});case"stop":{let c=r.str("reason");return await vn({...a===void 0?{}:{manifestPath:d()},dryRun:r.bool("dry-run"),...c===void 0?{}:{reason:c},...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"start":return await Zo({manifestPath:d(),...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")});case"web":{let{webCommand:c}=await import("./web-zvf80ns1.js");return await c({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},noOpen:r.bool("no-open"),...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"credential":{let{credentialCommand:c}=await import("./credential-vdbkfk65.js");return await c({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...r.str("label")===void 0?{}:{label:r.str("label")},...r.str("agents")===void 0?{}:{agents:r.str("agents")},...r.str("sessions")===void 0?{}:{sessions:r.str("sessions")},...r.str("can")===void 0?{}:{can:r.str("can")},...r.str("expires")===void 0?{}:{expires:r.str("expires")},...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"daemon":{let c=r.num("lines");return await Ft({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{lines:c},follow:r.bool("follow"),truncate:r.bool("truncate"),dryRun:r.bool("dry-run"),...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"model":{let c=r.num("price");return await zr({manifestPath:Ge(i[1]),window:r.bool("window"),...c===void 0?{}:{price:c},write:r.bool("write"),yes:r.bool("yes"),json:r.bool("json")})}case"tools":return await ri({manifestPath:d(),warm:r.bool("warm"),json:r.bool("json")});default:throw new n({code:"cli_command_unwired",message:`Command "${s.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}Tr();Cs();Pr();await xl(process.argv.slice(2)).catch(Tl).then((e)=>lr(e));
|
|
487
500
|
|
|
488
|
-
//# debugId=
|
|
501
|
+
//# debugId=AA0149936B525AEA64756E2164756E21
|
|
489
502
|
//# sourceMappingURL=index.js.map
|