dispach 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/APEv2Parser-ysjr6adv.js +5 -0
- package/dist/{AiffParser-y21k3fak.js → AiffParser-9hj6fpmy.js} +3 -3
- package/dist/{AiffParser-y21k3fak.js.map → AiffParser-9hj6fpmy.js.map} +1 -1
- package/dist/{App-4w3qkcs4.js → App-2f72vhjv.js} +7 -7
- package/dist/{App-4w3qkcs4.js.map → App-2f72vhjv.js.map} +3 -3
- package/dist/{AsfParser-wd98k2h4.js → AsfParser-7emspn04.js} +3 -3
- package/dist/{AsfParser-wd98k2h4.js.map → AsfParser-7emspn04.js.map} +1 -1
- package/dist/{DsdiffParser-cbfaj500.js → DsdiffParser-dz88pnnr.js} +3 -3
- package/dist/{DsdiffParser-cbfaj500.js.map → DsdiffParser-dz88pnnr.js.map} +1 -1
- package/dist/{DsfParser-tybrja4x.js → DsfParser-qgh63tbs.js} +2 -2
- package/dist/FlacParser-drm5wq0p.js +5 -0
- package/dist/{MP4Parser-gc94h1n9.js → MP4Parser-yr7p3z12.js} +3 -3
- package/dist/{MP4Parser-gc94h1n9.js.map → MP4Parser-yr7p3z12.js.map} +1 -1
- package/dist/{MatroskaParser-cy2k4fac.js → MatroskaParser-jkbsbsk3.js} +3 -3
- package/dist/{MatroskaParser-cy2k4fac.js.map → MatroskaParser-jkbsbsk3.js.map} +1 -1
- package/dist/{MpegParser-c460fwf0.js → MpegParser-t93vwnew.js} +3 -3
- package/dist/{MpegParser-c460fwf0.js.map → MpegParser-t93vwnew.js.map} +1 -1
- package/dist/{MusepackParser-8mq2eabg.js → MusepackParser-6e8kbh2d.js} +3 -3
- package/dist/{MusepackParser-8mq2eabg.js.map → MusepackParser-6e8kbh2d.js.map} +1 -1
- package/dist/{OggParser-7dnc6apg.js → OggParser-ggcypmag.js} +3 -3
- package/dist/{OggParser-7dnc6apg.js.map → OggParser-ggcypmag.js.map} +1 -1
- package/dist/{WavPackParser-kt7cds9c.js → WavPackParser-jw9stzqp.js} +3 -3
- package/dist/{WavPackParser-kt7cds9c.js.map → WavPackParser-jw9stzqp.js.map} +1 -1
- package/dist/{WaveParser-g47ja0vy.js → WaveParser-epmncs9w.js} +3 -3
- package/dist/{WaveParser-g47ja0vy.js.map → WaveParser-epmncs9w.js.map} +1 -1
- package/dist/{WizardApp-q4p979d1.js → WizardApp-pgzcz9zq.js} +2 -2
- package/dist/{channels-4t89qpdt.js → channels-m8nambmm.js} +2 -2
- package/dist/client.d.ts +43 -0
- package/dist/client.js +9 -9
- package/dist/client.js.map +5 -5
- package/dist/components/App.d.ts.map +1 -1
- package/dist/{config-35r6n1gh.js → config-hmgrqgf2.js} +4 -4
- package/dist/{config-35r6n1gh.js.map → config-hmgrqgf2.js.map} +1 -1
- package/dist/{credential-dpdgg4j6.js → credential-nkb2ya59.js} +2 -2
- package/dist/index-1mbdz3f7.js +12 -0
- package/dist/{index-wc4entme.js.map → index-1mbdz3f7.js.map} +3 -3
- package/dist/{index-ew997be5.js → index-22fzzn7z.js} +7 -7
- package/dist/{index-ew997be5.js.map → index-22fzzn7z.js.map} +1 -1
- package/dist/{index-ynsvkqgb.js → index-308y9xt0.js} +2 -2
- package/dist/{index-7mn8ack9.js → index-836hc2h1.js} +3 -3
- package/dist/{index-7mn8ack9.js.map → index-836hc2h1.js.map} +1 -1
- package/dist/{index-twn9bfm2.js → index-9t4dz145.js} +5 -5
- package/dist/{index-twn9bfm2.js.map → index-9t4dz145.js.map} +1 -1
- package/dist/{index-r4ax3x4d.js → index-djeqvfms.js} +25 -25
- package/dist/index-djeqvfms.js.map +13 -0
- package/dist/{index-z157at3s.js → index-dpcm1j62.js} +17 -17
- package/dist/{index-z157at3s.js.map → index-dpcm1j62.js.map} +1 -1
- package/dist/{index-kjqksgch.js → index-dv9pdjy4.js} +2 -2
- package/dist/{index-8h6kewy1.js → index-eztfverw.js} +2 -2
- package/dist/{index-haypwvzd.js → index-fxpmx6cr.js} +76 -76
- package/dist/{index-haypwvzd.js.map → index-fxpmx6cr.js.map} +3 -3
- package/dist/{index-a2eh8dnk.js → index-hgm2gchq.js} +2 -2
- package/dist/{index-qg9bn980.js → index-hpvfqq6r.js} +280 -241
- package/dist/{index-qg9bn980.js.map → index-hpvfqq6r.js.map} +15 -14
- package/dist/{index-fa9wvpyw.js → index-hrwakb11.js} +2 -2
- package/dist/{index-ma6p7bt4.js → index-jff5q27j.js} +2 -2
- package/dist/index-k8e9f466.js +110 -0
- package/dist/index-k8e9f466.js.map +13 -0
- package/dist/{index-gq1npngp.js → index-mjfv7k5w.js} +2 -2
- package/dist/{index-p1zy871m.js → index-pqw1n1pv.js} +3 -3
- package/dist/{index-p1zy871m.js.map → index-pqw1n1pv.js.map} +1 -1
- package/dist/{index-9914wh1d.js → index-qv6ktepc.js} +2 -2
- package/dist/{index-zce9gy22.js → index-ry6a4bqh.js} +2 -2
- package/dist/{index-fcsg95m5.js → index-sh44ymqz.js} +2 -2
- package/dist/{index-gbkma7ds.js → index-xg7s813b.js} +3 -3
- package/dist/{index-gbkma7ds.js.map → index-xg7s813b.js.map} +1 -1
- package/dist/{index-eqqd4k4f.js → index-y7dxq4a4.js} +3 -3
- package/dist/index.js +149 -149
- package/dist/index.js.map +6 -6
- package/dist/lib/source.d.ts +8 -0
- package/dist/lib/source.d.ts.map +1 -1
- package/dist/lib/types.d.ts +8 -2
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/run.d.ts.map +1 -1
- package/dist/transcript.d.ts.map +1 -1
- package/dist/{web-zph4h3p9.js → web-gfv0mzgs.js} +2 -2
- package/dist/wire.d.ts +19 -0
- package/dist/wire.js +5 -5
- package/dist/wire.js.map +4 -4
- package/package.json +1 -1
- package/dist/APEv2Parser-etzjd528.js +0 -5
- package/dist/FlacParser-7t7da7qy.js +0 -5
- package/dist/index-664xcamy.js +0 -110
- package/dist/index-664xcamy.js.map +0 -13
- package/dist/index-r4ax3x4d.js.map +0 -13
- package/dist/index-wc4entme.js +0 -12
- /package/dist/{APEv2Parser-etzjd528.js.map → APEv2Parser-ysjr6adv.js.map} +0 -0
- /package/dist/{DsfParser-tybrja4x.js.map → DsfParser-qgh63tbs.js.map} +0 -0
- /package/dist/{FlacParser-7t7da7qy.js.map → FlacParser-drm5wq0p.js.map} +0 -0
- /package/dist/{WizardApp-q4p979d1.js.map → WizardApp-pgzcz9zq.js.map} +0 -0
- /package/dist/{channels-4t89qpdt.js.map → channels-m8nambmm.js.map} +0 -0
- /package/dist/{credential-dpdgg4j6.js.map → credential-nkb2ya59.js.map} +0 -0
- /package/dist/{index-ynsvkqgb.js.map → index-308y9xt0.js.map} +0 -0
- /package/dist/{index-kjqksgch.js.map → index-dv9pdjy4.js.map} +0 -0
- /package/dist/{index-8h6kewy1.js.map → index-eztfverw.js.map} +0 -0
- /package/dist/{index-a2eh8dnk.js.map → index-hgm2gchq.js.map} +0 -0
- /package/dist/{index-fa9wvpyw.js.map → index-hrwakb11.js.map} +0 -0
- /package/dist/{index-ma6p7bt4.js.map → index-jff5q27j.js.map} +0 -0
- /package/dist/{index-gq1npngp.js.map → index-mjfv7k5w.js.map} +0 -0
- /package/dist/{index-9914wh1d.js.map → index-qv6ktepc.js.map} +0 -0
- /package/dist/{index-zce9gy22.js.map → index-ry6a4bqh.js.map} +0 -0
- /package/dist/{index-fcsg95m5.js.map → index-sh44ymqz.js.map} +0 -0
- /package/dist/{index-eqqd4k4f.js.map → index-y7dxq4a4.js.map} +0 -0
- /package/dist/{web-zph4h3p9.js.map → web-gfv0mzgs.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{t,j,p,A,Co,ii,Dt,HA,$t,KA,gA,ye,fo,gi,ci,cA,ho,Nt,Bo,Mt,YA,ht,yo,Qo,Le,Ne,F,V,di,Or,jA,J,wo,Do,dA,JA,bo,uA,Z,ne,pi,Ee,yn,Oo,No,fi,hi,Bi,k,Js}from"./index-
|
|
2
|
+
import{t,j,p,A,Co,ii,Dt,HA,$t,KA,gA,ye,fo,gi,ci,cA,ho,Nt,Bo,Mt,YA,ht,yo,Qo,Le,Ne,F,V,di,Or,jA,J,wo,Do,dA,JA,bo,uA,Z,ne,pi,Ee,yn,Oo,No,fi,hi,Bi,k,Js}from"./index-hpvfqq6r.js";import{Ir,xe,dr,ur,Jt,Er,Cr,pr}from"./index-djeqvfms.js";import{ie,Se,de,ue,le,Be,Jr}from"./index-fxpmx6cr.js";import{oa}from"./index-dzy19wtf.js";import{mn}from"./index-2zjh5zd5.js";import{_A,kA,to,Fe,ls,Is,sr,jr,ar,Et,gr,vA,Ht,cr,Kt,LA,ds,us}from"./index-ry6a4bqh.js";import{tr,rn,Ft,xr,Ar,bA,nr,jn,OA,NA,sn,Jn,qn,es,Vn,Wn,zn}from"./index-dpcm1j62.js";import{Vt,FA,Io,En,uo,UA,Sr,Cn,at,aA,Wt,xA,wr}from"./index-dv9pdjy4.js";import{Yr,As,an,ns,os,rs,AA}from"./index-k8e9f466.js";import{gn,rt,cn,as}from"./index-qv6ktepc.js";import{Hn,Kn,nn,Xo,DA,ji,Yn,Vi,Wi}from"./index-1mbdz3f7.js";import"./index-p6ya59m6.js";import{$o}from"./index-bqdkm3de.js";import{Gt,on,$i,Xi}from"./index-mjfv7k5w.js";import{MA,ts}from"./index-095hrkyr.js";import{Je}from"./index-sh44ymqz.js";import{is}from"./index-jff5q27j.js";import{gs,rr,ir,qe,Ve,Ut,cs,xt,me,RA,ut,eo}from"./index-836hc2h1.js";import{Ue,it}from"./index-308y9xt0.js";import{oo,St,Cs,U,fs,We,Ct,lr,hs}from"./index-38gs9anh.js";import{u,v,Q,y,nA,dn,oA,rA}from"./index-3vzf253k.js";import{zt,we,q,Dr,P,ae,br,pn,fn,ri,xs,Zt,Hs,Ae,ve}from"./index-9t4dz145.js";import{Pe}from"./index-jc4kmfwa.js";import{Xs,ta}from"./index-4fj1k64j.js";import{ko,Ia,Rt,be,Po,Ho,o,d,Sn}from"./index-8tmv33mr.js";async function Tn(e){let n=await xt(e),r=[];for(let i of Ae()){let s=i.id??i.ref,a=await ir(s,e)??{enabled:!0},l=n.find((m)=>m.agentId===s),c=l===void 0?Number.NaN:Date.now()-Date.parse(l.startedAt);r.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...l===void 0?{}:{pid:l.pid,serving:`serving · ${l.mode} · pid ${l.pid}${Number.isFinite(c)?` · up ${dn(c)}`:""}`}})}return r}function In(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((n)=>({label:n.ref,value:n.problem!==void 0?"broken":n.enabled?"on":"off",note:n.problem??n.serving??(n.enabled?`not hosted${n.modelId===void 0?"":` · ${n.modelId}`}`:`switched off${n.reason===void 0?"":` — ${n.reason}`}`)}))}async function vt(e){if(e.manifestPaths.length===0){let a=await Tn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
|
|
3
3
|
`);else process.stdout.write(`${u(In(a))}
|
|
4
|
-
`);return o}let n=await Ee.create({agents:[...e.manifestPaths],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k(e.manifestPaths),store:e.store??
|
|
4
|
+
`);return o}let n=await Ee.create({agents:[...e.manifestPaths],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k(e.manifestPaths),store:e.store??P(),lease:!1});U(()=>n.stop("cli-exit"));let r=n.list().map((a)=>a.describe()),i=new Map;for(let a of await n.store.leases.all()){if(a.runtimeId===n.runtimeId||!Z(a.pid))continue;let l=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(l)?` · up ${dn(l)}`:""}`)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:r.map((a)=>({...a,serving:i.get(a.id)??null}))},null,2)}
|
|
5
5
|
`),o;let s=r.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(`${u(s)}
|
|
6
|
-
`),o}import{basename as en,dirname as
|
|
6
|
+
`),o}import{basename as en,dirname as Fi,join as fe,resolve as Ki}from"node:path";import{rmSync as li}from"node:fs";import{isAbsolute as kt,join as ui,resolve as Pt}from"node:path";var mi=3;async function Tt(e){if(e.answers.skills!=="find")return;let n=e.answers.skillsSearch?.trim()??"";if(n===""){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 r=Fe(e.env);if(r.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
7
|
searching ${r.length} skill source(s) for ${JSON.stringify(n)}
|
|
8
8
|
`);let i=[],s=[];for(let f of r){if(!Et(f.name,e.env))try{await vA(f,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(h){s.push(`${f.name} — ${p(h)?h.message:String(h)}`);continue}i.push(...Ht(f,e.env))}for(let f of s)process.stdout.write(y(`could not fetch ${f}
|
|
9
9
|
`));if(i.length===0){process.stdout.write(`${y("no source could be read, so no skill was installed — the directory is there and empty")}
|
|
10
10
|
${y("`sources update` reports why; `sources search <words>` when it works",4)}
|
|
11
|
-
`);return}let a=
|
|
11
|
+
`);return}let a=yi(n,i);if(a.length===0){process.stdout.write(`${y(`nothing in ${i.length} skills matches those words, so none was installed`)}
|
|
12
12
|
${y("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
|
|
13
13
|
`);return}let l=a[0],c=`${l.source}/${l.skill}`;if(process.stdout.write(`${y(`best of ${i.length}: ${c}`)}
|
|
14
|
-
`),a.length>1)process.stdout.write(`${y(`also matched: ${a.slice(1,1+
|
|
14
|
+
`),a.length>1)process.stdout.write(`${y(`also matched: ${a.slice(1,1+mi).map((f)=>`${f.source}/${f.skill}`).join(", ")}`,4)}
|
|
15
15
|
`);if(process.stdout.write(`
|
|
16
|
-
`),Kt({action:"install",manifestPath:e.manifestPath,name:c,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let w=
|
|
16
|
+
`),Kt({action:"install",manifestPath:e.manifestPath,name:c,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let w=wi(e.manifestPath,e.envOverlay);if(w!==void 0)bi(e.manifestPath,l.skill,e.envOverlay),process.stdout.write(`
|
|
17
17
|
${Q(`${c} was removed again: it does not load on this machine`)}
|
|
18
18
|
${y(w,4)}
|
|
19
19
|
${y("everything else is fine; `sources search` for one that needs no extra runtime",4)}
|
|
20
|
-
`)}function
|
|
21
|
-
`,{encoding:"utf8",mode:384}),r}function
|
|
22
|
-
`),o;return n.kind==="failed"?n.code:o}async function Ln(e){return Yt(e)}async function Yt(e){let n=
|
|
23
|
-
`);let h=fe(w,"agent.yaml"),g=wr(m,c);_e(w,g);let b=m.apiKeyEnv,
|
|
24
|
-
${
|
|
25
|
-
`),{kind:"failed",code:d};throw
|
|
26
|
-
`),m.skills==="find"){let
|
|
27
|
-
`);let{outcome:
|
|
28
|
-
`)}}let
|
|
29
|
-
${es(at(m.name))}`);return process.stdout.write(
|
|
20
|
+
`)}function yi(e,n){let r=new Map,i=n.filter((s)=>s.problem===void 0).map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return JA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}function wi(e,n){try{let r=V(e,{...n===void 0?{}:{env:{...process.env,...n}}}),i=r.manifest.skills;if(i===void 0)return;let s=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities);dA({dir:kt(i.dir)?i.dir:Pt(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:s.promptStyle,agentDir:r.dir,runner:ue()});return}catch(r){return p(r)?r.message:String(r)}}function bi(e,n,r){try{let i=V(e,{...r===void 0?{}:{env:{...process.env,...r}}}),s=i.manifest.skills;if(s===void 0)return;let a=kt(s.dir)?s.dir:Pt(i.dir,s.dir);li(ui(a,n),{recursive:!0,force:!0}),cr(a,n)}catch{}}var On=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function It(e,n,r={}){let i=r.fetch??fetch,s=e.replace(/\/+$/,""),a=r.apiKey===void 0?{}:{authorization:`Bearer ${r.apiKey}`},l=async(b)=>{try{let T=await i(b,{headers:a,signal:AbortSignal.timeout(3000)});if(!T.ok)return;let x=await T.json();return x!==null&&typeof x==="object"?x:void 0}catch{return}},w=((await l(`${s}/models/${n}/endpoints`))?.data?.endpoints??[]).map((b)=>On(b.context_length)).filter((b)=>b!==void 0);if(w.length>0)return{tokens:Math.min(...w),source:`the smallest of ${w.length} published endpoint${w.length===1?"":"s"} at ${s}`};let h=((await l(`${s}/models`))?.data??[]).find((b)=>b.id===n),g=On(h?.context_length)??On(h?.max_model_len);return g===void 0?void 0:{tokens:g,source:`${s}/models`}}import{randomBytes as vi}from"node:crypto";import{mkdirSync as Si,readFileSync as Ot,writeFileSync as ki}from"node:fs";import{join as Pi}from"node:path";function Ye(e){return Pi(e,".owner")}function Ei(e,n=vi){try{let i=Ot(Ye(e),"utf8").trim();if(i!=="")return i}catch{}let r=`me:${Co(n(6))}`;return Si(e,{recursive:!0}),ki(Ye(e),`${r}
|
|
21
|
+
`,{encoding:"utf8",mode:384}),r}function Ri(e){return e.flatMap((n)=>(n.allowFrom??[]).filter((r)=>r!=="*").map((r)=>`${n.type}:${r}`))}async function xi(e,n){let r=e.conversations,i=(n.now??new Date).toISOString(),s=await r.assignment(n.agentId);if(s!==void 0&&s.participantId!==n.owner)throw new A({code:"owner_assigned_elsewhere",message:`Agent "${n.agentId}" is assigned to ${s.participantId}, not to ${n.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/${n.agentId}/assignee) and run \`${t.slug} owner adopt ${n.agentId}\` again.`});if(await r.participant(n.owner)===void 0)await r.upsertParticipant({id:n.owner,kind:"human",role:"admin",createdAt:i});let a=[...new Set([...s?.channelIds??[],...n.channelIds])];return await r.assign({agentId:n.agentId,participantId:n.owner,...a.length===0?{}:{channelIds:a},assignedAt:i}),{channelIds:a}}async function Te(e,n,r){let i=Ot(n,"utf8"),s=String(Ne(i,["id"])??""),a=Ne(i,["channels"]),l=Ei(r),{channelIds:c}=await xi(e,{agentId:s,owner:l,channelIds:Ri(Array.isArray(a)?a.filter((m)=>typeof m?.type==="string"):[])});return{agentId:s,owner:l,channelIds:c}}import{existsSync as Ti,mkdirSync as Ii,writeFileSync as Oi}from"node:fs";import{dirname as Ai,join as An,resolve as _n,sep as _i}from"node:path";var Qe={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 Nn(e,n,r,i){let s=[];for(;;){let a=aA(e,r);if(a===void 0)break;if(a.optional===!0){e[a.step]="";continue}if(a.fallback===""){s.push(a.step),e[a.step]="(missing)";continue}let l=Wt(a.step,a.fallback);if(l.ok)e[a.step]=l.value}if(s.length>0){if(i?.naming==="answers"){let l=s.map((c)=>`answers.${c}`).join(", ");throw new A({code:"cli_init_missing_answers",message:`Not interactive (${n}), and ${s.join(", ")} ${s.length===1?"has":"have"} no default.`,hint:`Provide ${l} in the request body. GET /v1/provision lists every question with its prompt, its default and its choices.`})}let a=s.map((l)=>Qe[l]).join(", ");throw new A({code:"cli_init_missing_answers",message:`Not interactive (${n}), and ${s.join(", ")} ${s.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 Fn(e,n){let r=e,i=Vt(r.preset),s=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",l=r.dir??FA(r.dirChoice,r.name,n);if(l===void 0)throw new A({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(r.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:r.user,name:r.name,purpose:r.purpose,preset:r.preset,model:r.model,baseUrl:r.baseUrl??"",...r.region===void 0?{}:{region:r.region},system:r.system,web:r.web,...r.webBackend===void 0?{}:{webBackend:r.webBackend},...r.webKey===void 0||r.webKey===""?{}:{webKey:r.webKey},composio:r.composio,...r.composioKey===void 0||r.composioKey===""?{}:{composioKey:r.composioKey},telegram:r.telegram,...r.telegramToken===void 0||r.telegramToken===""?{}:{telegramToken:r.telegramToken},...r.telegramAllow===void 0||r.telegramAllow===""?{}:{telegramAllow:r.telegramAllow},whatsapp:r.whatsapp??"none",...r.whatsappNumber===void 0||r.whatsappNumber===""?{}:{whatsappNumber:r.whatsappNumber},schedules:r.schedules??"none",server:a,skills:r.skills,...r.skillsSearch===void 0||r.skillsSearch===""?{}:{skillsSearch:r.skillsSearch},...r.skillsPick===void 0||r.skillsPick===""?{}:{skillsPick:r.skillsPick},daemon:r.daemon,...a==="local"?{serverToken:Ci(l,n.agentDirBase)?xs(n.agentDirBase,At):At()}:{},...s===void 0?{}:{apiKeyEnv:s},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:l}}function Ci(e,n){let r=_n(e),i=_n(n);return r===i||r.startsWith(i+_i)}function At(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((n)=>n.toString(16).padStart(2,"0")).join("")}function _e(e,n){let r=n.map((i)=>An(e,i.relPath)).filter((i)=>Ti(i));if(r.length>0)throw new A({code:"cli_init_target_exists",message:`${r.length} of the files init would write already exist: ${r.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 n){let s=An(e,i.relPath);Ii(Ai(s),{recursive:!0}),Oi(s,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function Ze(e,n){let r=V(e,{...n===void 0?{}:{env:{...process.env,...n}}}),i=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:s,warnings:a}=uA(r,i.promptStyle),l=$t(s,r.manifest.context.rules);if(l!==void 0&&r.manifest.context.rules.onExceed==="fail")throw l;return{distilled:a.some((c)=>c.code==="soul_distilled")}}var jt=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 Lt(e){let n=Wt(e.step,e.fallback);return n.ok?n.value:e.fallback}function Ni(e,n){let r=Un.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Lt(e),optional:e.optional===!0,secret:Cn.has(e.step),...n===void 0?{}:{requires:n},...e.options===void 0?{}:{choices:e.options.filter((i)=>r?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var _t=64;function Bt(e){let n=new Map,r=new Set,i=(a,l)=>{let c={...a},m=[];for(let w=0;w<_t;w+=1){let f=aA(c,e);if(f===void 0)break;let h=Lt(f);if(!jt.has(f.step)&&!n.has(f.step))n.set(f.step,Ni(f,l));for(let g of f.options??[]){if(g.value===h)continue;if(Un.get(f.step)?.has(g.value)===!0)continue;m.push({seed:{...c,[f.step]:g.value},opened:{step:f.step,value:g.value}})}c[f.step]=h}return m},s=[...i({})];for(let a=0;a<_t&&s.length>0;a+=1){let l=s.splice(0,s.length);for(let c of l){let m=`${c.opened.step}=${c.opened.value}`;if(r.has(m))continue;r.add(m),s.push(...i(c.seed,c.opened))}}return[...n.values()].sort((a,l)=>Sr.indexOf(a.step)-Sr.indexOf(l.step))}function qt(e){let n={};for(let[c,m]of Object.entries(e.answers)){let w=c;if(!(w in Qe))throw new A({code:"provision_unknown_answer",message:`"${c}" 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:c});let f=jt.get(w);if(f!==void 0)throw new A({code:f.code,message:`"${c}" cannot be set over the API.`,hint:f.hint,field:c});let h=Un.get(w)?.get(m.trim().toLowerCase());if(h!==void 0)throw new A({code:h.code,message:`${c} is ${JSON.stringify(m)}, which this runtime cannot do over the API.`,hint:h.hint,field:c});let g=Wt(w,m);if(!g.ok)throw new A({code:"provision_answer_invalid",message:`${c} is ${JSON.stringify(m)}, which ${g.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:c});n[w]=g.value}Nn(n,"this is the provisioning API",e.defaults,{naming:"answers"});let r=Fn(n,e.defaults),i=at(r.name),s=FA("sandbox",r.name,e.defaults);if(s===void 0)throw new A({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(r.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=_n(s),l=wr({...r,dir:a});return _e(a,l),{agentId:i,dir:a,manifestPath:An(a,"agent.yaml"),files:l.map((c)=>c.relPath)}}function Ui(e){if(e.web!=="search")return;return Io(e.webBackend??"tavily")?.apiKeyEnv}async function Xt(e){let n=await Yt(e);if(n.kind==="aborted")return process.stdout.write(`nothing written
|
|
22
|
+
`),o;return n.kind==="failed"?n.code:o}async function Ln(e){return Yt(e)}async function Yt(e){let n=Di(e),r=it({json:!1,plain:e.plain===!0,oneShot:!1}),i=r.mode==="rich"&&e.yes!==!0,s={agentDirBase:q()};if(i){let E=await Hi(n,s);if(E===void 0)return{kind:"aborted"};Object.assign(n,E)}else Nn(n,e.yes===!0?"--yes was passed":r.because,s);let a=Fn(n,s),l=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),c=(i||e.measureWindow===!0)&&a.baseUrl!==""?await It(a.baseUrl,a.model,{...l===void 0||l===""?{}:{apiKey:l}}):void 0,m=a,w=Ki(process.cwd(),m.dir),f=Hs(w);if(f!==void 0)process.stderr.write(`${f}
|
|
23
|
+
`);let h=fe(w,"agent.yaml"),g=wr(m,c);_e(w,g);let b=m.apiKeyEnv,x=b!==void 0&&m.apiKey===void 0&&(process.env[b]===void 0||process.env[b]==="")&&b!==void 0?{[b]:"(pending)"}:void 0,S=!1;try{S=Ze(fe(w,"agent.yaml"),x).distilled}catch(E){if(p(E))return process.stderr.write(`init wrote ${g.length} files to ${w}, but the result does not load:
|
|
24
|
+
${E.format()}
|
|
25
|
+
`),{kind:"failed",code:d};throw E}if(process.stdout.write(`wrote ${g.length} files to ${w} — validated ok
|
|
26
|
+
`),m.skills==="find"){let E=(m.skillsPick??"").split(",").map((I)=>I.trim()).filter((I)=>I!=="");if(E.length>0)ds(E,h,{...x===void 0?{}:{envOverlay:x}});else if(!i)await Tt({answers:m,manifestPath:h,...x===void 0?{}:{envOverlay:x}})}await Li(h,w,s.agentDirBase);let L;if(m.daemon==="service"){process.stdout.write(`
|
|
27
|
+
`);let{outcome:E,host:I}=await jn({...e.installServer===void 0?{}:{install:e.installServer}}),_=bA(E);if(_!==void 0)process.stderr.write(_);if(I?.baseUrl!==void 0){let N=await OA(I,h);if(N.ok)L=I.baseUrl;else process.stderr.write(`pid ${I.pid} did not adopt ${at(m.name)}${N.detail===void 0?"":`: ${N.detail}`}
|
|
28
|
+
`)}}let G;if(m.whatsapp==="connected"&&(m.whatsappNumber??"")!==""&&i)G=L!==void 0?await Jn({manifestPath:h,channelId:"wa"}):await qn({manifestPath:h,dir:w,number:m.whatsappNumber??"",channelId:"wa"});if(m.whatsapp==="connected"&&G!=="paired")process.stdout.write(`
|
|
29
|
+
${es(at(m.name))}`);return process.stdout.write(Gi(m,w,S,L)),{kind:"ok",manifestPath:fe(w,"agent.yaml")}}async function Li(e,n,r){let i=en(n);if(!Zt(n)){process.stdout.write(`
|
|
30
30
|
To make it yours across every surface: ${t.slug} owner adopt ${e}
|
|
31
|
-
`);return}let s;try{s=await ne.open({path:
|
|
31
|
+
`);return}let s;try{s=await ne.open({path:P()}),await Te(s,e,r)}catch(a){let l=a instanceof Error?a.message:String(a);process.stderr.write(`could not record you as ${i}'s owner: ${l}
|
|
32
32
|
hint: run \`${t.slug} owner adopt ${i}\` once the store is reachable.
|
|
33
|
-
`)}finally{await s?.close()}}function
|
|
33
|
+
`)}finally{await s?.close()}}function Mi(e){if(e===void 0)return[];if(UA.some((n)=>n.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function Di(e){let n={},r=[["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],...Mi(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,s]of r){if(s===void 0)continue;let a=Wt(i,s);if(!a.ok)throw new A({code:"cli_init_flag_invalid",message:`${Qe[i]} is ${JSON.stringify(s)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});n[i]=a.value}return n}async function Hi(e,n){let[{render:r},{createElement:i},{WizardApp:s}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-pgzcz9zq.js")]),a;oo();let l=r(i(s,{title:`${t.name} ${J}`,given:e,defaults:n,onDone:(c)=>{a=c}}),{exitOnCtrlC:!1,...Ue()});return U(()=>l.unmount()),await l.waitUntilExit(),l.unmount(),a}function Gi(e,n,r,i){let s=i!==void 0,l=Fi(n)===q()?en(n):fe(n,"agent.yaml"),c=fe(n,"agent.yaml"),m=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)m.push(`Add your key: edit ${fe(n,".env")} and set ${e.apiKeyEnv}=`);let w=Ui(e);if(w!==void 0&&e.webKey===void 0)m.push(`Add your search key: edit ${fe(n,".env")} and set ${w}= — web_fetch works without it, web_search does not`);if(xA(e)&&e.composioKey===void 0)m.push(`Add your Composio key: edit ${fe(n,".env")} and set ${En}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)m.push(`Add your bot token: message @BotFather with /newbot, then edit ${fe(n,".env")} and set ${uo}=`);let f=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],h=f.length>0||e.server==="local",g=[...f,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(s)m.push(`open ${AA(i,en(n))} — the web UI. The service is serving `+`${en(n)} now; ${g} ${f.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),m.push(`${t.slug} run ${l} — talks to it here, attached to that same service.`);else m.push(`${t.slug} run ${l}`);if(h&&!s){if(m.push(`${t.slug} serve ${l} — starts ${g}; \`run\` starts neither`),e.daemon==="service")m.push(`${t.slug} daemon install — the same thing, supervised: one service hosts `+"every agent, starts at login and survives a reboot.")}if(e.telegram==="connected"&&e.telegramAllow===void 0)m.push("Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print "+"the exact line to paste into agent.yaml.");if(xA(e))m.push('Ask it for an app — "connect my Gmail" — and it finds the tools, gives you the '+"sign-in link, and pins what you need. New tools go live on the next restart.");m.push(e.skills==="find"?`Add more skills: \`${t.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${t.slug} skills install ${l} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${t.slug} sources search <what it should do>\` searches 440+ from two catalogues.`:`Skills are off but the directory is there — \`${t.slug} sources search <what it should do>\` finds one, \`${t.slug} skills new ${l} <name>\` writes one.`),m.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${t.slug} workspace ${c}\` shows exactly what still reads as a template.`);let b=s?`
|
|
34
34
|
it is running in the background now — \`${t.slug} status\` at any time,
|
|
35
35
|
\`${t.slug} restart ${l}\` after editing it, and \`${t.slug} stop\` turns everything off.
|
|
36
36
|
`:"";return`${r?`
|
|
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
39
|
`:""}${b}
|
|
40
|
-
`+m.map((
|
|
40
|
+
`+m.map((x,S)=>` ${S+1}. ${x}
|
|
41
41
|
`).join("")}var tn=16;function ln(e=process.stdin){let n=[],r=[],i=(s)=>{let a=typeof s==="string"?s:s.toString("utf8");if(r.push(a),r.length>tn)r.splice(0,r.length-tn);if(n.push(...Xs(a)),n.length>tn)n.splice(0,n.length-tn)};return e.on("data",i),{correct:(s,a)=>ta(s,a,n),takeRaw:()=>r.shift(),close:()=>{e.off("data",i)}}}var Qt=[{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 — \`${t.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 un(e){let n=e.TERM_PROGRAM??"";if(n==="vscode")return"vscode";if(n==="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(n==="WarpTerminal")return"warp";if(n==="iTerm.app")return"iterm2";if(n==="Apple_Terminal")return"apple";return"unknown"}function hn(e){return Qt.find((n)=>n.id===e)}function ss(){return Qt}function ms(e,n){return n.marker!==void 0&&e.includes(n.marker)}function ps(e,n){let r=n.line;if(r===void 0)return;if(n.id!=="vscode"){let c=e.trimEnd();return c===""?`${r}
|
|
42
42
|
`:`${c}
|
|
43
43
|
${r}
|
|
@@ -46,13 +46,13 @@ ${r}
|
|
|
46
46
|
]
|
|
47
47
|
`;let s=i.indexOf("[");if(s===-1)return;let l=i.slice(s+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,s+1)}
|
|
48
48
|
${r}${l}
|
|
49
|
-
${i.slice(s+1)}`}async function ys(e={}){let n=it({plain:!1,json:!1,oneShot:!1});if(n.mode!=="rich")throw new A({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${n.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 r=Ue(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,s=un(process.env),a=hn(s)?.name??s,[{render:l},{createElement:c},{KeyProbe:m}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-5anphmb7.js")]),w=()=>{},f=new Promise((b)=>{w=b}),h=ln();U(()=>{h.close()}),St(),process.stdout.write(Rt);let g=l(c(m,{columns:Pe(process.stdout.columns,be),asked:i,terminal:a,takeRaw:h.takeRaw,correctKeys:h.correct,onDone:w}),{exitOnCtrlC:!1,...r});return U(()=>g.unmount()),await f,g.unmount(),h.close(),We(),await Ct(),o}var
|
|
50
|
-
delivery reads the channel back out of the key.`;function
|
|
49
|
+
${i.slice(s+1)}`}async function ys(e={}){let n=it({plain:!1,json:!1,oneShot:!1});if(n.mode!=="rich")throw new A({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${n.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 r=Ue(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,s=un(process.env),a=hn(s)?.name??s,[{render:l},{createElement:c},{KeyProbe:m}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-5anphmb7.js")]),w=()=>{},f=new Promise((b)=>{w=b}),h=ln();U(()=>{h.close()}),St(),process.stdout.write(Rt);let g=l(c(m,{columns:Pe(process.stdout.columns,be),asked:i,terminal:a,takeRaw:h.takeRaw,correctKeys:h.correct,onDone:w}),{exitOnCtrlC:!1,...r});return U(()=>g.unmount()),await f,g.unmount(),h.close(),We(),await Ct(),o}var qi=24,Mn=22;function Dn(e){let n=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${t.slug} ${e.name}${n===""?"":` ${n}`}`}function ws(e){let n=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?n:`-${e.short}, ${n}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(qi-1)} ${e.help}${i}`}var bs=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
|
|
50
|
+
delivery reads the channel back out of the key.`;function Ji(e){let n=[];for(let r of e.args){if(r.choices===void 0||r.choices.length===0)continue;let i=Math.max(...r.choices.map((s)=>s.value.length))+2;n.push("",`${r.name}:`);for(let s of r.choices)n.push(` ${s.value.padEnd(i)}${s.help}`)}return n}function Gn(e){if(e!==void 0){let r=[e.summary,"","usage:",` ${Dn(e)} [flags]`,...Ji(e),"","flags:",...cn(e).map(ws)];if(e.flags.some((i)=>i.name==="session"))r.push("",bs);return`${r.join(`
|
|
51
51
|
`)}
|
|
52
52
|
`}let n=Math.max(...rt.map((r)=>Dn(r).length))+2;return`${[`${t.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...rt.map((r)=>` ${Dn(r).padEnd(n)}${r.summary}`),` ${t.slug} --version`,` ${t.slug} --help`,"",`Per-command flags: ${t.slug} <command> --help`,"","global flags:",...gn.map(ws),"",bs,"","environment:",` ${`${t.envPrefix}BRAND`.padEnd(Mn)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Mn)}set to anything to force plain output`,` ${"DEBUG".padEnd(Mn)}print stack traces on failure`].join(`
|
|
53
53
|
`)}
|
|
54
|
-
`}function $s(e){if(!(e instanceof Error))return;let n=e.code;if(n!=="ERR_MODULE_NOT_FOUND"&&n!=="MODULE_NOT_FOUND")return;let r=/['"](ink|react)(?:\/[^'"]*)?['"]/.exec(e.message);return r?.[1]==="ink"||r?.[1]==="react"?r[1]:void 0}import{readFileSync as
|
|
55
|
-
`)){let r=[];for(let[i,s]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||s===void 0||s==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(
|
|
54
|
+
`}function $s(e){if(!(e instanceof Error))return;let n=e.code;if(n!=="ERR_MODULE_NOT_FOUND"&&n!=="MODULE_NOT_FOUND")return;let r=/['"](ink|react)(?:\/[^'"]*)?['"]/.exec(e.message);return r?.[1]==="ink"||r?.[1]==="react"?r[1]:void 0}import{readFileSync as zi,statSync as Yi}from"node:fs";var Qi=65536;function vs(e=process.env,n=(r)=>process.stderr.write(`${r}
|
|
55
|
+
`)){let r=[];for(let[i,s]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||s===void 0||s==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(Yi(s).size>Qi)continue;e[a]=zi(s,"utf8").replace(/\r?\n$/,""),r.push(a)}catch(l){n(`${i} names ${s}, which could not be read (${l instanceof Error?l.message:String(l)}); ${a} is not set from it.`)}}return r}var Zi=[{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 ea(e,n){return Zi.some((r)=>r.name===e&&n.includes(r.contains))}function na(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var Ss;function ks(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(Ss)return;if(na(e))return;let n=process.emitWarning;Ss=n,process.emitWarning=(r,...i)=>{let s=typeof r==="string"?sa(i):r.name,a=typeof r==="string"?r:r.message;if(ea(s,a))return;Reflect.apply(n,process,[r,...i])}}function sa(e){let n=e[0];return typeof n==="string"?n:"Warning"}var Ps=96;async function Rs(e){let n=await Ee.create({agents:[e.manifestPath],store:e.store??P(),toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath])});try{let r=n.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let m=await r.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(m,null,2)}
|
|
56
56
|
`),o;return process.stdout.write(u([{label:"passages",value:String(m.passages)},{label:"files read",value:String(m.indexed.length)},{label:"conversations",value:m.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(m.sessions.length)},{label:"shared scopes",value:m.scopes.length===0?"none":m.scopes.join(", ")},{label:"dropped",value:m.dropped.length===0?"":m.dropped.join(", ")}])),process.stdout.write(m.indexed.length===0&&m.sessions.length===0?"\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\n":`
|
|
57
57
|
Read: ${[...m.indexed,...m.sessions].join(", ")}
|
|
58
58
|
`),o}let i=e.query??"";if(i.trim()==="")return process.stderr.write(`memory search needs something to search for.
|
|
@@ -61,17 +61,17 @@ Read: ${[...m.indexed,...m.sessions].join(", ")}
|
|
|
61
61
|
Nothing ${e.all===!0?"matched":`scored above ${s.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
|
|
62
62
|
`),o;let c=Math.max(6,...l.map((m)=>Es(m,s.carried).length));process.stdout.write(`
|
|
63
63
|
${oe("SCORE",6)} ${oe("LEXICAL",7)} ${oe("COVER",5)} ${oe("SOURCE",c)} ${oe("LEARNED",10)} PASSAGE
|
|
64
|
-
`);for(let m of l){let w=m.score>=s.threshold?" ":"·";process.stdout.write(`${oe(m.score.toFixed(3),6)} ${oe(m.lexical.toFixed(3),7)} ${oe(m.coverage.toFixed(2),5)} ${oe(Es(m,s.carried),c)} ${oe(m.passage.at.slice(0,10),10)} ${w}${
|
|
64
|
+
`);for(let m of l){let w=m.score>=s.threshold?" ":"·";process.stdout.write(`${oe(m.score.toFixed(3),6)} ${oe(m.lexical.toFixed(3),7)} ${oe(m.coverage.toFixed(2),5)} ${oe(Es(m,s.carried),c)} ${oe(m.passage.at.slice(0,10),10)} ${w}${ra(m.passage.text)}
|
|
65
65
|
`)}if(e.all===!0&&a.length<l.length)process.stdout.write(`
|
|
66
66
|
${l.length-a.length} shown below the threshold; a turn would not inject those.
|
|
67
67
|
`);if(s.carried!==void 0&&l.some((m)=>m.passage.source===s.carried))process.stdout.write(`
|
|
68
68
|
${s.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
|
|
69
|
-
`);return o}finally{await n.stop("cli-exit")}}function
|
|
70
|
-
`)}function js(e,n,r){return`measured ${n} against ${e} — ${r}`}function Fs(e,n){let r=Math.max(1,e),i=0,s=0;while(r<n)i+=r,s+=1,r*=2;return i+=n,s+=1,{requests:s,tokens:i}}var
|
|
71
|
-
Reply with the single character x.`;try{let s=await
|
|
69
|
+
`);return o}finally{await n.stop("cli-exit")}}function ra(e){let n=e.replace(/\s+/g," ").trim();return n.length<=Ps?n:`${n.slice(0,Ps-1)}…`}function oe(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function Es(e,n){return e.passage.source===n?`${e.passage.source} *`:e.passage.source}var ia=["context_length","context_window","max_context_length","max_model_len"],aa=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let n=e.prompt_tokens_details;return wn(n)?n.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function wn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Bn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function Ts(e,n){let r=wn(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let s=n.toLowerCase();for(let a of i){if(!wn(a))continue;let l=typeof a.id==="string"?a.id.toLowerCase():void 0;if(l===void 0)continue;if(!(l===s||l.endsWith(`/${s}`)||s.endsWith(`/${l}`)))continue;for(let m of ia){let w=Bn(a[m]);if(w!==void 0)return{technique:"metadata",tokens:w,bound:"ceiling",detail:`GET /models published ${m}: ${w}`}}return}return}function Xn(e){let n=[/(?: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],r=[];for(let i of n){let s=i.exec(e);if(s?.[1]===void 0)continue;let a=Bn(Number(s[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function Os(e){if(!wn(e))return;let n=Bn(e.prompt_tokens)??0;for(let[r,i]of aa){let s=i(e);if(typeof s==="number"&&Number.isFinite(s))return{cached:s,promptTokens:n,field:r}}return{cached:void 0,promptTokens:n,field:void 0}}function _s(e,n,r){if(e===void 0||n===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(n.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=n.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${n.promptTokens} prompt tokens, via ${n.field}`};return{supported:!1,detail:`${n.field} came back 0 on an identical repeat of a ${r}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function Ce(e){let n=e.filter((i)=>i.bound==="ceiling");return(n.length>0?n:e).reduce((i,s)=>i===void 0||s.tokens>i.tokens?s:i,void 0)}function Ns(e,n,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${n.toLocaleString("en-US").replaceAll(",","_")},`,...r===void 0?[]:[` maxOutput: ${r.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
|
|
70
|
+
`)}function js(e,n,r){return`measured ${n} against ${e} — ${r}`}function Fs(e,n){let r=Math.max(1,e),i=0,s=0;while(r<n)i+=r,s+=1,r*=2;return i+=n,s+=1,{requests:s,tokens:i}}var da=2000000000,Ks=1024,Ls=8192,Ms=2097152;function Ds(e){return"context ".repeat(Math.max(1,e))}async function je(e){let n=await e.text();try{return{text:n,json:JSON.parse(n)}}catch{return{text:n,json:void 0}}}function Gs(e,n){if(typeof e==="object"&&e!==null){let r=e,i=r.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let s=i.message;if(typeof s==="string")return s}if(typeof r.message==="string")return r.message}return n}async function la(e,n,r){try{let i=await n(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:s}=await je(i),a=Ts(s,e.modelId);if(a===void 0)r.push("GET /models published no context length");return a}catch(i){r.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function ca(e,n,r){try{let i=await n(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:da})}),{text:s,json:a}=await je(i);if(i.ok)return r.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 l=Gs(a,s.slice(0,400)),c=Xn(l);if(c===void 0)return r.push(`the refusal named no number: ${l.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let m=/max_?tokens/i.test(l);return{window:m?void 0:{technique:"refusal",tokens:c,bound:"ceiling",detail:`refused an over-range request naming ${c}`},outputCeiling:m?c:void 0}}catch(i){return r.push(`the over-range request failed: ${i instanceof Error?i.message:String(i)}`),{window:void 0,outputCeiling:void 0}}}async function Us(e,n,r){let i=await n(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:r}],max_tokens:1})});if(!i.ok)return;let{json:s}=await je(i),a=typeof s==="object"&&s!==null?s.usage:void 0;return Os(a)}async function ua(e,n,r){let i=`${Ds(Ks)}
|
|
71
|
+
Reply with the single character x.`;try{let s=await Us(e,n,i),a=await Us(e,n,i);return _s(s,a,Ks)}catch(s){return r.push(`the caching probe failed: ${s instanceof Error?s.message:String(s)}`),{supported:void 0,detail:"the probe did not complete"}}}async function fa(e,n,r){let i=Ls,s=0;while(i<=Ms){let a;try{a=await n(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Ds(i)}],max_tokens:1})})}catch(w){r.push(`the search stopped at ${i}: ${w instanceof Error?w.message:String(w)}`);break}if(a.ok){let{json:w}=await je(a),f=typeof w==="object"&&w!==null?w.usage:void 0,h=typeof f==="object"&&f!==null?f.prompt_tokens:void 0;s=typeof h==="number"&&Number.isFinite(h)?h:s,i*=2;continue}let{text:l,json:c}=await je(a),m=Xn(Gs(c,l.slice(0,400)));if(m!==void 0)return{technique:"search",tokens:m,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${m}`};break}if(s===0)return;return{technique:"search",tokens:s,bound:"floor",detail:`accepted a prompt the endpoint counted at ${s} tokens; nothing above it named a number`}}function ma(e,n){let r=Ce(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,s=r===void 0?"":r.tokens===e.declared?"matches what is configured":r.bound==="ceiling"&&r.tokens>e.declared?`configured value is ${e.declared}, which is ${(r.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[v(` ${e.role} · ${e.modelId}`),u([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:s},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...n===void 0?[]:[{label:"price",value:`$${n}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((l)=>` · ${l}`)],...r===void 0||r.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",Ns(e.modelId,r.tokens,e.outputCeiling).split(`
|
|
72
72
|
`).map((l)=>` ${l}`).join(`
|
|
73
73
|
`)]].join(`
|
|
74
|
-
`)}async function Ws(e){let n=e.fetch??globalThis.fetch;try{let r=V(e.manifestPath,{env:k([e.manifestPath])}),{manifest:i}=r,s=Nt(i).filter((m)=>m.role===m.configuredAs),a=!1;if(e.window){let m=Fs(
|
|
74
|
+
`)}async function Ws(e){let n=e.fetch??globalThis.fetch;try{let r=V(e.manifestPath,{env:k([e.manifestPath])}),{manifest:i}=r,s=Nt(i).filter((m)=>m.role===m.configuredAs),a=!1;if(e.window){let m=Fs(Ls,Ms),w=m.tokens*s.length,f=e.price===void 0?"":` ≈ $${(w/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${m.requests} requests per role, about ${w.toLocaleString("en-US")} input tokens in total${f}.
|
|
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?`
|
|
@@ -79,23 +79,23 @@ Tokens rather than dollars unless --price says otherwise: a price table in this
|
|
|
79
79
|
Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
|
|
80
80
|
|
|
81
81
|
`)}let l=[];for(let m of s){let w=i.model[m.role]??i.model.main;if(w.baseUrl===void 0){process.stdout.write(`model.${m.role} uses the ${w.api??"chat-completions"} transport, which this probe does not speak. Its window comes from the capability registry: ${m.window.contextWindow.toLocaleString("en-US")} tokens (${m.window.source}).
|
|
82
|
-
`);continue}let f={chat:fo(w.baseUrl),models:gi(w.baseUrl),headers:ci(w.apiKeyEnv,r.env,`model.${m.role}`),modelId:w.id},h=[],g=[],b=await
|
|
83
|
-
`),o;let c=e.write?await
|
|
82
|
+
`);continue}let f={chat:fo(w.baseUrl),models:gi(w.baseUrl),headers:ci(w.apiKeyEnv,r.env,`model.${m.role}`),modelId:w.id},h=[],g=[],b=await la(f,n,h);if(b!==void 0)g.push(b);let T=await ca(f,n,h);if(T.window!==void 0)g.push(T.window);let x=await ua(f,n,h);if(a){let S=await fa(f,n,h);if(S!==void 0)g.push(S)}l.push({role:m.role,modelId:w.id,baseUrl:w.baseUrl,declared:m.window.contextWindow,declaredSource:m.window.source,findings:g,cache:x,outputCeiling:T.outputCeiling,failures:h})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:l},null,2)}
|
|
83
|
+
`),o;let c=e.write?await pa(r.path,l):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${l.length} role${l.length===1?"":"s"}`,...l.map((m)=>ma(m,e.price)),"",...e.write?[...c.written.length===0?[]:[" written to the manifest:",...c.written.map((m)=>` ${m}`)],...c.refused.length===0?[]:[" not written:",...c.refused.map((m)=>` ${m}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[ha(l)],""].join(`
|
|
84
84
|
`)),o}catch(r){if(p(r))return process.stderr.write(`${r.format()}
|
|
85
|
-
`),d;throw r}}async function
|
|
86
|
-
`)}import{readFileSync as
|
|
85
|
+
`),d;throw r}}async function pa(e,n){let r=[],i=[];for(let s of n){let a=Ce(s.findings);if(a===void 0){i.push(`${s.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${s.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===s.declared){i.push(`${s.role}: already ${a.tokens}, nothing to change`);continue}await Le({file:e,path:["model",s.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${s.role}: ${s.declared} → ${a.tokens}`)}return{written:r,refused:i}}function ha(e){let n=e.filter((a)=>Ce(a.findings)?.bound==="ceiling");if(n.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=n[0],i=r===void 0?void 0:Ce(r.findings);if(r===void 0||i===void 0)return"";let s=new URL(r.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${js(s,new Date().toISOString().slice(0,10),i.detail)}`].join(`
|
|
86
|
+
`)}import{readFileSync as ga}from"node:fs";async function Bs(e){let n=q();if(e.action==="show"){let w;try{w=ga(Ye(n),"utf8").trim()||void 0}catch{w=void 0}if(e.json)process.stdout.write(`${JSON.stringify({owner:w??null})}
|
|
87
87
|
`);else process.stdout.write(w===void 0?`No owner yet. \`${t.slug} init\` or \`${t.slug} owner adopt <agent>\` makes you one.
|
|
88
88
|
`:`${w}
|
|
89
|
-
`);return o}let r=e.manifestPath;if(r===void 0||r==="")throw new A({code:"owner_agent_required",message:"owner adopt needs an agent.",hint:`Name one: \`${t.slug} owner adopt milo\`, or a path to its agent.yaml.`});let i=F(r).id??"",s=await ne.open({path:e.store??
|
|
89
|
+
`);return o}let r=e.manifestPath;if(r===void 0||r==="")throw new A({code:"owner_agent_required",message:"owner adopt needs an agent.",hint:`Name one: \`${t.slug} owner adopt milo\`, or a path to its agent.yaml.`});let i=F(r).id??"",s=await ne.open({path:e.store??P()}),a;try{a=await Te(s,r,n)}finally{await s.close()}let l=await Le({file:r,path:["sessions","scope"],value:"owner",fallback:(w)=>/^sessions:/m.test(w)?void 0:`${w.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
94
|
`}),c=await NA(r,e.store),m=c.kind==="reloaded"||c.kind==="pending"?`reloaded by pid ${c.pid}`:c.kind==="no-host"?"not running here; takes effect when it next starts":`pid ${c.pid} did not reload it (${c.kind}); restart it to take effect`;if(e.json)return process.stdout.write(`${JSON.stringify({agent:i,owner:a.owner,channelIds:a.channelIds,scopeChanged:l.changed,reload:c.kind})}
|
|
95
95
|
`),o;return process.stdout.write([`owner ${a.owner}`,`agent ${i} sessions.scope: owner${l.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 ${m}`,""].join(`
|
|
96
|
-
`)),o}import{existsSync as fr,rmSync as
|
|
97
|
-
`),{dir:i,commit:c}}function
|
|
98
|
-
`).slice(-3).join(" ");if(r)return new A({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 A({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 mr(e){switch(e.action){case"list":return await
|
|
96
|
+
`)),o}import{existsSync as fr,rmSync as ka}from"node:fs";import{resolve as Pa}from"node:path";var ya={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function qs(e){if(e===null||typeof e!=="object")return!1;let n=e.kind;return n==="network"||n==="env"||n==="fs"||n==="exec"||n==="store"}async function Vs(e,n={}){let r=[],i=[],s=n.hostVersion??xe,a=(g,b,T)=>{r.push({level:"error",check:g,message:b,hint:T})},l=(g,b,T)=>{r.push({level:"warning",check:g,message:b,hint:T})};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 c=dr(s,e.dispachApi);if(c===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(!c)l("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${s}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")l("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[g,b]of(e.permissions??[]).entries())if(!qs(b))a("permissions",`\`permissions[${g}]\` is not one of the declared kinds.`,"Kinds are network, env, fs, exec and store. Advisory in v1 — but authors who declare accurately before enforcement lands are the ones who will not have to scramble afterwards.");let m=n.config??{};if(e.configSchema!==void 0){let g=e.configSchema.safeParse(m);if(g.success)m=g.data;else l("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 w={defineChannel:(g)=>i.push(`channel:${g}`),defineToolProvider:(g)=>i.push(`toolProvider:${g}`),defineModelTransport:(g)=>i.push(`modelTransport:${g}`),defineMediaProvider:(g)=>i.push(`mediaProvider:${g}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(g)=>i.push(`middleware:${g.name}`),defineRoute:(g)=>i.push(`route:${g.method} ${g.path}`),config:m,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:ya,events:new Ir({runtimeId:"conformance"})},f=performance.now();try{await e.setup(w)}catch(g){a("setup",`\`setup\` threw: ${g instanceof Error?g.message:String(g)}`,"`setup` registers capabilities and does no work, so it must succeed with an empty environment and a workspace that does not exist. Read a token in the factory you register, not here — that runs only when an agent actually uses the capability.")}let h=Math.round((performance.now()-f)*100)/100;if(h>ur)a("setup budget",`\`setup\` took ${h} 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)l("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:r.every((g)=>g.level!=="error"),findings:r,registered:i,setupMs:h,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(qs)}}}import{existsSync as he,mkdirSync as wa,readdirSync as ba,readFileSync as Qn,renameSync as zs,rmSync as pe,writeFileSync as $a}from"node:fs";import{join as Y}from"node:path";var Ys=".origin.json";function va(e){let n=Y(e,Ys);if(!he(n))return;try{return JSON.parse(Qn(n,"utf8"))}catch{return}}function Zn(e){let n=ae(e),r;try{r=ba(n)}catch{return[]}let i=[];for(let s of r.sort()){if(s.startsWith(".")||s.endsWith(".partial"))continue;let a=Y(n,s);if(!he(Y(a,"package.json"))&&!he(Y(a,"index.js")))continue;let l=va(a);i.push({name:s,dir:a,...l===void 0?{}:{origin:l}})}return i}function Qs(e){let n=Y(e,"package.json");if(!he(n))return Y(e,"index.js");try{let r=JSON.parse(Qn(n,"utf8"));if(typeof r.main==="string"&&r.main!=="")return Y(e,r.main)}catch{}return Y(e,"index.js")}function Zs(e){let n=Y(e,"package.json");if(!he(n))return;let r;try{r=JSON.parse(Qn(n,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(r.dependencies??{});if(i.length===0)return;if(he(Y(e,"node_modules")))return;let s=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${s}${i.length>4?", …":""}) and ships no node_modules`}function er(e,n){let i=((n??e).split("/").filter((s)=>s.length>0).pop()??"").replace(/\.git$/,"");if(!kA(i))throw new A({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 or(e,n={}){let r=n.git??jr,i=br(e.name,n.env),s=`${i}.partial`;wa(ae(n.env),{recursive:!0}),pe(s,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,s]);if(a.code!==0)throw pe(s,{recursive:!0,force:!0}),Sa(e,a.stderr,a.timedOut===!0);let l=await r(["rev-parse","--short","HEAD"],s),c=l.code===0?l.stdout.trim():"unknown",m=e.path===void 0?s:Y(s,e.path);if(!he(m))throw pe(s,{recursive:!0,force:!0}),new A({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${c}`,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."});pe(Y(m,".git"),{recursive:!0,force:!0});try{await n.inspect?.(m)}catch(f){throw pe(s,{recursive:!0,force:!0}),f}if(pe(i,{recursive:!0,force:!0}),m===s)zs(s,i);else zs(m,i),pe(s,{recursive:!0,force:!0});let w={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:c,fetchedAt:new Date().toISOString()};return $a(Y(i,Ys),`${JSON.stringify(w,null,4)}
|
|
97
|
+
`),{dir:i,commit:c}}function Sa(e,n,r){let i=n.trim().split(`
|
|
98
|
+
`).slice(-3).join(" ");if(r)return new A({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 A({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 mr(e){switch(e.action){case"list":return await Ea(e);case"add":return await xa(e);case"remove":return await _a(e);default:throw new A({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(e.action)} is not an action`,hint:`Actions are list, add and remove — \`${t.slug} plugins list <agent>\`.`})}}async function Ea(e){let n=await Ee.create({agents:[e.manifestPath],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(e.env),scriptRunner:ue(),channels:le,env:k([e.manifestPath]),store:P(e.env),lease:!1});U(()=>n.stop("cli-exit"));let r=[...n.plugins.values()].flat(),i=Zn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:r,installed:i,available:Jr},null,2)}
|
|
99
99
|
`),o;if(r.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
|
|
100
100
|
|
|
101
101
|
${Jr.map((c)=>` - "${c}"`).join(`
|
|
@@ -106,15 +106,15 @@ Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one wi
|
|
|
106
106
|
Installed in ${ae(e.env)} and named by no agent:
|
|
107
107
|
${i.map((c)=>` - "${c.name}"`).join(`
|
|
108
108
|
`)}
|
|
109
|
-
`);return o}let s=r.map((c)=>({label:c.name,value:`${c.version} ${`${c.setupMs} ms`.padStart(9)}`,note:`${
|
|
109
|
+
`);return o}let s=r.map((c)=>({label:c.name,value:`${c.version} ${`${c.setupMs} ms`.padStart(9)}`,note:`${Ra(c.spec,c.lookup,i)} — ${c.registered.length===0?"registered nothing":c.registered.join(", ")}`}));process.stdout.write(`${u(s)}
|
|
110
110
|
`);let a=r.filter((c)=>c.permissions.length>0);if(a.length>0){process.stdout.write(`
|
|
111
111
|
Declared access — advisory in v1, recorded and not enforced:
|
|
112
112
|
`);for(let c of a)for(let m of c.permissions)process.stdout.write(` ${c.name} ${m.kind} ${hr(m)}
|
|
113
113
|
`)}let l=i.filter((c)=>!r.some((m)=>m.spec===c.name));if(l.length>0)process.stdout.write(`
|
|
114
114
|
Also installed, named by no agent: ${l.map((c)=>c.name).join(", ")}
|
|
115
|
-
`);return o}function
|
|
116
|
-
`);let l,c=await or({name:s,url:r.url,...i===void 0?{}:{ref:i},...r.path===void 0?{}:{path:r.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(h)=>{let g=Zs(h);if(g!==void 0)throw new A({code:"plugin_not_self_contained",message:`${s} cannot be loaded as fetched: ${g}`,hint:"A plugin is distributed as one self-contained bundle. Nothing is installed while this runtime runs (hard rule 5), so a declared dependency would simply be missing at boot. Ask the author to bundle their dependencies, or commit node_modules in the distribution repository."});let b=Qs(h);if(!fr(b))throw new A({code:"plugin_entry_missing",message:`${s} has no entry file — ${b.slice(h.length+1)} is not in the repository`,hint:"A plugin directory is entered through the `main` its package.json names, defaulting to index.js. A distribution repository commits its built entry file; a source checkout does not, which is usually what this means."});let
|
|
117
|
-
${l.findings.filter((
|
|
115
|
+
`);return o}function Ra(e,n,r){if(n!=="installed")return n==="registry"?"built in":"imported";let i=r.find((s)=>s.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function hr(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 xa(e){let n=e.rest?.[0];if(n===void 0||n==="")throw new A({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${t.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 r=gr(n)?{url:Pa(n.replace(/^file:\/\//,""))}:sr(n),i=e.ref??r.ref,s=e.name===void 0?er(r.url,r.path):Ta(e.name),a=Zn(e.env).find((h)=>h.name===s);if(a?.origin!==void 0&&a.origin.url!==r.url)throw new A({code:"plugin_name_taken",message:`A different plugin is already installed as "${s}" — from ${a.origin.url}`,hint:`Two repositories cannot share one directory, and the directory name is what a manifest's \`plugins:\` entry means. Pass \`--name <name>\`, or \`${t.slug} plugins remove <agent> ${s}\` first.`});process.stdout.write(`Fetching ${r.url}${i===void 0?"":` at ${i}`} as "${s}"…
|
|
116
|
+
`);let l,c=await or({name:s,url:r.url,...i===void 0?{}:{ref:i},...r.path===void 0?{}:{path:r.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(h)=>{let g=Zs(h);if(g!==void 0)throw new A({code:"plugin_not_self_contained",message:`${s} cannot be loaded as fetched: ${g}`,hint:"A plugin is distributed as one self-contained bundle. Nothing is installed while this runtime runs (hard rule 5), so a declared dependency would simply be missing at boot. Ask the author to bundle their dependencies, or commit node_modules in the distribution repository."});let b=Qs(h);if(!fr(b))throw new A({code:"plugin_entry_missing",message:`${s} has no entry file — ${b.slice(h.length+1)} is not in the repository`,hint:"A plugin directory is entered through the `main` its package.json names, defaulting to index.js. A distribution repository commits its built entry file; a source checkout does not, which is usually what this means."});let T=await Oa(s,b);if(l=await Vs(T),!l.ok)throw new A({code:"plugin_not_conformant",message:`${l.declared.name} does not meet the plugin contract:
|
|
117
|
+
${l.findings.filter((x)=>x.level==="error").map((x)=>` ${x.check}: ${x.message}`).join(`
|
|
118
118
|
`)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${t.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(wo(J,l.declared.apiRange)!==!0)throw new A({code:"plugin_api_mismatch",message:`${l.declared.name} ${l.declared.version} supports host ${l.declared.apiRange}, and this host is ${J}`,hint:"The loader refuses this at boot, so installing it would write an entry that stops the agent starting. Look for a newer release of the plugin, or a `--ref` that matches this host."})}}),m=l?.declared;if(process.stdout.write(`
|
|
119
119
|
${m?.name??s} ${m?.version??"?"} (${c.commit})
|
|
120
120
|
from ${r.url}${i===void 0?"":` at ${i}`}
|
|
@@ -134,29 +134,29 @@ plugin that declares nothing can still do anything this process can. Install plu
|
|
|
134
134
|
note: ${h.check} — ${h.message}
|
|
135
135
|
`);if(m!==void 0&&m.name!==s)process.stdout.write(`
|
|
136
136
|
note: it calls itself "${m.name}"; the \`plugins:\` entry is the directory, "${s}".
|
|
137
|
-
`);let f=await
|
|
137
|
+
`);let f=await Aa(e.manifestPath,s);return process.stdout.write(f==="already"?`
|
|
138
138
|
${e.manifestPath} already names "${s}".
|
|
139
139
|
`:`
|
|
140
140
|
Added "${s}" 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
|
|
142
|
+
`),o}function Ta(e){if(kA(e))return e;throw new A({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 Oa(e,n){let r;try{r=await import(n)}catch(s){throw new A({code:"plugin_import_failed",message:`${e}: ${n} could not be imported — ${s instanceof Error?s.message:String(s)}`,hint:"A plugin is one self-contained ES module. A bare `require` or an unresolved import is what this usually means, and neither can be fixed by installing anything: nothing is installed while this runtime runs. Nothing was installed.",cause:s})}let i=r.default;if(i===null||typeof i!=="object")throw new A({code:"plugin_malformed",message:`${e}: ${n} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${t.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 A({code:"plugin_malformed",message:`${e}: the default export of ${n} 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 Aa(e,n){let i=F(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===n))return"already";return await Le({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),n]}),"written"}async function _a(e){let n=e.rest?.[0];if(n===void 0||n==="")throw new A({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${t.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let i=(F(e.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec);if(i.includes(n))await Le({file:e.manifestPath,path:["plugins"],value:i.filter((l)=>l!==n)}),process.stdout.write(`Dropped "${n}" from ${e.manifestPath}.
|
|
143
143
|
Run \`${t.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
|
|
144
144
|
`);else process.stdout.write(`${e.manifestPath} does not name "${n}".
|
|
145
145
|
`);let s=br(n,e.env);if(!fr(s))return process.stdout.write(`Nothing installed at ${s}.
|
|
146
|
-
`),o;let a=
|
|
146
|
+
`),o;let a=Ca(n,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${s} — 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
|
|
148
|
+
`),o;return ka(s,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${s}.
|
|
149
|
+
`),o}function Ca(e,n,r){let i=[];for(let s of Ae(r)){if(s.manifestPath===n)continue;try{if((F(s.manifestPath).plugins??[]).map((c)=>typeof c==="string"?c:c.spec).includes(e))i.push(s.ref)}catch{}}return i}import{existsSync as Ha,readdirSync as Tr,rmSync as et,statSync as _r}from"node:fs";import{homedir as Ga}from"node:os";import{join as Nr}from"node:path";function yr(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let n=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${n} — 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 $r(e){let n=[];if(e.running!==void 0)n.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)n.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let r=e.footprint;if(n.push({kind:"store",detail:`delete ${H(r.sessions,"conversation")}, ${H(r.messages,"message")}, ${H(r.passages,"memory passage")}`}),e.logs.length>0)n.push({kind:"logs",detail:`delete ${H(e.logs.length,"log file")}`})}return n.push({kind:"directory",detail:`delete ${e.dir}`}),n}function vr(e){let n=e.footprint,r=[{label:"directory",value:`${e.dir}`,note:`${H(e.files.count,"file")}, ${nA(e.files.bytes)}`}];if(e.agentId!==e.ref)r.push({label:"manifest id",value:e.agentId,note:"keys the store, logs and service"});if(e.filesOnly)r.push({label:"keeping",value:`${H(n.sessions,"conversation")}, ${H(n.passages,"memory passage")}, and the logs`,note:"--files-only"});else r.push({label:"sessions",value:`${H(n.sessions,"conversation")}, ${H(n.messages,"message")}, ${H(n.turns,"turn")}`},{label:"memory",value:`${H(n.passages,"passage")} from ${H(n.memorySources,"source")}`},{label:"outbox",value:n.outbox===0?"nothing queued":`${H(n.outbox,"delivery")}${n.outboxPending===0?"":`, ${n.outboxPending} not yet sent`}`,...n.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:n.schedules===0?"none":H(n.schedules,"schedule"),...n.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${H(e.logs.length,"file")}, ${nA(e.logs.reduce((i,s)=>i+s.bytes,0))}`},{label:"service",value:e.service??"not installed"});return r.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),u(r)}function kr(e){if(e.length===0)return"";return e.map((n)=>{let r=n.footprint,i=[];if(r.sessions>0)i.push(`${H(r.sessions,"conversation")}, ${H(r.messages,"message")}`);if(r.passages>0)i.push(`${H(r.passages,"memory passage")}`);if(r.outbox>0)i.push(`${H(r.outbox,"queued delivery")}`);if(r.schedules>0)i.push(`${H(r.schedules,"schedule")}`);if(r.lease)i.push("a stale lease");if(n.logs.length>0)i.push(`${H(n.logs.length,"log file")}, ${nA(n.logs.reduce((s,a)=>s+a.bytes,0))}`);return` ${n.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
|
|
150
|
+
`)}function H(e,n){return`${e} ${n}${e===1?"":"s"}`}import{homedir as Na}from"node:os";var Pr=12000,ja=250;async function $n(e){if(e.manifestPath!==void 0)return await Fa(e,e.manifestPath);return await Ka(e)}async function Fa(e,n){let r=Da(n),i=[];if(e.dryRun===!0){let c=await qe(r,e.store);return process.stdout.write(`would stop 1 agent:
|
|
151
151
|
${Q(`${r} — ${c===void 0?"not running; would be switched off for the next start":c.baseUrl===void 0?`pid ${c.pid} (${c.mode}), which serves no HTTP — would be signalled`:`pid ${c.pid} (${c.mode}) at ${c.baseUrl}, which would drop it and keep serving`}`)}
|
|
152
152
|
`),o}await rr(r,!1,e.reason,e.store),i.push("switched off for the next start");let s=await qe(r,e.store),a=!0;if(s===void 0)i.push("nothing was running");else if(s.baseUrl===void 0){let c=await bn(s.pid,"SIGTERM");a=c||await bn(s.pid,"SIGKILL",!0),i.push(c?`pid ${s.pid} stopped cleanly`:a?`pid ${s.pid} had to be killed`:`pid ${s.pid} would not stop — check it by hand`)}else{let c=await ut(s,`/v1/agents/${encodeURIComponent(r)}/stop`,e.reason===void 0?{}:{reason:e.reason},n);if(c.ok)i.push(`pid ${s.pid} dropped it and kept serving`);else if(c.status===409)a=!1,i.push(c.detail??"a turn is running");else if(c.status===401)a=!1,i.push(`pid ${s.pid} refused the request — set ${t.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${s.pid} at ${s.baseUrl} could not be reached${c.detail===void 0?"":`: ${c.detail}`}`)}let l={agentId:r,service:!1,...s===void 0?{}:{pid:s.pid,mode:s.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[l]},null,2)}
|
|
153
153
|
`);else process.stdout.write(`${u([{label:r,value:a?"stopped":"NOT FULLY STOPPED",note:l.note}])}
|
|
154
154
|
`),process.stdout.write(`
|
|
155
155
|
Stays off across restarts. \`${t.slug} start ${r}\` switches it back on.
|
|
156
|
-
`);return a?o:d}async function
|
|
156
|
+
`);return a?o:d}async function Ka(e){let n=e.platform??process.platform,r=n==="darwin"?rn(n,{home:Na(),uid:process.getuid?.()??0,envPrefix:t.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await Ua(r,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)=>Q(
|
|
159
|
+
${i.map((a)=>Q(Ma(a))).join(`
|
|
160
160
|
`)}
|
|
161
161
|
`),o;let s=[];for(let a of i)s.push(await La(a,r));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:s},null,2)}
|
|
162
162
|
`);else{let a=s.map((l)=>({label:Rr(l.agentId),value:l.stopped?"stopped":"STILL RUNNING",note:l.note}));if(process.stdout.write(`${u(a)}
|
|
@@ -167,7 +167,7 @@ Start one again with \`${t.slug} daemon start <agent>\`.
|
|
|
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 s.every((a)=>a.stopped)?o:d}async function Ua(e,n){let r=`${t.slug}.agent.`,i=new Map;for(let s of e?.labels(r)??[]){let a=s.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let s=await ne.open({path:n??
|
|
170
|
+
`)}return s.every((a)=>a.stopped)?o:d}async function Ua(e,n){let r=`${t.slug}.agent.`,i=new Map;for(let s of e?.labels(r)??[]){let a=s.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let s=await ne.open({path:n??P()});for(let a of await s.leases.all()){if(a.pid===process.pid||!Z(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await s.close()}catch{}return[...i.values()].sort((s,a)=>s.agentId.localeCompare(a.agentId))}async function La(e,n){let r=[];if(e.service&&n!==void 0)try{n.stop(tr(t.slug,e.agentId)),r.push("service disabled and unloaded")}catch(a){r.push(`service could not be unloaded: ${a instanceof Error?a.message:String(a)}`)}if(e.pid===void 0)return{...e,stopped:!0,note:r.join(" · ")||"no process was running"};if(!Z(e.pid))return{...e,stopped:!0,note:r.join(" · ")||`pid ${e.pid} exited`};if(await bn(e.pid,"SIGTERM"))return r.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:r.join(" · ")};let s=await bn(e.pid,"SIGKILL",!0);return r.push(s?`pid ${e.pid} did not stop in ${Math.round(Pr/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:s,forced:!0,note:r.join(" · ")}}async function bn(e,n,r=!1){try{process.kill(r?-e:e,n)}catch(s){if(s.code==="ESRCH")return!0;if(r)try{process.kill(e,n)}catch{return!Z(e)}}let i=Date.now()+(n==="SIGKILL"?3000:Pr);while(Date.now()<i){if(!Z(e))return!0;await new Promise((s)=>setTimeout(s,ja))}return!Z(e)}function Ma(e){let n=[];if(e.service)n.push("background service");if(e.pid!==void 0)n.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${Rr(e.agentId)} — ${n.join(", ")}`}function Rr(e){return e===Ut?"(host, no agents)":e}function Da(e){let n=F(e);if(n.id===void 0||n.id==="")throw new A({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 \`${t.slug} stop\` with no argument to stop everything.`});return n.id}async function Fr(e){let n=await ne.open({path:e.store??P()});try{if(e.prune===!0)return await qa(e,n);if(e.all===!0)return await Ba(e,n);if(e.ref===void 0)throw new A({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${t.slug} remove <name>\` takes a sandbox agent's name — the ones \`${t.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await Wa(e.ref,e,n)}finally{await n.close()}}async function Wa(e,n,r){let i=await Ur(e,n,r),s=yr(i);if(s.length>0){let c=s[0];throw new A({code:c.code,message:c.message,hint:c.hint})}let a=$r(i),l=`${v(`removing ${e} will:`,!0)}
|
|
171
171
|
${vr(i)}
|
|
172
172
|
|
|
173
173
|
${a.map((c)=>Q(c.detail)).join(`
|
|
@@ -177,16 +177,16 @@ ${a.map((c)=>Q(c.detail)).join(`
|
|
|
177
177
|
Nothing was deleted — this was --dry-run.
|
|
178
178
|
`),o;if(process.stdout.write(l),!await nt(n,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 Kr(i,n,r)}async function Kr(e,n,r){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await $n({manifestPath:e.manifestPath,...n.exec===void 0?{}:{exec:n.exec},...n.platform===void 0?{}:{platform:n.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
182
|
hint: check what is still running with \`${t.slug} stop --dry-run\`, then run remove again.
|
|
183
|
-
`),d;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let s=
|
|
183
|
+
`),d;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let s=Lr(n);try{s?.uninstall(e.service),i.push({label:"service",value:`${e.service} removed`})}catch(a){i.push({label:"service",value:`${e.service} could NOT be removed`,note:a instanceof Error?a.message:String(a)})}}if(!e.filesOnly){let s=await r.purgeAgent(e.agentId);i.push({label:"store",value:`${s.sessions} conversation(s), ${s.messages} message(s), ${s.passages} passage(s)`});for(let a of e.logs)et(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(et(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),n.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
|
${u(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
|
|
189
|
+
`);return o}async function Ba(e,n){let r=Ae();if(r.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
|
|
190
190
|
`),o;if(process.stdout.write(`${v(`removing every agent in ${q()}:`,!0)}
|
|
191
191
|
${r.map((s)=>Q(`${s.ref}${s.id===void 0||s.id===s.ref?"":` (id ${s.id})`}`)).join(`
|
|
192
192
|
`)}
|
|
@@ -194,7 +194,7 @@ ${r.map((s)=>Q(`${s.ref}${s.id===void 0||s.id===s.ref?"":` (id ${s.id})`}`)).joi
|
|
|
194
194
|
Nothing was deleted — this was --dry-run.
|
|
195
195
|
`),o;if(!await nt(e,"all",`type \`all\` to remove all ${r.length}:`))return process.stdout.write(`
|
|
196
196
|
Nothing was deleted.
|
|
197
|
-
`),o;let i=o;for(let s of r){let a=await
|
|
197
|
+
`),o;let i=o;for(let s of r){let a=await Ur(s.ref,e,n),l=await Kr({...a,sharesIdWith:[]},e,n);if(l!==o)i=l}return i}async function qa(e,n){let r=new Set(Ae().map((l)=>l.id??l.ref).filter((l)=>l!=="")),i=new Set((await n.agentIds()).filter((l)=>!r.has(l)));for(let l of Ja())if(!r.has(l))i.add(l);let s=[];for(let l of[...i].sort())s.push({agentId:l,footprint:await n.agentFootprint(l),logs:Mr(l)});if(s.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
|
|
198
198
|
`:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${q()}.
|
|
199
199
|
`),o;if(process.stdout.write(`${v("no sandbox directory claims these:",!0)}
|
|
200
200
|
${kr(s)}
|
|
@@ -206,60 +206,60 @@ Nothing was deleted.
|
|
|
206
206
|
`:`
|
|
207
207
|
pruned ${s.length} agent id(s).
|
|
208
208
|
${u(a)}
|
|
209
|
-
`),o}async function
|
|
209
|
+
`),o}async function Ur(e,n,r){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new A({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${q()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${t.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let i=Ae(),s=i.find((g)=>g.ref===e);if(s===void 0){let g=i.map((b)=>b.ref);throw new A({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${g.length===0?", which is empty":""}.`,hint:g.length===0?`Nothing to remove. \`${t.slug} init\` creates one.`:`Known agents: ${g.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=s.id;if(a===void 0)try{a=F(s.manifestPath).id}catch{}let l=n.filesOnly===!0||a===void 0,c=a??e,m=await r.agentFootprint(c),w=m.lease?await r.leases.get(c):void 0,f=Lr(n),h=tr(t.slug,c);return{ref:e,agentId:c,manifestPath:s.manifestPath,dir:s.dir,files:Va(s.dir),footprint:m,logs:Mr(c),sharesIdWith:i.filter((g)=>g.ref!==e&&(g.id??"")===c).map((g)=>g.ref),...w!==void 0&&Z(w.pid)?{running:{pid:w.pid,mode:w.mode}}:{},...f?.state(h).installed===!0?{service:h}:{},filesOnly:l}}function Lr(e){let n=e.platform??process.platform;if(n!=="darwin")return;return rn(n,{home:Ga(),uid:process.getuid?.()??0,envPrefix:t.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function Va(e){let n=0,r=0,i=(s)=>{let a;try{a=Tr(s)}catch{return}for(let l of a){let c=Nr(s,l);try{let m=_r(c);if(m.isDirectory()){i(c);continue}n+=1,r+=m.size}catch{}}};return i(e),{count:n,bytes:r}}function Mr(e){let n=pn(e),r=[];for(let i of[n.out,n.err])try{if(!Ha(i))continue;r.push({path:i,bytes:_r(i).size})}catch{}return r}function Ja(){let e;try{e=Tr(Nr(we(),"logs"))}catch{return[]}let n=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))n.add(r.slice(0,-i.length));return[...n]}async function nt(e,n,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,n)}async function Hr(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 n=me(e.manifestPath),r=await NA(e.manifestPath,e.store),i,s,a=o;switch(r.kind){case"reloaded":i="reloaded",s=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",s=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",s=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=d;break;case"failed":i="not reloaded",s=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=d;break;case"no-host":{let l=await Ve(e.store);if(l===void 0)throw new A({code:"cli_restart_nothing_running",message:`Nothing is hosting ${n}, and no server is running to adopt it.`,hint:`\`${t.slug} serve ${n}\` runs it in this terminal; \`${t.slug} daemon install\` keeps a server running that hosts every agent. Then \`${t.slug} restart ${n}\` reloads it in place.`});let c=await OA(l,e.manifestPath,e.store);if(c.ok)i="started",s=`nothing was hosting it — adopted by pid ${l.pid}`;else i="not started",s=`pid ${l.pid} did not adopt it${c.detail===void 0?"":`: ${c.detail}`}`,a=d;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:n,result:r,ok:a===o},null,2)}
|
|
210
210
|
`);else process.stdout.write(`${u([{label:n,value:i,note:s}])}
|
|
211
|
-
`);return a}import{randomBytes as st}from"node:crypto";import{existsSync 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 Ja(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 Xa(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(za(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*za(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*Ya(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*Qa(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*Za(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(x){throw Ja(x,{method:f,path:h,baseUrl:r})}if(!b.ok)throw await Xa(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 x=(S)=>{let N=new URLSearchParams;if(S?.chunks===!0)N.set("chunks","true");if(S?.children===!0)N.set("children","true");let H=N.toString();return H===""?"":`?${H}`},R={turnId:h,sessionKey:g,replayed:b.replayed===!0,async*stream(S){let N=await c(`/v1/agents/${encodeURIComponent(f)}/turns/${encodeURIComponent(h)}/stream${x(S)}`,S?.signal);yield*Ya(N)},async*tokens(S){yield*Za(R.stream({chunks:!0,...S,children:!1}),{...S?.allowTruncated===void 0?{}:{allowTruncated:S.allowTruncated}})},async text(){for await(let S of R.stream()){if(S.kind==="ended")break;if(S.kind==="unavailable")break;if(S.kind==="event"&&S.event.type==="turn.end")break}return(await R.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 R}function w(f){let h=(g)=>`/v1/agents/${encodeURIComponent(f)}${g}`;return{id:f,async send(g,b){let x=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,x.turnId,x.sessionKey,{replayed:x.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 x=new URLSearchParams;if(b?.before!==void 0)x.set("before",String(b.before));if(b?.limit!==void 0)x.set("limit",String(b.limit));let R=x.size===0?"":`?${x.toString()}`;return l("GET",h(`/sessions/${encodeURIComponent(g)}/messages${R}`))},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 x=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/turns${x}`))},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,x)=>l("PATCH",h("/config"),{body:{path:g,value:b,...x?.confirm===void 0?{}:{confirm:x.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}}),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 x=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/context${x}`))}}}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*Qa(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`
|
|
211
|
+
`);return a}import{randomBytes as st}from"node:crypto";import{existsSync as td}from"node:fs";import{resolve as Zr}from"node:path";import{createInterface as no}from"node:readline";class ge extends Error{code;hint;field;details;status;request;constructor(e,n={}){super([e.message,...(e.details??[]).map((r)=>` - ${r.field===void 0?"":`${r.field}: `}${r.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=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`
|
|
213
213
|
${Ia}Resume this session with:
|
|
214
214
|
${r}${ko}
|
|
215
|
-
`}function tt(e,n){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 n===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${n}, still in the store. /sessions goes back to it.`}}function
|
|
215
|
+
`}function tt(e,n){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 n===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${n}, still in the store. /sessions goes back to it.`}}function nd(e){return e==="nlt"?pr():Cr()}function Xr(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(n)=>e.bus.on("*",n,{chunks:!0}),send:(n,r)=>e.send(n,{...r,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 zr(e){let n=e.client.agent(e.agentId),r=new Set,i=new AbortController,s,a=()=>{if(s!==void 0)return;s=(async()=>{for await(let l of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(l.kind!=="event"||l.event===void 0)continue;for(let c of r)c(l.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(l)=>(r.add(l),a(),()=>r.delete(l)),send:async(l,c)=>{let m=!1,w,f=()=>{if(m=!0,w!==void 0)n.turn(w).stop().catch(()=>{})};c.signal.addEventListener("abort",f,{once:!0});let h,g=new Promise((b)=>{let T=(x)=>{if(w!==void 0&&x.turnId!==void 0&&x.turnId!==w)return;if(x.type==="error"){h=x.data;return}if(x.type!=="turn.end")return;r.delete(T),b({text:"",reason:x.data.reason,steps:x.data.steps,durationMs:x.data.durationMs,tokens:x.data.tokens,...h===void 0?{}:{error:h}})};r.add(T),a()});try{if(w=(await n.send(l,{sessionKey:c.sessionKey})).turnId,m)n.turn(w).stop().catch(()=>{});return await g}finally{c.signal.removeEventListener("abort",f)}},streamFilter:()=>nd(e.description.dialect),history:async(l)=>{let c=await n.messages(l);return Ke([...c.messages].reverse().map((m)=>({role:m.role,content:m.content,...m.origin===void 0?{}:{origin:m.origin}})),e.description.dialect)},sessions:()=>n.sessions(),clearSession:async(l)=>{await n.clearSession(l)},ownConversation:async()=>(await n.sessions()).find((l)=>l.head!==!1&&l.sessionKey.startsWith("owner:"))?.sessionKey,resolveSessionKey:async(l)=>{try{return await n.resolveSessionKey(l)}catch{return l}},rotateSession:async()=>{try{return(await n.rotateSession()).sessionKey}catch{return}},tools:async()=>{let l=await n.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:l.map((c)=>({slug:c.slug,mutating:c.mutating,trust:c.trust,...c.trustReason===void 0?{}:{trustReason:c.trustReason},summary:c.summary}))}},context:async(l)=>{let c=await n.context({sessionKey:l});return{...c,windowSource:"as the host resolved it",...c.lastCompaction===void 0&&c.compactions!==void 0?{lastCompaction:c.compactions===0?void 0:`${c.compactions} stage${c.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await n.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function Qr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function sd(e,n,r,i,s,a=[],l){let c=e.describe(),[m,w]=await Promise.all([e.turns(n,1),e.store.messages.count(e.id,n)]),f=[`${t.name} ${J} · ${c.id} · ${c.model}`,`session ${n} · ${w} message(s) · window ${c.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],h=tt(s,l);if(h!==void 0)f.push(h);if(m[0]?.errorCode==="turn_abandoned")f.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let g of[...e.warnings,...e.tools.warnings])f.push(`note: ${g.message}
|
|
216
216
|
${g.hint}`);if(a.length>0)f.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 f}async function ot(e){let n=e.once!==void 0,r=it({json:!1,plain:e.plain===!0,oneShot:n}),{mode:i}=r;if(e.manifestPath===void 0){let
|
|
218
|
-
`);let a;U(()=>a?.stop("cli-exit"));let l={current:void 0},c={current:""},m={current:e.sessionKey},w={current:!1},f={current:void 0},h=e.quiet===!0,g="first",b={current:void 0},
|
|
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 f}async function ot(e){let n=e.once!==void 0,r=it({json:!1,plain:e.plain===!0,oneShot:n}),{mode:i}=r;if(e.manifestPath===void 0){let x=await od(i,r.because,e);if(typeof x==="number")return x;return ot({...e,manifestPath:x})}let s=pi();if(e.store===void 0&&e.ephemeral!==!0&&Zr(s)!==Zr(P())&&td(s))process.stdout.write(`note: a session store exists at ${s} from an earlier version — pass --store ${s} to keep using it; the default is now ${P()}
|
|
218
|
+
`);let a;U(()=>a?.stop("cli-exit"));let l={current:void 0},c={current:""},m={current:e.sessionKey},w={current:!1},f={current:void 0},h=e.quiet===!0,g="first",b={current:void 0},T=e.ephemeral===!0?void 0:Qr(await qe(me(e.manifestPath),e.store));if(T!==void 0)return await ld({...e,host:T,mode:i==="rich"?"rich":"plain",quiet:h,oneShot:n,reader:l,draft:c,session:m,random:st});for(;;){let x=await Ee.create({agents:[e.manifestPath],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??P()});a=x;let S=x.list()[0];if(S===void 0)throw Error("The manifest produced no agent.");if(m.current===void 0||m.current===""){let K=await ro({list:async()=>co(await S.store.sessions.list(S.id)),mode:i,asked:m.current,wantsContinue:e.continueSession===!0,random:st});if(typeof K==="number")return await x.stop("cli-exit"),K;if(m.current=K.sessionKey,w.current=K.fresh,K.fresh)m.current=await so(S)??K.sessionKey}if(g==="new"){let K=await S.rotateSession({source:"repl"});if(K!==void 0)m.current=K.sessionKey}m.current=await S.resolveSessionKey(m.current??"",{source:"repl"});let L=m.current,G=S.roles.main.capabilities.thinking!=="none",E=e.noReasoning===!0?!1:G,I=h||n?[]:await sd(S,L,x.store.location,g==="first"?x.boot.processMs:x.boot.bootMs,g,Js([e.manifestPath]),f.current),_=i==="rich"&&!h&&!n?Ke(await S.history(L),S.describe().dialect):[],N=Xr({agent:S,bus:x.bus,send:(K,ee)=>S.send(K,ee),history:async(K)=>Ke(await S.history(K),S.describe().dialect),sessions:async()=>{let K=await S.store.sessions.heads(S.id);return(await S.store.sessions.list(S.id)).map((ee)=>({...ee,head:ii(ee.sessionKey,K)}))},clearSession:async(K)=>{await S.clearSession(K)},ownConversation:()=>so(S),resolveSessionKey:(K)=>S.resolveSessionKey(K,{source:"repl"}),rotateSession:async()=>(await S.rotateSession({source:"repl"}))?.sessionKey,context:async(K)=>cd(S,K),streamFilter:()=>S.streamFilter(),description:{agentId:S.id,name:S.describe().name,model:S.describe().model,dialect:S.describe().dialect,window:S.describe().window,catalogueTokens:S.describe().catalogueTokens,thinking:S.roles.main.capabilities.thinking,warnings:[...S.warnings,...S.tools.warnings]}}),M={...e,source:N,embedded:{agent:S,runtime:x},sessionKey:L,banner:I,prior:_,quiet:h,reader:l,draft:c,showReasoning:E,freshSession:w.current,switchTo:b,random:st},B=i==="rich"?await io(M):await ao(M);if(await x.stop(B===$e?"restart":"cli-exit"),B!==$e)return B;if(b.current===void 0)g="restart";else g=b.current.reason,f.current=L,m.current=b.current.key,b.current=void 0;w.current=!1}}function rd(e,n){let r=[];for(let i of e)Kt({action:"install",manifestPath:n,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var $e=Symbol("restart");async function od(e,n,r){let i=Ae();if(i.length===0){if(e==="rich"){let f=await Ln({plain:r.plain===!0});if(f.kind==="aborted")return process.stdout.write(`nothing to run
|
|
219
219
|
`),o;if(f.kind==="failed")return f.code;return f.manifestPath}throw new A({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${t.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
220
|
`),i[0].manifestPath;if(e!=="rich"){for(let f of i)process.stdout.write(`${f.ref} ${f.problem??f.modelId??"?"} ${f.dir}
|
|
221
221
|
`);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${n})
|
|
222
222
|
`),d}let[{render:s},{createElement:a},{Picker:l}]=await Promise.all([import("ink"),import("react"),import("./Picker-j7txnm7w.js")]),c={kind:"quit"};oo();let m=s(a(l,{title:`${t.name} ${J}`,agents:i,onDone:(f)=>{c=f}}),{exitOnCtrlC:!1,...Ue(r.noEnhancedKeys)});U(()=>m.unmount()),await m.waitUntilExit(),m.unmount();let w=c;if(w.kind==="quit")return process.stdout.write(`nothing run
|
|
223
223
|
`),o;if(w.kind==="create"){let f=await Ln({plain:r.plain===!0});if(f.kind==="aborted")return process.stdout.write(`nothing to run
|
|
224
|
-
`),o;if(f.kind==="failed")return f.code;return f.manifestPath}return w.manifestPath}async function
|
|
224
|
+
`),o;if(f.kind==="failed")return f.code;return f.manifestPath}return w.manifestPath}async function so(e){let r=await e.resolveSessionKey("local:-",{source:"repl"});return r==="local:-"?void 0:r}async function ro(e){let n=()=>({sessionKey:$o(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new A({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(e.wantsContinue){let r=await e.list(),i=id(r);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
|
|
225
225
|
`),n();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let r=await e.list();if(r.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
|
|
226
226
|
`),n();if(e.mode!=="rich"){for(let s of[...r].sort(vn))process.stdout.write(`${s.sessionKey} ${s.messages} ${s.turns} ${s.lastActivityAt}
|
|
227
227
|
`);return process.stderr.write(`pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one
|
|
228
|
-
`),d}let i=await
|
|
229
|
-
`)},l=(
|
|
230
|
-
`);a(`${
|
|
228
|
+
`),d}let i=await ad([...r].sort(vn));return i===void 0?n():{sessionKey:i,fresh:!1}}return e.asked===void 0?n():{sessionKey:e.asked,fresh:!1}}function vn(e,n){return Date.parse(n.lastActivityAt)-Date.parse(e.lastActivityAt)}function id(e){return[...e].sort(vn)[0]}async function ad(e){let[{render:n},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-hpv2ncsb.js")]),s;oo();let a=n(r(i,{sessions:e,now:Date.now(),columns:Pe(process.stdout.columns,be),maxRows:Sn,onDone:(l)=>{s=l,a.unmount()}}),{exitOnCtrlC:!1,...Ue()});return U(()=>a.unmount()),await a.waitUntilExit(),s}function dd(e,n,r,i,s){let a=e.describe(),l=[`${t.name} ${J} · ${a.agentId} · ${a.model}`,`session ${n} · window ${a.window} · attached to ${r.baseUrl} (pid ${r.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],c=tt(i,s);if(c!==void 0)l.push(c);for(let m of a.warnings)l.push(`warning: ${m.message}`);return l}async function ld(e){let n=e.manifestPath??"",r=me(n),i=RA(n),s=qr({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await s.agent(r).describe();if(a.status==="disabled")throw new A({code:"agent_disabled",message:`${r} was stopped while this run was attaching.`,hint:`Start it with \`${t.slug} start ${r}\`, then run again.`});let l=zr({client:s,agentId:r,host:e.host,description:{agentId:r,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),c={current:void 0},m="first",w={current:void 0},f={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let S=await ro({list:()=>mo(l),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof S==="number")return S;if(e.session.current=S.sessionKey,f.current=S.fresh,S.fresh)e.session.current=await l.ownConversation()??S.sessionKey}if(m==="new"){let S=await l.rotateSession();if(S!==void 0)e.session.current=S}e.session.current=await l.resolveSessionKey(e.session.current??"");let h=e.session.current??"",g=e.quiet||e.oneShot?[]:dd(l,h,e.host,m,w.current),b=e.mode==="rich"&&!e.quiet&&!e.oneShot?await l.history(h):[],T={...e,source:l,sessionKey:h,banner:g,prior:b,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:f.current,switchTo:c,random:e.random},x=e.mode==="rich"?await io(T):await ao(T);if(x!==$e)return await l.close(),x;if(c.current===void 0)m="restart";else m=c.current.reason,w.current=h,e.session.current=c.current.key,c.current=void 0;f.current=!1}}async function io(e){let[{render:n},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-2f72vhjv.js")]),s=ln();U(()=>{s.close()}),St(),Cs(),process.stdout.write(`${Rt}${oa}`);let a=!1,l=n(r(i,{source:e.source,onSwitch:(c,m)=>{a=!0,e.switchTo.current={key:c,reason:"switch"},e.draft.current=m},onNew:(c)=>{a=!0,e.switchTo.current={key:$o(e.random),reason:"new"},e.draft.current=c},sessions:async()=>[...await mo(e.source)].sort(vn),onRestart:(c)=>{a=!0,e.draft.current=c},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((c)=>c.message),initial:Wi(Vi(e.banner.slice(1)),e.prior),correctKeys:s.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(c)=>LA({onStatus:c}),install:async(c,m)=>mn(rd(c,m))},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,...Ue(e.noEnhancedKeys)});if(U(()=>l.unmount()),await l.waitUntilExit(),We(),!a)process.stdout.write(Vr({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?$e:o}async function ao(e){let{source:n,sessionKey:r,quiet:i}=e,s=!0,a=(I)=>{if(I==="")return;process.stdout.write(I),s=I.endsWith(`
|
|
229
|
+
`)},l=(I)=>{if(!s)a(`
|
|
230
|
+
`);a(`${I}
|
|
231
231
|
`)};if(e.banner.length>0)a(`${e.banner.join(`
|
|
232
232
|
`)}
|
|
233
233
|
|
|
234
|
-
`);let c=!i&&e.once===void 0,m=!1,w,f=n.streamFilter(),h=(
|
|
234
|
+
`);let c=!i&&e.once===void 0,m=!1,w,f=n.streamFilter(),h=(I)=>{if(I==="")return;a(I),m=!0},g=e.source.subscribe((I)=>{if(I.sessionKey!==void 0&&I.sessionKey!==r)return;switch(I.type){case"model.result":h(f.endStep());return;case"model.chunk":{let{delta:_,kind:N}=I.data;if(N==="reasoning"&&e.showReasoning!==!0)return;if(N!==w){if(w!==void 0)a(`
|
|
235
235
|
|
|
236
|
-
`);if(e.showReasoning===!0)a(
|
|
236
|
+
`);if(e.showReasoning===!0)a(N==="reasoning"?`· reasoning ·
|
|
237
237
|
`:`· reply ·
|
|
238
|
-
`);w=
|
|
239
|
-
${
|
|
240
|
-
`)},
|
|
241
|
-
`);else if(!m&&
|
|
242
|
-
`);let
|
|
243
|
-
(${
|
|
244
|
-
`);if(
|
|
245
|
-
${
|
|
246
|
-
hint: ${
|
|
247
|
-
`);if(Bo(
|
|
238
|
+
`);w=N}if(N==="reasoning"){a(_),m=!0;return}h(f.push(_));return}case"tool.result":{if(!c)return;let{slug:_,ok:N,latencyMs:M,truncated:B}=I.data;l(` · ${_} — ${N?"ok":"failed"} · ${M} ms${B?" · observation trimmed":""}`);return}case"agent.warning":l(` · ${I.data.message}
|
|
239
|
+
${I.data.hint}`);return;case"tool.repair":if(c)l(I.data.slugs.length===0?` · reply stopped short (${I.data.errors.join("; ")}), asking again`:` · ${I.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":l(` · ${I.data.slug} — blocked: ${I.data.reason}`);return;case"context.dropped":l(` · context: ${I.data.messages} older message(s) did not fit the ${I.data.budget}-token budget and were left out`);return;default:return}}),b=async(I)=>{let _=Hn(I,Yn());if(_===void 0)return"prompt";switch(_.kind){case"exit":return"exit";case"restart":{let N=n.reload;if(N===void 0)return"restart";try{let M=await N();l(`reloaded ${M.join(", ")} — this conversation continues`)}catch(M){l(`could not reload: ${M instanceof Error?M.message:String(M)}`)}return"handled"}case"new":return e.switchTo.current={key:$o(e.random),reason:"new"},"restart";case"help":return l(Kn()),"handled";case"tools":return l(DA(await n.tools())),"handled";case"status":return l(e.embedded===void 0?await po(n):await lo(e.embedded)),"handled";case"context":return l(await go(e,r)),"handled";case"reset":return await n.clearSession(r),l("session cleared — memory files on disk are untouched"),"handled";case"unknown":return l(nn(_)),"handled";case"command":return l(`${_.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${t.slug} ${_.name}${_.rest===""?"":` ${_.rest}`}\``),"handled"}},T,x=0,S=o,L=(I=e.reader.current)=>{if(T!==void 0&&!T.signal.aborted){x=performance.now(),T.abort();return}I?.close(),a(`
|
|
240
|
+
`)},G=async(I)=>{T=new AbortController,m=!1,w=void 0,f=n.streamFilter();let _=await n.send(I,{sessionKey:r,signal:T.signal});if(T=void 0,h(f.end()),m&&!s)a(`
|
|
241
|
+
`);else if(!m&&_.text!=="")a(`${_.text}
|
|
242
|
+
`);let N=Mt(_.reason,{steps:_.steps,durationMs:_.durationMs,...x===0?{}:{cancelledAfterMs:performance.now()-x}});if(N!==void 0)a(`
|
|
243
|
+
(${N})
|
|
244
|
+
`);if(_.reason==="error"&&_.error!==void 0)process.stderr.write(`
|
|
245
|
+
${_.error.code}: ${_.error.message}
|
|
246
|
+
hint: ${_.error.hint}
|
|
247
|
+
`);if(Bo(_.reason))S=d;if(!i&&_.reason==="final")a(` ${_.tokens.prompt} prompt · ${_.tokens.output} output · ${_.durationMs} ms
|
|
248
248
|
|
|
249
|
-
`);await Ct()},
|
|
250
|
-
`);for(let a of e)process.stdout.write(`${te(a.id,r)} ${te(`${a.kind} ${a.expr}`,i)} ${te(
|
|
249
|
+
`);await Ct()},E=()=>L();process.on("SIGINT",E);try{if(e.once!==void 0)return await G(e.once),S;if(process.stdin.isTTY!==!0){let _=e.reader.current??no({input:process.stdin});e.reader.current=_;for await(let N of _){let M=N.trim();if(M==="")continue;let B=await b(M);if(B==="exit")break;if(B==="restart"){S=$e;break}if(B==="handled")continue;await G(M)}return S}let I=e.reader.current??no({input:process.stdin,output:process.stdout,prompt:Po,terminal:!1});e.reader.current=I,I.prompt();for await(let _ of I){let N=_.trim();if(N===""){I.prompt();continue}let M=await b(N);if(M==="exit")break;if(M==="restart"){S=$e;break}if(M==="handled"){I.prompt();continue}await G(N),I.prompt()}if(S!==$e)I.close(),e.reader.current=void 0;return S}finally{process.off("SIGINT",E),g()}}async function lo(e){let{agent:n,runtime:r}=e,i=n.describe(),s=n.manifest,a=s.channels.filter((f)=>f.enabled).map((f)=>`${f.id} (${f.type})`).join(", "),l=a===""?"none — reached through this session and the HTTP API only":r.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,c=!s.server.enabled?"off":`enabled on ${s.server.host}:${s.server.port}, NOT bound here — \`serve\` binds it`,m=Nt(s),w=m.filter((f)=>f.role!=="main"&&f.role===f.configuredAs);return u([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${s.tools.dialect} · ${i.window} token window (${gA(m[0]?.window)})`},...w.map((f)=>({label:f.role,value:`${f.modelId} · ${f.window.contextWindow} token window (${gA(f.window)})`})),{label:"channels",value:l},{label:"http api",value:c},{label:"store",value:r.store.location},{label:"background",value:await ud(r,i.id)}])}function co(e){return e.filter((n)=>!fi(n.sessionKey))}async function mo(e){return co(await e.sessions())}async function po(e){let n=e.describe(),r=e.host,[i,s]=await Promise.all([e.tools(),e.sessions()]);return u([{label:"agent",value:`${n.agentId} (${n.name})`},{label:"attached to",value:r===void 0?"a host":`${r.baseUrl} · pid ${r.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${n.model} · ${n.window} token window`},{label:"dialect",value:n.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${s.length} on this agent`},{label:"warnings",value:n.warnings.length===0?"none":n.warnings.map((a)=>a.message).join("; ")}])}async function cd(e,n){let r=await e.previewContext({sessionKey:n}),[i]=Nt(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:gA(i?.window),wireTokens:r.wireTokens,reserveOutput:r.reserveOutput,calibration:r.calibration,lastCompaction:r.compactions===0?void 0:`${r.compactions} stage${r.compactions===1?"":"s"} run this session`}}async function go(e,n){return ji(await e.source.context(n))}async function ud(e,n){if(e.owned.includes(n))return"this session is serving this agent";let r=await e.store.leases.get(n);if(r!==void 0&&Z(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${t.slug} daemon status ${n}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${t.slug} daemon install ${n}\` keeps it running without a terminal`}function te(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function fd(e,n){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-n;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let s=Math.round(r/3600000);return s<48?`in ${s}h`:`in ${Math.round(s/24)}d`}function md(e,n){if(e.lastFiredAt===void 0)return"never run";let r=rA(e.lastFiredAt,n);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function pd(e,n){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let r=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${te("SCHEDULE",r)} ${te("WHEN",i)} ${te("NEXT",7)} LAST
|
|
250
|
+
`);for(let a of e)process.stdout.write(`${te(a.id,r)} ${te(`${a.kind} ${a.expr}`,i)} ${te(fd(a,n),7)} ${md(a,n)}
|
|
251
251
|
`);let s=e.filter((a)=>a.lastStatus==="error");if(s.length>0)process.stdout.write(`
|
|
252
252
|
${s.length} failing — \`schedules --id ${s[0]?.id}\` for the error
|
|
253
|
-
`)}function
|
|
253
|
+
`)}function hd(e){let n=[["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)n.push(["last error",e.lastError]);let r=Math.max(...n.map(([i])=>i.length));process.stdout.write(`${e.id}
|
|
254
254
|
`);for(let[i,s]of n)process.stdout.write(` ${te(i,r)} ${s}
|
|
255
|
-
`)}function
|
|
255
|
+
`)}function gd(e,n){let r=new Set(n),i=new Map;for(let s of e){if(!r.has(s.channel))continue;let a=`${s.channel}\x00${s.peerId}`,l=i.get(a);if(l!==void 0&&l.lastSeen>=s.lastActivityAt)continue;i.set(a,{channelId:s.channel,address:s.peerId,lastSeen:s.lastActivityAt})}return[...i.values()].sort((s,a)=>s.channelId===a.channelId?a.lastSeen.localeCompare(s.lastSeen):s.channelId.localeCompare(a.channelId))}function yd(e,n){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
257
|
`);return}let r=Math.max(7,...e.map((s)=>s.channelId.length)),i=Math.max(7,...e.map((s)=>s.address.length));process.stdout.write(`${te("CHANNEL",r)} ${te("ADDRESS",i)} LAST SEEN
|
|
258
258
|
`);for(let s of e)process.stdout.write(`${te(s.channelId,r)} ${te(s.address,i)} ${rA(s.lastSeen,n)}
|
|
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
|
|
262
|
+
`)}async function vo(e){let n=await Ee.create({agents:[e.manifestPath],store:e.store??P(),toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath]),lease:!1});U(()=>n.stop("cli-exit"));let r=n.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,l]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let c=await r.store.schedules.get(r.id,a);if(c===void 0)return process.stderr.write(`no schedule "${a}" on ${r.id}
|
|
263
263
|
hint: run \`schedules\` with no flags to see what this agent has.
|
|
264
264
|
`),d;if(c.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
|
|
@@ -269,78 +269,78 @@ Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
|
|
|
269
269
|
${e.manifestPath}
|
|
270
270
|
`),d;await r.store.schedules.setEnabled(r.id,a,l,new Date(i).toISOString()),process.stdout.write(l?`${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
|
|
272
|
+
`)}if(e.recipients===!0){let a=gd(await r.store.sessions.list(r.id),r.manifest.channels.map((l)=>l.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
|
|
273
|
+
`),o;return yd(a,i),o}let s=await r.store.schedules.list(r.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:s},null,2)}
|
|
274
274
|
`),o;if(e.id!==void 0){let a=s.find((l)=>l.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${r.id}
|
|
275
|
-
`),d;return
|
|
276
|
-
`,{mode:384})}function
|
|
277
|
-
`,{mode:384})}}}function
|
|
278
|
-
`,{mode:384}),
|
|
275
|
+
`),d;return hd(a),o}if(e.enable===void 0&&e.disable===void 0)pd(s,i);return o}import{rmSync as Id}from"node:fs";import{dirname as Mo,join as Od}from"node:path";import{readFileSync as wd}from"node:fs";var bd="server.tokenEnv";function dt(e){let n=wd(e,"utf8"),r=Gt(e),i=new Map,s=new Set(jA(n).filter((a)=>a.path===bd).map((a)=>a.name));for(let a of jA(n)){if(s.has(a.name))continue;let l=i.get(a.name)??[];l.push(a.path),i.set(a.name,l)}return[...i].map(([a,l])=>({name:a,set:on(r,a),usedBy:l}))}function So(e,n){let r=dt(e).map((l)=>l.name);for(let[l,c]of Object.entries(n)){if(!r.includes(l))throw new A({code:"secret_not_referenced",message:`"${l}" is not a variable this agent's manifest reads.`,hint:r.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${r.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.${l}`});if(c==="")throw new A({code:"secret_value_empty",message:`An empty value for ${l} 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.${l}`})}let i=k([e]),s=[],a=[];for(let[l,c]of Object.entries(n))if(Je(e,l,c),s.push(l),on(i,l))a.push(l);return{written:s,shadowed:a}}import{createHash as $d}from"node:crypto";import{existsSync as ke,lstatSync as ft,mkdirSync as lt,readdirSync as Ro,readFileSync as He,renameSync as vd,rmSync as xo,writeFileSync as De}from"node:fs";import{basename as Ge,dirname as To,join as X}from"node:path";var Me="template.yaml",Ao=/^[a-z0-9][a-z0-9-]*$/;function mt(e){let n;try{n=Ro(e)}catch{return[]}let r=[];for(let i of n.sort()){if(!Ao.test(i))continue;let s=X(e,i);if(!ft(s).isDirectory())continue;try{let a=Pn(s);r.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((l)=>({name:l.name,...l.description===void 0?{}:{description:l.description},required:l.required,...l.default===void 0?{}:{default:l.default},secret:l.secret!==void 0}))})}catch(a){if(!p(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function Pn(e){let n=X(e,Me);if(!ke(n))throw new A({code:"template_spec_missing",message:`${Ge(e)} has no ${Me}.`,hint:`A template is an agent directory with a ${Me} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return di(He(n,"utf8"),`${Ge(e)}/${Me}`)}function pt(e,n=""){let r=[];for(let i of Ro(X(e,n)).sort()){let s=n===""?i:`${n}/${i}`;if(s===Me)continue;let a=X(e,s),l=ft(a);if(l.isSymbolicLink())throw new A({code:"template_symlink",message:`${s} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:s});if(l.isDirectory()){r.push(...pt(e,s));continue}let c=He(a);if(c.includes(0))throw new A({code:"template_binary_file",message:`${s} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:s});r.push({relPath:s,contents:c.toString("utf8")})}return r}function _o(e){if(!Ao.test(e.template))throw ct(e.template,e.templatesDir);let n=X(e.templatesDir,e.template);if(!ke(n)||!ft(n).isDirectory())throw ct(e.template,e.templatesDir);let r=e.name.trim();if(r==="")throw new A({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=at(r),s=X(e.agentDirBase,i);if(ke(s))throw new A({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:Pn(n),files:pt(n),id:i,name:r,vars:e.vars}),l=X(To(e.agentDirBase),`.${Ge(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);lt(l,{recursive:!0});try{_e(l,a.files),Fo(l,{template:e.template,name:r,vars:jo(Pn(n),e.vars),files:Sd(a.files)});let c=X(l,"agent.yaml");for(let[f,h]of Object.entries(a.env))Je(c,f,h);let m=a.files.find((f)=>f.relPath==="agent.yaml"),w={};for(let f of jA(m?.contents??""))if(a.env[f.name]===void 0&&!process.env[f.name])w[f.name]="(pending)";Ze(c,w),lt(e.agentDirBase,{recursive:!0}),vd(l,s)}catch(c){throw xo(l,{recursive:!0,force:!0}),c}return{agentId:i,dir:s,manifestPath:X(s,"agent.yaml"),files:[...a.files.map((c)=>c.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function ct(e,n){let r=mt(n).map((i)=>i.name);return new A({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:r.length===0?`This server has no templates. An operator adds one as a directory under ${n}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var gt=".template.json";function kn(e){return $d("sha256").update(e).digest("hex")}function Sd(e){return Object.fromEntries(e.map((n)=>[n.relPath,kn(n.contents)]))}function jo(e,n){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(n).filter(([i])=>!r.has(i)))}function Fo(e,n){De(X(e,gt),`${JSON.stringify({version:1,...n},null,2)}
|
|
276
|
+
`,{mode:384})}function Ko(e){let n=X(e,gt);if(!ke(n))return;let r=JSON.parse(He(n,"utf8"));return{template:r.template,vars:r.vars}}function Uo(e){let n=X(e.agentDir,gt);if(!ke(n))throw new A({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 r=JSON.parse(He(n,"utf8")),i=X(e.templatesDir,r.template);if(!ke(i))throw ct(r.template,e.templatesDir);let s=Pn(i);for(let h of Object.keys(e.vars)){let g=s.vars.find((b)=>b.name===h);if(g?.secret!==void 0)throw new A({code:"template_var_secret",message:`"${h}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${g.secret}.`,field:`vars.${h}`})}let a={...r.vars,...e.vars},l=Or({spec:s,files:pt(i),id:Ge(e.agentDir),name:r.name,vars:{...Object.fromEntries(s.vars.filter((h)=>h.secret!==void 0&&h.required).map((h)=>[h.name,"(in .env)"])),...a}}),c=[],m=[],w=[],f={...r.files};try{for(let h of l.files){let g=X(e.agentDir,h.relPath),b=r.files[h.relPath];if(!ke(g)){if(b!==void 0){w.push({file:h.relPath,reason:"removed"});continue}lt(To(g),{recursive:!0}),De(g,h.contents),c.push({path:g,before:void 0}),f[h.relPath]=kn(h.contents),m.push(h.relPath);continue}let T=He(g,"utf8");if(kd(h.relPath,T)){w.push({file:h.relPath,reason:"memory"});continue}if(b===void 0||kn(T)!==b){w.push({file:h.relPath,reason:"edited"});continue}if(T===h.contents)continue;De(g,h.contents),c.push({path:g,before:T}),f[h.relPath]=kn(h.contents),m.push(h.relPath)}Fo(e.agentDir,{template:r.template,name:r.name,vars:jo(s,a),files:f})}catch(h){throw Eo(c),h}return{rendered:m,skipped:w,undo:()=>{Eo(c),De(n,`${JSON.stringify(r,null,2)}
|
|
277
|
+
`,{mode:384})}}}function Eo(e){for(let n of e)if(n.before===void 0)xo(n.path,{force:!0});else De(n.path,n.before)}function kd(e,n){if(Ge(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return HA(e,n).frontmatter.eviction==="oldest"}catch{return!1}}import{readFileSync as Pd,renameSync as Ed,writeFileSync as Rd}from"node:fs";function xd(e){try{let n=JSON.parse(Pd(e,"utf8"));return typeof n==="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function Td(e,n){let i=(await e.json().catch(()=>({}))).error;return Error(i?.message===void 0?`the control plane answered ${e.status} to ${n}`:`${i.message}${i.hint===void 0?"":` ${i.hint}`}`)}function Lo(e){let n=e.fetch??globalThis.fetch,r=e.url.replace(/\/+$/,""),i={authorization:`Bearer ${e.token}`},s=xd(e.cacheFile);return{cachedPeers:(a)=>s[a]??[],async refreshPeers(a,l){let c=await n(`${r}/v1/relay/peers?participant=${encodeURIComponent(l)}`,{headers:i});if(!c.ok)throw await Td(c,"the peer list");let{peers:m}=await c.json();s[a]=m;let w=`${e.cacheFile}.partial`;return Rd(w,`${JSON.stringify(s,null,2)}
|
|
278
|
+
`,{mode:384}),Ed(w,e.cacheFile),m},async ask(a){let l=await n(`${r}/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(!l.ok){let c=await l.json().catch(()=>({}));return{text:"",reason:"error",steps:0,tokens:{prompt:0,output:0},error:c.error??{code:"relay_unavailable",message:`The control plane answered ${l.status}.`,hint:"Check the control plane is reachable from this silo."}}}return await l.json()}}}function Ad(){return KA.shape.server.parse({})}async function Go(e){let n=k(e.manifestPaths),r=_d(n),i=e.store??P(),s=await gs(e.manifestPaths,n,i),a=s.filter((R)=>!R.enabled),l=s.filter((R)=>R.enabled),c=e.manifestPaths.length===0,m=[],w=[];for(let R of l)try{m.push({path:R.manifestPath,loaded:V(R.manifestPath,{env:n})})}catch(O){if(!c)throw O;w.push({path:R.manifestPath,detail:p(O)?O.message:String(O),...p(O)&&O.hint!==void 0?{hint:O.hint}:{}})}let f=m[0],h=f?.loaded,g=h?.manifest.server??Ad();for(let R of m.slice(1)){let O=R.loaded.manifest.server;for(let[C,z,ze,Re]of[["server.port",g.port,O.port,e.port!==void 0],["server.host",g.host,O.host,e.host!==void 0],["server.tokenEnv",g.tokenEnv,O.tokenEnv,!1]]){if(Re||z===ze)continue;throw new A({code:"serve_bind_conflict",message:`${f?.path??"the first manifest"} sets ${C} to ${String(z)} and ${R.path} sets it to ${String(ze)}.`,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:C})}}let b=e.port??g.port,T=e.port===void 0,x=e.host??g.host,S=h===void 0?n[g.tokenEnv]:h.env[g.tokenEnv],L=n[g.tokenEnv],G=m.every((R)=>Zt(Mo(R.path),n)),E=S;if(G&&(L===void 0||L==="")){let R=fn(q(n));if(R!==void 0)E=R;else if(S!==void 0&&S!=="")ri(q(n),S)}let I=n[`${t.envPrefix}SERVICE`]!==void 0,_=new Dt({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)_.on("agent.channel.status",(R)=>{let O=R.data,C=O.input===void 0?"":O.input.kind==="pairing_code"?`
|
|
279
279
|
|
|
280
|
-
${
|
|
281
|
-
${
|
|
282
|
-
expires ${
|
|
283
|
-
`)}),
|
|
284
|
-
hint: ${
|
|
285
|
-
`)}),
|
|
286
|
-
hint: ${
|
|
287
|
-
`)}),
|
|
288
|
-
`)});let
|
|
289
|
-
`);else{let
|
|
280
|
+
${O.input.payload}
|
|
281
|
+
${O.input.expiresAt===void 0?"":`
|
|
282
|
+
expires ${O.input.expiresAt}`}`:` (${O.input.kind}${O.input.expiresAt===void 0?"":`, expires ${O.input.expiresAt}`} — GET /v1/agents/${R.agentId??""} carries it)`;process.stdout.write(` ${O.channelId}: ${O.status}${O.detail===void 0?"":` — ${O.detail}`}${C}
|
|
283
|
+
`)}),_.on("agent.channel.error",(R)=>{let O=R.data;process.stderr.write(` ${O.channelId}: ${O.message}
|
|
284
|
+
hint: ${O.hint}
|
|
285
|
+
`)}),_.on("error",(R)=>{let O=R.data,C=R.sessionKey===void 0?"":` [${R.sessionKey}]`;process.stderr.write(` turn failed${C}: ${O.code}: ${O.message}
|
|
286
|
+
hint: ${O.hint}
|
|
287
|
+
`)}),_.on("agent.channel.rejected",(R)=>{let O=R.data;process.stdout.write(` ${O.channelId}: ${O.reason} — ${O.detail}
|
|
288
|
+
`)});let N=Yr(),M=n[`${t.envPrefix}RELAY_URL`],B=n[`${t.envPrefix}RELAY_TOKEN`],K=M===void 0||M===""||B===void 0||B===""?void 0:Lo({url:M,token:B,cacheFile:Od(Mo(i),"relay-peers.json")}),ee=(R)=>({agents:R,...K===void 0?{}:{relay:K},approve:N.approver,env:n,bus:_,toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,startChannels:!0,startSchedules:!0,store:i,mode:I?"daemon":"terminal"}),D;try{D=await Ee.create(ee(m.map((R)=>R.path)))}catch(R){if(!c||m.length===0)throw R;let O=[];for(let C of m)try{await(await Ee.create({...ee([C.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),O.push(C)}catch(z){w.push({path:C.path,detail:p(z)?z.message:String(z),...p(z)&&z.hint!==void 0?{hint:z.hint}:{}})}if(O.length===m.length)throw R;m.splice(0,m.length,...O),D=await Ee.create(ee(O.map((C)=>C.path)))}fs();let Xe=Cd(),Ie=await D.store.operatorKeys.liveCount(),se=Ie===0||e.claim===!0?As():void 0,re,xn=[];try{re=await jd(b,T,(R)=>(xn.push(R),rs({runtime:D,host:x,port:R,approvals:N,allowedOrigins:g.allowedOrigins,allowedHosts:g.allowedHosts,resolveAgent:(O)=>eo(O,n),provision:{steps:()=>Bt({agentDirBase:q(n)}),create:(O)=>qt({answers:O,defaults:{agentDirBase:q(n)}}),claim:async(O)=>{await Te(D.store,O,q(n))},templates:()=>mt(Dr(n)),createFromTemplate:(O)=>_o({...O,templatesDir:Dr(n),agentDirBase:q(n)}),rerender:(O)=>Uo({...O,templatesDir:Dr(n)}),templateOf:Ko},secrets:{status:dt,write:So},remover:Kd(n),home:we(n),channels:{setEnabled:Vn,setCredential:Wn,unpair:zn},...se===void 0?{}:{claim:se},...E===void 0||E===""?{}:{token:E}})))}catch(R){if(await D.stop("server failed to bind"),p(R))throw R;let O=xn.length>1?` — also tried ${xn.slice(1).join(", ")}`:"";throw new A({code:"server_bind_failed",message:`Could not bind ${x}:${b}${O}: ${R instanceof Error?R.message:String(R)}`,hint:T?`Every port in the range is taken. Pass --port to name a free one, or stop whatever is holding them — \`${t.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:R})}let oi=D.owned.length===0&&await cs(D.store.leases,{runtimeId:D.runtimeId,mode:I?"daemon":"terminal"});await D.publishAddress(re.url);let ce=D.list(),yt=ce[0];if(yt!==void 0)process.title=ce.length===1?`${t.slug} ${yt.id}`:`${t.slug} ${ce.length} agents`;for(let R of ce)R.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:re.url,websocket:re.websocket,authenticated:E!==void 0&&E!=="",keys:Ie,...se===void 0?{}:{claim:se.token},agents:ce.map((R)=>({id:R.id,channels:D.channels.statusOf(R.id)})),declined:D.declined.map((R)=>({agentId:R.agentId,pid:R.pid,mode:R.mode,since:R.startedAt})),disabled:a.map((R)=>({agentId:R.agentId,...R.reason===void 0?{}:{reason:R.reason}})),broken:w.map((R)=>({path:R.path,detail:R.detail,...R.hint===void 0?{}:{hint:R.hint}}))})}
|
|
289
|
+
`);else{let R=`http://${an(x)}:${re.port}`,O=R===re.url?"":` (bound ${x} — every interface)`;if(process.stdout.write(`${t.name} serving on ${R}${O}
|
|
290
290
|
`),re.port!==b)process.stdout.write(` moved from ${b} — something else is on it. \`--port ${b}\` would refuse instead of moving.
|
|
291
|
-
`);process.stdout.write(` web UI ${
|
|
292
|
-
`);for(let
|
|
293
|
-
`)}for(let
|
|
294
|
-
`);for(let
|
|
295
|
-
`),
|
|
296
|
-
`);for(let
|
|
297
|
-
`);if(
|
|
291
|
+
`);process.stdout.write(` web UI ${R}/ · API reference ${R}/docs
|
|
292
|
+
`);for(let C of ce){let z=D.channels.statusOf(C.id),ze=z.length===0?"no channels":z.map((Oe)=>`${Oe.id} (${Oe.type}${Oe.status==="error"?", BROKEN":""})`).join(", "),Re=C.manifest.schedules.filter((Oe)=>Oe.enabled),ai=C.manifest.schedules.length===0?"":`, ${Re.length} schedule${Re.length===1?"":"s"}${C.manifest.schedules.length>Re.length?` (+${C.manifest.schedules.length-Re.length} disabled)`:""}`;process.stdout.write(` ${C.id} — ${ze}${ai}
|
|
293
|
+
`)}for(let C of a)process.stdout.write(` ${C.agentId} — stopped${C.reason===void 0?"":` (${C.reason})`}, \`${t.slug} start ${C.agentId}\`
|
|
294
|
+
`);for(let C of w)if(process.stdout.write(` ${C.path} — NOT served: ${C.detail}
|
|
295
|
+
`),C.hint!==void 0)process.stdout.write(` hint: ${C.hint}
|
|
296
|
+
`);for(let C of D.declined)process.stdout.write(` ${C.agentId} — NOT served here: pid ${C.pid} (${C.mode}) already has it
|
|
297
|
+
`);if(D.declined.length>0)process.stdout.write(` \`${t.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
|
|
298
298
|
`);if(se!==void 0){if(process.stdout.write(` open once to claim this server:
|
|
299
|
-
${ns(
|
|
300
|
-
without a browser: ${os(
|
|
301
|
-
`),
|
|
302
|
-
`)}if(
|
|
303
|
-
`);if(
|
|
299
|
+
${ns(x,re.port,se.token)}
|
|
300
|
+
without a browser: ${os(x,re.port,se.token)}
|
|
301
|
+
`),E===void 0||E==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
|
|
302
|
+
`)}if(E===void 0||E==="")process.stdout.write(` unauthenticated — loopback only. Set ${g.tokenEnv} to bind a public host.
|
|
303
|
+
`);if(I)process.stdout.write(` running as a background service · ${t.slug} daemon status ${ce[0]?.id??""}
|
|
304
304
|
`);else if(xr())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
|
|
305
305
|
`);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${t.slug} daemon install${ce[0]?.id===void 0?"":` ${ce[0].id}`}\` keeps it running.
|
|
306
|
-
`)}let wt=!1,bt=async()=>{if(wt)return;if(wt=!0,r>0&&
|
|
307
|
-
`);let
|
|
308
|
-
`:`${
|
|
309
|
-
`)}if(await re.stop(),
|
|
310
|
-
`),await bt(),o}function
|
|
306
|
+
`)}let wt=!1,bt=async()=>{if(wt)return;if(wt=!0,r>0&&D.all().some((R)=>R.inFlight>0)){let R=Date.now();process.stdout.write(`draining — waiting up to ${r} ms for running turns
|
|
307
|
+
`);let O=await D.drain(r);process.stdout.write(O===0?`drained in ${Date.now()-R} ms
|
|
308
|
+
`:`${O} turn(s) still running after ${r} ms; the next start marks them interrupted
|
|
309
|
+
`)}if(await re.stop(),oi)await D.store.leases.release(Ut,D.runtimeId).catch(()=>{});await D.stop("interrupted")};return U(bt),await Xe,process.stdout.write(`stopping
|
|
310
|
+
`),await bt(),o}function _d(e){let n=`${t.envPrefix}DRAIN_MS`,r=e[n];if(r===void 0||r==="")return 0;if(!/^\d+$/.test(r))throw new A({code:"serve_drain_invalid",message:`${n} is "${r}", 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:n});return Number(r)}function Cd(){return new Promise((e)=>{let n=()=>{process.off("SIGINT",n),process.off("SIGTERM",n),e()};process.once("SIGINT",n),process.once("SIGTERM",n)})}var Nd=16;async function jd(e,n,r){let i=n&&e!==0?e+Nd:e;for(let s=e;;s+=1)try{return await r(s)}catch(a){if(s>=i||!Fd(a))throw a}}function Fd(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let n=e instanceof Error?e.message:String(e);return n.includes("EADDRINUSE")||n.includes("in use")}function Kd(e){return{locate(n){let r=Ae(e).filter((s)=>s.id===n),i=r[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${n}" 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(r.length>1)return{ok:!1,status:409,error:{code:"agent_remove_shared_id",message:`${r.length} sandbox directories declare id "${n}": ${r.map((s)=>s.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(n){if(!Zt(n,e))throw Error(`refusing to delete ${n}: it is outside the sandbox`);Id(n,{recursive:!0,force:!0})}}}function W(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function Ud(e){let n=new Map,r=[];for(let i of e){let s=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(s.length!==3||s[0]!=="schedule"){r.push(a);continue}let l=`schedule:${s[1]}`,c=n.get(l);if(c===void 0){let m={...a,sessionKey:`${l}:*`,runs:1};n.set(l,m),r.push(m);continue}if(c.runs=(c.runs??1)+1,c.messages+=i.messages,c.turns+=i.turns,i.lastActivityAt>c.lastActivityAt)c.lastActivityAt=i.lastActivityAt}return r}function Ld(e){if(e.length===0){process.stdout.write(`no sessions yet
|
|
311
311
|
`);return}let n=Ud(e),r=Math.max(7,...n.map((i)=>i.sessionKey.length));process.stdout.write(`${W("SESSION",r)} ${W("MSGS",5)} ${W("TURNS",5)} ${W("PHASE",8)} LAST
|
|
312
312
|
`);for(let i of n){let s=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${W(i.sessionKey,r)} ${W(String(i.messages),5)} ${W(String(i.turns),5)} ${W(i.phase??"-",8)} ${rA(i.lastActivityAt,Date.now())}${s}
|
|
313
|
-
`)}}async function
|
|
313
|
+
`)}}async function Md(e,n,r){let i=await e.store.messages.page(e.id,n,{limit:r});if(i.messages.length===0){process.stdout.write(`no messages in ${n}
|
|
314
314
|
`);return}for(let s of[...i.messages].reverse())process.stdout.write(`${s.role}: ${s.content}
|
|
315
315
|
`);if(i.nextBefore!==void 0)process.stdout.write(`
|
|
316
316
|
… older messages exist; raise --limit
|
|
317
|
-
`)}async function
|
|
317
|
+
`)}async function Dd(e,n,r){let i=await e.turns(n,r);if(i.length===0){process.stdout.write(`no turns in ${n}
|
|
318
318
|
`);return}process.stdout.write(`${W("TURN",22)} ${W("STATUS",9)} ${W("STEPS",5)} ${W("TOKENS",13)} ${W("MS",6)} SOURCE
|
|
319
319
|
`);for(let s of i)if(process.stdout.write(`${W(s.turnId,22)} ${W(s.status,9)} ${W(String(s.steps),5)} ${W(`${s.promptTokens}/${s.outputTokens}`,13)} ${W(String(s.durationMs??"-"),6)} ${s.source}
|
|
320
320
|
`),s.errorCode!==void 0){if(process.stdout.write(` ${s.errorCode}: ${s.errorMessage}
|
|
321
321
|
`),s.errorHint!==void 0)process.stdout.write(` hint: ${s.errorHint}
|
|
322
|
-
`)}}async function
|
|
322
|
+
`)}}async function Wo(e){let n=await Ee.create({agents:[e.manifestPath],store:e.store??P(),toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath])});U(()=>n.stop("cli-exit"));let r=n.list()[0];if(r===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 r.store.messages.count(r.id,e.sessionKey);return await r.clearSession(e.sessionKey),process.stdout.write(`cleared ${e.sessionKey}: ${a} message(s) removed, memory files untouched
|
|
323
323
|
`),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:n.store.location,sessions:await r.sessions()}:{store:n.store.location,session:await r.store.sessions.get(r.id,e.sessionKey),messages:(await r.store.messages.page(r.id,e.sessionKey,{limit:i})).messages,turns:await r.turns(e.sessionKey,i)};return process.stdout.write(`${JSON.stringify(a,null,2)}
|
|
324
324
|
`),o}if(process.stdout.write(`store: ${n.store.location}
|
|
325
325
|
|
|
326
326
|
`),e.sessionKey===void 0)return Ld(await r.sessions()),o;if(await r.store.sessions.get(r.id,e.sessionKey)===void 0)return process.stderr.write(`no session "${e.sessionKey}" for agent ${r.id}
|
|
327
327
|
hint: run \`sessions ${e.manifestPath}\` to list the keys that exist
|
|
328
|
-
`),d;if(e.turns===!0)await
|
|
328
|
+
`),d;if(e.turns===!0)await Dd(r,e.sessionKey,i);else await Md(r,e.sessionKey,i);return o}import{existsSync as Hd,readFileSync as Gd,writeFileSync as Wd}from"node:fs";import{basename as Bd,dirname as qd,join as Vd}from"node:path";var Jd=/^(#{1,6})\s+(.*)$/,Xd=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,zd=/^[ \t]*<\/rules>[ \t]*$/,Yd=/^\s*(?:```|~~~)/;function qo(e){if(e.action!=="distill")throw new A({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 n;try{n=Gd(e.file,"utf8")}catch{throw new A({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 r=Bd(e.file),i=e.out??Vd(qd(e.file),`${r.replace(/\.md$/i,"")}.compact.md`);if(Hd(i))throw new A({code:"cli_soul_out_exists",message:`${i} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:s}=HA(r,n),a=Qd(r,s);return Wd(i,a,"utf8"),process.stdout.write(`wrote ${i}
|
|
329
329
|
|
|
330
330
|
The scaffold copies ${r}'s headings and its <rules> blocks verbatim, and leaves a
|
|
331
331
|
{{PLACEHOLDER}} under each heading. Now:
|
|
332
332
|
`+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
|
|
333
333
|
`+` document's own voice. The workspace command warns until none are left.
|
|
334
334
|
2. Name the file in context.soul.distilled.
|
|
335
|
-
`),o}function
|
|
336
|
-
`)){if(
|
|
335
|
+
`),o}function Qd(e,n){let r=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${e}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],i=!1,s=!1,a=0,l=!1;for(let c of n.split(`
|
|
336
|
+
`)){if(Yd.test(c)){if(i=!i,s)r.push(c);continue}if(i){if(s)r.push(c);continue}if(Xd.test(c)){s=!0,r.push(c);continue}if(s){if(r.push(c),zd.test(c))s=!1,r.push("");continue}if(Jd.exec(c)!==null)l=!0,a+=1,r.push(c),r.push(""),r.push(`{{SECTION_${a}}}`),r.push("")}if(!l)r.push("{{ESSENCE}}"),r.push("");return`${r.join(`
|
|
337
337
|
`).replace(/\n{3,}/g,`
|
|
338
338
|
|
|
339
339
|
`).trimEnd()}
|
|
340
|
-
`}var
|
|
340
|
+
`}var Zd=["list","add","remove","update","search"],el=12;async function Vo(e){try{switch(e.action){case"list":return nl(e);case"add":return tl(e);case"remove":return rl(e);case"update":return await ol(e);case"search":return await il(e);default:throw new A({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${Zd.join(", ")}.`})}}catch(n){if(p(n))return process.stdout.write(`${n.message}
|
|
341
341
|
|
|
342
342
|
${n.hint}
|
|
343
|
-
`),d;throw n}}function
|
|
343
|
+
`),d;throw n}}function nl(e){let r=Fe(e.env).map((i)=>{let s=ar(i.name,e.env);return{...i,cached:Et(i.name,e.env),commit:s.commit,fetchedAt:s.fetchedAt,skills:s.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:to(e.env),sources:r},null,2)}
|
|
344
344
|
`),o;if(r.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
|
|
345
345
|
|
|
346
346
|
\`sources add <name> <url>\` to add one, or \`sources add ${_A[0]?.name??"anthropic"} ${_A[0]?.url??""}\` to put a built-in back.
|
|
@@ -349,15 +349,15 @@ ${Q(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
|
|
|
349
349
|
`),process.stdout.write(y(u([{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(`
|
|
350
350
|
${v("registry")}
|
|
351
351
|
${y(to(e.env))}
|
|
352
|
-
`),o}function
|
|
352
|
+
`),o}function tl(e){let[n,r]=e.rest;if(n===void 0)throw new A({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let i=r!==void 0,s=i?r:n,a=sr(s),l=i?n:sl(a.url);if(!kA(l))throw new A({code:"sources_name_invalid",message:`${JSON.stringify(l)} 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 c=Fe(e.env).find((h)=>h.name===l);if(c!==void 0&&!i)throw new A({code:"sources_name_taken",message:`${l} is already a source, pointing at ${c.url}`,hint:`Give this one its own name: \`sources add <name> ${s}\`.`});let m=e.path??a.path,w=e.ref??a.ref,f={name:l,url:a.url,...m===void 0?{}:{path:m},...w===void 0?{}:{ref:w}};if(ls(f,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:f},null,2)}
|
|
353
353
|
`),o;return process.stdout.write(`${u([{label:c===void 0?"added":"replaced",value:l},{label:"url",value:f.url},...f.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:f.path}],...f.ref===void 0?[]:[{label:"branch",value:f.ref}]])}
|
|
354
354
|
`),process.stdout.write(`${v("next")}
|
|
355
355
|
${Q(`sources update ${l}`)}
|
|
356
356
|
${Q("sources search <what you need>")}
|
|
357
|
-
`),o}function
|
|
357
|
+
`),o}function sl(e){let n=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(n[n.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function rl(e){let n=e.rest[0];if(n===void 0)throw new A({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let r=Fe(e.env).map((s)=>s.name);if(!Is(n,e.env)){let s=j(n,r);throw new A({code:"sources_unknown",message:`no source called ${n}`,hint:s===void 0?`Configured: ${r.join(", ")||"none"}.`:`Did you mean ${s}?`})}let i=_A.some((s)=>s.name===n);return process.stdout.write(`removed ${n}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
|
|
358
358
|
`),process.stdout.write(`
|
|
359
359
|
The cached copy is left on disk; nothing already installed into an agent is touched.
|
|
360
|
-
`),o}async function
|
|
360
|
+
`),o}async function ol(e){let n=Fe(e.env),r=e.rest.length===0?n:e.rest.map((a)=>{let l=n.find((c)=>c.name===a);if(l===void 0){let c=j(a,n.map((m)=>m.name));throw new A({code:"sources_unknown",message:`no source called ${a}`,hint:c===void 0?`Configured: ${n.map((m)=>m.name).join(", ")||"none"}.`:`Did you mean ${c}?`})}return l});if(r.length===0)return process.stdout.write(`no sources configured
|
|
361
361
|
|
|
362
362
|
\`sources add <url>\` to add one.
|
|
363
363
|
`),o;let i=[],s=[];for(let a of r){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let l=await vA(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:l.commit,skills:l.skills}),e.json!==!0)process.stdout.write(`${l.skills} skills at ${l.commit}${l.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
|
|
@@ -365,7 +365,7 @@ ${Q("sources search <what you need>")}
|
|
|
365
365
|
`);if(e.json!==!0&&p(l))process.stdout.write(`${y(l.message)}
|
|
366
366
|
${y(l.hint,4)}
|
|
367
367
|
`)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:s},null,2)}
|
|
368
|
-
`);return i.length===0?d:o}async function
|
|
368
|
+
`);return i.length===0?d:o}async function il(e){let n=e.rest.join(" ").trim(),r=Fe(e.env);if(r.length===0)return process.stdout.write(`no sources configured
|
|
369
369
|
|
|
370
370
|
\`sources add <url>\` to add one.
|
|
371
371
|
`),d;let i=r.filter((c)=>!Et(c.name,e.env));for(let c of i){if(e.json!==!0)process.stdout.write(`fetching ${c.name} for the first time … `);try{let m=await vA(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${m.skills} skills
|
|
@@ -375,12 +375,12 @@ ${y(l.hint,4)}
|
|
|
375
375
|
nothing to search — no source has been fetched successfully
|
|
376
376
|
|
|
377
377
|
\`sources update\` reports why.
|
|
378
|
-
`),d;let a=n.length===0?s:
|
|
378
|
+
`),d;let a=n.length===0?s:al(n,s);if(a.length===0)return process.stdout.write(`
|
|
379
379
|
nothing in ${s.length} skills across ${r.length} sources matches ${JSON.stringify(n)}
|
|
380
380
|
|
|
381
381
|
Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
|
|
382
382
|
`),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:n,searched:s.length,results:a.map((c)=>({source:c.source,skill:c.skill,description:c.description,tokens:c.tokens,scripts:c.scripts.length,repoPath:c.repoPath,...c.problem===void 0?{}:{problem:c.problem}}))},null,2)}
|
|
383
|
-
`),o;let l=a.slice(0,
|
|
383
|
+
`),o;let l=a.slice(0,el);process.stdout.write(`
|
|
384
384
|
${v(n.length===0?`${s.length} skills`:`${a.length} of ${s.length} skills match ${JSON.stringify(n)}`,!0)}
|
|
385
385
|
`);for(let c of l){process.stdout.write(`${Q(`${c.source}/${c.skill}`)} ${c.tokens} tokens${c.scripts.length===0?"":`, ${c.scripts.length} runnable file${c.scripts.length===1?"":"s"}`}${c.problem===void 0?"":" — will not load"}
|
|
386
386
|
`);let m=c.problem??c.description;process.stdout.write(`${y(m.length>160?`${m.slice(0,157)}…`:m,4)}
|
|
@@ -389,15 +389,15 @@ ${y(`… and ${a.length-l.length} more; narrow the query or use --json`)}
|
|
|
389
389
|
`);return process.stdout.write(`
|
|
390
390
|
${v("install")}
|
|
391
391
|
${y(`skills install <agent> ${l[0]?.source}/${l[0]?.skill}`)}
|
|
392
|
-
`),o}function
|
|
392
|
+
`),o}function al(e,n){let r=new Map,i=n.map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return JA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}async function Jo(e){let n=dl(e.manifestPath),r=await ir(n,e.store),i=[];if(r?.enabled===!0)i.push("was already switched on");await rr(n,!0,void 0,e.store);let s=await Ve(e.store),a=!1;if(s===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(s.baseUrl===void 0)i.push(`pid ${s.pid} is a ${s.mode} session, which serves no HTTP to adopt into`);else{let l=await ut(s,`/v1/agents/${encodeURIComponent(n)}/start`,{},e.manifestPath);if(l.ok)a=!0,i.push(`adopted by pid ${s.pid}, live now`);else if(l.status===501)i.push(`pid ${s.pid} cannot look up manifests — restart it to pick this up`);else if(l.status===401)i.push(`pid ${s.pid} refused the request — set ${t.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${s.pid} could not adopt it${l.detail===void 0?"":`: ${l.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:n,enabled:!0,running:a,...s===void 0?{}:{pid:s.pid,mode:s.mode},note:i.join(" · ")}]},null,2)}
|
|
393
393
|
`);else if(process.stdout.write(`${u([{label:n,value:a?"running":"switched on",note:i.join(" · ")}])}
|
|
394
394
|
`),!a&&s!==void 0&&s.baseUrl!==void 0)process.stdout.write(`
|
|
395
395
|
Switched on but not yet running. \`${t.slug} daemon restart\` picks it up.
|
|
396
|
-
`);return s!==void 0&&s.baseUrl!==void 0&&!a?d:o}function
|
|
396
|
+
`);return s!==void 0&&s.baseUrl!==void 0&&!a?d:o}function dl(e){let n=F(e);if(n.id===void 0||n.id==="")throw new A({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 n.id}async function zo(e){let n=await Tn(e.store),r=new Map;for(let a of n){if(a.serving===void 0)continue;let l=await sn(a.manifestPath,e.store);if(l!==void 0)r.set(a.ref,l)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:n.map((a)=>({...a,channels:[...r.get(a.ref)?.values()??[]]}))},null,2)}
|
|
397
397
|
`),o;let i=await Ft({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${u(In(n))}
|
|
398
398
|
`);let s=[];for(let[a,l]of r)for(let c of l.values())s.push({label:`${a} / ${c.id}`,value:c.status,note:c.input!==void 0?`${c.detail??"enter this code"}: ${c.input.payload}`:c.detail??""});if(s.length>0)process.stdout.write(`
|
|
399
399
|
${u(s)}
|
|
400
|
-
`);return i}import{copyFileSync as
|
|
400
|
+
`);return i}import{copyFileSync as ll,existsSync as cl,mkdirSync as ul,readFileSync as fl,writeFileSync as ml}from"node:fs";import{dirname as pl,join as Yo}from"node:path";async function Zo(e){let n=e.env??k([]),r=e.home??n.HOME??"",i=un(n),s=hn(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:s?.how??"unknown",configPath:s?.configPath===void 0?void 0:Yo(r,s.configPath),line:s?.line,steps:s?.steps},null,2)}
|
|
401
401
|
`),s===void 0?d:o;if(process.stdout.write(`${v("shift+enter",!0)}
|
|
402
402
|
${y("⌥ 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.")}
|
|
403
403
|
`),s===void 0)return process.stdout.write(`
|
|
@@ -414,7 +414,7 @@ ${v(s.name)}
|
|
|
414
414
|
${Q("⌥⏎ works here today — nothing has to be configured for it")}
|
|
415
415
|
`:`
|
|
416
416
|
${Q("then restart the terminal and press shift+⏎ in a session to check it")}
|
|
417
|
-
`),o}return await
|
|
417
|
+
`),o}return await hl(s,{...e,env:n,home:r})}async function hl(e,n){let r=Yo(n.home,e.configPath??""),i=cl(r)?fl(r,"utf8"):"";if(ms(i,e))return process.stdout.write(`${y("already configured — a binding for shift+enter is present")}
|
|
418
418
|
${y(oA(r,n.home),4)}
|
|
419
419
|
`),o;let s=ps(i,e);if(s===void 0)return process.stdout.write(`${y("this file is not in a shape this command can edit safely:")}
|
|
420
420
|
${y(oA(r,n.home),4)}
|
|
@@ -425,12 +425,12 @@ ${y(e.line??"",4)}
|
|
|
425
425
|
${Q("--dry-run: nothing was written")}
|
|
426
426
|
`),o;if(n.yes!==!0){if(!(n.confirm===void 0?!1:await n.confirm("write this change?")))return process.stdout.write(`
|
|
427
427
|
${Q("nothing was written")}
|
|
428
|
-
`),o}try{if(
|
|
428
|
+
`),o}try{if(ul(pl(r),{recursive:!0}),i!=="")ll(r,`${r}.${t.slug}-backup`);ml(r,s,"utf8")}catch(a){return process.stderr.write(`could not write ${r}: ${a instanceof Error?a.message:String(a)}
|
|
429
429
|
`),d}return process.stdout.write(`
|
|
430
430
|
${v("done")}
|
|
431
431
|
${i===""?"":`${y(`a copy of the old file is at ${oA(`${r}.${t.slug}-backup`,n.home)}`)}
|
|
432
432
|
`}${Q("restart the terminal, then press shift+⏎ in a session to check it")}
|
|
433
|
-
`),o}async function
|
|
433
|
+
`),o}async function ei(e){return e.warm===!0?await gl(e):await yl(e)}async function gl(e){let n=V(e.manifestPath,{env:k([e.manifestPath])}),r=ht(n.manifest.tools).selections,i=n.manifest.tools.pinned;if(r.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
|
|
434
434
|
`),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${r.map((c)=>c.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
|
|
435
435
|
`),o;let s=[],a=new Set;for(let c of r){let m=ie[c.id];if(m===void 0)return d;let w;try{let f=m({dir:n.dir,env:n.env,config:c.config,agentId:n.manifest.id});if(f.refresh===void 0){for(let h of await f.resolve(i))a.add(h.spec.slug);if(e.json!==!0)process.stdout.write(`${c.id}: nothing to warm — it resolves without a cache.
|
|
436
436
|
`);continue}w=await f.refresh(i)}catch(f){let h=p(f)?`${f.message}
|
|
@@ -440,30 +440,30 @@ ${i===""?"":`${y(`a copy of the old file is at ${oA(`${r}.${t.slug}-backup`,n.ho
|
|
|
440
440
|
`),c.changed.length>0)process.stdout.write(` changed: ${c.changed.join(", ")}
|
|
441
441
|
`);if(c.cachePath!=="")process.stdout.write(` cache: ${c.cachePath}
|
|
442
442
|
`)}let l=i.filter((c)=>!a.has(c));for(let c of l)process.stdout.write(` missing: ${c} — no configured provider has a tool with that slug
|
|
443
|
-
`);return l.length>0?d:o}async function
|
|
443
|
+
`);return l.length>0?d:o}async function yl(e){let n=await Ee.create({agents:[e.manifestPath],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath])});try{let r=n.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Xo(r);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
|
|
444
444
|
`:`${DA(i)}
|
|
445
|
-
`),o}finally{await n.stop("cli-exit")}}import{dirname as
|
|
446
|
-
`),o;let
|
|
445
|
+
`),o}finally{await n.stop("cli-exit")}}import{dirname as ni,isAbsolute as wl,resolve as Rn}from"node:path";async function ti(e){try{let n=F(e.manifestPath),r=await Do({refs:n.plugins??[],agentId:n.id??e.manifestPath,paths:{workspace:ni(Rn(e.manifestPath)),state:ni(Rn(e.manifestPath)),manifest:Rn(e.manifestPath)},env:k([e.manifestPath]),bus:new Dt({runtimeId:"validate"}),builtIn:Be,pluginRoot:ae(),base:{toolProviders:ie,modelTransports:Se,mediaProviders:de,channels:le}}),i=V(e.manifestPath,{env:k([e.manifestPath])}),{manifest:s}=i,a=ye(s.model.main.id,s.model.main.capabilities),{workspace:l,warnings:c}=uA(i,a.promptStyle),m=No(Oo(i,{channels:r.channels})),w=await yn(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let E of w.providers)await E.stop?.();let f=ho(s,{env:i.env,transports:new Map([...cA,...Object.entries(r.modelTransports)])});YA(s,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let h=$t(l,s.context.rules);if(h!==void 0&&s.context.rules.onExceed==="fail")throw h;let g=[...c,...r.failed,...w.warnings,...w.registry.warnings,...m,...Qo(s),...yo(s),...h===void 0?[]:[h.toDetail()]],b=s.knowledge===void 0?void 0:bo({dir:wl(s.knowledge.dir)?s.knowledge.dir:Rn(i.dir,s.knowledge.dir),maxActive:s.knowledge.maxActive,budget:s.knowledge.budget,style:a.promptStyle}),T=["static","volatile","reminder"].map((E)=>{let I=l.files.filter((_)=>_.tier===E).map((_)=>_.name);if(I.length===0)return;return`${E}=${I.join(",")} (${l.tokens[E]}/${s.context.budgets[E]})`}).filter((E)=>E!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:s.id,model:s.model.main.id,window:i.window,capabilities:a,workspace:{files:l.files.map((E)=>({name:E.name,tier:E.tier,editable:E.editable,tokens:E.tokens,budget:E.budget})),tokens:l.tokens},knowledge:b===void 0?[]:b.entries.map((E)=>({name:E.name,keywords:E.keywords,tokens:E.tokens})),warnings:g},null,2)}
|
|
446
|
+
`),o;let x=Nt(s),S=x.map((E)=>E.role===E.configuredAs?`${E.role}=${E.modelId}`:`${E.role}=→main`).join(" "),L=x.filter((E)=>E.role===E.configuredAs),G=Xi({manifestPath:e.manifestPath,rawModelId:n.modelId,apiKeyEnv:s.model.main.apiKeyEnv}).flatMap((E)=>{let I=$i(E.origin);return I===void 0?[]:[` env ${E.variable} — ${I}
|
|
447
447
|
`]}).join("");return process.stdout.write(`ok ${i.path}
|
|
448
448
|
id ${s.id}${s.name===void 0?"":` (${s.name})`}
|
|
449
449
|
models ${S}
|
|
450
|
-
`+
|
|
451
|
-
`+(
|
|
450
|
+
`+G+` window ${i.window} ${gA(x[0]?.window)} (reserveOutput ${s.context.reserveOutput}, maxOutput ${a.maxOutput})
|
|
451
|
+
`+(L.length<2?"":`${L.slice(1).map((E)=>` ${E.role.padEnd(12)} ${E.modelId} · window ${E.window.contextWindow} ${gA(E.window)}
|
|
452
452
|
`).join("")}`)+` capabilities thinking=${f.main.capabilities.thinking} promptCache=${f.main.capabilities.promptCache} nativeTools=${f.main.capabilities.nativeTools} strictSchema=${f.main.capabilities.strictSchema}
|
|
453
|
-
`+
|
|
454
|
-
workspace ${
|
|
453
|
+
`+bl(f.main.capabilities.promptCache,s.model.main.id)+` dialect ${s.tools.dialect}
|
|
454
|
+
workspace ${T===""?"(none)":T}
|
|
455
455
|
`+(b===void 0?"":` knowledge ${b.entries.length} entries, maxActive=${b.maxActive}, budget=${b.budget}
|
|
456
456
|
`)+` memory ${s.memory===void 0?"none — nothing is retrieved across sessions":`${s.memory.retriever} at ${s.memory.dir}, maxActive=${s.memory.maxActive}, threshold=${s.memory.threshold}, budget=${s.memory.budget}, history=${s.memory.includeHistory}`}
|
|
457
|
-
schedules ${s.schedules.length===0?"none":s.schedules.map((
|
|
458
|
-
team ${s.team===void 0?"none — no delegation; `handoff` is not registered":`${s.team.members.map((
|
|
457
|
+
schedules ${s.schedules.length===0?"none":s.schedules.map((E)=>`${E.id} (${E.kind} ${E.expr}${E.timezone===void 0?"":` ${E.timezone}`}${E.role===void 0?"":` role=${E.role}`}${E.enabled?"":", disabled"})`).join(" ")}
|
|
458
|
+
team ${s.team===void 0?"none — no delegation; `handoff` is not registered":`${s.team.members.map((E)=>`${E.id} (${E.manifest})`).join(" ")} — run one at a time`}
|
|
459
459
|
limits maxSteps=${s.limits.maxSteps} turnTimeoutMs=${s.limits.turnTimeoutMs}
|
|
460
|
-
`+g.map((
|
|
460
|
+
`+g.map((E)=>` warning ${E.message}
|
|
461
461
|
`).join("")),o}catch(n){if(e.json===!0&&p(n))return process.stdout.write(`${JSON.stringify({ok:!1,error:n.toDetail(),details:n.details},null,2)}
|
|
462
|
-
`),d;throw n}}function
|
|
462
|
+
`),d;throw n}}function bl(e,n){if(e!=="none")return"";return/(^|\/)claude-/i.test(n)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
|
|
463
463
|
`+` caching at all, so no request field reaches it. Caching lives on the native
|
|
464
464
|
Messages API, which this runtime does not speak.
|
|
465
465
|
`:` promptCache none — this runtime sends no cache directives. Many endpoints cache
|
|
466
|
-
`+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function
|
|
466
|
+
`+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function si(e){try{let n=V(e.manifestPath,{env:k([e.manifestPath])}),{manifest:r}=n,i=ye(r.model.main.id,r.model.main.capabilities),{workspace:s,warnings:a}=uA(n,i.promptStyle),l=[...a,...Bi(s.files.map((w)=>({name:w.name,authored:w.authored,tier:w.tier,field:w.field})))],c=$t(s,r.context.rules);if(c!==void 0)l.push(c.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:l.length===0,path:n.path,promptStyle:i.promptStyle,files:s.files.map((w)=>({name:w.name,tier:w.tier,editable:w.editable,tokens:w.tokens,budget:w.budget})),tokens:s.tokens,findings:l},null,2)}
|
|
467
467
|
`),e.strict===!0&&l.length>0?d:o;let m=i.promptStyle;process.stdout.write(`${n.path}
|
|
468
468
|
rendering delimiters=${m.delimiters} intensity=${m.intensity} examplesIn=${m.examplesIn}
|
|
469
469
|
total ${s.tokens.total} tokens (static ${s.tokens.static}, volatile ${s.tokens.volatile}, reminder ${s.tokens.reminder})
|
|
@@ -476,14 +476,14 @@ no findings
|
|
|
476
476
|
`);return process.stdout.write(`
|
|
477
477
|
${l.length} finding(s)
|
|
478
478
|
`),e.strict===!0?d:o}catch(n){if(e.json===!0&&p(n))return process.stdout.write(`${JSON.stringify({ok:!1,error:n.toDetail(),details:n.details},null,2)}
|
|
479
|
-
`),d;throw n}}function
|
|
479
|
+
`),d;throw n}}function $l(e){let n=$s(e);if(n!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${n} is not installed.
|
|
480
480
|
hint: it is an optional dependency, left out by an install with --omit=optional. Reinstall without it (npm i -g ${t.slug}), or pass --plain where the command has it.
|
|
481
481
|
`),d;if(p(e))process.stderr.write(`${e.format()}
|
|
482
482
|
`);else if(e instanceof Error){if(process.stderr.write(`${e.message}
|
|
483
483
|
`),zt().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
|
|
484
484
|
`)}else process.stderr.write(`${String(e)}
|
|
485
|
-
`);return d}async function
|
|
486
|
-
`),o;case"help":return process.stdout.write(Gn(n.command)),o;case"usage":return process.stdout.write(Gn()),d;case"command":break}let{command:r,positionals:i,flags:s}=n.parsed,a=i[0],l=()=>ve(a),c=r.flags.some((f)=>f.name==="store")?s.str("store"):void 0,m=await Ar({needsServer:r.needsServer,disabled:s.bool("no-bootstrap"),install:()=>nr(),...c===void 0?{}:{store:c}}),w=bA(m);if(w!==void 0)process.stderr.write(w);switch(r.name){case"init":{let f=s.str("dir"),h=s.str("user"),g=s.str("name"),b=s.str("purpose"),
|
|
485
|
+
`);return d}async function vl(e){let n=is(e);switch(n.kind){case"version":return process.stdout.write(`${J}
|
|
486
|
+
`),o;case"help":return process.stdout.write(Gn(n.command)),o;case"usage":return process.stdout.write(Gn()),d;case"command":break}let{command:r,positionals:i,flags:s}=n.parsed,a=i[0],l=()=>ve(a),c=r.flags.some((f)=>f.name==="store")?s.str("store"):void 0,m=await Ar({needsServer:r.needsServer,disabled:s.bool("no-bootstrap"),install:()=>nr(),...c===void 0?{}:{store:c}}),w=bA(m);if(w!==void 0)process.stderr.write(w);switch(r.name){case"init":{let f=s.str("dir"),h=s.str("user"),g=s.str("name"),b=s.str("purpose"),T=s.str("preset"),x=s.str("model"),S=s.str("base-url"),L=s.str("region"),G=s.str("api-key-env"),E=s.str("system"),I=s.str("web"),_=s.str("web-backend"),N=s.str("composio"),M=s.str("telegram"),B=s.str("telegram-allow"),K=s.str("whatsapp"),ee=s.str("whatsapp-number"),D=s.str("server"),Xe=s.str("schedules"),Ie=s.str("skills"),se=s.str("daemon");return await Xt({...f===void 0?{}:{dir:f},...h===void 0?{}:{user:h},...g===void 0?{}:{name:g},...b===void 0?{}:{purpose:b},...T===void 0?{}:{preset:T},...x===void 0?{}:{model:x},...S===void 0?{}:{baseUrl:S},...L===void 0?{}:{region:L},...G===void 0?{}:{apiKeyEnv:G},...E===void 0?{}:{system:E},...I===void 0?{}:{web:I},..._===void 0?{}:{webBackend:_},...N===void 0?{}:{composio:N},...M===void 0?{}:{telegram:M},...Xe===void 0?{}:{schedules:Xe},...B===void 0?{}:{telegramAllow:B},...K===void 0?{}:{whatsapp:K},...ee===void 0?{}:{whatsappNumber:ee},...D===void 0?{}:{server:D},...Ie===void 0?{}:{skills:Ie},...se===void 0?{}:{daemon:se},yes:s.bool("yes"),plain:s.bool("plain"),measureWindow:s.bool("measure-window"),installServer:nr})}case"run":{let f=s.str("session"),h=s.str("input"),g=s.str("store");return await ot({...i[0]===void 0?{}:{manifestPath:l()},...f===void 0?{}:{sessionKey:f},continueSession:s.bool("continue"),...h===void 0?{}:{once:h},...g===void 0?{}:{store:g},ephemeral:s.bool("ephemeral"),quiet:s.bool("quiet"),showReasoning:s.bool("show-reasoning"),noReasoning:s.bool("no-reasoning"),...s.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:s.bool("plain")})}case"schedules":{let f=s.str("store"),h=s.str("id"),g=s.str("enable"),b=s.str("disable");return await vo({manifestPath:l(),...f===void 0?{}:{store:f},...h===void 0?{}:{id:h},...g===void 0?{}:{enable:g},...b===void 0?{}:{disable:b},recipients:s.bool("recipients"),json:s.bool("json")})}case"sessions":{let f=s.str("session"),h=s.str("store"),g=s.num("limit");return await Wo({manifestPath:l(),...f===void 0?{}:{sessionKey:f},...h===void 0?{}:{store:h},...g===void 0?{}:{limit:g},json:s.bool("json"),clear:s.bool("clear"),turns:s.bool("turns")})}case"owner":{let f=s.str("store");return await Bs({action:a,...i[1]===void 0?{}:{manifestPath:ve(i[1])},...f===void 0?{}:{store:f},json:s.bool("json")})}case"memory":{let f=s.num("limit"),h=s.str("store");return await Rs({action:a,manifestPath:ve(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...f===void 0?{}:{limit:f},...h===void 0?{}:{store:h},all:s.bool("all"),json:s.bool("json")})}case"config":{let{configCommand:f,readAction:h}=await import("./config-hmgrqgf2.js"),g=h(a,i[1]);return await f({action:g.action,...g.ref===void 0?{}:{ref:g.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...s.str("channel")===void 0?{}:{channel:s.str("channel")},remove:s.bool("remove"),yes:s.bool("yes"),...s.str("store")===void 0?{}:{store:s.str("store")}})}case"validate":return await ti({manifestPath:l(),json:s.bool("json")});case"workspace":return si({manifestPath:l(),json:s.bool("json"),strict:s.bool("strict")});case"soul":{let f=s.str("out");return qo({action:a,file:i[1],...f===void 0?{}:{out:f}})}case"skills":{if(i.length===0)return await us({plain:s.bool("plain"),json:s.bool("json")});let f=i[2];return Kt({action:a,manifestPath:ve(i[1]??""),...f===void 0?{}:{name:f},json:s.bool("json"),strict:s.bool("strict")})}case"sources":{let f=s.str("path"),h=s.str("ref");return await Vo({action:a,rest:i.slice(1),...f===void 0?{}:{path:f},...h===void 0?{}:{ref:h},json:s.bool("json")})}case"channels":{let f=as("channels",a),h=f.ref??i[1]??"",{channelsCommand:g}=await import("./channels-m8nambmm.js");return await g({...f.action===void 0?{}:{action:f.action},manifestPath:ve(h),...i[2]===void 0?{}:{channelId:i[2]},json:s.bool("json"),installServer:nr})}case"plugins":{let f=s.str("ref"),h=s.str("name");return await mr({action:a,manifestPath:ve(i[1]??""),rest:i.slice(2),...f===void 0?{}:{ref:f},...h===void 0?{}:{name:h},json:s.bool("json")})}case"agents":{let f=s.str("store");return await vt({manifestPaths:i.map((h)=>ve(h)),...f===void 0?{}:{store:f},json:s.bool("json")})}case"restart":{let f=s.str("store");return await Hr({...a===void 0?{}:{manifestPath:l()},...f===void 0?{}:{store:f},json:s.bool("json")})}case"status":{let f=s.str("store");return await zo({...f===void 0?{}:{store:f},json:s.bool("json")})}case"logs":{let f=s.num("lines"),h=s.str("store");return await Ft({action:"logs",...a===void 0?{}:{manifestPath:l()},...f===void 0?{}:{lines:f},follow:s.bool("follow"),truncate:s.bool("truncate"),...h===void 0?{}:{store:h},json:s.bool("json")})}case"serve":{let f=s.num("port"),h=s.str("host"),g=s.str("store");return await Go({manifestPaths:i.map((b)=>ve(b)),...f===void 0?{}:{port:f},...h===void 0?{}:{host:h},...g===void 0?{}:{store:g},claim:s.bool("claim"),json:s.bool("json")})}case"keys":return await ys({noEnhancedKeys:s.bool("no-enhanced-keys")});case"terminal-setup":return await Zo({dryRun:s.bool("dry-run"),yes:s.bool("yes"),json:s.bool("json"),confirm:MA});case"remove":return await Fr({...a===void 0?{}:{ref:a},dryRun:s.bool("dry-run"),filesOnly:s.bool("files-only"),prune:s.bool("prune"),all:s.bool("all"),yes:s.bool("yes"),json:s.bool("json"),...s.str("store")===void 0?{}:{store:s.str("store")},confirm:ts});case"stop":{let f=s.str("reason");return await $n({...a===void 0?{}:{manifestPath:l()},dryRun:s.bool("dry-run"),...f===void 0?{}:{reason:f},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"start":return await Jo({manifestPath:l(),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")});case"web":{let{webCommand:f}=await import("./web-gfv0mzgs.js");return await f({action:a,...i[1]===void 0?{}:{manifestPath:ve(i[1])},noOpen:s.bool("no-open"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"credential":{let{credentialCommand:f}=await import("./credential-nkb2ya59.js");return await f({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...s.str("label")===void 0?{}:{label:s.str("label")},...s.str("agents")===void 0?{}:{agents:s.str("agents")},...s.str("sessions")===void 0?{}:{sessions:s.str("sessions")},...s.str("can")===void 0?{}:{can:s.str("can")},...s.str("expires")===void 0?{}:{expires:s.str("expires")},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"daemon":{let f=s.num("lines");return await Ft({action:a,...i[1]===void 0?{}:{manifestPath:ve(i[1])},...f===void 0?{}:{lines:f},follow:s.bool("follow"),truncate:s.bool("truncate"),dryRun:s.bool("dry-run"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"model":{let f=s.num("price");return await Ws({manifestPath:ve(i[1]),window:s.bool("window"),...f===void 0?{}:{price:f},write:s.bool("write"),yes:s.bool("yes"),json:s.bool("json")})}case"tools":return await ei({manifestPath:l(),warm:s.bool("warm"),json:s.bool("json")});default:throw new A({code:"cli_command_unwired",message:`Command "${r.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}ks();hs();vs();await vl(process.argv.slice(2)).catch($l).then((e)=>lr(e));
|
|
487
487
|
|
|
488
|
-
//# debugId=
|
|
488
|
+
//# debugId=44203BB87EB6E96464756E2164756E21
|
|
489
489
|
//# sourceMappingURL=index.js.map
|