@agensis/agensis-agent 0.1.32 → 0.1.34
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/bin/agensis.mjs +49 -43
- package/package.json +1 -1
package/bin/agensis.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),
|
|
4
|
-
`}async function
|
|
5
|
-
`)}async function
|
|
2
|
+
var Cr=Object.defineProperty;var xe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Dt=(e,t)=>{for(var n in t)Cr(e,n,{get:t[n],enumerable:!0})};var Vt={};Dt(Vt,{createE2bProvider:()=>Xr});function ze(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function Xr({apiKey:e,anthropicApiKey:t,gitToken:n="",repoUrl:r="",template:o=""}={}){if(!e)throw new Error("E2B_API_KEY is not set on the daemon host.");if(!r)throw new Error("Sandbox needs a repo URL (set sandbox_config.repoUrl or the agent's repo).");return{async ensureEnv(){let s={apiKey:e,envs:t?{ANTHROPIC_API_KEY:t}:{}},i;try{({Sandbox:i}=await import("e2b"))}catch(d){if(d&&(d.code==="ERR_MODULE_NOT_FOUND"||d.code==="MODULE_NOT_FOUND"||/Cannot find package 'e2b'/.test(String(d&&d.message)))){let c=Number(String(process.versions.node).split(".")[0])||0,l=c<20||c===21?` Sandbox mode needs Node >=20.18.1 (<21 or >=22); you have ${process.versions.node}. Upgrade Node, then run \`npm i e2b\` in the daemon.`:" Run `npm i e2b` in the daemon to enable Sandbox mode.";throw new Error(`Sandbox execution requires the optional 'e2b' package, which is not installed.${l}`)}throw d}let a=o?await i.create(o,s):await i.create(s);return await a.commands.run("bash -lc 'command -v claude >/dev/null || npm i -g @anthropic-ai/claude-code'"),{sbx:a,dir:Vr}},async putRepo(s){let i=n?r.replace(/^https:\/\//,`https://x-access-token:${n}@`):r;try{let a=await s.sbx.commands.run(`git clone ${ze(i)} ${ze(s.dir)}`);if(a&&typeof a.exitCode=="number"&&a.exitCode!==0)throw new Error(`git clone failed: ${a.stderr||`exit ${a.exitCode}`}`)}catch(a){if(a&&String(a.message||"").startsWith("git clone failed:"))throw a;let d=a&&(a.stderr||a.exitCode!=null)?a.stderr||`exit ${a.exitCode}`:String(a?.message||a);throw new Error(`git clone failed: ${d}`)}},async exec(s,{cmd:i,args:a=[],env:d={},onData:c}){let l=`${i} ${a.map(ze).join(" ")}`,g={cwd:s.dir,envs:{...d,IS_SANDBOX:"1",AGENSIS_ALLOW_ROOT_SKIP_PERMISSIONS:"1"},onStdout:m=>{try{c?.(m)}catch{}}};try{let m=await s.sbx.commands.run(l,g);return{status:m.exitCode,stdout:m.stdout||"",stderr:m.stderr||"",error:null}}catch(m){return m&&typeof m.exitCode=="number"?{status:m.exitCode,stdout:m.stdout||"",stderr:m.stderr||"",error:null}:{status:null,stdout:"",stderr:String(m?.message||m),error:m}}},async getResult(s){try{return{patch:(await s.sbx.commands.run("git add -A && git diff --cached",{cwd:s.dir})).stdout||""}}catch(i){return{patch:i&&i.stdout||""}}},async destroy(s){await s.sbx.kill()}}}var Vr,Xt=xe(()=>{Vr="/home/user/repo"});import Dn from"node:fs";import G from"node:fs/promises";import Xo from"node:os";import H from"node:path";function Rn(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/\.{2,}/g,".").replace(/^[.-]+/,"").slice(0,96)||t}function K({workspace:e,agent:t,homedir:n=Xo.homedir()}={}){return H.join(n,".agensis",Rn(e,"workspace"),Rn(t,"agent"))}function Un(e){return H.join(K(e),Bn)}function jn(e){return H.join(K(e),ct)}async function De(e){let t=K(e);try{return await G.mkdir(t,{recursive:!0}),t}catch{return null}}async function we(e,t){let n=`${e}.tmp-${process.pid}`;try{return await G.writeFile(n,t),await G.rename(n,e),!0}catch{try{await G.rm(n,{force:!0})}catch{}return!1}}async function lt(e,t){if(!t||typeof t!="object")return!1;let n=await De(e);if(!n)return!1;let r={id:t.id??e.agent??"",workspace:t.workspace_id??e.workspace??"",name:t.name??e.name??"",handle:t.handle??e.handle??"",model:t.model??e.model??"",permissionMode:t.permissionMode??t.permission_mode??e.permissionMode??"",description:t.description??"",instructions:t.instructions??"",systemPrompt:t.system_prompt??t.systemPrompt??"",tools:Array.isArray(t.tools)?t.tools:[],skills:Array.isArray(t.skills)?t.skills:[],memoryDir:t.memory_dir??t.memoryDir??"",version:Number(t.version||0),updatedAt:new Date().toISOString()},o=await we(H.join(n,Zo),`${JSON.stringify(r,null,2)}
|
|
3
|
+
`),s=String(t.soul??""),i=await we(H.join(n,es),s);return o&&i}async function Fn(e,t={}){let n=await De(e);return n?we(H.join(n,Pn),Hn(e,t)):!1}function Gn(e,t={}){let n=K(e);try{return Dn.mkdirSync(n,{recursive:!0}),Dn.writeFileSync(H.join(n,Pn),Hn(e,t)),!0}catch{return!1}}function Hn(e,t){let n=Date.now(),r={ts:n,iso:new Date(n).toISOString(),status:t.status||(t.busy?"busy":"online"),busy:!!t.busy,active:Number(t.active||0),queueSize:Number(t.queueSize||0),connected:!!t.connected,model:e.model||"",permissionMode:e.permissionMode||"",handle:e.handle||"",agent:e.agent||"",workspace:e.workspace||"",pid:process.pid,heartbeatMs:e.heartbeatMs,...t.agentStatus?{agentStatus:t.agentStatus}:{},...t.agentNote?{agentNote:t.agentNote}:{}};return`${JSON.stringify(r,null,2)}
|
|
4
|
+
`}async function ut(e){let t=H.join(K(e),Bn),n;try{let a=await G.stat(t);if(!a.isFile()||a.size>as)return null;n=await G.readFile(t,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let o=at(r.status),s=at(r.note??r.message);if(!o&&!s)return null;let i={};return o&&(i.status=o),s&&(i.note=s),r.ts!=null&&Number.isFinite(Number(r.ts))&&(i.ts=Number(r.ts)),i}function at(e){return e==null?"":String(e).trim().replace(/\s+/g," ").slice(0,cs)}function dt(e){return H.join(K(e),Qo)}async function qn(e){let t=dt(e),n;try{let i=await G.stat(t);if(!i.isFile()||i.size>ls)return null;n=await G.readFile(t,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let o={};for(let i of us){let a=i==="description"&&r.description==null?r.profile:r[i];typeof a!="string"||!a.trim()||(o[i]=a.trim())}let s=ms(r.voice,r.attitude);return s&&(o.voice=s),Object.keys(o).length>0?o:null}function ms(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r={};for(let o of ds){let s=n[o];typeof s=="string"&&s.trim()?r[o]=s.trim():o==="speed"&&typeof s=="number"&&Number.isFinite(s)&&(r.speed=s)}return!r.emotion&&!r.attitude&&typeof t=="string"&&t.trim()&&(r.attitude=t.trim()),Object.keys(r).length>0?r:null}function Jn(e){return H.join(K(e),ts)}function fs(e){return H.join(K(e),Ln)}async function Kn(e){let t=Jn(e),n;try{let a=await G.stat(t);if(!a.isFile()||a.size>ns)return null;n=await G.readFile(t,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let o=String(r.targetVersion||"").trim();if(!os.test(o))return null;let s={targetVersion:o},i=at(r.note);return i&&(s.note=i),typeof r.requestedAt=="string"&&(s.requestedAt=r.requestedAt),s}async function zn(e){try{return await G.rm(Jn(e),{force:!0}),!0}catch{return!1}}async function Re(e){let t=fs(e),n;try{let r=await G.stat(t);if(!r.isFile()||r.size>rs)return null;n=await G.readFile(t,"utf8")}catch{return null}try{let r=JSON.parse(n);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}async function ae(e,t={}){let n=await De(e);if(!n)return!1;let r={...t,updatedAt:new Date().toISOString()};return we(H.join(n,Ln),`${JSON.stringify(r,null,2)}
|
|
5
|
+
`)}async function Wn(e){let t=await De(e);if(!t)return!1;let n=H.join(t,ct);try{return await G.access(n),!0}catch{}return we(n,is)}async function Yn(e){let t=H.join(K(e),ct);try{let n=await G.stat(t);return!n.isFile()||n.size>ss?null:(await G.readFile(t,"utf8")).trim()||null}catch{return null}}var Bn,Qo,Pn,ct,Zo,es,ts,Ln,ns,rs,os,ss,is,as,cs,ls,us,ds,Be=xe(()=>{Bn="status.json",Qo="identity.json",Pn="heartbeat.json",ct="heartbeat.md",Zo="agent.json",es="soul.md",ts="update-request.json",Ln="update.json",ns=4*1024,rs=16*1024,os=/^[a-zA-Z0-9._+-]{1,64}$/,ss=16*1024,is=`# Heartbeat
|
|
6
6
|
|
|
7
7
|
This file tells you what to do on each heartbeat \u2014 the recurring "still here, still
|
|
8
8
|
working" moment. Edit it freely; the daemon reads it but never overwrites your edits.
|
|
@@ -15,52 +15,57 @@ On each heartbeat:
|
|
|
15
15
|
- If you've finished and there's nothing to do, a short idle note is fine.
|
|
16
16
|
|
|
17
17
|
Add your own recurring checks below.
|
|
18
|
-
`,
|
|
19
|
-
`),signal:i,installFn:
|
|
20
|
-
`}function
|
|
21
|
-
`}function
|
|
22
|
-
`}function
|
|
23
|
-
`}var
|
|
24
|
-
`):
|
|
25
|
-
`))>=0;){let
|
|
26
|
-
`)})},notify(i,
|
|
27
|
-
`)},respond(i,
|
|
28
|
-
`)},respondError(i,
|
|
29
|
-
`)},onMessage(i){return
|
|
18
|
+
`,as=8*1024,cs=400;ls=16*1024,us=["name","avatar","accent_color","description","soul"],ds=["cartesia_voice_id","voice_id","id","speed","emotion","attitude"]});import{spawn as vi,execFile as Ei}from"node:child_process";import At from"node:fs";import Ie from"node:fs/promises";import ki from"node:os";import ye from"node:path";import{promisify as Ai}from"node:util";function xt({homedir:e=ki.homedir()}={}){return ye.join(e,".agensis","versions")}function Ge(e,t){return ye.join(e,t)}function Ct(e){return ye.join(e,xi)}function ge(e){return ye.join(e,"node_modules",It,"bin","agensis.mjs")}async function _r(e,t){await Ie.mkdir(ye.dirname(e),{recursive:!0}),await Ie.rm(e,{force:!0}),await Ie.symlink(t,e)}async function Tt({root:e,version:t,log:n=()=>{}}){let r=Ge(e,t),o=ge(r);if(At.existsSync(o))return n(`[self-update] ${t} already installed at ${r}`),r;if(await Ie.mkdir(r,{recursive:!0}),n(`[self-update] installing ${It}@${t} into ${r}`),await Ii("npm",["install","--prefix",r,`${It}@${t}`,"--no-audit","--no-fund","--no-save","--omit=dev"]),!At.existsSync(o))throw new Error(`npm install reported success but ${o} is missing`);return r}function Mt({entry:e,profileName:t,extraArgs:n=[],env:r=process.env}){let o=["connect","--profile",t,...n],s=vi(process.execPath,[e,...o],{detached:!0,stdio:"inherit",env:r});return s.unref(),s}async function Nt(e,{graceMs:t=5e3}={}){return!e||e.exitCode!==null||e.killed||await new Promise(n=>{let r=!1,o=()=>{r||(r=!0,clearTimeout(s),n())},s=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},t);s.unref?.(),e.once("exit",o);try{e.kill("SIGTERM")}catch{o()}}),!0}async function Ot({config:e,pid:t,timeoutMs:n=vr}){let r=ye.join(K(e),"heartbeat.json"),o=Date.now()+n;for(;Date.now()<o;){try{let s=await Ie.readFile(r,"utf8"),i=JSON.parse(s);if(Number.isFinite(i.ts)&&Date.now()-i.ts<=Ti&&i.connected&&(t==null||i.pid===t))return!0}catch{}await new Promise(s=>setTimeout(s,Ci))}return!1}async function Er({config:e,targetVersion:t,currentVersion:n,root:r=xt({}),profileName:o="default",runningChild:s=null,installFn:i=Tt,spawnFn:a=Mt,stopFn:d=Nt,healthCheckFn:c=Ot,healthTimeoutMs:l=vr,log:g=()=>{}}={}){let m=await Re(e)||{},y=n||m.currentVersion||null,S=Ct(r),f={version:t,startedAt:new Date().toISOString()};if(t===y){let u={currentVersion:y,previousVersion:m.previousVersion||null,lastAttempt:{...f,result:"noop_already_current"}};return await ae(e,u),{...u,child:s}}let b;try{b=await i({root:r,version:t,log:g})}catch(u){let h={currentVersion:y,previousVersion:m.previousVersion||null,lastAttempt:{...f,result:"install_failed",error:String(u?.message||u)}};return await ae(e,h),{...h,child:s}}s&&await d(s),await _r(S,b);let w=ge(b),E=a({entry:w,profileName:o});if(await c({config:e,pid:E.pid,timeoutMs:l})){let u={currentVersion:t,previousVersion:y,lastAttempt:{...f,result:"ok"}};return await ae(e,u),{...u,child:E}}g(`[self-update] ${t} failed its health check within ${l}ms \u2014 rolling back to ${y||"(no known previous version)"}`),await d(E);let A=!1,N=null;if(y){let u=Ge(r,y);At.existsSync(ge(u))&&(await _r(S,u),N=a({entry:ge(u),profileName:o}),A=!0)}let O={currentVersion:A?y:m.currentVersion||y,previousVersion:y,lastAttempt:{...f,result:A?"rolled_back":"failed_no_fallback"}};return await ae(e,O),{...O,child:N}}var Ii,It,xi,vr,Ci,Ti,kr=xe(()=>{Be();Ii=Ai(Ei),It="@agensis/agensis-agent",xi="current",vr=3e4,Ci=1e3,Ti=1e4});var Ir={};Dt(Ir,{runSupervisor:()=>Di});import Mi from"node:fs";import $t from"node:fs/promises";import Ni from"node:path";async function $i({root:e,runningVersion:t,installFn:n,log:r}){let o=Ct(e);if(Mi.existsSync(o))return;r(`[supervise] no current version linked yet \u2014 adopting the running version ${t}`);let s=await n({root:e,version:t,log:r});await $t.mkdir(Ni.dirname(o),{recursive:!0}),await $t.rm(o,{force:!0}),await $t.symlink(s,o)}async function Di({config:e,runningVersion:t,profileName:n="default",pollIntervalMs:r=Oi,root:o=xt({}),log:s=m=>process.stdout.write(`${m}
|
|
19
|
+
`),signal:i,installFn:a=Tt,spawnFn:d=Mt,stopFn:c=Nt,healthCheckFn:l=Ot,maxIterations:g=1/0}={}){if(!e?.workspace||!e?.agent)throw new Error("supervise requires a resolved profile with workspace + agent (run `agensis setup`/`agensis connect` first).");await $i({root:o,runningVersion:t,installFn:a,log:s});let m=await Re(e);m?.currentVersion||(m={currentVersion:t,previousVersion:null,lastAttempt:null},await ae(e,m));let y=null,S=!1,f=0,b=()=>{let v=Ge(o,m.currentVersion);return y=d({entry:ge(v),profileName:n}),y.on?.("exit",(A,N)=>{if(S)return;s(`[supervise] daemon (version ${m.currentVersion}) exited (code=${A} signal=${N}); respawning`);let O=Ar[Math.min(f,Ar.length-1)];f+=1,setTimeout(()=>{S||b()},O).unref?.()}),y.on?.("spawn",()=>{f=0}),y};b();let w=async()=>{S=!0,y&&await c(y)};i?.addEventListener("abort",()=>{w()}),process.once("SIGTERM",()=>{w().then(()=>process.exit(0))}),process.once("SIGINT",()=>{w().then(()=>process.exit(0))});let E=0;for(;!S&&!i?.aborted&&E<g&&(E+=1,await new Promise(N=>setTimeout(N,r)),!(S||i?.aborted));){let v=await Kn(e);if(!v||v.targetVersion===m.currentVersion)continue;s(`[supervise] update requested: ${m.currentVersion} -> ${v.targetVersion}${v.note?` (${v.note})`:""}`);let A=await Er({config:e,targetVersion:v.targetVersion,currentVersion:m.currentVersion,root:o,profileName:n,runningChild:y,installFn:a,spawnFn:d,stopFn:c,healthCheckFn:l,log:s});await zn(e),m=A,y=A.child||y,f=0,s(`[supervise] update attempt "${v.targetVersion}" -> ${A.lastAttempt?.result} (running ${A.currentVersion})`)}return{state:m,child:y}}var Oi,Ar,xr=xe(()=>{kr();Be();Oi=5e3,Ar=[1e3,5e3,15e3,3e4]});import Z from"node:process";import ve from"node:fs";import le from"node:path";import Ee from"node:os";import ps from"node:crypto";import C from"node:process";import _e from"ws";import{spawn as Tr}from"node:child_process";function Rt(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}var Mr=50*1024*1024;function V(e){let{cmd:t,args:n=[],env:r={},cwd:o,timeoutMs:s=0,label:i="working",heartbeatMs:a=15e3,input:d="",now:c=Date.now,log:l=console,signal:g,onData:m}=e||{};return new Promise(y=>{if(g?.aborted){y({status:null,stdout:"",stderr:"",aborted:!0,error:new Error("cancelled")});return}let S;try{let I=n.some(q=>q==="--dangerously-skip-permissions"),k=typeof process.getuid=="function"&&process.getuid()===0,$={...process.env,...r};delete $.AGENSIS_TOKEN,delete $.ANTHROPIC_API_KEY,delete $.ANTHROPIC_AUTH_TOKEN,I&&k&&($.IS_SANDBOX="1"),S=Tr(t,n,{cwd:o,detached:!0,env:$})}catch(I){y({status:null,stdout:"",stderr:"",error:I});return}d?S.stdin?.end(String(d)):S.stdin?.end();let f="",b="";S.stdout?.setEncoding("utf8"),S.stderr?.setEncoding("utf8");let w=(I,k)=>I.length>=Mr?I:I+k;S.stdout?.on("data",I=>{if(f=w(f,I),m)try{m(I)}catch{}}),S.stderr?.on("data",I=>b=w(b,I));let E=c(),v=a>0?setInterval(()=>{l.log(` \u2026 still ${i} (${Rt(c()-E)}) \u2014 Ctrl+C to cancel`)},a):null;v?.unref&&v.unref();let A=I=>{if(S.pid!=null)try{process.kill(-S.pid,I)}catch{try{S.kill(I)}catch{}}},N=!1,O=s>0?setTimeout(()=>{N=!0,A("SIGKILL")},s):null;O?.unref&&O.unref();let u=!1,h=null,M=()=>{u=!0,A("SIGTERM"),h=setTimeout(()=>A("SIGKILL"),3e3),h?.unref&&h.unref()};g&&g.addEventListener("abort",M,{once:!0});let p=(I,k)=>{v&&clearInterval(v),O&&clearTimeout(O),h&&clearTimeout(h),g&&g.removeEventListener("abort",M),y({status:I,stdout:f,stderr:b,aborted:u,error:k||(u?new Error("cancelled"):N?new Error(`timed out after ${Rt(s)}`):null)})};S.on("error",I=>p(null,I)),S.on("close",I=>p(I,null))})}import{spawn as Dr}from"node:child_process";import Nr from"node:crypto";var Or=Number(process.env.AGENSIS_PERMISSION_TIMEOUT_MS||10*60*1e3),Bt=["once","session","always"];function Pt(e){let t=String(e?.toolName??"").trim();if(!t)return"";let n=String(e?.ruleContent??"").trim();return n?`${t}(${n})`:t}function Lt(e){let t=[];for(let n of Array.isArray(e)?e:[])if(!(!n||n.type!=="addRules"||n.behavior!=="allow"))for(let r of Array.isArray(n.rules)?n.rules:[]){let o=Pt(r);o&&!t.includes(o)&&t.push(o)}return t}function $r(e){let t=Array.isArray(e)?e:Array.isArray(e?.allow)?e.allow:[],n=[];for(let r of t){let o=typeof r=="string"?r.trim():Pt(r);o&&!n.includes(o)&&n.push(o)}return n}function Ut(e){return $r(e?.agent?.metadata?.permission_rules??e?.agent?.permissionRules??e?.permissionRules??e?.permission_rules)}function jt(e,{toolName:t,suggestions:n}={}){let r=Array.isArray(e)?e:[];if(r.length===0)return!1;let o=String(t||"").trim();return o&&r.includes(o)?!0:Lt(n).some(s=>r.includes(s))}function de(e){return{behavior:"deny",message:e}}function Ft({send:e,timeoutMs:t=Or,log:n=()=>{},idFactory:r=()=>Nr.randomUUID()}={}){if(typeof e!="function")throw new Error("createPermissionBroker requires send()");let o=new Map,s=(i,a)=>{let d=o.get(i);return d?(o.delete(i),clearTimeout(d.timer),d.resolve(a),!0):!1};return{request({jobId:i,toolName:a,title:d,description:c,detail:l,input:g,suggestions:m,signal:y}={}){let S=r(),f=Lt(m);return e({action:"agent_permission_request",jobId:i||"",requestId:S,toolName:String(a||"").trim(),title:String(d||"").trim(),description:String(c||"").trim(),detail:String(l||"").trim(),input:g||null,rules:f,scopes:f.length>0?Bt:["once","session"],expiresInMs:t})?(n(`permission requested for ${a||"a tool"} (${S})`),new Promise(w=>{let E=setTimeout(()=>{s(S,de(`Nobody approved this within ${Math.round(t/6e4)} minutes. Ask again in the chat, or have the workspace grant it on the agent.`))},t);E.unref?.();let v={jobId:i||"",timer:E,resolve:w};o.set(S,v),y?.addEventListener?.("abort",()=>{s(S,de("The job was cancelled before this was approved."))},{once:!0})})):Promise.resolve(de("Agensis was unreachable, so this tool call could not be approved."))},decide(i){let a=String(i?.requestId||"");if(!a||!o.has(a))return!1;let d=i.behavior==="allow",c=Bt.includes(i.scope)?i.scope:"once",l=String(i.decidedBy||"").trim();return n(`permission ${d?`allowed (${c})`:"denied"} for ${a}${l?` by ${l}`:""}`),s(a,d?{behavior:"allow",scope:c,decidedBy:l}:de(String(i.message||"").trim()||`${l||"The workspace"} denied this tool call.`))},cancelJob(i,a="The job ended before this was approved."){let d=String(i||""),c=0;for(let[l,g]of[...o.entries()])g.jobId===d&&s(l,de(a))&&(c+=1);return c},shutdown(i="The agent daemon disconnected before this was approved."){let a=0;for(let d of[...o.keys()])s(d,de(i))&&(a+=1);return a},pendingCount(){return o.size}}}var qt=10*60*1e3;function Jt(e={}){let t={...process.env,...e};return delete t.AGENSIS_TOKEN,delete t.ANTHROPIC_API_KEY,delete t.ANTHROPIC_AUTH_TOKEN,t}var Ke=class{#e=[];#t=[];#n=!1;push(t){if(this.#n)return;let n=this.#t.shift();n?n({value:t,done:!1}):this.#e.push(t)}close(){this.#n=!0;for(let t of this.#t.splice(0))t({value:void 0,done:!0})}[Symbol.asyncIterator](){return{next:()=>this.#e.length?Promise.resolve({value:this.#e.shift(),done:!1}):this.#n?Promise.resolve({value:void 0,done:!0}):new Promise(t=>this.#t.push(t))}}};function Kt(){let e=new Map;return(t,n)=>{let r=(e.get(t)||Promise.resolve()).then(n,n);return e.set(t,r.catch(()=>{})),r}}var Rr=["mcp__agensis"],Br=["Grep","Glob"];function Pr(e){return e==="yolo"?{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0}:e==="accept_edits"?{permissionMode:"acceptEdits"}:{permissionMode:"default"}}function Lr(e){if(!e||e.type!=="content_block_delta")return"";let t=e.delta;return t&&t.type==="text_delta"&&typeof t.text=="string"?t.text:""}function Ur(e){return`${JSON.stringify({type:"stream_event",event:{type:"content_block_delta",delta:{type:"text_delta",text:e}}})}
|
|
20
|
+
`}function jr(e){return`${JSON.stringify({type:"result",result:e})}
|
|
21
|
+
`}function Fr(e){return`${JSON.stringify({type:"agensis_step",step:e})}
|
|
22
|
+
`}function Gr(e){return`${JSON.stringify({type:"agensis_segment",segment:e})}
|
|
23
|
+
`}var Hr=["file_path","path","pattern","command","description","prompt"],Gt=120;function Ce(e){if(!e||typeof e!="object")return"";for(let t of Hr){let n=e[t];if(typeof n!="string")continue;let r=n.replace(/\s+/g," ").trim();if(r)return r.length>Gt?`${r.slice(0,Gt)}\u2026`:r}return""}function zt(e){return JSON.stringify({cwd:e.cwd||"",model:e.model||"",permissionMode:e.permissionMode||"default",hostFolders:[...e.hostFolders||[]].sort(),leanCli:!!e.leanCli,mcpUrl:e.mcp?.url||"",mcpToken:e.mcp?.env?.AGENSIS_MCP_TOKEN||"",canAsk:!!e.requestPermission})}function qr(e,t){return async(n,r,o={})=>{let s=e.activeTurn;if(!s)return{behavior:"deny",message:"This tool call arrived with no active job to ask about."};let i=s.requestPermission||t;if(!i)return{behavior:"deny",message:"This agent has no way to ask for approval right now."};if(jt(s.permissionRules,{toolName:n,suggestions:o.suggestions}))return{behavior:"allow"};let a=await i({jobId:s.jobId,toolName:n,title:o.title,description:o.description,detail:Ce(r),input:r,suggestions:o.suggestions,signal:o.signal});if(a?.behavior!=="allow")return{behavior:"deny",message:a?.message||"This tool call was not approved."};let d=a.scope==="once"?void 0:o.suggestions;return d?.length?{behavior:"allow",updatedPermissions:d}:{behavior:"allow"}}}function Wt({queryFn:e,idleCloseMs:t=qt,requestPermission:n}={}){let r=new Map,o=Kt(),s=(c,l,g)=>{let m=r.get(c);if(!(!m||l&&m!==l))if(r.delete(c),clearTimeout(m.idleTimer),m.closed=!0,m.queue.close(),g&&m.activeTurn&&m.activeTurn.finish(g),typeof m.query.close=="function")try{m.query.close()}catch{}else Promise.resolve(m.query.return?.()).catch(()=>{})},i=c=>{let l=r.get(c);l&&(clearTimeout(l.idleTimer),l.idleTimer=setTimeout(()=>s(c),t),l.idleTimer.unref?.())},a=async(c,l)=>{let g=r.get(c),m=zt(l);if(g&&g.fingerprint===m&&!g.closed)return g;g&&s(c,g),e||(e=(await import("@anthropic-ai/claude-agent-sdk")).query);let y=new Ke,S=Pr(l.permissionMode),f={query:null,queue:y,sessionId:"",idleTimer:null,activeTurn:null,closed:!1,terminalError:null,fingerprint:m},b=l.leanCli&&l.mcp?{agensis:{type:"http",url:l.mcp.url,headers:{Authorization:"Bearer ${AGENSIS_MCP_TOKEN}"}}}:void 0,w=e({prompt:y,options:{cwd:l.cwd,model:l.model,...S,allowedTools:[...Rr,...Br],canUseTool:n||l.requestPermission?qr(f,n):void 0,additionalDirectories:l.hostFolders&&l.hostFolders.length?l.hostFolders:void 0,mcpServers:b,strictMcpConfig:l.leanCli?!0:void 0,settingSources:l.leanCli?[]:void 0,persistSession:l.leanCli?!1:void 0,includePartialMessages:!0,env:Jt(l.mcp?.env)}});return f.query=w,r.set(c,f),f.pump=(async()=>{let E=null;try{for await(let v of w){v.session_id&&(f.sessionId=v.session_id);let A=f.activeTurn;if(A){if(v.type==="stream_event"){let N=Lr(v.event);N&&(A.streamed+=N,A.onData?.(Ur(N)))}else if(v.type==="result")if(v.subtype==="success"){let N=v.result==null?A.text:String(v.result);A.onData?.(jr(N)),A.finish({status:0,stdout:N,stderr:"",error:null})}else{let N=Array.isArray(v.errors)?v.errors.filter(Boolean).join(`
|
|
24
|
+
`):v.result,O=new Error(N||`claude-agent-sdk result error: ${v.subtype}`);A.finish({status:1,stdout:A.text,stderr:O.message,error:O})}else if(v.type==="assistant"){let N=v.message?.content;if(Array.isArray(N)){let O=N.filter(u=>u&&u.type==="text"&&typeof u.text=="string").map(u=>u.text).join("");O&&(A.onData?.(Gr({text:O})),A.flushed+=A.streamed,A.streamed="");for(let u of N)!u||u.type!=="tool_use"||!u.name||A.onData?.(Fr({kind:"tool",name:String(u.name),detail:Ce(u.input)}))}}}}E=new Error("claude-agent-sdk connection closed")}catch(v){E=v}finally{f.closed=!0,f.terminalError=E,clearTimeout(f.idleTimer),f.queue.close(),r.get(c)===f&&r.delete(c),f.activeTurn&&f.activeTurn.finish({status:null,stdout:f.activeTurn.text,stderr:String(E?.message||E||""),error:E})}})(),f};return{run:c=>o(c.sessionKey||"default",async()=>{let{sessionKey:l="default",prompt:g,signal:m,onData:y,timeoutMs:S=0}=c;if(m?.aborted)return{status:null,stdout:"",stderr:"",aborted:!0,error:new Error("cancelled")};let f;try{f=await a(l,c)}catch(w){return{status:null,stdout:"",stderr:"",error:w}}if(f.closed){let w=f.terminalError||new Error("claude-agent-sdk connection closed");return{status:null,stdout:"",stderr:String(w.message||w),error:w}}clearTimeout(f.idleTimer);let b=await new Promise(w=>{let E=!1,v=null,A={streamed:"",flushed:"",get text(){return this.flushed+this.streamed},onData:y,jobId:c.job?.id||"",permissionRules:Ut(c.job),requestPermission:c.requestPermission||null,finish(O){E||(E=!0,f.activeTurn===A&&(f.activeTurn=null),m&&m.removeEventListener("abort",N),v&&clearTimeout(v),w(O))}},N=()=>{let O={status:null,stdout:A.text,stderr:"",aborted:!0,error:new Error("cancelled")};Promise.resolve(f.query.interrupt?.()).catch(()=>{}),s(l,f,O)};f.activeTurn=A,m&&m.addEventListener("abort",N,{once:!0}),S>0&&(v=setTimeout(()=>{let O=new Error(`timed out after ${S}ms`);Promise.resolve(f.query.interrupt?.()).catch(()=>{}),s(l,f,{status:null,stdout:A.text,stderr:O.message,error:O})},S),v.unref?.()),f.queue.push({type:"user",message:{role:"user",content:g},parent_tool_use_id:null,session_id:f.sessionId})});return r.get(l)===f&&i(l),b}),shutdown:()=>{for(let c of[...r.keys()])s(c)}}}function Jr(e){let t=1,n="",r=new Map,o=new Set;e.stdout.setEncoding("utf8"),e.stdout.on("data",i=>{n+=i;let a;for(;(a=n.indexOf(`
|
|
25
|
+
`))>=0;){let d=n.slice(0,a);if(n=n.slice(a+1),!d.trim())continue;let c;try{c=JSON.parse(d)}catch{continue}if(c.id!==void 0&&r.has(c.id)){let{resolve:l,reject:g}=r.get(c.id);r.delete(c.id),c.error?g(new Error(c.error.message||"codex app-server error")):l(c.result)}else if(c.method)for(let l of o)l(c.method,c.params,c.id)}});let s=i=>{for(let{reject:a}of r.values())a(i);r.clear()};return e.on("exit",()=>s(new Error("codex app-server exited"))),e.on("error",i=>s(i)),{request(i,a){let d=t++;return new Promise((c,l)=>{r.set(d,{resolve:c,reject:l}),e.stdin.write(`${JSON.stringify({id:d,method:i,params:a})}
|
|
26
|
+
`)})},notify(i,a){e.stdin.write(`${JSON.stringify({method:i,params:a})}
|
|
27
|
+
`)},respond(i,a){e.stdin.write(`${JSON.stringify({id:i,result:a})}
|
|
28
|
+
`)},respondError(i,a){e.stdin.write(`${JSON.stringify({id:i,error:{code:-32601,message:a}})}
|
|
29
|
+
`)},onMessage(i){return o.add(i),()=>o.delete(i)}}}function Kr(e){return e==="yolo"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{}}function zr(e,t,n){let r=Array.isArray(e)?e.map(String):[];if(r.length){let o=t.find(s=>r.includes(s));if(o)return o}return n}var qe={preferences:["decline"],fallback:"decline"},Wr={preferences:["accept","acceptForSession"],fallback:"acceptForSession"},Ht={preferences:["acceptForSession","accept"],fallback:"acceptForSession"};function Je(e,t){return zr(e,t.preferences,t.fallback)}function Yr(e,t){let n=t?.command,r=Array.isArray(n)?n.join(" "):String(n||"");if(r.trim())return r.replace(/\s+/g," ").trim().slice(0,200);let o=t?.fileChanges||t?.changes,s=o&&typeof o=="object"?Object.keys(o):[];return s.length?s.slice(0,4).join(", "):e==="item/fileChange/requestApproval"?"apply a file change":"run a command"}function Yt({spawnFn:e=Dr,idleCloseMs:t=qt,requestPermission:n}={}){let r=new Map,o=Kt(),s=c=>{let l=r.get(c);if(l){r.delete(c),clearTimeout(l.idleTimer);try{l.child.kill("SIGTERM")}catch{}}},i=c=>{let l=r.get(c);l&&(clearTimeout(l.idleTimer),l.idleTimer=setTimeout(()=>s(c),t),l.idleTimer.unref?.())},a=async(c,l)=>{let g=r.get(c),m=zt(l);if(g&&g.fingerprint===m)return g;g&&s(c);let y=e("codex",["app-server"],{cwd:l.cwd,env:Jt(l.mcp?.env),stdio:["pipe","pipe","pipe"]}),S=Jr(y);await S.request("initialize",{clientInfo:{name:"agensis-agent",version:l.clientVersion||"unknown"}}),S.notify("initialized");let f=l.leanCli&&l.mcp?{mcp_servers:{agensis:{url:l.mcp.url,bearer_token_env_var:"AGENSIS_MCP_TOKEN"}}}:void 0,b=await S.request("thread/start",{cwd:l.cwd,ephemeral:l.leanCli||void 0,model:l.model,config:f,...Kr(l.permissionMode)}),w={child:y,rpc:S,threadId:b.thread.id,fingerprint:m,idleTimer:null};return r.set(c,w),w};return{run:c=>o(c.sessionKey||"default",async()=>{let{sessionKey:l="default",prompt:g,signal:m,onData:y,timeoutMs:S=0}=c;if(m?.aborted)return{status:null,stdout:"",stderr:"",aborted:!0,error:new Error("cancelled")};let f;try{f=await a(l,c)}catch(N){return{status:null,stdout:"",stderr:"",error:N}}let b="",w="",E=null,v=!1,A=await new Promise(N=>{let O=!1,u=k=>{O||(O=!0,I(),N(k))},h=f.rpc.onMessage((k,$,q)=>{if(q!==void 0){let T=k==="item/commandExecution/requestApproval",R=k==="item/fileChange/requestApproval";if(!T&&!R){f.rpc.respondError(q,`Agensis daemon cannot handle Codex request ${k}`);return}let _=c.permissionMode==="yolo"||R&&c.permissionMode==="accept_edits",x=c.requestPermission||n;if(_||!x){let B=Je($?.availableDecisions,_?Ht:qe);f.rpc.respond(q,{decision:B});return}Promise.resolve(x({jobId:c.job?.id||"",toolName:T?"Codex command":"Codex file change",detail:Yr(k,$),description:String($?.reason||"").trim(),input:$||null})).then(B=>{let j=B?.behavior!=="allow"?qe:B.scope==="once"?Wr:Ht;f.rpc.respond(q,{decision:Je($?.availableDecisions,j)})}).catch(()=>{f.rpc.respond(q,{decision:Je($?.availableDecisions,qe)})});return}if(!(!$||$.threadId!==f.threadId)){if(k==="turn/started"){E=$.turn?.id??E;return}if(!(E&&$.turnId&&$.turnId!==E)){if(k==="item/agentMessage/delta")b+=$.delta||"",y?.($.delta||"");else if(k==="item/completed"&&$.item?.type==="agentMessage")w=$.item.text||w;else if(k==="turn/completed"){let T=$.turn?.status==="failed"||$.turn?.error;u({status:T?1:0,stdout:w||b,stderr:T?String($.turn?.error?.message||$.turn?.error||""):"",error:T?new Error(String($.turn?.error?.message||$.turn?.error||"codex turn failed")):null})}}}}),M=()=>{v=!0,f.rpc.request("turn/interrupt",{threadId:f.threadId}).catch(()=>{});let k={status:null,stdout:b,stderr:"",aborted:!0,error:new Error("cancelled")};u(k),s(l)};m&&m.addEventListener("abort",M,{once:!0});let p=S>0?setTimeout(()=>{let k=new Error(`timed out after ${S}ms`);f.rpc.request("turn/interrupt",{threadId:f.threadId}).catch(()=>{}),u({status:null,stdout:b,stderr:k.message,error:k}),s(l)},S):null;p?.unref?.();function I(){h(),m&&m.removeEventListener("abort",M),p&&clearTimeout(p)}f.rpc.request("turn/start",{threadId:f.threadId,input:[{type:"text",text:g}]}).then(k=>{E=k?.turn?.id||E}).catch(k=>u({status:null,stdout:"",stderr:"",error:k}))});return v||i(l),A}),shutdown:()=>{for(let c of[...r.keys()])s(c)}}}function Zt({run:e=V}={}){return{run:t=>e(t)}}var Qr=null,Zr=null,Qt=new Set;function eo(e){let t=String(e&&e.message||e||"");return/Cannot find module|ERR_MODULE_NOT_FOUND|ENOENT|command not found/i.test(t)}function to(e,{local:t,pooled:n,log:r=console}={}){let o=t||Zt(),s=n||(e==="claude"?Qr||=Wt():e==="codex"?Zr||=Yt():null);return s?{async run(i){if(Qt.has(e))return o.run(i);let a=await s.run(i);return a.error&&eo(a.error)?(Qt.add(e),r.log?.(`[executor] ${e} fast connection unavailable (${a.error.message}); falling back to subprocess mode for this and future jobs.`),o.run(i)):a}}:o}function no(e){return{async run({cmd:t,args:n=[],env:r={},onData:o,signal:s,job:i}){let a=null;try{a=await e.ensureEnv({job:i,signal:s}),await e.putRepo(a,{job:i,signal:s});let d=await e.exec(a,{cmd:t,args:n,env:r,onData:o,signal:s}),c=await e.getResult(a,{job:i}).catch(()=>({})),l=c&&c.patch?String(c.patch).trim():"",g=l?`${d.stdout||""}
|
|
30
30
|
|
|
31
31
|
\`\`\`diff
|
|
32
|
-
${
|
|
33
|
-
\`\`\``:
|
|
32
|
+
${l}
|
|
33
|
+
\`\`\``:d.stdout||"";return{status:d.status,stdout:g,stderr:d.stderr||"",error:d.error||null}}catch(d){return{status:null,stdout:"",stderr:"",error:d}}finally{if(a)try{await e.destroy(a)}catch{}}}}}function en(e,{makeProvider:t,family:n}={}){return(e&&e.agent&&e.agent.run_mode)==="sandbox"?no((t||ro)(e)):n==="claude"||n==="codex"?to(n):Zt()}function ro(e){let t=e.agent&&e.agent.sandbox_provider||"e2b",n=e.agent&&e.agent.sandbox_config||{};if(t!=="e2b")throw new Error(`Sandbox provider "${t}" is not available yet (only e2b is wired).`);return so({apiKey:process.env.E2B_API_KEY,anthropicApiKey:process.env.ANTHROPIC_API_KEY,gitToken:process.env.GIT_TOKEN||"",repoUrl:e.repoUrl||e.agent&&e.agent.repo_url||n.repoUrl||"",template:n.template||""})}function oo(e=process.versions.node){let[t,n,r]=String(e).split(".").map(o=>Number(o)||0);return t===21?!1:t>=22?!0:t!==20?!1:n>18?!0:n<18?!1:r>=1}function so(e){let t=null,n=async()=>{if(!t){if(!oo())throw new Error(`Sandbox execution requires Node >=20.18.1 (you have ${process.versions.node}). Upgrade Node to use Sandbox agents; Built-in and Remote daemon modes still work on Node 18.`);t=(await Promise.resolve().then(()=>(Xt(),Vt))).createE2bProvider(e)}return t};return{ensureEnv:async r=>(await n()).ensureEnv(r),putRepo:async(r,o)=>(await n()).putRepo(r,o),exec:async(r,o)=>(await n()).exec(r,o),getResult:async(r,o)=>(await n()).getResult(r,o),destroy:async r=>(await n()).destroy(r)}}import tn from"node:fs/promises";import Te from"node:path";var Ye="amp",io=/^T-[A-Za-z0-9-]{20,100}$/,We={amp_not_installed:"Amp CLI is not installed on the connected machine. Install Amp, then reconnect this agent.",amp_version_unsupported:"The installed Amp CLI does not support orb execute streaming. Update Amp, then reconnect this agent.",amp_not_authenticated:"Amp is not signed in on the connected machine. Run `amp login` there, then try again.",amp_auth_expired:"The Amp sign-in on the connected machine has expired. Run `amp login` there, then try again.",amp_project_not_found:"This repository is not an Amp project. Create or join its Amp project, then try again.",amp_project_forbidden:"The connected Amp account cannot access this repository project.",amp_repo_not_allowed:"This repository is not allowed by the connected Agensis daemon profile.",amp_insufficient_credit:"The connected Amp account does not have enough credit to start or continue this orb.",amp_orb_provision_failed:"Amp could not provision the orb for this turn.",amp_setup_failed:"The repository `.agents/setup` script exists but is not executable.",amp_thread_not_found:"The Amp thread linked to this conversation no longer exists. Start a new Agensis conversation to create a new thread.",amp_stream_invalid:"Amp completed without returning a valid thread stream.",amp_cli_crashed:"The Amp CLI stopped unexpectedly on the connected machine.",amp_turn_cancelled:"The Amp turn was cancelled.",amp_turn_timed_out:"The Amp turn timed out on the connected machine."};function X(e,t=""){let n=new Error(We[e]||We.amp_cli_crashed);return n.code=e,t&&(n.detail=String(t).slice(0,1e3)),n}function nn(e){return String(e?.agent?.metadata?.runtime||"").trim().toLowerCase()===Ye}function me(e){let t=String(e||"").trim();return io.test(t)?t:""}function ao(e){let t=me(e);return t?`https://ampcode.com/threads/${t}`:""}function rn({prompt:e,threadId:t="",executable:n="amp"}={}){let r=me(t);return r?{cmd:n,args:["threads","continue",r,"-x",String(e||""),"--stream-json"]}:{cmd:n,args:["-o","-x",String(e||""),"--stream-json","--no-archive-after-execute"]}}function on(){let e="",t="",n=r=>{try{let o=JSON.parse(String(r).trim()),s=me(o?.session_id||o?.sessionId||o?.thread_id||o?.threadId);s&&(t=s)}catch{}};return{feed(r){e+=String(r||"");let o;for(;(o=e.indexOf(`
|
|
34
|
+
`))>=0;)n(e.slice(0,o)),e=e.slice(o+1)},end(){e&&n(e),e=""},get threadId(){return t},get threadUrl(){return ao(t)}}}function Me(e={}){let t=`${e?.error?.message||""}
|
|
35
|
+
${e?.stderr||""}
|
|
36
|
+
${e?.stdout||""}`.trim(),n="amp_cli_crashed";return e?.error?.code==="ENOENT"||/spawn\s+amp\s+ENOENT|command not found/i.test(t)?n="amp_not_installed":e?.aborted===!0||/^cancelled$/i.test(String(e?.error?.message||"").trim())?n="amp_turn_cancelled":/timed out|timeout/i.test(t)?n="amp_turn_timed_out":/(?:auth(?:entication)?|session|token|credential)[^\n]*(?:expired|invalid|revoked)/i.test(t)?n="amp_auth_expired":/not (?:logged|signed) in|not authenticated|please (?:log|sign) ?in|(?:log|sign) ?in (?:to|required)|authentication required|unauthenticated|unauthorized/i.test(t)?n="amp_not_authenticated":/insufficient[^\n]*(?:credit|balance)|(?:credit|balance)[^\n]*(?:exhausted|too low|not enough|run out|out of)|(?:run )?out of[^\n]*(?:credit|balance)|(?:usage|spend)[^\n]*limit[^\n]*(?:exceeded|reached)/i.test(t)?n="amp_insufficient_credit":/thread[^\n]*(?:not found|does not exist|unknown)/i.test(t)?n="amp_thread_not_found":/project[^\n]*(?:forbidden|permission|access denied|not allowed)/i.test(t)?n="amp_project_forbidden":/project[^\n]*(?:not found|does not exist|unmatched)/i.test(t)?n="amp_project_not_found":/\.agents\/setup|setup script/i.test(t)?n="amp_setup_failed":/provision|creating orb|start(?:ing)? orb/i.test(t)&&(n="amp_orb_provision_failed"),{code:n,message:We[n],detail:t.slice(0,1e3)}}async function sn({cwd:e,allowedRoots:t=[]}={}){let n=Te.resolve(String(e||""));if(!t.map(s=>String(s||"").trim()).filter(Boolean).map(s=>Te.resolve(s)).includes(n))throw X("amp_repo_not_allowed");try{await tn.access(Te.join(n,".git"))}catch{throw X("amp_repo_not_allowed","cwd is not a Git repository root")}let o=Te.join(n,".agents","setup");try{let s=await tn.stat(o);if(s.isFile()&&!(s.mode&73))throw X("amp_setup_failed")}catch(s){if(s?.code!=="ENOENT")throw s}return n}function ie(e,t){return{id:Ye,available:!1,version:e,reason:t,project:null}}function co(e){return!e||typeof e!="object"?null:{id:String(e.id||"").slice(0,160),name:String(e.name||e.slug||"").slice(0,200),repository:String(e.repository||e.repo||e.repositoryUrl||"").slice(0,500)}}async function Ve({cwd:e,executable:t="amp",run:n=V,signal:r}={}){let o=(m,y=1e4)=>n({cmd:t,args:m,cwd:e,timeoutMs:y,heartbeatMs:0,label:"checking Amp",signal:r}),s=await o(["version"],5e3);if(s?.status!==0){let m=Me(s);return ie("",m.code)}let i=String(s.stdout||s.stderr||"").trim().split(/\r?\n/).at(-1)?.slice(0,120)||"",a=await o(["--help"],5e3),d=`${a?.stdout||""}
|
|
37
|
+
${a?.stderr||""}`;if(a?.status!==0||!/--stream-json/.test(d)||!/threads[\s\S]*continue/i.test(d)||!/\borb\b/i.test(d))return ie(i,"amp_version_unsupported");let c=await o(["usage"]);if(c?.status!==0){let m=Me(c);return ie(i,m.code)}let l=await o(["projects","status","--json"]);if(l?.status!==0){let m=Me(l);return ie(i,m.code)}let g;try{g=JSON.parse(String(l.stdout||""))}catch{return ie(i,"amp_version_unsupported")}return["forbidden","permission_denied","access_denied"].includes(String(g?.status||"").toLowerCase())?ie(i,"amp_project_forbidden"):g?.status!=="matched"||!g?.project?ie(i,"amp_project_not_found"):{id:Ye,available:!0,version:i,reason:null,project:co(g.project)}}function an(e){let t=Me(e);return X(t.code,t.detail)}function cn(e={}){let{runJob:t}=e,n=Math.max(1,Number(e.concurrency)||1),r=new Map,o=0,s=[];function i(b){let w=r.get(b);return w||(w={queued:[],active:null},r.set(b,w)),w}function a(b){if(b==null)return!1;for(let w of r.values())if(w.active&&!w.active.cancelled&&w.active.job.key===b||w.queued.some(E=>E.key===b))return!0;return!1}function d(){for(let[b,w]of r){if(o>=n)break;if(w.active||w.queued.length===0)continue;let E=w.queued.shift(),v=new AbortController;w.active={job:E,controller:v,cancelled:!1},o+=1,Promise.resolve().then(()=>v.signal.aborted?void 0:t(E,{signal:v.signal})).catch(()=>{}).finally(()=>{w.active=null,o-=1,w.queued.length===0&&!w.active&&r.delete(b),d(),c()})}}function c(){if(o>0)return;for(let w of r.values())if(w.queued.length)return;let b=s;s=[];for(let w of b)w()}function l(b){if(b&&b.key!=null&&a(b.key))return{accepted:!1,deduped:!0,position:0,startedImmediately:!1};let w=b&&b.lane!=null?String(b.lane):"",E=i(w),v=!E.active&&E.queued.length===0&&o<n;E.queued.push(b);let A=E.queued.length+(E.active?1:0);return d(),{accepted:!0,deduped:!1,position:A,startedImmediately:v}}function g(b,w){let E=!1;for(let[v,A]of r)w!=null&&v!==String(w)||A.active&&(A.active.cancelled=!0,A.active.controller.abort(b||"cancelled"),E=!0);return E}function m(b,w){if(b==null)return!1;let E=!1;for(let[v,A]of[...r]){A.active?.job?.key===b&&(A.active.cancelled=!0,A.active.controller.abort(w||"cancelled"),E=!0);let N=A.queued.length;A.queued=A.queued.filter(O=>O.key!==b),A.queued.length!==N&&(E=!0),!A.active&&A.queued.length===0&&r.delete(v)}return c(),E}function y(){let b=0;for(let w of r.values())b+=w.queued.length;return b}function S(){return o}function f(){return o===0&&y()===0?Promise.resolve():new Promise(b=>s.push(b))}return{enqueue:l,cancel:m,cancelActive:g,has:a,size:y,active:S,idle:f}}import pn from"node:crypto";import lo from"node:http";import hn from"node:os";import ee from"node:process";var ln=8787,Xe="claude-haiku-4-5",uo=/^cbk_[a-z0-9_]+_[A-Z2-9]{18}$/,mo=100,fo=new Set(["say","wave","hush","open","choose"]),$e="x-agensis-bridge-secret";function po(){return`cbs_${pn.randomBytes(24).toString("base64url")}`}function ho(e){let t=e?.headers||{},n=String(t[$e]||t[$e.toLowerCase()]||"").trim();if(n)return n;let o=String(t.authorization||t.Authorization||"").trim().match(/^Bearer\s+(.+)$/i);return o?o[1].trim():""}function go(e,t){let n=String(t||""),r=ho(e);if(!n||!r)return!1;let o=Buffer.from(r),s=Buffer.from(n);return o.length!==s.length?!1:pn.timingSafeEqual(o,s)}function yo(e={},t={}){let n=String(t.authSecret||"").trim();if(n)return n;let r=String(e.cursorBuddyBridgeSecret||"").trim();if(r)return r;let o=String(ee.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim();return o||po()}function So(e,t){return e==="OPTIONS"||e==="GET"&&t==="/cursorbuddy/health"}function F(e,t,n){e.writeHead(t,{"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST, OPTIONS","access-control-allow-headers":"content-type, authorization, x-agensis-bridge-secret"}),e.end(JSON.stringify(n))}function un(e){e.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store, no-transform",connection:"keep-alive","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST, OPTIONS","access-control-allow-headers":"content-type, authorization, x-agensis-bridge-secret","x-accel-buffering":"no"})}function z(e,t){e.write(`data: ${typeof t=="string"?t:JSON.stringify(t)}
|
|
34
38
|
|
|
35
|
-
`)}function
|
|
36
|
-
${
|
|
39
|
+
`)}function Se(e){return new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o,r.length>256*1024&&(n(new Error("request body is too large")),e.destroy())}),e.on("error",n),e.on("end",()=>t(r))})}function wo(e){let t=[],n="",r="",o=!1;for(let s of String(e||"")){if(o){n+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(r){s===r?r="":n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n&&(t.push(n),n="");continue}n+=s}if(n&&t.push(n),!t.length)throw new Error("coding command is empty");return{cmd:t[0],args:t.slice(1)}}function bo(e){return/(^|\/)claude(?:$|\.)/.test(String(e||""))}function Ne(e,t){return e.some(n=>n===t||String(n).startsWith(`${t}=`))}function dn(e,t){let n=[];t&&n.push("CursorBuddy local runtime context:",JSON.stringify(t,null,2),"");for(let r of Array.isArray(e)?e:[]){let o=String(r?.role||"user"),s=String(r?.content||"");s.trim()&&n.push(`${o.toUpperCase()}:
|
|
40
|
+
${s}`)}return n.join(`
|
|
37
41
|
|
|
38
|
-
`).trim()||"Say that the local Agensis runtime is connected."}function
|
|
39
|
-
`))>=0;)l(t.slice(0,u)),t=t.slice(u+1)},end(){t&&(l(t),t="")},get live(){return r?n:s},get result(){return o??(r?n:s)}}}function se(e,t,n,r=null){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,delta:n?{content:n}:{},finish_reason:r}]}}function Ee(e){return`http://127.0.0.1:${e}`}function Gr(e={},t={}){return String(t.agensisUrl||t.baseUrl||e.url||X.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function Hr(e){return String(e||"").slice(0,18)}function U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jr(e={},t={},n={}){let r=U(e.metadata)||{},s=U(e.page)||U(r.page)||{},o=U(e.client)||U(r.client)||{},i=U(r.runtime)||{},c=U(e.manifest)||U(r.manifest)||null;return{url:String(e.url||s.url||r.websiteSource||e.websiteSource||"").slice(0,2048),title:String(e.title||s.title||"").slice(0,300),surface:String(e.surface||i.surface||t.surface||"").slice(0,80),instanceId:String(e.instanceId||i.instanceId||"").slice(0,140),workspaceId:String(t.workspaceId||e.workspaceId||n.workspace||"").slice(0,120),agentId:String(t.agentId||e.agentId||n.agent||"").slice(0,120),runtime:{...i,local:!0,connected:!0,connection:t},page:s,client:o,project:U(e.project)||U(r.project)||null,manifest:c,selection:U(e.selection)||null,updatedAt:new Date().toISOString()}}function qr(e,t){return t?.error?.message||t?.message||`CursorBuddy key claim failed with HTTP ${e.status}`}async function Kr(e,t={},n=globalThis.fetch){let r=String(t.key||"").trim();if(!xr.test(r))throw new Error("Connection key format is invalid. Create a fresh CursorBuddy key first.");if(typeof n!="function")throw new Error("This Node.js runtime does not provide fetch; use a current Node.js release.");let s=Gr(e,t),o=await n(`${s}/backend/cursorbuddy/connection-keys/claim`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:r,baseUrl:s,host:Gt.hostname(),cwd:t.cwd||e.cwd||X.cwd(),name:t.name||e.name||e.handle||"CursorBuddy runtime",surface:t.surface||"browser_extension",scope:t.scope||"machine",runtimeKind:t.runtimeKind||"agensis-cli-local-bridge",version:t.version||e.version||X.env.npm_package_version||"",permissionMode:t.permissionMode||e.permissionMode,model:t.model||e.model,metadata:U(t.metadata)||null,websiteSource:t.websiteSource||t.metadata?.websiteSource||"",page:U(t.page)||U(t.metadata?.page)||null,client:U(t.client)||U(t.metadata?.client)||null,manifest:U(t.manifest)||U(t.metadata?.manifest)||null})}),i=await o.json().catch(()=>({}));if(!o.ok)throw new Error(qr(o,i));return{key:r,baseUrl:s,data:i?.data||i}}async function qt(e,t={}){let n=Number(t.port??e.cursorBuddyPort??X.env.AGENSIS_CURSORBUDDY_PORT??Rt),r=$r(e,t),s=new Date().toISOString(),o=[],i=[],c=new Set,l=t.fetchImpl||globalThis.fetch,a=1,u=null,g=n,w=null,f=(d,b={})=>{let M={ts:new Date().toISOString(),event:d,detail:b};return o.push(M),o.length>200&&o.shift(),t.log?.(`CursorBuddy local bridge: ${d}${Object.keys(b).length?` ${JSON.stringify(b)}`:""}`),M},h=()=>({connected:!!e.cursorBuddyRuntime,mode:e.cursorBuddyRuntime?"agensis-cli":"agensis-cli-unclaimed",agentId:e.agent,workspaceId:e.workspace,agensisUrl:e.url,handle:e.handle,name:e.name,cwd:e.cwd,updatedAt:new Date().toISOString()}),v=()=>{if(typeof t.connectionProvider!="function")return null;try{let d=t.connectionProvider();return!d||typeof d!="object"||Array.isArray(d)?null:{...h(),...d,connected:d.connected===!0}}catch{return null}},S=()=>{let d=v();return d?.connected===!1?d:w?{...h(),...d||{},...w,connected:!0,updatedAt:d?.updatedAt||w.updatedAt}:d||h()};function p(d={}){if(!d||typeof d!="object"||Array.isArray(d))return null;let b=String(d.action||d.type||"").trim().toLowerCase();if(!Mr.has(b))return null;let M={id:a++,ts:new Date().toISOString(),action:b,text:String(d.text||d.say||d.message||"").slice(0,1200),label:String(d.label||"").slice(0,80),value:String(d.value||d.prompt||"").slice(0,1200),holdMs:Number.isFinite(d.holdMs)?Math.max(0,Math.min(6e4,d.holdMs)):void 0,source:String(d.source||"agensis-daemon").slice(0,80)};return d.options&&Array.isArray(d.options)&&(M.options=d.options.map(m=>({label:String(m?.label||"").slice(0,80),value:String(m?.value||m?.task||"").slice(0,1200)})).filter(m=>m.label).slice(0,6)),M}function E(d){for(i.push(d);i.length>Cr;)i.shift();f("control",{id:d.id,action:d.action,chars:d.text.length});for(let b of[...c])try{K(b,{type:"command",command:d})}catch{c.delete(b)}return d}function k(d){let b=Ur(d);if(b){let M=p(b.command);return M&&(E(M),f("chat_control",{id:M.id,action:M.action})),{content:b.content,model:"cursorbuddy-local-control",fast:!0}}return null}async function A(d){let b=k(d);if(b)return b;let M=Lt(d?.messages,u),m=Ft(e,M,d?.model),y=await ue({cmd:m.cmd,args:m.args,cwd:e.cwd,timeoutMs:Math.min(Number(e.timeoutMs||18e5),5*60*1e3),heartbeatMs:e.heartbeatMs,label:"cursorbuddy local chat",input:m.stdin});if(y.error||y.status!==0)throw new Error(y.error?.message||String(y.stderr||"").trim()||`Command exited with status ${y.status}`);return{content:Ut(y.stdout||y.stderr),model:m.model}}async function T(d,b){let M=`agensis-cursorbuddy-${Date.now()}`,m=k(d);if(m){let $=m.model||"cursorbuddy-local-control";return K(b,se(M,$,m.content)),K(b,se(M,$,"","stop")),K(b,"[DONE]"),f("chat_fast",{chars:m.content.length,model:$}),{content:m.content,model:$,fast:!0}}let y=Lt(d?.messages,u),I=Ft(e,y,d?.model,{stream:!0}),R="",C=$=>{$&&(R+=$,K(b,se(M,I.model||e.model,$)))},O=I.streamJson?jr(C):null,_=await ue({cmd:I.cmd,args:I.args,cwd:e.cwd,timeoutMs:Math.min(Number(e.timeoutMs||18e5),5*60*1e3),heartbeatMs:e.heartbeatMs,label:"cursorbuddy local chat",input:I.stdin,onData:$=>{if(O)O.feed($);else{let F=String($||"");R+=F,K(b,se(M,I.model||e.model,F))}}});if(O){O.end();let $=O.result||"";!R&&$?C($):R=$||R}if(_.error||_.status!==0){let $=_.error?.message||String(_.stderr||"").trim()||`Command exited with status ${_.status}`;throw new Error($)}let N=O?R:Ut(R||_.stdout||_.stderr);return!O&&N&&N!==R&&(K(b,se(M,I.model||e.model,N)),R=N),K(b,se(M,I.model||e.model,"","stop")),K(b,"[DONE]"),{content:R||N,model:I.model}}let B=Ir.createServer(async(d,b)=>{if(b.setHeader("access-control-allow-origin","*"),b.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),b.setHeader("access-control-allow-headers","content-type, authorization, x-agensis-bridge-secret"),d.method==="OPTIONS"){b.writeHead(204),b.end();return}let M=new URL(d.url||"/",Ee(g||Rt));if(!Dr(d.method,M.pathname)&&!Or(d,r)){j(b,401,{ok:!1,error:"Authentication required",code:"bridge_auth_required"});return}if(d.method==="GET"&&M.pathname==="/cursorbuddy/health"){let m=Ee(g);j(b,200,{ok:!0,runtime:"agensis-cli",backend:e.codingCmd,model:Ue(e),daemonModel:e.model,port:g,host:Gt.hostname(),pid:X.pid,bootedAt:s,authRequired:!0,authHeader:ke,stream:!0,streaming:!0,supportsStreaming:!0,chatStream:!0,capabilities:{chatStream:!0,controlStream:!0,fastAvatarReplies:!1,nativeCursorBuddyControl:!0},latestControlId:i.at(-1)?.id||0,connection:S(),context:u,endpoints:{chat:`${m}/v1/chat/completions`,chatStream:`${m}/v1/chat/completions`,edit:`${m}/cursorbuddy/edit`,context:`${m}/cursorbuddy/context`,control:`${m}/cursorbuddy/control`,controlStream:`${m}/cursorbuddy/control/stream`,logs:`${m}/cursorbuddy/logs`}});return}if(d.method==="GET"&&M.pathname==="/cursorbuddy/logs"){j(b,200,{ok:!0,events:o.slice(-100)});return}if(d.method==="GET"&&M.pathname==="/cursorbuddy/context"){j(b,200,{ok:!0,context:u});return}if(d.method==="GET"&&M.pathname==="/cursorbuddy/control"){let m=Number(M.searchParams.get("after")||0),y=i.filter(I=>I.id>m);j(b,200,{ok:!0,commands:y,latestId:i.at(-1)?.id||0});return}if(d.method==="GET"&&M.pathname==="/cursorbuddy/control/stream"){let m=Number(M.searchParams.get("after")||0);Pt(b),c.add(b),K(b,{type:"ready",latestId:i.at(-1)?.id||0});for(let I of i.filter(R=>R.id>m))K(b,{type:"command",command:I});let y=setInterval(()=>{try{K(b,{type:"ping",ts:new Date().toISOString()})}catch{c.delete(b),clearInterval(y)}},15e3);y.unref&&y.unref(),d.on("close",()=>{c.delete(b),clearInterval(y)});return}if(d.method==="POST"&&M.pathname==="/cursorbuddy/control"){try{let m=JSON.parse(await de(d)||"{}"),y=p(m);if(!y){j(b,400,{ok:!1,error:"unsupported CursorBuddy control command"});return}let I=E(y);j(b,200,{ok:!0,command:I})}catch(m){f("control_error",{error:String(m?.message||m)}),j(b,400,{ok:!1,error:String(m?.message||m)})}return}if(d.method==="POST"&&M.pathname==="/cursorbuddy/context"){try{let m=JSON.parse(await de(d)||"{}");u={url:String(m.url||"").slice(0,2048),title:String(m.title||"").slice(0,300),surface:String(m.surface||"").slice(0,80),instanceId:String(m.instanceId||"").slice(0,140),workspaceId:String(m.workspaceId||e.workspace||"").slice(0,120),agentId:String(m.agentId||e.agent||"").slice(0,120),runtime:m.runtime&&typeof m.runtime=="object"?m.runtime:null,page:m.page&&typeof m.page=="object"?m.page:null,client:m.client&&typeof m.client=="object"?m.client:null,project:m.project&&typeof m.project=="object"?m.project:null,manifest:m.manifest&&typeof m.manifest=="object"?m.manifest:null,selection:m.selection&&typeof m.selection=="object"?m.selection:null,updatedAt:new Date().toISOString()},f("context",{url:u.url,surface:u.surface,instanceId:u.instanceId}),j(b,200,{ok:!0,context:u})}catch(m){f("context_error",{error:String(m?.message||m)}),j(b,400,{ok:!1,error:String(m?.message||m)})}return}if(d.method==="POST"&&M.pathname==="/cursorbuddy/connect"){try{let m=JSON.parse(await de(d)||"{}"),y=await Kr(e,m,l),I=y.data||{};w={connected:!0,mode:"agensis-claimed",keyId:Hr(y.key),agentId:String(I.agentId||I.agent?.id||e.agent||""),workspaceId:String(I.workspaceId||I.workspace_id||I.agent?.workspace_id||e.workspace||""),agensisUrl:y.baseUrl,handle:String(I.handle||I.agent?.handle||e.handle||""),name:String(I.agent?.name||m.name||e.name||"CursorBuddy runtime"),cwd:String(m.cwd||e.cwd||X.cwd()),surface:String(m.surface||"browser_extension"),command:String(I.command||I.localCommand||""),updatedAt:new Date().toISOString()},u=Jr(m,w,e),f("connect",{mode:w.mode,keyId:w.keyId,agentId:w.agentId,workspaceId:w.workspaceId,url:u.url}),j(b,200,{ok:!0,connection:w,claim:I})}catch(m){f("connect_error",{error:String(m?.message||m)}),j(b,400,{ok:!1,error:String(m?.message||m)})}return}if(d.method==="POST"&&M.pathname==="/cursorbuddy/edit"){try{let m=JSON.parse(await de(d)||"{}"),y=[{role:"system",content:"You are the local CursorBuddy edit agent. The user selected a DOM element in their own site. Use the payload to inspect and change the local checkout, then report what changed."},{role:"user",content:JSON.stringify(m,null,2)}];f("edit_request",{selector:m?.target?.selector||""});let I=await A({messages:y,model:m?.model});f("edit_done",{chars:I.content.length}),j(b,200,{ok:!0,backend:e.codingCmd,cwd:e.cwd,content:I.content})}catch(m){f("edit_error",{error:String(m?.message||m)}),j(b,500,{ok:!1,error:String(m?.message||m)})}return}if(d.method==="POST"&&M.pathname.endsWith("/chat/completions")){try{let m=JSON.parse(await de(d)||"{}");if(f("chat_request",{messages:Array.isArray(m.messages)?m.messages.length:0,model:Ht(m.model,Ue(e))}),m.stream===!0){Pt(b);let I=await T(m,b);f("chat_done",{chars:I.content.length,stream:!0,fast:I.fast===!0}),b.end();return}let y=await A(m);f("chat_done",{chars:y.content.length,fast:y.fast===!0}),j(b,200,{id:`agensis-cursorbuddy-${Date.now()}`,object:"chat.completion",model:y.model||m.model||e.model,choices:[{index:0,message:{role:"assistant",content:y.content},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}})}catch(m){f("chat_error",{error:String(m?.message||m)}),j(b,500,{error:{message:String(m?.message||m)}})}return}b.writeHead(404),b.end("CursorBuddy local bridge")});return await new Promise((d,b)=>{B.once("error",b),B.listen(n,"127.0.0.1",()=>{g=B.address().port,B.off("error",b),d()})}),f("listening",{url:`${Ee(g)}/cursorbuddy/health`}),{port:g,url:Ee(g),secret:r,authHeader:ke,close(){return new Promise(d=>B.close(()=>d()))},getContext(){return u}}}import ie from"node:fs/promises";import zr from"node:os";import z from"node:path";var Kt=200,zt=256*1024,Wr=2,Yr=new Set([".md",".markdown",".txt"]);function Vr(e){return String(e||"").replace(/[^a-zA-Z0-9]/g,"-")}function Fe({cwd:e,memoryDir:t,homedir:n=zr.homedir()}={}){let r=String(t||"").trim();if(r)return r.startsWith("~")?z.join(n,r.slice(1)):z.resolve(r);let s=String(e||"").trim();return s?z.join(n,".claude","projects",Vr(s),"memory"):null}async function je(e){if(!e)return null;try{let t=await ie.realpath(e);return(await ie.stat(t)).isDirectory()?t:null}catch{return null}}async function Xr(e,t){if(!e)throw new Error("memory root unavailable");let n=z.isAbsolute(String(t))?String(t):z.join(e,String(t)),r=await ie.realpath(n),s=e.endsWith(z.sep)?e:e+z.sep;if(r!==e&&!r.startsWith(s))throw new Error(`path escapes memory root: ${t}`);return r}function Qr(e){let t=z.basename(e).toLowerCase();return t==="memory.md"?"index":t==="claude.md"?"instructions":"memory"}async function Ge(e,t,n,r){if(n>Wr||r.length>=Kt)return;let s;try{s=await ie.readdir(t,{withFileTypes:!0})}catch{return}for(let o of s){if(r.length>=Kt)break;if(o.name.startsWith("."))continue;let i=z.join(t,o.name);if(o.isDirectory())await Ge(e,i,n+1,r);else if(o.isFile()&&Yr.has(z.extname(o.name).toLowerCase())){let c=z.relative(e,i);r.push({path:c,kind:Qr(c)})}}}async function Zr(e){let t=await je(e);if(!t)return[];let n=[];return await Ge(t,t,0,n),n.sort((r,s)=>r.kind==="index"?-1:s.kind==="index"?1:r.path.localeCompare(s.path)),n}async function eo(e,t){let n=await je(e),r=await Xr(n,t),s=await ie.readFile(r),o=s.length>zt;return{content:s.subarray(0,zt).toString("utf8"),byteSize:s.length,truncated:o}}async function Wt(e){let t=await je(e);if(!t)return"";let n=[];await Ge(t,t,0,n),n.sort((s,o)=>s.path.localeCompare(o.path));let r=[];for(let s of n)try{let o=await ie.stat(z.join(t,s.path));r.push(`${s.path}:${o.size}:${Math.floor(o.mtimeMs)}`)}catch{}return r.join("|")}async function Yt(e){let t=await Zr(e),n=[];for(let r of t)try{let{content:s,byteSize:o}=await eo(e,r.path);n.push({path:r.path,kind:r.kind,content:s,byteSize:o})}catch{}return n}import Je from"node:fs";import Q from"node:path";import Vt from"node:os";function to(e){try{return Je.statSync(e).isDirectory()}catch{return!1}}function no(e){try{return Je.statSync(e).isFile()}catch{return!1}}function He(e){try{return Je.readdirSync(e,{withFileTypes:!0})}catch{return[]}}function Xt({home:e=Vt.homedir(),cwd:t=process.cwd()}={}){let n=[e&&Q.join(e,".claude","commands"),t&&Q.join(t,".claude","commands")].filter(Boolean),r=new Set,s=[],o=(i,c)=>{if(!i)return;let l=c?`${c}:${i}`:i;r.has(l)||(r.add(l),s.push({name:i,parent:c||null}))};for(let i of n)for(let c of He(i)){if(c.name.startsWith("."))continue;if(c.name.endsWith(".md")){o(c.name.slice(0,-3),null);continue}let l=Q.join(i,c.name);if(c.isDirectory()||c.isSymbolicLink()&&to(l))for(let a of He(l))a.name.startsWith(".")||a.name.endsWith(".md")&&o(a.name.slice(0,-3),c.name)}return s}function qe({home:e=Vt.homedir(),cwd:t=process.cwd()}={}){let n=[e&&Q.join(e,".claude","skills"),e&&Q.join(e,".codex","skills"),t&&Q.join(t,".claude","skills")].filter(Boolean),r=new Map,s=(o,i)=>{!o||r.has(o)||r.set(o,{name:o,file:i||""})};for(let o of n)for(let i of He(o)){if(i.name.startsWith("."))continue;let c=Q.join(o,i.name);if(i.name.endsWith(".md"))s(i.name.slice(0,-3),c);else if(i.isDirectory()||i.isSymbolicLink()){let l=Q.join(c,"SKILL.md");s(i.name,no(l)?l:"")}}return[...r.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function Qt(e={}){return qe(e).map(t=>t.name)}import Ke from"node:fs/promises";var ae=64*1024,ro=200,en=4*1024*1024,oo=2e3,so=512;function Zt(e,t,n=ae){let r=`
|
|
42
|
+
`).trim()||"Say that the local Agensis runtime is connected."}function mn(e){let t=String(e||"").trim();if(!t)return"";try{let n=JSON.parse(t);if(typeof n?.result=="string")return n.result;if(typeof n?.message=="string")return n.message;if(typeof n?.content=="string")return n.content}catch{}return t}function _o(e){let t=Array.isArray(e?.messages)?e.messages:[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(String(r?.role||"user")!=="user")continue;let o=String(r?.content||"").trim();if(o)return o}return""}function vo(e,t=280){let n=_o(e).replace(/\s+/g," ").trim();if(!n)return"";if(n.length<=t)return n;let r=[/\b(tell me (?:a )?joke)\b/i,/\b(make (?:him|the buddy|cursorbuddy|avatar) wave|wave(?: hello)?|say hi|say hello)\b/i,/\b(what site|which site|what page|where am i|where are you|current url)\b/i,/\b(are you connected|connected|working|online|there)\b/i,/\b(show|guide|tour|walk|around|sections?|features?|important|highlight|what can i do|what should i do|help me)\b/i,/\b(open|show|bring up|get back|display)\b.{0,80}\b(prompt|bubble|dialog|panel|options|menu)\b/i,/\b(hide|hush|close|dismiss|clear|stop|cancel|be quiet)\b.{0,80}\b(bubble|prompt|dialog|panel|options|menu)?\b/i,/^(hi|hello|hey|yo|sup)\b/i];for(let o of r){let s=n.match(o);if(s?.[0])return s[0].trim()}return n.slice(-t).trim()}function Eo(e){let t=vo(e);if(!t)return null;if(/\b(?:him|the buddy|cursorbuddy|cursor buddy|avatar|buddy|pet|character)\b/i.test(t)&&/\bwave(?: hello)?\b/i.test(t))return{content:"Waving now.",command:{action:"wave",text:"Hi. How can I help?",source:"chat"}};let r=t.match(/^(?:say|speak)\s+(.{1,180})$/i)||t.match(/\b(?:make|tell)\s+(?:him|the buddy|cursorbuddy|avatar)\s+(?:say|speak)\s+(.{1,180})$/i);return r?.[1]?{content:"Saying it now.",command:{action:"say",text:r[1].trim(),source:"chat"}}:/^(stop|cancel|dismiss|close|hide|hush|be quiet)\b/i.test(t)?{content:"Closed.",command:{action:"hush",source:"chat"}}:/\b(open|show)\b.*\b(options|chat|bubble|prompt)\b/i.test(t)?{content:"Opening options.",command:{action:"open",text:"What should I help with?",source:"chat"}}:null}function ko(e){let t=String(e||"").trim();return t?/\s/.test(t)||t.startsWith("-")?!0:/^(claude|codex|node|npm|bun|python|python3|sh|bash|zsh)(?:$|\.)/.test(t):!1}function gn(e,t){let n=String(e||"").trim();return!n||ko(n)?t:n}function yn(e){let t=String(e||"").trim();return!t||t==="haiku-4.5"||t==="claude-haiku-4.5"?Xe:t}function Qe(e={}){return yn(e.cursorBuddyModel||ee.env.AGENSIS_CURSORBUDDY_MODEL||Xe)}function fn(e,t,n,r={}){let{cmd:o,args:s}=wo(e.codingCmd||"claude -p"),i=[...s],a=yn(gn(n,Qe(e))),d="",c=!1;return bo(o)?(a&&!Ne(i,"--model")&&i.push("--model",a),r.stream===!0&&!Ne(i,"--output-format")?(i.push("--output-format","stream-json","--include-partial-messages"),Ne(i,"--verbose")||i.push("--verbose"),c=!0):(Ne(i,"--output-format")||i.push("--output-format","json"),c=i.some(g=>String(g).includes("stream-json"))),d=t):i.push(t),{cmd:o,args:i,model:a,stdin:d,streamJson:c}}function Ao(e=()=>{}){let t="",n="",r=!1,o="",s=null,i=c=>{c&&e(c)},a=c=>{if(!c||typeof c!="object")return;let l=c.event&&c.event.delta||c.delta;if(l&&l.type==="text_delta"&&typeof l.text=="string"){r=!0,n+=l.text,i(l.text);return}if(c.type==="result"&&typeof c.result=="string"){s=c.result;return}if(c.type==="assistant"&&c.message&&Array.isArray(c.message.content)){let g=c.message.content.filter(m=>m&&m.type==="text"&&typeof m.text=="string").map(m=>m.text).join("");g&&(o+=g)}},d=c=>{let l=String(c).trim();if(l)try{a(JSON.parse(l))}catch{}};return{feed(c){t+=String(c||"");let l;for(;(l=t.indexOf(`
|
|
43
|
+
`))>=0;)d(t.slice(0,l)),t=t.slice(l+1)},end(){t&&(d(t),t="")},get live(){return r?n:o},get result(){return s??(r?n:o)}}}function fe(e,t,n,r=null){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,delta:n?{content:n}:{},finish_reason:r}]}}function Oe(e){return`http://127.0.0.1:${e}`}function Io(e={},t={}){return String(t.agensisUrl||t.baseUrl||e.url||ee.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function xo(e){return String(e||"").slice(0,18)}function U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Co(e={},t={},n={}){let r=U(e.metadata)||{},o=U(e.page)||U(r.page)||{},s=U(e.client)||U(r.client)||{},i=U(r.runtime)||{},a=U(e.manifest)||U(r.manifest)||null;return{url:String(e.url||o.url||r.websiteSource||e.websiteSource||"").slice(0,2048),title:String(e.title||o.title||"").slice(0,300),surface:String(e.surface||i.surface||t.surface||"").slice(0,80),instanceId:String(e.instanceId||i.instanceId||"").slice(0,140),workspaceId:String(t.workspaceId||e.workspaceId||n.workspace||"").slice(0,120),agentId:String(t.agentId||e.agentId||n.agent||"").slice(0,120),runtime:{...i,local:!0,connected:!0,connection:t},page:o,client:s,project:U(e.project)||U(r.project)||null,manifest:a,selection:U(e.selection)||null,updatedAt:new Date().toISOString()}}function To(e,t){return t?.error?.message||t?.message||`CursorBuddy key claim failed with HTTP ${e.status}`}async function Mo(e,t={},n=globalThis.fetch){let r=String(t.key||"").trim();if(!uo.test(r))throw new Error("Connection key format is invalid. Create a fresh CursorBuddy key first.");if(typeof n!="function")throw new Error("This Node.js runtime does not provide fetch; use a current Node.js release.");let o=Io(e,t),s=await n(`${o}/backend/cursorbuddy/connection-keys/claim`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:r,baseUrl:o,host:hn.hostname(),cwd:t.cwd||e.cwd||ee.cwd(),name:t.name||e.name||e.handle||"CursorBuddy runtime",surface:t.surface||"browser_extension",scope:t.scope||"machine",runtimeKind:t.runtimeKind||"agensis-cli-local-bridge",version:t.version||e.version||ee.env.npm_package_version||"",permissionMode:t.permissionMode||e.permissionMode,model:t.model||e.model,metadata:U(t.metadata)||null,websiteSource:t.websiteSource||t.metadata?.websiteSource||"",page:U(t.page)||U(t.metadata?.page)||null,client:U(t.client)||U(t.metadata?.client)||null,manifest:U(t.manifest)||U(t.metadata?.manifest)||null})}),i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(To(s,i));return{key:r,baseUrl:o,data:i?.data||i}}async function Sn(e,t={}){let n=Number(t.port??e.cursorBuddyPort??ee.env.AGENSIS_CURSORBUDDY_PORT??ln),r=yo(e,t),o=new Date().toISOString(),s=[],i=[],a=new Set,d=t.fetchImpl||globalThis.fetch,c=1,l=null,g=n,m=null,y=(u,h={})=>{let M={ts:new Date().toISOString(),event:u,detail:h};return s.push(M),s.length>200&&s.shift(),t.log?.(`CursorBuddy local bridge: ${u}${Object.keys(h).length?` ${JSON.stringify(h)}`:""}`),M},S=()=>({connected:!!e.cursorBuddyRuntime,mode:e.cursorBuddyRuntime?"agensis-cli":"agensis-cli-unclaimed",agentId:e.agent,workspaceId:e.workspace,agensisUrl:e.url,handle:e.handle,name:e.name,cwd:e.cwd,updatedAt:new Date().toISOString()}),f=()=>{if(typeof t.connectionProvider!="function")return null;try{let u=t.connectionProvider();return!u||typeof u!="object"||Array.isArray(u)?null:{...S(),...u,connected:u.connected===!0}}catch{return null}},b=()=>{let u=f();return u?.connected===!1?u:m?{...S(),...u||{},...m,connected:!0,updatedAt:u?.updatedAt||m.updatedAt}:u||S()};function w(u={}){if(!u||typeof u!="object"||Array.isArray(u))return null;let h=String(u.action||u.type||"").trim().toLowerCase();if(!fo.has(h))return null;let M={id:c++,ts:new Date().toISOString(),action:h,text:String(u.text||u.say||u.message||"").slice(0,1200),label:String(u.label||"").slice(0,80),value:String(u.value||u.prompt||"").slice(0,1200),holdMs:Number.isFinite(u.holdMs)?Math.max(0,Math.min(6e4,u.holdMs)):void 0,source:String(u.source||"agensis-daemon").slice(0,80)};return u.options&&Array.isArray(u.options)&&(M.options=u.options.map(p=>({label:String(p?.label||"").slice(0,80),value:String(p?.value||p?.task||"").slice(0,1200)})).filter(p=>p.label).slice(0,6)),M}function E(u){for(i.push(u);i.length>mo;)i.shift();y("control",{id:u.id,action:u.action,chars:u.text.length});for(let h of[...a])try{z(h,{type:"command",command:u})}catch{a.delete(h)}return u}function v(u){let h=Eo(u);if(h){let M=w(h.command);return M&&(E(M),y("chat_control",{id:M.id,action:M.action})),{content:h.content,model:"cursorbuddy-local-control",fast:!0}}return null}async function A(u){let h=v(u);if(h)return h;let M=dn(u?.messages,l),p=fn(e,M,u?.model),I=await V({cmd:p.cmd,args:p.args,cwd:e.cwd,timeoutMs:Math.min(Number(e.timeoutMs||18e5),5*60*1e3),heartbeatMs:e.heartbeatMs,label:"cursorbuddy local chat",input:p.stdin});if(I.error||I.status!==0)throw new Error(I.error?.message||String(I.stderr||"").trim()||`Command exited with status ${I.status}`);return{content:mn(I.stdout||I.stderr),model:p.model}}async function N(u,h){let M=`agensis-cursorbuddy-${Date.now()}`,p=v(u);if(p){let x=p.model||"cursorbuddy-local-control";return z(h,fe(M,x,p.content)),z(h,fe(M,x,"","stop")),z(h,"[DONE]"),y("chat_fast",{chars:p.content.length,model:x}),{content:p.content,model:x,fast:!0}}let I=dn(u?.messages,l),k=fn(e,I,u?.model,{stream:!0}),$="",q=x=>{x&&($+=x,z(h,fe(M,k.model||e.model,x)))},T=k.streamJson?Ao(q):null,R=await V({cmd:k.cmd,args:k.args,cwd:e.cwd,timeoutMs:Math.min(Number(e.timeoutMs||18e5),5*60*1e3),heartbeatMs:e.heartbeatMs,label:"cursorbuddy local chat",input:k.stdin,onData:x=>{if(T)T.feed(x);else{let B=String(x||"");$+=B,z(h,fe(M,k.model||e.model,B))}}});if(T){T.end();let x=T.result||"";!$&&x?q(x):$=x||$}if(R.error||R.status!==0){let x=R.error?.message||String(R.stderr||"").trim()||`Command exited with status ${R.status}`;throw new Error(x)}let _=T?$:mn($||R.stdout||R.stderr);return!T&&_&&_!==$&&(z(h,fe(M,k.model||e.model,_)),$=_),z(h,fe(M,k.model||e.model,"","stop")),z(h,"[DONE]"),{content:$||_,model:k.model}}let O=lo.createServer(async(u,h)=>{if(h.setHeader("access-control-allow-origin","*"),h.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),h.setHeader("access-control-allow-headers","content-type, authorization, x-agensis-bridge-secret"),u.method==="OPTIONS"){h.writeHead(204),h.end();return}let M=new URL(u.url||"/",Oe(g||ln));if(!So(u.method,M.pathname)&&!go(u,r)){F(h,401,{ok:!1,error:"Authentication required",code:"bridge_auth_required"});return}if(u.method==="GET"&&M.pathname==="/cursorbuddy/health"){let p=Oe(g);F(h,200,{ok:!0,runtime:"agensis-cli",backend:e.codingCmd,model:Qe(e),daemonModel:e.model,port:g,host:hn.hostname(),pid:ee.pid,bootedAt:o,authRequired:!0,authHeader:$e,stream:!0,streaming:!0,supportsStreaming:!0,chatStream:!0,capabilities:{chatStream:!0,controlStream:!0,fastAvatarReplies:!1,nativeCursorBuddyControl:!0},latestControlId:i.at(-1)?.id||0,connection:b(),context:l,endpoints:{chat:`${p}/v1/chat/completions`,chatStream:`${p}/v1/chat/completions`,edit:`${p}/cursorbuddy/edit`,context:`${p}/cursorbuddy/context`,control:`${p}/cursorbuddy/control`,controlStream:`${p}/cursorbuddy/control/stream`,logs:`${p}/cursorbuddy/logs`}});return}if(u.method==="GET"&&M.pathname==="/cursorbuddy/logs"){F(h,200,{ok:!0,events:s.slice(-100)});return}if(u.method==="GET"&&M.pathname==="/cursorbuddy/context"){F(h,200,{ok:!0,context:l});return}if(u.method==="GET"&&M.pathname==="/cursorbuddy/control"){let p=Number(M.searchParams.get("after")||0),I=i.filter(k=>k.id>p);F(h,200,{ok:!0,commands:I,latestId:i.at(-1)?.id||0});return}if(u.method==="GET"&&M.pathname==="/cursorbuddy/control/stream"){let p=Number(M.searchParams.get("after")||0);un(h),a.add(h),z(h,{type:"ready",latestId:i.at(-1)?.id||0});for(let k of i.filter($=>$.id>p))z(h,{type:"command",command:k});let I=setInterval(()=>{try{z(h,{type:"ping",ts:new Date().toISOString()})}catch{a.delete(h),clearInterval(I)}},15e3);I.unref&&I.unref(),u.on("close",()=>{a.delete(h),clearInterval(I)});return}if(u.method==="POST"&&M.pathname==="/cursorbuddy/control"){try{let p=JSON.parse(await Se(u)||"{}"),I=w(p);if(!I){F(h,400,{ok:!1,error:"unsupported CursorBuddy control command"});return}let k=E(I);F(h,200,{ok:!0,command:k})}catch(p){y("control_error",{error:String(p?.message||p)}),F(h,400,{ok:!1,error:String(p?.message||p)})}return}if(u.method==="POST"&&M.pathname==="/cursorbuddy/context"){try{let p=JSON.parse(await Se(u)||"{}");l={url:String(p.url||"").slice(0,2048),title:String(p.title||"").slice(0,300),surface:String(p.surface||"").slice(0,80),instanceId:String(p.instanceId||"").slice(0,140),workspaceId:String(p.workspaceId||e.workspace||"").slice(0,120),agentId:String(p.agentId||e.agent||"").slice(0,120),runtime:p.runtime&&typeof p.runtime=="object"?p.runtime:null,page:p.page&&typeof p.page=="object"?p.page:null,client:p.client&&typeof p.client=="object"?p.client:null,project:p.project&&typeof p.project=="object"?p.project:null,manifest:p.manifest&&typeof p.manifest=="object"?p.manifest:null,selection:p.selection&&typeof p.selection=="object"?p.selection:null,updatedAt:new Date().toISOString()},y("context",{url:l.url,surface:l.surface,instanceId:l.instanceId}),F(h,200,{ok:!0,context:l})}catch(p){y("context_error",{error:String(p?.message||p)}),F(h,400,{ok:!1,error:String(p?.message||p)})}return}if(u.method==="POST"&&M.pathname==="/cursorbuddy/connect"){try{let p=JSON.parse(await Se(u)||"{}"),I=await Mo(e,p,d),k=I.data||{};m={connected:!0,mode:"agensis-claimed",keyId:xo(I.key),agentId:String(k.agentId||k.agent?.id||e.agent||""),workspaceId:String(k.workspaceId||k.workspace_id||k.agent?.workspace_id||e.workspace||""),agensisUrl:I.baseUrl,handle:String(k.handle||k.agent?.handle||e.handle||""),name:String(k.agent?.name||p.name||e.name||"CursorBuddy runtime"),cwd:String(p.cwd||e.cwd||ee.cwd()),surface:String(p.surface||"browser_extension"),command:String(k.command||k.localCommand||""),updatedAt:new Date().toISOString()},l=Co(p,m,e),y("connect",{mode:m.mode,keyId:m.keyId,agentId:m.agentId,workspaceId:m.workspaceId,url:l.url}),F(h,200,{ok:!0,connection:m,claim:k})}catch(p){y("connect_error",{error:String(p?.message||p)}),F(h,400,{ok:!1,error:String(p?.message||p)})}return}if(u.method==="POST"&&M.pathname==="/cursorbuddy/edit"){try{let p=JSON.parse(await Se(u)||"{}"),I=[{role:"system",content:"You are the local CursorBuddy edit agent. The user selected a DOM element in their own site. Use the payload to inspect and change the local checkout, then report what changed."},{role:"user",content:JSON.stringify(p,null,2)}];y("edit_request",{selector:p?.target?.selector||""});let k=await A({messages:I,model:p?.model});y("edit_done",{chars:k.content.length}),F(h,200,{ok:!0,backend:e.codingCmd,cwd:e.cwd,content:k.content})}catch(p){y("edit_error",{error:String(p?.message||p)}),F(h,500,{ok:!1,error:String(p?.message||p)})}return}if(u.method==="POST"&&M.pathname.endsWith("/chat/completions")){try{let p=JSON.parse(await Se(u)||"{}");if(y("chat_request",{messages:Array.isArray(p.messages)?p.messages.length:0,model:gn(p.model,Qe(e))}),p.stream===!0){un(h);let k=await N(p,h);y("chat_done",{chars:k.content.length,stream:!0,fast:k.fast===!0}),h.end();return}let I=await A(p);y("chat_done",{chars:I.content.length,fast:I.fast===!0}),F(h,200,{id:`agensis-cursorbuddy-${Date.now()}`,object:"chat.completion",model:I.model||p.model||e.model,choices:[{index:0,message:{role:"assistant",content:I.content},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}})}catch(p){y("chat_error",{error:String(p?.message||p)}),F(h,500,{error:{message:String(p?.message||p)}})}return}h.writeHead(404),h.end("CursorBuddy local bridge")});return await new Promise((u,h)=>{O.once("error",h),O.listen(n,"127.0.0.1",()=>{g=O.address().port,O.off("error",h),u()})}),y("listening",{url:`${Oe(g)}/cursorbuddy/health`}),{port:g,url:Oe(g),secret:r,authHeader:$e,close(){return new Promise(u=>O.close(()=>u()))},getContext(){return l}}}import pe from"node:fs/promises";import No from"node:os";import W from"node:path";var wn=200,bn=256*1024,Oo=2,$o=new Set([".md",".markdown",".txt"]);function Do(e){return String(e||"").replace(/[^a-zA-Z0-9]/g,"-")}function Ze({cwd:e,memoryDir:t,homedir:n=No.homedir()}={}){let r=String(t||"").trim();if(r)return r.startsWith("~")?W.join(n,r.slice(1)):W.resolve(r);let o=String(e||"").trim();return o?W.join(n,".claude","projects",Do(o),"memory"):null}async function et(e){if(!e)return null;try{let t=await pe.realpath(e);return(await pe.stat(t)).isDirectory()?t:null}catch{return null}}async function Ro(e,t){if(!e)throw new Error("memory root unavailable");let n=W.isAbsolute(String(t))?String(t):W.join(e,String(t)),r=await pe.realpath(n),o=e.endsWith(W.sep)?e:e+W.sep;if(r!==e&&!r.startsWith(o))throw new Error(`path escapes memory root: ${t}`);return r}function Bo(e){let t=W.basename(e).toLowerCase();return t==="memory.md"?"index":t==="claude.md"?"instructions":"memory"}async function tt(e,t,n,r){if(n>Oo||r.length>=wn)return;let o;try{o=await pe.readdir(t,{withFileTypes:!0})}catch{return}for(let s of o){if(r.length>=wn)break;if(s.name.startsWith("."))continue;let i=W.join(t,s.name);if(s.isDirectory())await tt(e,i,n+1,r);else if(s.isFile()&&$o.has(W.extname(s.name).toLowerCase())){let a=W.relative(e,i);r.push({path:a,kind:Bo(a)})}}}async function Po(e){let t=await et(e);if(!t)return[];let n=[];return await tt(t,t,0,n),n.sort((r,o)=>r.kind==="index"?-1:o.kind==="index"?1:r.path.localeCompare(o.path)),n}async function Lo(e,t){let n=await et(e),r=await Ro(n,t),o=await pe.readFile(r),s=o.length>bn;return{content:o.subarray(0,bn).toString("utf8"),byteSize:o.length,truncated:s}}async function _n(e){let t=await et(e);if(!t)return"";let n=[];await tt(t,t,0,n),n.sort((o,s)=>o.path.localeCompare(s.path));let r=[];for(let o of n)try{let s=await pe.stat(W.join(t,o.path));r.push(`${o.path}:${s.size}:${Math.floor(s.mtimeMs)}`)}catch{}return r.join("|")}async function vn(e){let t=await Po(e),n=[];for(let r of t)try{let{content:o,byteSize:s}=await Lo(e,r.path);n.push({path:r.path,kind:r.kind,content:o,byteSize:s})}catch{}return n}import rt from"node:fs";import te from"node:path";import En from"node:os";function Uo(e){try{return rt.statSync(e).isDirectory()}catch{return!1}}function jo(e){try{return rt.statSync(e).isFile()}catch{return!1}}function nt(e){try{return rt.readdirSync(e,{withFileTypes:!0})}catch{return[]}}function kn({home:e=En.homedir(),cwd:t=process.cwd()}={}){let n=[e&&te.join(e,".claude","commands"),t&&te.join(t,".claude","commands")].filter(Boolean),r=new Set,o=[],s=(i,a)=>{if(!i)return;let d=a?`${a}:${i}`:i;r.has(d)||(r.add(d),o.push({name:i,parent:a||null}))};for(let i of n)for(let a of nt(i)){if(a.name.startsWith("."))continue;if(a.name.endsWith(".md")){s(a.name.slice(0,-3),null);continue}let d=te.join(i,a.name);if(a.isDirectory()||a.isSymbolicLink()&&Uo(d))for(let c of nt(d))c.name.startsWith(".")||c.name.endsWith(".md")&&s(c.name.slice(0,-3),a.name)}return o}function ot({home:e=En.homedir(),cwd:t=process.cwd()}={}){let n=[e&&te.join(e,".claude","skills"),e&&te.join(e,".codex","skills"),t&&te.join(t,".claude","skills")].filter(Boolean),r=new Map,o=(s,i)=>{!s||r.has(s)||r.set(s,{name:s,file:i||""})};for(let s of n)for(let i of nt(s)){if(i.name.startsWith("."))continue;let a=te.join(s,i.name);if(i.name.endsWith(".md"))o(i.name.slice(0,-3),a);else if(i.isDirectory()||i.isSymbolicLink()){let d=te.join(a,"SKILL.md");o(i.name,jo(d)?d:"")}}return[...r.values()].sort((s,i)=>s.name<i.name?-1:s.name>i.name?1:0)}function An(e={}){return ot(e).map(t=>t.name)}import st from"node:fs/promises";var he=64*1024,Fo=200,xn=4*1024*1024,Go=2e3,Ho=512;function In(e,t,n=he){let r=`
|
|
40
44
|
|
|
41
45
|
... [truncated by agensis-agent: ${t}]
|
|
42
|
-
`,s=Math.max(0,n-Buffer.byteLength(r));return`${Buffer.from(String(e||"")).subarray(0,s).toString("utf8").replace(/\uFFFD+$/,"")}${r}`}function io(e){let t=String(e||"").split(/\r?\n/),n="";if(t[0]?.trim()==="---")for(let r=1;r<t.length&&r<200&&t[r].trim()!=="---";r+=1){let s=/^description:\s*(.*)$/i.exec(t[r]);if(!s)continue;let o=s[1].trim();if(o&&!/^[|>][-+]?$/.test(o)){n=o.replace(/^["']|["']$/g,"");break}let i=[];for(let c=r+1;c<t.length&&c<200&&!(t[c].trim()==="---"||t[c].trim()&&!/^\s/.test(t[c]));c+=1)i.push(t[c].trim());n=i.join(" ").trim();break}if(!n){let r=t.findIndex((i,c)=>c>0&&i.trim()==="---"),o=(t[0]?.trim()==="---"&&r>0?t.slice(r+1):t).find(i=>i.trim()&&i.trim()!=="---");n=String(o||"").replace(/^#+\s*/,"").trim()}return n.slice(0,oo)}function tn(e){try{return qe(e).slice(0,ro)}catch{return[]}}async function ao(e){let t;try{t=await Ke.open(e,"r")}catch{return null}try{let n=Buffer.alloc(ae+1),{bytesRead:r}=await t.read(n,0,n.length,0);return n.subarray(0,r)}catch{return null}finally{await t.close().catch(()=>{})}}async function co(e,t){let n=await ao(e.file);if(!n)return null;let r=n.toString("utf8"),s=io(r),o=n.length>ae,i=Math.min(ae,Math.max(0,t)),c=Buffer.byteLength(r)>i;if(!o&&!c)return{skill:e.name,path:e.file,summary:s,content:r,truncated:!1};let l=o?await lo(e.file):0,a=o&&!c?`the file is ${l?`${l} bytes`:`over ${ae} bytes`}; only the first ${ae} were synced`:`this sync reached its ${en}-byte ceiling`,u=i<so?Zt("",a,Number.MAX_SAFE_INTEGER):Zt(r,a,i);return{skill:e.name,path:e.file,summary:s,content:u,truncated:!0}}async function lo(e){try{return(await Ke.stat(e)).size}catch{return 0}}async function ze(e={}){let t=[];for(let n of tn(e)){if(!n.file){t.push(`${n.name}:-`);continue}try{let r=await Ke.stat(n.file);t.push(`${n.name}:${n.file}:${r.size}:${Math.floor(r.mtimeMs)}`)}catch{t.push(`${n.name}:-`)}}return t.join("|")}async function nn(e={}){let t=[],n=0;for(let r of tn(e))if(r.file)try{let s=await co(r,en-n);if(!s)continue;n+=Buffer.byteLength(s.content),t.push(s)}catch{}return t}import{readFile as uo}from"node:fs/promises";var mo=new Set(["127.0.0.1","localhost","::1","[::1]"]);function rn(e,t,n){let r=Number(e);return Number.isFinite(r)?Math.max(1,Math.min(n,Math.trunc(r))):t}function fo(e,t){if(!e||typeof e!="object"||e.shared===!1)return null;let n=String(e.id||e.upstreamModel||`model-${t+1}`).trim();if(!n)return null;if(!/^[a-zA-Z0-9._:@/-]+$/.test(n))throw new Error(`Shared model id '${n}' may only contain letters, numbers, dot, underscore, colon, at, slash, or dash.`);let r=new URL(String(e.baseUrl||"http://127.0.0.1:11434/v1"));if(!mo.has(r.hostname))throw new Error(`Shared model '${n}' must use a loopback endpoint.`);if(!["http:","https:"].includes(r.protocol))throw new Error(`Shared model '${n}' must use an HTTP endpoint.`);return{id:n.slice(0,160),name:String(e.name||n).trim().slice(0,160)||n,provider:String(e.provider||"local").trim().slice(0,80)||"local",protocol:"openai-chat",baseUrl:r.toString().replace(/\/$/,""),upstreamModel:String(e.upstreamModel||n).trim().slice(0,200)||n,apiKeyEnv:String(e.apiKeyEnv||"").trim().slice(0,120),capabilities:[...new Set((Array.isArray(e.capabilities)?e.capabilities:["text","streaming"]).map(s=>String(s||"").trim().toLowerCase()).filter(Boolean))].slice(0,16),...e.contextWindow?{contextWindow:rn(e.contextWindow,void 0,1e7)}:{},maxConcurrency:rn(e.maxConcurrency,1,64),shared:!0}}async function on(e){if(!e)return[];let t=JSON.parse(await uo(e,"utf8")),n=Array.isArray(t)?t:t?.models;if(!Array.isArray(n))throw new Error("Shared model config must contain a models array.");return n.slice(0,32).map(fo).filter(Boolean)}function sn(e){return(Array.isArray(e)?e:[]).filter(t=>t?.shared).map(t=>({id:t.id,name:t.name,provider:t.provider,protocol:t.protocol,upstreamModel:t.upstreamModel,capabilities:[...t.capabilities],...t.contextWindow?{contextWindow:t.contextWindow}:{},maxConcurrency:t.maxConcurrency,shared:!0}))}async function an({models:e,request:t,send:n,signal:r,fetchImpl:s=fetch,env:o=process.env}){let i=String(t?.requestId||"").trim();if(!i)throw new Error("Inference requestId is required.");let c=(Array.isArray(e)?e:[]).find(p=>p.id===t?.model);if(!c)throw new Error(`Shared model '${t?.model||""}' is not available.`);let l={"content-type":"application/json"},a=c.apiKeyEnv?o[c.apiKeyEnv]:"";a&&(l.authorization=`Bearer ${a}`),n({action:"agent_inference_started",requestId:i,model:c.id});let{requestId:u,model:g,type:w,action:f,...h}=t,v=await s(`${c.baseUrl}/chat/completions`,{method:"POST",headers:l,body:JSON.stringify({...h,model:c.upstreamModel,stream:t.stream===!0}),signal:r});if(!v.ok){let p=await v.text().catch(()=>"");throw new Error(p||`Local model returned HTTP ${v.status}.`)}if(t.stream===!0){if(!v.body)throw new Error("Local model returned an empty stream.");let p=v.body.getReader(),E=new TextDecoder,k="",A,T=b=>{let M=b.trim();if(!M.startsWith("data:"))return!1;let m=M.slice(5).trim();if(!m)return!1;if(m==="[DONE]")return!0;try{let y=JSON.parse(m);y?.usage&&(A=y.usage),n({action:"agent_inference_delta",requestId:i,model:c.id,chunk:y})}catch{}return!1},B=!1;for(;!B;){let{done:b,value:M}=await p.read();k+=E.decode(M||new Uint8Array,{stream:!b});let m=k.split(/\r?\n/);k=b?"":m.pop()||"";for(let y of m)if(T(y)){B=!0;break}if(b)break}k&&T(k);let d={action:"agent_inference_result",requestId:i,model:c.id,...A?{usage:A}:{}};return n(d),d}let S=await v.json();return n({action:"agent_inference_result",requestId:i,model:c.id,response:S}),S}xe();var Oo=30*60*1e3,$o=15*1e3,kn=2,Do=10*1024,Bo="claude-opus-4-8",ee="0.1.32";async function Me(e={}){let t=Ro(e);t.sharedModels=t.share?await on(t.sharedModelsFile):[];let n=!1,r=null,s=null,o=null,i=null,c=0,l=null,a=null,u="",g=null,w=!1,f=null,h=new Map,v=null,S={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"},p=new Map,E=new Map,k=[],A=()=>S,T=()=>({connected:w&&!!t.cursorBuddyRuntime,mode:t.cursorBuddyRuntime?"agensis-cli":"agensis-cli-unclaimed",agentId:f?.agentId||f?.agent_id||t.agent,workspaceId:f?.workspaceId||f?.workspace_id||t.workspace,agensisUrl:t.url,handle:f?.handle||t.handle,name:f?.name||t.name,cwd:t.cwd,updatedAt:new Date().toISOString()}),B=()=>{v||!t.lanListener||(v=new pe.Server({port:0}),v.on("listening",()=>{let{port:C}=v.address();S={transport:"ws",listening:!0,addrs:as(C),auth:"hub-pairwise"},D(`Agent-mesh LAN listener on port ${C}`),fe(r,t,A())}),v.on("connection",C=>{let O=!1,_=setTimeout(()=>{if(!O)try{C.close(1008,"peer auth required")}catch{}},5e3);C.once("message",N=>{clearTimeout(_);let $=et(N),F=$?.type==="peer_auth"?p.get($.ticket):null;if(!F||F.fromAgentId!==$.fromAgentId||Date.now()>F.exp){try{C.close(1008,"invalid ticket")}catch{}return}p.delete($.ticket),O=!0,C.on("message",J=>{let L=et(J);L?.type==="agent_job"&&L.job?.id&&a.enqueue({...L.job,key:L.job.id,lane:An(L.job),ws:r}).accepted&&D(`Queued peer-handoff job ${L.job.id} from ${$.fromAgentId}`)})})}),v.on("error",C=>D(`LAN listener error: ${C?.message||C}`)))},d=()=>{if(v){try{v.close()}catch{}v=null}S={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"}},b=C=>new Promise((O,_)=>{if(!P(r,{action:"peer_ticket_request",targetAgentId:C})){_(new Error("hub socket not open"));return}let N=E.get(C)||[];N.push({resolve:O,reject:_}),E.set(C,N),setTimeout(()=>{let $=E.get(C)||[],F=$.findIndex(J=>J.resolve===O);F>=0&&($.splice(F,1),_(new Error("peer ticket request timed out")))},1e4)}),M=()=>new Promise((C,O)=>{if(!P(r,{action:"peer_list_request"})){O(new Error("hub socket not open"));return}k.push(C),setTimeout(()=>{let _=k.indexOf(C);_>=0&&(k.splice(_,1),C([]))},1e4)}),m=async(C,O)=>{let _=null;try{let $=(await M()).find(L=>L.agentId===C&&L.reach?.listening&&L.reach.addrs?.length);if(!$)return!1;let F=await b(C),J=F.peer?.addrs?.[0]||$.reach.addrs[0];return!J?.host||!J?.port?!1:(_=new pe(`ws://${J.host}:${J.port}`),await new Promise((L,De)=>{_.once("open",L),_.once("error",De),setTimeout(()=>De(new Error("peer connect timed out")),5e3)}),P(_,{type:"peer_auth",ticket:F.ticket,fromAgentId:t.agent}),P(_,{type:"agent_job",job:O}),!0)}catch(N){return D(`Peer handoff to ${C} failed, falling back to hub relay: ${N?.message||N}`),!1}finally{try{_?.close()}catch{}}},y=()=>{n=!0,Mn(h),s&&clearTimeout(s),o&&clearInterval(o),i&&clearInterval(i),g&&(g.close().catch(()=>{}),g=null),d(),gn(t,{status:"stopped",connected:!1});try{r?.close()}catch{}l&&l()};if(a=Bt({concurrency:t.once?1:t.maxConcurrency,runJob:async(C,O)=>{await Xo(t,C,O),t.once&&y()}}),t.cursorBuddyBridge)try{g=await qt(t,{port:t.cursorBuddyPort,authSecret:t.cursorBuddyBridgeSecret||void 0,log:D,connectionProvider:T}),g?.secret&&(t.cursorBuddyBridgeSecret=g.secret)}catch(C){if(ds(C)){let O=await ms(t.cursorBuddyPort);if(O?.ok){let _=O.pid?` pid ${O.pid}`:"";D(`CursorBuddy local bridge already running on http://127.0.0.1:${t.cursorBuddyPort}${_}`)}else D(`CursorBuddy local bridge port ${t.cursorBuddyPort} is in use but did not answer health`)}else D(`CursorBuddy local bridge unavailable: ${C?.message||C}`);g=null}x.once("SIGINT",y),x.once("SIGTERM",y);let I=()=>{if(n)return;let C=Lo(t.url,t.token,t);u="",D(`Connecting to ${C.replace(t.token,"redacted")}`),r=new pe(C),r.on("open",async()=>{w=!1,f=null,D(`Connected. Registering @${t.handle||"agent"} from ${t.cwd}`),P(r,{type:"auth",token:t.token});let O=await Sn(t);P(r,{action:"agent_register",workspaceId:t.workspace,agentId:t.agent,handle:t.handle,name:t.name,host:ye.hostname(),cwd:t.cwd,...O?{identity:O}:{},metadata:{codingCmd:t.codingCmd,model:t.model,permissionMode:t.permissionMode,permissionFlags:ot(t.permissionMode),once:t.once,runtime:"agensis",version:ee}}),o=setInterval(()=>{Promise.all([Bn(t,A()).catch(()=>null),Xe(t).catch(()=>null)]).then(([_,N])=>{P(r,{action:"agent_heartbeat",..._?{capabilitiesHash:_.capabilitiesHash,memoryHash:_.memoryHash}:{},..._?.skillsHash?{skillsHash:_.skillsHash}:{},metadata:Ze(t,a,N,Tn(t)?g?.getContext?.():null,h)})})},t.heartbeatMs),o.unref&&o.unref()}),r.on("message",O=>{let _=et(O);if(_){if(_.type==="agent_registered"){w=!0,f=_.connection||_.agent||null,In(t,_.agent),D(`Registered as ${_.connection?.name||t.name} on ${_.connection?.host||ye.hostname()}`),t.onRegistered&&Promise.resolve(t.onRegistered(t,_)).catch(N=>{D(`Profile save failed: ${N?.message||N}`)}),Ve(t,_.agent).catch(()=>{}),vn(t).catch(()=>{}),xn(r,t),Cn(r,t),B(),fe(r,t,A());return}if(_.type==="agent_config"){In(t,_.agent),D(`Updated config for @${t.handle||"agent"}: model=${t.model}, permission=${t.permissionMode}`),Ve(t,_.agent).catch(()=>{});return}if(_.type==="agent_memory_refresh"){xn(r,t),fe(r,t,A());return}if(_.type==="agent_capabilities_refresh"){fe(r,t,A());return}if(_.type==="agent_skills_refresh"){Cn(r,t);return}if(_.type==="agent_inference_cancel"){h.get(String(_.requestId||""))?.abort();return}if(_.type==="agent_job_cancel"){let N=String(_.jobId||"");N&&a.cancel(N,_.reason||"Cancelled by Agensis")&&D(`Cancelled job ${N}`);return}if(_.type==="agent_inference_request"&&_.requestId){let N=String(_.requestId),$=t.sharedModels.find(L=>L.id===_.model),F=[...h.values()].filter(L=>L.model===_.model).length;if(!$){P(r,{action:"agent_inference_error",requestId:N,error:`Shared model '${_.model||""}' is not available.`});return}if(F>=$.maxConcurrency){P(r,{action:"agent_inference_error",requestId:N,error:"Shared model is at capacity.",code:"capacity_exhausted"});return}let J=new AbortController;h.set(N,{abort:()=>J.abort(),model:$.id}),P(r,{action:"agent_heartbeat",metadata:Ze(t,a,null,null,h)}),an({models:t.sharedModels,request:_,signal:J.signal,send:L=>P(r,L)}).catch(L=>{P(r,{action:"agent_inference_error",requestId:N,error:J.signal.aborted?"Inference cancelled.":L?.message||String(L),code:J.signal.aborted?"cancelled":"inference_failed"})}).finally(()=>{h.delete(N),P(r,{action:"agent_heartbeat",metadata:Ze(t,a,null,null,h)})});return}if(_.type==="peer_ticket"){let N=_.peer?.agentId,$=E.get(N)||[],F=$.shift();$.length?E.set(N,$):E.delete(N),F&&F.resolve(_);return}if(_.type==="peer_ticket_grant"){p.set(_.ticket,{fromAgentId:_.fromAgentId,exp:_.exp});return}if(_.type==="peer_list"){let N=k.shift();N&&N(Array.isArray(_.peers)?_.peers:[]);return}if(_.type==="agent_reach_disable"){d(),fe(r,t,A());return}if(_.type==="error"){D(`Server rejected request: ${_.message||"unknown error"}`);return}if(_.type==="agent_disabled"){w=!1,f=null,D(`Agent disabled by Agensis: ${_.reason||"deactivated"}`),y();return}if(_.type==="agent_job"&&_.job?.id){let N=a.enqueue({..._.job,key:_.job.id,lane:An(_.job),ws:r});N.accepted&&(c+=1,D(`Queued job ${_.job.id} at position ${N.position}`),t.once&&a.idle().then(()=>y()))}}}),r.on("close",(O,_)=>{Mn(h),w=!1,f=null;let N=String(_||"");if(D(`Socket closed (${O||"no-code"}${N?`: ${N}`:""})`),o&&(clearInterval(o),o=null),O===1008&&/agent deactivated|authentication failed/i.test(N)){D("Stopping daemon because Agensis rejected this agent connection."),y();return}if(u==="ECONNREFUSED"&&Fo(t.url)){D("Local agent backend is not running on 127.0.0.1:3142."),D("Start it in another terminal with: npm run backend"),D("Then rerun this connect command."),y();return}t.once&&c>0&&a.active()===0&&a.size()===0&&y(),!(n||t.once)&&(s=setTimeout(I,2e3),s.unref&&s.unref())}),r.on("error",O=>{u=O?.code||"",D(`Socket error: ${O?.message||O}`)})},R=async()=>{let C=await Xe(t).catch(()=>null);await hn(t,{busy:a.active()>0,active:a.active(),queueSize:a.size(),connected:r?.readyState===pe.OPEN,agentStatus:C?.status,agentNote:C?.note}).catch(()=>{})};R(),i=setInterval(()=>{R()},t.heartbeatMs),i.unref&&i.unref(),I(),await new Promise(C=>{let O=setInterval(async()=>{t.once&&c>0&&a.active()===0&&a.size()===0&&y(),n&&y()},500);l=()=>{clearInterval(O),C()}}),l=null,x.off("SIGINT",y),x.off("SIGTERM",y)}function Ro(e){let t=Po(e.cursorBuddyBridge),n=e.noCoding===!0||x.env.AGENSIS_NO_CODING==="1",s=!Z(e.fullCliContext,Z(x.env.AGENSIS_FULL_CLI_CONTEXT,!1))&&Z(e.leanCli,!0),o={url:String(e.url||e.baseUrl||x.env.AGENSIS_URL||"").trim(),token:String(e.token||x.env.AGENSIS_TOKEN||"").trim(),workspace:String(e.workspace||e.workspaceId||x.env.AGENSIS_WORKSPACE||x.env.AGENSIS_WORKSPACE_ID||"").trim(),agent:String(e.agent||e.agentId||x.env.AGENSIS_AGENT||x.env.AGENSIS_AGENT_ID||"").trim(),handle:Ln(e.handle||x.env.AGENSIS_HANDLE||e.name||x.env.AGENSIS_NAME||"agent"),name:String(e.name||x.env.AGENSIS_NAME||e.handle||x.env.AGENSIS_HANDLE||"agensis Agent").trim(),cwd:String(e.cwd||x.env.AGENSIS_CWD||x.cwd()).trim(),codingCmd:n?"":String(e.codingCmd||x.env.AGENSIS_CODING_CMD||x.env.CODING_CMD||"claude -p").trim(),model:rt(e.model||x.env.AGENSIS_MODEL||x.env.CLAUDE_MODEL||""),permissionMode:Te(e.permissionMode||e.permission_mode||e.permission||x.env.AGENSIS_PERMISSION_MODE||"default"),timeoutMs:Number(e.timeoutMs||x.env.AGENSIS_TIMEOUT_MS||Oo),heartbeatMs:Number(e.heartbeatMs||x.env.AGENSIS_HEARTBEAT_MS||$o),maxConcurrency:Math.max(1,Number(e.maxConcurrency||x.env.AGENSIS_MAX_CONCURRENCY||kn)||kn),once:!!(e.once||x.env.AGENSIS_ONCE==="1"),exitOnOnce:!!e.exitOnOnce,onRegistered:typeof e.onRegistered=="function"?e.onRegistered:null,primaryDaemon:!!(e.primaryDaemon||x.env.AGENSIS_PRIMARY_DAEMON==="1"),cursorBuddyRuntime:!!(e.cursorBuddyRuntime||x.env.AGENSIS_CURSORBUDDY_RUNTIME==="1"),cursorBuddyBridge:t,cursorBuddyPort:Number(e.cursorBuddyPort||x.env.AGENSIS_CURSORBUDDY_PORT||8787),cursorBuddyBridgeSecret:String(e.cursorBuddyBridgeSecret||x.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim(),cursorBuddyModel:String(e.cursorBuddyModel||x.env.AGENSIS_CURSORBUDDY_MODEL||"haiku-4.5").trim(),lanListener:!!(e.lanListener||e.lan||x.env.AGENSIS_LAN==="1"),share:!!(e.share||x.env.AGENSIS_SHARE==="1"),sharedModelsFile:String(e.sharedModelsFile||x.env.AGENSIS_SHARED_MODELS_FILE||"").trim(),noCoding:n,leanCli:s,fastConnection:Z(e.fastConnection,Z(x.env.AGENSIS_FAST_CONNECTION,!0)),syncMemory:Z(e.syncMemory,x.env.AGENSIS_SYNC_MEMORY==="1"),syncSkills:Z(e.syncSkills,Z(x.env.AGENSIS_SYNC_SKILLS,!0)),hostFolders:$n(e.hostFolders??e.host_folders??x.env.AGENSIS_HOST_FOLDERS)};o.sharedModelsFile&&!ge.isAbsolute(o.sharedModelsFile)&&(o.sharedModelsFile=ge.resolve(o.cwd,o.sharedModelsFile));let i=[];if(o.url||i.push("--url"),o.token||i.push("--token"),o.workspace||i.push("--workspace"),o.agent||i.push("--agent"),o.share&&!o.sharedModelsFile&&i.push("--shared-models-file"),i.length)throw new Error(`Missing required option(s): ${i.join(", ")}`);return o}function Z(e,t){return e==null||e===""?t:typeof e=="boolean"?e:!/^(0|false|off|no)$/i.test(String(e).trim())}function Po(e){let t=x.env.AGENSIS_CURSORBUDDY_BRIDGE;return t!==void 0&&t!==""?!/^(0|false|off|no)$/i.test(String(t).trim()):e==null||e===""?!1:typeof e=="boolean"?e:!/^(0|false|off|no)$/i.test(String(e).trim())}function Lo(e,t,n={}){let r=nt(e);return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.pathname="/backend/ws",r.search="",n.workspace&&r.searchParams.set("workspaceId",n.workspace),n.agent&&r.searchParams.set("agentId",n.agent),r.toString()}function nt(e){let t=new URL(e);return Uo(t)&&(t.protocol="http:",t.hostname="127.0.0.1",t.port="3142"),t}function Uo(e){if(!(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="0.0.0.0")||e.port==="3142")return!1;if(e.port==="5173"||e.port==="8888")return!0;let t=Number(e.port||0);return t>=49152&&t<=65535}function Fo(e){try{let t=nt(e);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="0.0.0.0")&&t.port==="3142"}catch{return!1}}function An(e){let t=String(e?.sessionId||""),n=String(e?.threadParentId||"");return`${t}::${n}`}var jo=/\b(cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\b/i,Go=[/\b(?:make|have|tell)\s+(?:the\s+)?(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\s+(?:say|speak)\s+(.+)$/i];function Ho(e){return String(e||"").trim().replace(/^[`"'“”‘’]+|[`"'“”‘’?.!]+$/g,"").trim().slice(0,1200)}function Jo(e){for(let t of Go){let n=String(e||"").match(t),r=Ho(n?.[1]||"");if(r)return r}return""}function qo(e){let t=String(e||"").replace(/\s+/g," ").trim();if(!t)return"";let n=/latest user message\s*:\s*/gi,r=null,s=null;for(;r=n.exec(t);)s=r;if(!s)return"";let o=t.slice(s.index+s[0].length).trim(),i=o.search(/\b(Return a useful response|Conversation context follows|Previous user|Previous assistant|Diagnostic notes|System prompt|Developer message)\b/i);return(i>=0?o.slice(0,i):o).trim().replace(/^["'“”‘’]+|["'“”‘’]+$/g,"").trim()}function Ko(e){let t=String(e||"").replace(/\s+/g," ").trim(),r=qo(t)||t;if(!r)return"";if(r.length<=500)return r;let s=[/\b(?:can you\s+)?(?:make|have|tell)\s+(?:the\s+)?(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\s+(?:wave|waves|waving|say|speak)\b.{0,160}/i,/\b(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\b.{0,120}\b(?:wave|waves|waving|say|speak|open|show|hide|hush|close|dismiss|clear)\b.{0,160}/i,/\b(?:wave|open|show|hide|hush|close|dismiss|clear)\b.{0,120}\b(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy|bubble|prompt|dialog|panel|options|menu)\b/i,/\b(?:say|speak)\s+[`"'“”‘’]?.{1,180}/i];for(let o of s){let i=r.match(o);if(i?.[0])return i[0].trim()}return""}function zo(e){let t=Ko(e);if(!t)return null;let n=/^(open|show|hide|hush|close|dismiss)\b/i.test(t),r=jo.test(t);if(!n&&!r)return null;let s="agensis-native-control";if(/\b(hide|hush|close|dismiss|clear)\b.*\b(bubble|prompt|dialog|panel|options|menu)\b/i.test(t)||/^hush\b/i.test(t))return{action:"hush",source:s};if(/\b(open|show|bring up|get back|display)\b.*\b(prompt|bubble|dialog|panel|options|menu)\b/i.test(t)||/^open\b/i.test(t))return{action:"open",source:s};let o=Jo(t);return o&&r?{action:"say",text:o,source:s}:r&&/\b(wave|waves|waving)\b/i.test(t)?{action:"wave",text:o,source:s}:null}async function Wo(e,t){let r=`http://127.0.0.1:${Number(e.cursorBuddyPort||8787)}/cursorbuddy/control`,s=String(e.cursorBuddyBridgeSecret||x.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim(),o={"content-type":"application/json"};s&&(o.authorization=`Bearer ${s}`,o["x-agensis-bridge-secret"]=s);let i=await fetch(r,{method:"POST",headers:o,body:JSON.stringify(t)}),c=null;try{c=await i.json()}catch{c=null}if(!i.ok||c?.ok===!1)throw new Error(c?.error||`CursorBuddy control failed with HTTP ${i.status}`);return c}function Yo(e){return e.action==="wave"?"Sent CursorBuddy a wave command.":e.action==="say"?`Sent CursorBuddy speech: ${e.text||""}`.trim():e.action==="open"?"Opened CursorBuddy's prompt.":e.action==="hush"?"Dismissed CursorBuddy's bubble.":e.action==="choose"?"Sent CursorBuddy options.":"Sent CursorBuddy control command."}function Tn(e={}){return e.cursorBuddyBridge===!1?!1:!!(e.cursorBuddyRuntime||e.primaryDaemon)}async function Vo(e,t,n,r){let s="cursorbuddy-control",o="native",i=[],c=(u="")=>{P(t.ws,{action:"agent_job_delta",jobId:t.id,content:u,elapsedMs:Date.now()-r,model:s,permissionMode:o,permissionFlags:i})};c("");let l="",a="";try{await Wo(e,n),l=Yo(n),c(l)}catch(u){a=String(u?.message||u),l=`CursorBuddy control failed: ${a}`,c(l)}P(t.ws,{action:"agent_job_result",jobId:t.id,response:l,error:a,elapsedMs:Date.now()-r,model:s,permissionMode:o,permissionFlags:i}),D(`Finished native CursorBuddy ${n.action} job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s`)}async function Xo(e,t,{signal:n}){let r=Date.now();D(`Starting job ${t.id}`);let s=zo(t.prompt);if(s&&Tn(e)){await Vo(e,t,s,r),e.once&&(D("One-shot CursorBuddy control job complete; exiting."),setTimeout(()=>x.exit(0),150));return}let o=es(e,t),i=await Qo(e,t),c="",l="",a=0,u=(d="")=>{P(t.ws,{action:"agent_job_delta",jobId:t.id,content:d,elapsedMs:Date.now()-r,model:o.model,permissionMode:o.permissionMode,permissionFlags:o.permissionFlags})},g=d=>{P(t.ws,{action:"agent_job_step",jobId:t.id,kind:d.kind,name:d.name,detail:d.detail,elapsedMs:Date.now()-r})},w=d=>{P(t.ws,{action:"agent_job_segment",jobId:t.id,text:d.text,elapsedMs:Date.now()-r})};u("");let f=o.streamJson?ts({onStep:g,onSegment:w}):null,h=setInterval(()=>u(c),1e3);h.unref&&h.unref();let v=!/[\\/]/.test(o.cmd),S=e.fastConnection&&v?Rn(o.cmd)?"claude":Pn(o.cmd)?"codex":null:null,E=await Dt(t,{family:S}).run({cmd:o.cmd,args:[...o.args,i],env:o.env,cwd:t.cwd||e.cwd,timeoutMs:e.timeoutMs,heartbeatMs:e.heartbeatMs,label:"agent job",signal:n,job:t,prompt:i,model:o.model,permissionMode:o.permissionMode,hostFolders:Dn(e,t),leanCli:e.leanCli,mcp:e.leanCli?tt(e):null,sessionKey:`${t.workspaceId||e.workspace||""}:${e.agent||e.handle||""}`,clientVersion:ee,onData:d=>{f?(f.feed(d),c=f.live):(c+=String(d||""),l=us(`${l}
|
|
43
|
-
${
|
|
44
|
-
${
|
|
46
|
+
`,o=Math.max(0,n-Buffer.byteLength(r));return`${Buffer.from(String(e||"")).subarray(0,o).toString("utf8").replace(/\uFFFD+$/,"")}${r}`}function qo(e){let t=String(e||"").split(/\r?\n/),n="";if(t[0]?.trim()==="---")for(let r=1;r<t.length&&r<200&&t[r].trim()!=="---";r+=1){let o=/^description:\s*(.*)$/i.exec(t[r]);if(!o)continue;let s=o[1].trim();if(s&&!/^[|>][-+]?$/.test(s)){n=s.replace(/^["']|["']$/g,"");break}let i=[];for(let a=r+1;a<t.length&&a<200&&!(t[a].trim()==="---"||t[a].trim()&&!/^\s/.test(t[a]));a+=1)i.push(t[a].trim());n=i.join(" ").trim();break}if(!n){let r=t.findIndex((i,a)=>a>0&&i.trim()==="---"),s=(t[0]?.trim()==="---"&&r>0?t.slice(r+1):t).find(i=>i.trim()&&i.trim()!=="---");n=String(s||"").replace(/^#+\s*/,"").trim()}return n.slice(0,Go)}function Cn(e){try{return ot(e).slice(0,Fo)}catch{return[]}}async function Jo(e){let t;try{t=await st.open(e,"r")}catch{return null}try{let n=Buffer.alloc(he+1),{bytesRead:r}=await t.read(n,0,n.length,0);return n.subarray(0,r)}catch{return null}finally{await t.close().catch(()=>{})}}async function Ko(e,t){let n=await Jo(e.file);if(!n)return null;let r=n.toString("utf8"),o=qo(r),s=n.length>he,i=Math.min(he,Math.max(0,t)),a=Buffer.byteLength(r)>i;if(!s&&!a)return{skill:e.name,path:e.file,summary:o,content:r,truncated:!1};let d=s?await zo(e.file):0,c=s&&!a?`the file is ${d?`${d} bytes`:`over ${he} bytes`}; only the first ${he} were synced`:`this sync reached its ${xn}-byte ceiling`,l=i<Ho?In("",c,Number.MAX_SAFE_INTEGER):In(r,c,i);return{skill:e.name,path:e.file,summary:o,content:l,truncated:!0}}async function zo(e){try{return(await st.stat(e)).size}catch{return 0}}async function it(e={}){let t=[];for(let n of Cn(e)){if(!n.file){t.push(`${n.name}:-`);continue}try{let r=await st.stat(n.file);t.push(`${n.name}:${n.file}:${r.size}:${Math.floor(r.mtimeMs)}`)}catch{t.push(`${n.name}:-`)}}return t.join("|")}async function Tn(e={}){let t=[],n=0;for(let r of Cn(e))if(r.file)try{let o=await Ko(r,xn-n);if(!o)continue;n+=Buffer.byteLength(o.content),t.push(o)}catch{}return t}import{readFile as Wo}from"node:fs/promises";var Yo=new Set(["127.0.0.1","localhost","::1","[::1]"]);function Mn(e,t,n){let r=Number(e);return Number.isFinite(r)?Math.max(1,Math.min(n,Math.trunc(r))):t}function Vo(e,t){if(!e||typeof e!="object"||e.shared===!1)return null;let n=String(e.id||e.upstreamModel||`model-${t+1}`).trim();if(!n)return null;if(!/^[a-zA-Z0-9._:@/-]+$/.test(n))throw new Error(`Shared model id '${n}' may only contain letters, numbers, dot, underscore, colon, at, slash, or dash.`);let r=new URL(String(e.baseUrl||"http://127.0.0.1:11434/v1"));if(!Yo.has(r.hostname))throw new Error(`Shared model '${n}' must use a loopback endpoint.`);if(!["http:","https:"].includes(r.protocol))throw new Error(`Shared model '${n}' must use an HTTP endpoint.`);return{id:n.slice(0,160),name:String(e.name||n).trim().slice(0,160)||n,provider:String(e.provider||"local").trim().slice(0,80)||"local",protocol:"openai-chat",baseUrl:r.toString().replace(/\/$/,""),upstreamModel:String(e.upstreamModel||n).trim().slice(0,200)||n,apiKeyEnv:String(e.apiKeyEnv||"").trim().slice(0,120),capabilities:[...new Set((Array.isArray(e.capabilities)?e.capabilities:["text","streaming"]).map(o=>String(o||"").trim().toLowerCase()).filter(Boolean))].slice(0,16),...e.contextWindow?{contextWindow:Mn(e.contextWindow,void 0,1e7)}:{},maxConcurrency:Mn(e.maxConcurrency,1,64),shared:!0}}async function Nn(e){if(!e)return[];let t=JSON.parse(await Wo(e,"utf8")),n=Array.isArray(t)?t:t?.models;if(!Array.isArray(n))throw new Error("Shared model config must contain a models array.");return n.slice(0,32).map(Vo).filter(Boolean)}function On(e){return(Array.isArray(e)?e:[]).filter(t=>t?.shared).map(t=>({id:t.id,name:t.name,provider:t.provider,protocol:t.protocol,upstreamModel:t.upstreamModel,capabilities:[...t.capabilities],...t.contextWindow?{contextWindow:t.contextWindow}:{},maxConcurrency:t.maxConcurrency,shared:!0}))}async function $n({models:e,request:t,send:n,signal:r,fetchImpl:o=fetch,env:s=process.env}){let i=String(t?.requestId||"").trim();if(!i)throw new Error("Inference requestId is required.");let a=(Array.isArray(e)?e:[]).find(w=>w.id===t?.model);if(!a)throw new Error(`Shared model '${t?.model||""}' is not available.`);let d={"content-type":"application/json"},c=a.apiKeyEnv?s[a.apiKeyEnv]:"";c&&(d.authorization=`Bearer ${c}`),n({action:"agent_inference_started",requestId:i,model:a.id});let{requestId:l,model:g,type:m,action:y,...S}=t,f=await o(`${a.baseUrl}/chat/completions`,{method:"POST",headers:d,body:JSON.stringify({...S,model:a.upstreamModel,stream:t.stream===!0}),signal:r});if(!f.ok){let w=await f.text().catch(()=>"");throw new Error(w||`Local model returned HTTP ${f.status}.`)}if(t.stream===!0){if(!f.body)throw new Error("Local model returned an empty stream.");let w=f.body.getReader(),E=new TextDecoder,v="",A,N=h=>{let M=h.trim();if(!M.startsWith("data:"))return!1;let p=M.slice(5).trim();if(!p)return!1;if(p==="[DONE]")return!0;try{let I=JSON.parse(p);I?.usage&&(A=I.usage),n({action:"agent_inference_delta",requestId:i,model:a.id,chunk:I})}catch{}return!1},O=!1;for(;!O;){let{done:h,value:M}=await w.read();v+=E.decode(M||new Uint8Array,{stream:!h});let p=v.split(/\r?\n/);v=h?"":p.pop()||"";for(let I of p)if(N(I)){O=!0;break}if(h)break}v&&N(v);let u={action:"agent_inference_result",requestId:i,model:a.id,...A?{usage:A}:{}};return n(u),u}let b=await f.json();return n({action:"agent_inference_result",requestId:i,model:a.id,response:b}),b}Be();var hs=30*60*1e3,gs=15*1e3,Vn=2,ys=10*1024,Ss="claude-opus-4-8",oe="0.1.34";async function Le(e={}){let t=ws(e);t.sharedModels=t.share?await Nn(t.sharedModelsFile):[];let n=!1,r=null,o=null,s=null,i=null,a=0,d=null,c=null,l="",g=null,m=!1,y=null,S=new Map,f=Ft({send:T=>P(r,T),log:D}),b=null,w={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"},E=new Map,v=new Map,A=[],N=()=>w,O=()=>({connected:m&&!!t.cursorBuddyRuntime,mode:t.cursorBuddyRuntime?"agensis-cli":"agensis-cli-unclaimed",agentId:y?.agentId||y?.agent_id||t.agent,workspaceId:y?.workspaceId||y?.workspace_id||t.workspace,agensisUrl:t.url,handle:y?.handle||t.handle,name:y?.name||t.name,cwd:t.cwd,updatedAt:new Date().toISOString()}),u=()=>{b||!t.lanListener||(b=new _e.Server({port:0}),b.on("listening",()=>{let{port:T}=b.address();w={transport:"ws",listening:!0,addrs:Js(T),auth:"hub-pairwise"},D(`Agent-mesh LAN listener on port ${T}`),be(r,t,N())}),b.on("connection",T=>{let R=!1,_=setTimeout(()=>{if(!R)try{T.close(1008,"peer auth required")}catch{}},5e3);T.once("message",x=>{clearTimeout(_);let B=ft(x),j=B?.type==="peer_auth"?E.get(B.ticket):null;if(!j||j.fromAgentId!==B.fromAgentId||Date.now()>j.exp){try{T.close(1008,"invalid ticket")}catch{}return}E.delete(B.ticket),R=!0,T.on("message",J=>{let L=ft(J);L?.type==="agent_job"&&L.job?.id&&c.enqueue({...L.job,key:L.job.id,lane:Xn(L.job),ws:r}).accepted&&D(`Queued peer-handoff job ${L.job.id} from ${B.fromAgentId}`)})})}),b.on("error",T=>D(`LAN listener error: ${T?.message||T}`)))},h=()=>{if(b){try{b.close()}catch{}b=null}w={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"}},M=T=>new Promise((R,_)=>{if(!P(r,{action:"peer_ticket_request",targetAgentId:T})){_(new Error("hub socket not open"));return}let x=v.get(T)||[];x.push({resolve:R,reject:_}),v.set(T,x),setTimeout(()=>{let B=v.get(T)||[],j=B.findIndex(J=>J.resolve===R);j>=0&&(B.splice(j,1),_(new Error("peer ticket request timed out")))},1e4)}),p=()=>new Promise((T,R)=>{if(!P(r,{action:"peer_list_request"})){R(new Error("hub socket not open"));return}A.push(T),setTimeout(()=>{let _=A.indexOf(T);_>=0&&(A.splice(_,1),T([]))},1e4)}),I=async(T,R)=>{let _=null;try{let B=(await p()).find(L=>L.agentId===T&&L.reach?.listening&&L.reach.addrs?.length);if(!B)return!1;let j=await M(T),J=j.peer?.addrs?.[0]||B.reach.addrs[0];return!J?.host||!J?.port?!1:(_=new _e(`ws://${J.host}:${J.port}`),await new Promise((L,He)=>{_.once("open",L),_.once("error",He),setTimeout(()=>He(new Error("peer connect timed out")),5e3)}),P(_,{type:"peer_auth",ticket:j.ticket,fromAgentId:t.agent}),P(_,{type:"agent_job",job:R}),!0)}catch(x){return D(`Peer handoff to ${T} failed, falling back to hub relay: ${x?.message||x}`),!1}finally{try{_?.close()}catch{}}},k=()=>{n=!0,tr(S),f.shutdown("The agent daemon shut down before this was approved."),o&&clearTimeout(o),s&&clearInterval(s),i&&clearInterval(i),g&&(g.close().catch(()=>{}),g=null),h(),Gn(t,{status:"stopped",connected:!1});try{r?.close()}catch{}d&&d()};if(c=cn({concurrency:t.once?1:t.maxConcurrency,runJob:async(T,R)=>{await Ds(t,T,{...R,requestPermission:f.request}),t.once&&k()}}),t.cursorBuddyBridge)try{g=await Sn(t,{port:t.cursorBuddyPort,authSecret:t.cursorBuddyBridgeSecret||void 0,log:D,connectionProvider:O}),g?.secret&&(t.cursorBuddyBridgeSecret=g.secret)}catch(T){if(Ys(T)){let R=await Vs(t.cursorBuddyPort);if(R?.ok){let _=R.pid?` pid ${R.pid}`:"";D(`CursorBuddy local bridge already running on http://127.0.0.1:${t.cursorBuddyPort}${_}`)}else D(`CursorBuddy local bridge port ${t.cursorBuddyPort} is in use but did not answer health`)}else D(`CursorBuddy local bridge unavailable: ${T?.message||T}`);g=null}C.once("SIGINT",k),C.once("SIGTERM",k);let $=()=>{if(n)return;let T=_s(t.url,t.token,t);l="",D(`Connecting to ${T.replace(t.token,"redacted")}`),r=new _e(T),r.on("open",async()=>{m=!1,y=null,D(`Connected. Registering @${t.handle||"agent"} from ${t.cwd}`),P(r,{type:"auth",token:t.token});let R=await qn(t);P(r,{action:"agent_register",workspaceId:t.workspace,agentId:t.agent,handle:t.handle,name:t.name,host:Ee.hostname(),cwd:t.cwd,...R?{identity:R}:{},metadata:{codingCmd:t.codingCmd,model:t.model,permissionMode:t.permissionMode,permissionFlags:yt(t.permissionMode),once:t.once,runtime:"agensis",version:oe}}),s=setInterval(()=>{Promise.all([cr(t,N()).catch(()=>null),ut(t).catch(()=>null)]).then(([_,x])=>{P(r,{action:"agent_heartbeat",..._?{capabilitiesHash:_.capabilitiesHash,memoryHash:_.memoryHash}:{},..._?.skillsHash?{skillsHash:_.skillsHash}:{},metadata:mt(t,c,x,nr(t)?g?.getContext?.():null,S)})})},t.heartbeatMs),s.unref&&s.unref()}),r.on("message",R=>{let _=ft(R);if(_){if(_.type==="agent_registered"){m=!0,y=_.connection||_.agent||null,Qn(t,_.agent),D(`Registered as ${_.connection?.name||t.name} on ${_.connection?.host||Ee.hostname()}`),t.onRegistered&&Promise.resolve(t.onRegistered(t,_)).catch(x=>{D(`Profile save failed: ${x?.message||x}`)}),lt(t,_.agent).catch(()=>{}),Wn(t).catch(()=>{}),Zn(r,t),er(r,t),u(),be(r,t,N());return}if(_.type==="agent_config"){Qn(t,_.agent),D(`Updated config for @${t.handle||"agent"}: model=${t.model}, permission=${t.permissionMode}`),lt(t,_.agent).catch(()=>{});return}if(_.type==="agent_memory_refresh"){Zn(r,t),be(r,t,N());return}if(_.type==="agent_capabilities_refresh"){be(r,t,N());return}if(_.type==="agent_skills_refresh"){er(r,t);return}if(_.type==="agent_inference_cancel"){S.get(String(_.requestId||""))?.abort();return}if(_.type==="agent_job_cancel"){let x=String(_.jobId||"");x&&(f.cancelJob(x,_.reason||"Cancelled by Agensis"),c.cancel(x,_.reason||"Cancelled by Agensis")&&D(`Cancelled job ${x}`));return}if(_.type==="agent_permission_decision"){f.decide(_);return}if(_.type==="agent_inference_request"&&_.requestId){let x=String(_.requestId),B=t.sharedModels.find(L=>L.id===_.model),j=[...S.values()].filter(L=>L.model===_.model).length;if(!B){P(r,{action:"agent_inference_error",requestId:x,error:`Shared model '${_.model||""}' is not available.`});return}if(j>=B.maxConcurrency){P(r,{action:"agent_inference_error",requestId:x,error:"Shared model is at capacity.",code:"capacity_exhausted"});return}let J=new AbortController;S.set(x,{abort:()=>J.abort(),model:B.id}),P(r,{action:"agent_heartbeat",metadata:mt(t,c,null,null,S)}),$n({models:t.sharedModels,request:_,signal:J.signal,send:L=>P(r,L)}).catch(L=>{P(r,{action:"agent_inference_error",requestId:x,error:J.signal.aborted?"Inference cancelled.":L?.message||String(L),code:J.signal.aborted?"cancelled":"inference_failed"})}).finally(()=>{S.delete(x),P(r,{action:"agent_heartbeat",metadata:mt(t,c,null,null,S)})});return}if(_.type==="peer_ticket"){let x=_.peer?.agentId,B=v.get(x)||[],j=B.shift();B.length?v.set(x,B):v.delete(x),j&&j.resolve(_);return}if(_.type==="peer_ticket_grant"){E.set(_.ticket,{fromAgentId:_.fromAgentId,exp:_.exp});return}if(_.type==="peer_list"){let x=A.shift();x&&x(Array.isArray(_.peers)?_.peers:[]);return}if(_.type==="agent_reach_disable"){h(),be(r,t,N());return}if(_.type==="error"){D(`Server rejected request: ${_.message||"unknown error"}`);return}if(_.type==="agent_disabled"){m=!1,y=null,D(`Agent disabled by Agensis: ${_.reason||"deactivated"}`),k();return}if(_.type==="agent_job"&&_.job?.id){let x=c.enqueue({..._.job,key:_.job.id,lane:Xn(_.job),ws:r});x.accepted&&(a+=1,D(`Queued job ${_.job.id} at position ${x.position}`),t.once&&c.idle().then(()=>k()))}}}),r.on("close",(R,_)=>{tr(S),f.shutdown(),m=!1,y=null;let x=String(_||"");if(D(`Socket closed (${R||"no-code"}${x?`: ${x}`:""})`),s&&(clearInterval(s),s=null),R===1008&&/agent deactivated|authentication failed/i.test(x)){D("Stopping daemon because Agensis rejected this agent connection."),k();return}if(l==="ECONNREFUSED"&&Es(t.url)){D("Local agent backend is not running on 127.0.0.1:3142."),D("Start it in another terminal with: npm run backend"),D("Then rerun this connect command."),k();return}t.once&&a>0&&c.active()===0&&c.size()===0&&k(),!(n||t.once)&&(o=setTimeout($,2e3),o.unref&&o.unref())}),r.on("error",R=>{l=R?.code||"",D(`Socket error: ${R?.message||R}`)})},q=async()=>{let T=await ut(t).catch(()=>null);await Fn(t,{busy:c.active()>0,active:c.active(),queueSize:c.size(),connected:r?.readyState===_e.OPEN,agentStatus:T?.status,agentNote:T?.note}).catch(()=>{})};q(),i=setInterval(()=>{q()},t.heartbeatMs),i.unref&&i.unref(),$(),await new Promise(T=>{let R=setInterval(async()=>{t.once&&a>0&&c.active()===0&&c.size()===0&&k(),n&&k()},500);d=()=>{clearInterval(R),T()}}),d=null,C.off("SIGINT",k),C.off("SIGTERM",k)}function ws(e){let t=bs(e.cursorBuddyBridge),n=e.noCoding===!0||C.env.AGENSIS_NO_CODING==="1",o=!ne(e.fullCliContext,ne(C.env.AGENSIS_FULL_CLI_CONTEXT,!1))&&ne(e.leanCli,!0),s={url:String(e.url||e.baseUrl||C.env.AGENSIS_URL||"").trim(),token:String(e.token||C.env.AGENSIS_TOKEN||"").trim(),workspace:String(e.workspace||e.workspaceId||C.env.AGENSIS_WORKSPACE||C.env.AGENSIS_WORKSPACE_ID||"").trim(),agent:String(e.agent||e.agentId||C.env.AGENSIS_AGENT||C.env.AGENSIS_AGENT_ID||"").trim(),handle:dr(e.handle||C.env.AGENSIS_HANDLE||e.name||C.env.AGENSIS_NAME||"agent"),name:String(e.name||C.env.AGENSIS_NAME||e.handle||C.env.AGENSIS_HANDLE||"agensis Agent").trim(),cwd:String(e.cwd||C.env.AGENSIS_CWD||C.cwd()).trim(),codingCmd:n?"":String(e.codingCmd||C.env.AGENSIS_CODING_CMD||C.env.CODING_CMD||"claude -p").trim(),ampCmd:String(e.ampCmd||C.env.AGENSIS_AMP_CMD||"amp").trim()||"amp",model:gt(e.model||C.env.AGENSIS_MODEL||C.env.CLAUDE_MODEL||""),permissionMode:Ue(e.permissionMode||e.permission_mode||e.permission||C.env.AGENSIS_PERMISSION_MODE||"default"),timeoutMs:Number(e.timeoutMs||C.env.AGENSIS_TIMEOUT_MS||hs),heartbeatMs:Number(e.heartbeatMs||C.env.AGENSIS_HEARTBEAT_MS||gs),maxConcurrency:Math.max(1,Number(e.maxConcurrency||C.env.AGENSIS_MAX_CONCURRENCY||Vn)||Vn),once:!!(e.once||C.env.AGENSIS_ONCE==="1"),exitOnOnce:!!e.exitOnOnce,onRegistered:typeof e.onRegistered=="function"?e.onRegistered:null,primaryDaemon:!!(e.primaryDaemon||C.env.AGENSIS_PRIMARY_DAEMON==="1"),cursorBuddyRuntime:!!(e.cursorBuddyRuntime||C.env.AGENSIS_CURSORBUDDY_RUNTIME==="1"),cursorBuddyBridge:t,cursorBuddyPort:Number(e.cursorBuddyPort||C.env.AGENSIS_CURSORBUDDY_PORT||8787),cursorBuddyBridgeSecret:String(e.cursorBuddyBridgeSecret||C.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim(),cursorBuddyModel:String(e.cursorBuddyModel||C.env.AGENSIS_CURSORBUDDY_MODEL||"haiku-4.5").trim(),lanListener:!!(e.lanListener||e.lan||C.env.AGENSIS_LAN==="1"),share:!!(e.share||C.env.AGENSIS_SHARE==="1"),sharedModelsFile:String(e.sharedModelsFile||C.env.AGENSIS_SHARED_MODELS_FILE||"").trim(),noCoding:n,leanCli:o,fastConnection:ne(e.fastConnection,ne(C.env.AGENSIS_FAST_CONNECTION,!0)),syncMemory:ne(e.syncMemory,C.env.AGENSIS_SYNC_MEMORY==="1"),syncSkills:ne(e.syncSkills,ne(C.env.AGENSIS_SYNC_SKILLS,!0)),hostFolders:ir(e.hostFolders??e.host_folders??C.env.AGENSIS_HOST_FOLDERS)};s.sharedModelsFile&&!le.isAbsolute(s.sharedModelsFile)&&(s.sharedModelsFile=le.resolve(s.cwd,s.sharedModelsFile));let i=[];if(s.url||i.push("--url"),s.token||i.push("--token"),s.workspace||i.push("--workspace"),s.agent||i.push("--agent"),s.share&&!s.sharedModelsFile&&i.push("--shared-models-file"),i.length)throw new Error(`Missing required option(s): ${i.join(", ")}`);return s}function ne(e,t){return e==null||e===""?t:typeof e=="boolean"?e:!/^(0|false|off|no)$/i.test(String(e).trim())}function bs(e){let t=C.env.AGENSIS_CURSORBUDDY_BRIDGE;return t!==void 0&&t!==""?!/^(0|false|off|no)$/i.test(String(t).trim()):e==null||e===""?!1:typeof e=="boolean"?e:!/^(0|false|off|no)$/i.test(String(e).trim())}function _s(e,t,n={}){let r=ht(e);return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.pathname="/backend/ws",r.search="",n.workspace&&r.searchParams.set("workspaceId",n.workspace),n.agent&&r.searchParams.set("agentId",n.agent),r.toString()}function ht(e){let t=new URL(e);return vs(t)&&(t.protocol="http:",t.hostname="127.0.0.1",t.port="3142"),t}function vs(e){if(!(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="0.0.0.0")||e.port==="3142")return!1;if(e.port==="5173"||e.port==="8888")return!0;let t=Number(e.port||0);return t>=49152&&t<=65535}function Es(e){try{let t=ht(e);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="0.0.0.0")&&t.port==="3142"}catch{return!1}}function Xn(e){let t=String(e?.sessionId||""),n=String(e?.threadParentId||"");return`${t}::${n}`}var ks=/\b(cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\b/i,As=[/\b(?:make|have|tell)\s+(?:the\s+)?(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\s+(?:say|speak)\s+(.+)$/i];function Is(e){return String(e||"").trim().replace(/^[`"'“”‘’]+|[`"'“”‘’?.!]+$/g,"").trim().slice(0,1200)}function xs(e){for(let t of As){let n=String(e||"").match(t),r=Is(n?.[1]||"");if(r)return r}return""}function Cs(e){let t=String(e||"").replace(/\s+/g," ").trim();if(!t)return"";let n=/latest user message\s*:\s*/gi,r=null,o=null;for(;r=n.exec(t);)o=r;if(!o)return"";let s=t.slice(o.index+o[0].length).trim(),i=s.search(/\b(Return a useful response|Conversation context follows|Previous user|Previous assistant|Diagnostic notes|System prompt|Developer message)\b/i);return(i>=0?s.slice(0,i):s).trim().replace(/^["'“”‘’]+|["'“”‘’]+$/g,"").trim()}function Ts(e){let t=String(e||"").replace(/\s+/g," ").trim(),r=Cs(t)||t;if(!r)return"";if(r.length<=500)return r;let o=[/\b(?:can you\s+)?(?:make|have|tell)\s+(?:the\s+)?(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\s+(?:wave|waves|waving|say|speak)\b.{0,160}/i,/\b(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\b.{0,120}\b(?:wave|waves|waving|say|speak|open|show|hide|hush|close|dismiss|clear)\b.{0,160}/i,/\b(?:wave|open|show|hide|hush|close|dismiss|clear)\b.{0,120}\b(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy|bubble|prompt|dialog|panel|options|menu)\b/i,/\b(?:say|speak)\s+[`"'“”‘’]?.{1,180}/i];for(let s of o){let i=r.match(s);if(i?.[0])return i[0].trim()}return""}function Ms(e){let t=Ts(e);if(!t)return null;let n=/^(open|show|hide|hush|close|dismiss)\b/i.test(t),r=ks.test(t);if(!n&&!r)return null;let o="agensis-native-control";if(/\b(hide|hush|close|dismiss|clear)\b.*\b(bubble|prompt|dialog|panel|options|menu)\b/i.test(t)||/^hush\b/i.test(t))return{action:"hush",source:o};if(/\b(open|show|bring up|get back|display)\b.*\b(prompt|bubble|dialog|panel|options|menu)\b/i.test(t)||/^open\b/i.test(t))return{action:"open",source:o};let s=xs(t);return s&&r?{action:"say",text:s,source:o}:r&&/\b(wave|waves|waving)\b/i.test(t)?{action:"wave",text:s,source:o}:null}async function Ns(e,t){let r=`http://127.0.0.1:${Number(e.cursorBuddyPort||8787)}/cursorbuddy/control`,o=String(e.cursorBuddyBridgeSecret||C.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim(),s={"content-type":"application/json"};o&&(s.authorization=`Bearer ${o}`,s["x-agensis-bridge-secret"]=o);let i=await fetch(r,{method:"POST",headers:s,body:JSON.stringify(t)}),a=null;try{a=await i.json()}catch{a=null}if(!i.ok||a?.ok===!1)throw new Error(a?.error||`CursorBuddy control failed with HTTP ${i.status}`);return a}function Os(e){return e.action==="wave"?"Sent CursorBuddy a wave command.":e.action==="say"?`Sent CursorBuddy speech: ${e.text||""}`.trim():e.action==="open"?"Opened CursorBuddy's prompt.":e.action==="hush"?"Dismissed CursorBuddy's bubble.":e.action==="choose"?"Sent CursorBuddy options.":"Sent CursorBuddy control command."}function nr(e={}){return e.cursorBuddyBridge===!1?!1:!!(e.cursorBuddyRuntime||e.primaryDaemon)}async function $s(e,t,n,r){let o="cursorbuddy-control",s="native",i=[],a=(l="")=>{P(t.ws,{action:"agent_job_delta",jobId:t.id,content:l,elapsedMs:Date.now()-r,model:o,permissionMode:s,permissionFlags:i})};a("");let d="",c="";try{await Ns(e,n),d=Os(n),a(d)}catch(l){c=String(l?.message||l),d=`CursorBuddy control failed: ${c}`,a(d)}P(t.ws,{action:"agent_job_result",jobId:t.id,response:d,error:c,elapsedMs:Date.now()-r,model:o,permissionMode:s,permissionFlags:i}),D(`Finished native CursorBuddy ${n.action} job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s`)}async function Ds(e,t,{signal:n,requestPermission:r=null}){let o=Date.now();if(D(`Starting job ${t.id}`),nn(t)){await Rs(e,t,{signal:n,started:o}),e.once&&(D("One-shot Amp job complete; exiting."),setTimeout(()=>C.exit(0),150));return}let s=Ms(t.prompt);if(s&&nr(e)){await $s(e,t,s,o),e.once&&(D("One-shot CursorBuddy control job complete; exiting."),setTimeout(()=>C.exit(0),150));return}let i=Ls(e,t),a=await Bs(e,t),d="",c="",l=0,g=(h="")=>{P(t.ws,{action:"agent_job_delta",jobId:t.id,content:h,elapsedMs:Date.now()-o,model:i.model,permissionMode:i.permissionMode,permissionFlags:i.permissionFlags})},m=h=>{P(t.ws,{action:"agent_job_step",jobId:t.id,kind:h.kind,name:h.name,detail:h.detail,elapsedMs:Date.now()-o})},y=h=>{P(t.ws,{action:"agent_job_segment",jobId:t.id,text:h.text,elapsedMs:Date.now()-o})};g("");let S=i.streamJson?rr({onStep:m,onSegment:y}):null,f=setInterval(()=>g(d),1e3);f.unref&&f.unref();let b=!/[\\/]/.test(i.cmd),w=e.fastConnection&&b?lr(i.cmd)?"claude":ur(i.cmd)?"codex":null:null,v=await en(t,{family:w}).run({cmd:i.cmd,args:[...i.args,a],env:i.env,cwd:t.cwd||e.cwd,timeoutMs:e.timeoutMs,heartbeatMs:e.heartbeatMs,label:"agent job",signal:n,job:t,prompt:a,model:i.model,permissionMode:i.permissionMode,hostFolders:ar(e,t),leanCli:e.leanCli,mcp:e.leanCli?pt(e):null,sessionKey:`${t.workspaceId||e.workspace||""}:${e.agent||e.handle||""}`,clientVersion:oe,requestPermission:r,onData:h=>{S?(S.feed(h),d=S.live):(d+=String(h||""),c=Ws(`${c}
|
|
47
|
+
${h}`));let M=Date.now();M-l>150&&(l=M,g(d))}});clearInterval(f),S&&(S.end(),d=S.live,g(d));let A=String(v.stdout||"").trim(),N=String(v.stderr||"").trim(),O=v.error?v.error.message:v.status===0?"":N||`Command exited with status ${v.status}`,u=S?S.result||(O?"":N):A||(O?"":N)||c||"";P(t.ws,{action:"agent_job_result",jobId:t.id,response:u,error:O,elapsedMs:Date.now()-o,model:i.model,permissionMode:i.permissionMode,permissionFlags:i.permissionFlags}),D(`Finished job ${t.id} in ${Math.round((Date.now()-o)/1e3)}s`),e.once&&(D("One-shot job complete; exiting."),setTimeout(()=>C.exit(0),150))}async function Rs(e,t,{signal:n,started:r=Date.now()}={}){let o="amp-orb",s="amp-managed",i=[],a=(u="")=>P(t.ws,{action:"agent_job_delta",jobId:t.id,content:u,elapsedMs:Date.now()-r,model:o,permissionMode:s,permissionFlags:i}),d=u=>P(t.ws,{action:"agent_job_step",jobId:t.id,kind:u.kind,name:u.name,detail:u.detail,elapsedMs:Date.now()-r}),c=u=>P(t.ws,{action:"agent_job_segment",jobId:t.id,text:u.text,elapsedMs:Date.now()-r}),l=({response:u="",error:h="",errorCode:M="",threadId:p=""}={})=>{let I=me(p);P(t.ws,{action:"agent_job_result",jobId:t.id,response:u,error:h,errorCode:M||void 0,elapsedMs:Date.now()-r,model:o,permissionMode:s,permissionFlags:i,metadata:{runtime:"amp",...I?{ampThreadId:I,ampThreadUrl:`https://ampcode.com/threads/${I}`}:{},...M?{ampErrorCode:M}:{}}})};a("");let g=le.resolve(String(t.cwd||e.cwd)),m=[e.cwd,...e.hostFolders||[]];try{await sn({cwd:g,allowedRoots:m});let u=await Ve({cwd:g,executable:e.ampCmd,signal:n});if(!u.available)throw X(u.reason||"amp_cli_crashed")}catch(u){let h=n?.aborted?"amp_turn_cancelled":String(u?.code||"amp_cli_crashed");l({error:u?.message||X(h).message,errorCode:h}),D(`Amp job ${t.id} refused: ${h}`);return}let y=String(t?.runtime?.threadId||t?.ampThreadId||t?.metadata?.ampThreadId||"").trim(),S=me(y);if(t?.runtime?.continuationRequired===!0&&!S||y&&!S){let u=X("amp_thread_not_found");l({error:u.message,errorCode:u.code}),D(`Amp job ${t.id} refused: ${u.code}`);return}let f=rn({executable:e.ampCmd,prompt:String(t.prompt||""),threadId:S}),b=rr({onStep:d,onSegment:c}),w=on(),E="",v=0,A=setInterval(()=>a(E),1e3);A.unref&&A.unref();let N=await V({cmd:f.cmd,args:f.args,cwd:g,timeoutMs:e.timeoutMs,heartbeatMs:e.heartbeatMs,label:"Amp orb turn",signal:n,onData:u=>{b.feed(u),w.feed(u),E=b.live;let h=Date.now();h-v>150&&(v=h,a(E))}});clearInterval(A),b.end(),w.end(),E=b.live,a(E);let O=w.threadId||S;if(N.status!==0||N.error){let u=an(N);l({error:u.message,errorCode:u.code,threadId:O}),D(`Amp job ${t.id} failed: ${u.code}`);return}if(!O){let u=X("amp_stream_invalid");l({error:u.message,errorCode:u.code}),D(`Amp job ${t.id} failed: ${u.code}`);return}l({response:b.result||"",threadId:O}),D(`Finished Amp job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s (${O})`)}async function Bs(e,t){let n=t.agent||{},r=Array.isArray(n.skills)?n.skills.join(", "):String(n.skills||""),o=Array.isArray(n.tools)?n.tools.join(", "):String(n.tools||""),s=or(e,t),i=sr(e,t),a=await Yn(e).catch(()=>null),d=a?`Heartbeat (recurring instructions \u2014 edit at ${jn(e)}):
|
|
48
|
+
${a}`:"",l=["You are running as a local agensis workspace agent daemon.",`Workspace: ${t.workspaceId||e.workspace}`,`Channel session: ${t.sessionId||""}`,`Agent: ${n.name||e.name} (@${n.handle||e.handle})`,`Requested model: ${s}`,`Permission mode: ${i}`,n.description?`Description:
|
|
45
49
|
${n.description}`:"",n.soul?`Soul:
|
|
46
50
|
${n.soul}`:"",n.system_prompt?`System instructions:
|
|
47
51
|
${n.system_prompt}`:"",n.instructions?`Additional instructions:
|
|
48
|
-
${n.instructions}`:"",
|
|
49
|
-
${
|
|
50
|
-
${r}`:"",'Thread widgets: this chat has a right-side widget rail the human watches. When you work a multi-step task here, surface it: call create_thread_item (kind "todo", "plan", or "blocker") with the Channel session id above to post your plan steps and to-dos, mark them done with update_thread_item as you finish, and raise a "blocker" when you need the human to answer something (read their reply from the item response via list_thread_items). Keep it to a few real items, not every micro-step; skip it for quick one-off replies.',`Status file: you can report your own working status by overwriting the JSON file at ${
|
|
52
|
+
${n.instructions}`:"",o?`Enabled tools:
|
|
53
|
+
${o}`:"",r?`Enabled skills:
|
|
54
|
+
${r}`:"",'Thread widgets: this chat has a right-side widget rail the human watches. When you work a multi-step task here, surface it: call create_thread_item (kind "todo", "plan", or "blocker") with the Channel session id above to post your plan steps and to-dos, mark them done with update_thread_item as you finish, and raise a "blocker" when you need the human to answer something (read their reply from the item response via list_thread_items). Keep it to a few real items, not every micro-step; skip it for quick one-off replies.',`Status file: you can report your own working status by overwriting the JSON file at ${Un(e)} with e.g. {"status":"working","note":"short summary of what you're doing"}. Your daemon reads it on its next heartbeat (~${Math.round((e.heartbeatMs||15e3)/1e3)}s) and surfaces it on your agent card. Optional and best-effort \u2014 overwrite the whole file, keep note under ~200 chars, and there's no need to clear it.`,`Identity file: you can declare how you appear \u2014 avatar, description, soul, and voice ({"cartesia_voice_id","speed","emotion"}) \u2014 by writing JSON to ${dt(e)}, e.g. {"avatar":"FX","description":"...","voice":{"emotion":"calm"}}. Your daemon sends it the next time it connects; anything a human has set in the app always wins, and "name" only applies to brand-new agents.`,d,"User message:",String(t.prompt||""),"Identity boundary: answer as the workspace agent named above. Do not adopt the identity of any browser, desktop, avatar, pet, widget, or UI surface.","Respond with a clear channel-ready result. Use markdown for structure \u2014 bullets, headers, and code blocks where appropriate. If you changed files, summarize the files and verification. If you cannot complete it, say exactly why."].filter(Boolean).join(`
|
|
51
55
|
|
|
52
|
-
`);return e.leanCli?
|
|
56
|
+
`);return e.leanCli?Ps(l,ys):l}function Ps(e,t){let n=String(e||"");if(Buffer.byteLength(n,"utf8")<=t)return n;let r=`[... older or optional Agensis context omitted ...]
|
|
53
57
|
|
|
54
|
-
`,
|
|
55
|
-
`))>=0;)
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
`),Y.stdout.write(`[agensis]
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
`),
|
|
58
|
+
`,o=Math.max(0,t-Buffer.byteLength(r,"utf8")),s=[...n],i=0,a=s.length;for(;i<a;){let d=Math.ceil((i+a)/2),c=s.slice(s.length-d).join("");Buffer.byteLength(c,"utf8")<=o?i=d:a=d-1}return r+s.slice(s.length-i).join("")}function Ls(e,t){let{cmd:n,args:r}=zs(e.codingCmd),o=or(e,t),s=sr(e,t),i=Ks(r),a=yt(s),d=ar(e,t);if(lr(n)){let c=[...i];o&&c.push("--model",o);let l;if(e.leanCli){let S=pt(e);c.push("--no-session-persistence","--safe-mode","--mcp-config",JSON.stringify({mcpServers:{agensis:{type:"http",url:S.url,headers:{Authorization:"Bearer ${AGENSIS_MCP_TOKEN}"}}}}),"--strict-mcp-config"),l=S.env}if(s==="accept_edits"&&c.push("--permission-mode","acceptEdits"),s==="yolo"){let S=t&&t.agent&&t.agent.run_mode==="sandbox",f=typeof C.getuid=="function"&&C.getuid()===0,b=S||js(),w=C.env.AGENSIS_ALLOW_ROOT_SKIP_PERMISSIONS==="1";b||!f||w?c.push("--dangerously-skip-permissions"):(a=[],D("running as root with no sandbox detected: dropping --dangerously-skip-permissions (Claude rejects it as root). Set AGENSIS_ALLOW_ROOT_SKIP_PERMISSIONS=1 if this host really is sandboxed."))}let g=i.some(S=>S==="--output-format"||String(S).startsWith("--output-format=")),m=i.includes("-p")||i.includes("--print"),y=!1;!g&&m?(c.push("--output-format","stream-json","--include-partial-messages"),i.includes("--verbose")||c.push("--verbose"),y=!0):g&&(y=i.some(S=>/stream-json/.test(String(S))));for(let S of d)c.push("--add-dir",S);return{cmd:n,args:c,model:o,permissionMode:s,permissionFlags:a,streamJson:y,env:l}}if(ur(n)){let c=[...i];o&&c.push("--model",o);let l;if(e.leanCli&&i.includes("exec")){let g=pt(e);c.push("--ephemeral","--ignore-user-config","--ignore-rules","--disable","plugins","--disable","memories","--disable","hooks","--disable","skill_search","-c","project_doc_max_bytes=0","-c",`mcp_servers.agensis.url=${JSON.stringify(g.url)}`,"-c",'mcp_servers.agensis.bearer_token_env_var="AGENSIS_MCP_TOKEN"'),l=g.env}return s==="yolo"&&c.push("--sandbox","danger-full-access","--ask-for-approval","never"),{cmd:n,args:c,model:o,permissionMode:s,permissionFlags:a,env:l}}return{cmd:n,args:r,model:o,permissionMode:s,permissionFlags:a}}function pt(e){let t=ht(e.url);return t.pathname="/backend/mcp",t.search="",t.hash="",{url:t.toString(),env:{AGENSIS_MCP_TOKEN:e.token}}}function rr({onStep:e,onSegment:t}={}){let n="",r="",o=!1,s="",i="",a=null,d=!1,c=!1,l=new Set,g=f=>{if(!(typeof e!="function"||!f.name))try{e(f)}catch{}},m=f=>{if(typeof t=="function"){i+=o?r:s,r="",s="";try{t(f)}catch{}}},y=f=>{if(!f||typeof f!="object")return;if(f.type==="agensis_step"){let w=f.step;w&&typeof w=="object"&&(d=!0,g({kind:w.kind||"tool",name:String(w.name||""),detail:String(w.detail||"")}));return}if(f.type==="agensis_segment"){let w=f.segment;w&&typeof w=="object"&&(c=!0,m({text:String(w.text||"")}));return}let b=f.event&&f.event.delta||f.delta;if(b&&b.type==="text_delta"&&typeof b.text=="string"){o=!0,r+=b.text;return}if(f.type==="result"&&typeof f.result=="string"){a=f.result;return}if(f.type==="assistant"&&f.message&&Array.isArray(f.message.content)){let w=f.message.content.filter(E=>E&&E.type==="text"&&typeof E.text=="string").map(E=>E.text).join("");if(w&&(s+=w),w&&!c&&m({text:w}),!d)for(let E of f.message.content){if(!E||E.type!=="tool_use")continue;let v=typeof E.id=="string"?E.id:"";if(v){if(l.has(v))continue;l.add(v)}g({kind:"tool",name:String(E.name||""),detail:Ce(E.input)})}}},S=f=>{let b=String(f).trim();if(b)try{y(JSON.parse(b))}catch{}};return{feed(f){n+=String(f||"");let b;for(;(b=n.indexOf(`
|
|
59
|
+
`))>=0;)S(n.slice(0,b)),n=n.slice(b+1)},end(){n&&(S(n),n="")},get live(){return o?r:s},get result(){return a??i+(o?r:s)}}}function or(e,t){return gt(t?.agent?.model||t?.model||e.model)}function gt(e){let t=String(e||"").trim();return!t||t==="auto"||t==="claude-fable-5"?Ss:t}function sr(e,t){return Ue(t?.agent?.permissionMode||t?.agent?.permission_mode||t?.permissionMode||t?.permission_mode||e.permissionMode)}function Ue(e){let t=String(e||"").trim().toLowerCase().replace(/[-\s]+/g,"_");return["yolo","no_sandbox","danger","danger_full_access","dangerously_skip_permissions"].includes(t)?"yolo":["accept_edits","acceptedits","auto_approve","auto_approve_edits"].includes(t)?"accept_edits":"default"}function yt(e){return Ue(e)==="yolo"?["--no-sandbox","--yolo"]:[]}function ir(e){let t=Array.isArray(e)?e:String(e||"").split(/[,\n]/),n=new Set,r=[];for(let o of t){let s=String(o||"").trim();!s||n.has(s)||(n.add(s),r.push(s))}return r}function Us(e,t){let n=t?.agent?.metadata?.host_folders??t?.agent?.hostFolders??t?.hostFolders??t?.host_folders,r=ir(n);return r.length>0?r:e.hostFolders||[]}function ar(e,t){let n=Us(e,t),r=K({workspace:e.workspace,agent:e.agent});return r&&!n.includes(r)?[...n,r]:n}var ce;function js(){if(ce!==void 0)return ce;let e=C.env;if(e.AGENSIS_ALLOW_ROOT_SKIP_PERMISSIONS==="1"||e.AGENSIS_SANDBOX_HOST==="1"||e.IS_SANDBOX==="1")return ce=!0;if(e.AGENSIS_NO_SANDBOX_AUTODETECT==="1")return ce=!1;try{if(ve.existsSync("/.dockerenv")||ve.existsSync("/run/.containerenv"))return ce=!0}catch{}try{let t=ve.readFileSync("/proc/1/cgroup","utf8");if(/docker|kubepods|containerd|lxc|podman/i.test(t))return ce=!0}catch{}return ce=!1}function mt(e,t,n,r=null,o=null){let s={busy:t.active()>0,queueSize:t.size(),cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,permissionFlags:yt(e.permissionMode),daemon:{runtime:"agensis-cli",version:oe,pid:C.pid,node:C.version,platform:C.platform,arch:C.arch,host:Ee.hostname(),cwd:e.cwd}};if(o instanceof Map){let i={};for(let a of o.values()){let d=String(a?.model||"");d&&(i[d]=(i[d]||0)+1)}s.activeInferenceByModel=i}return r&&typeof r=="object"&&(s.cursorBuddy=Fs(r)),n?.status&&(s.agentStatus=n.status),n?.note&&(s.agentNote=n.note),(n?.status||n?.note)&&(s.agentStatusAt=new Date().toISOString()),s}function Fs(e={}){let t=e.client&&typeof e.client=="object"?e.client:{},n=e.page&&typeof e.page=="object"?e.page:{},r=e.runtime&&typeof e.runtime=="object"?e.runtime:{},o=e.manifest&&typeof e.manifest=="object"?e.manifest:{},s=e.project&&typeof e.project=="object"?e.project:{};return{surface:String(e.surface||"").slice(0,80),instanceId:String(e.instanceId||"").slice(0,140),url:String(e.url||"").slice(0,2048),title:String(e.title||"").slice(0,300),origin:String(n.origin||"").slice(0,300),hostname:String(n.hostname||"").slice(0,200),pathname:String(n.pathname||"").slice(0,500),visibilityState:String(n.visibilityState||"").slice(0,40),focused:n.focused===!0,userAgent:String(t.userAgent||"").slice(0,500),platform:String(t.platform||"").slice(0,120),language:String(t.language||"").slice(0,80),viewport:t.viewport&&typeof t.viewport=="object"?{width:Number(t.viewport.width)||0,height:Number(t.viewport.height)||0,devicePixelRatio:Number(t.viewport.devicePixelRatio)||0}:null,runtimeMarker:String(r.marker||"").slice(0,120),extensionMarker:String(r.extensionMarker||"").slice(0,120),manifest:{name:String(o.name||"").slice(0,120),version:String(o.version||"").slice(0,80),source:String(o.source||"").slice(0,500)},project:{name:String(s.name||"").slice(0,120),root:String(s.root||"").slice(0,500),agent:String(s.agent||"").slice(0,80)},updatedAt:String(e.updatedAt||"").slice(0,80)}}function Qn(e,t){if(!t||typeof t!="object")return;t.name&&(e.name=String(t.name).trim()||e.name),(t.handle||t.name)&&(e.handle=dr(t.handle||t.name||e.handle)),t.model&&(e.model=gt(t.model));let n=t.permissionMode||t.permission_mode;n&&(e.permissionMode=Ue(n)),(t.memory_dir!==void 0||t.memoryDir!==void 0)&&(e.memoryDir=String(t.memory_dir??t.memoryDir??"").trim())}function Gs(){let e=["amp","claude","codex","gh","node","npm","python3","git","fly","vercel"],t=(C.env.PATH||"").split(le.delimiter).filter(Boolean);return e.filter(n=>t.some(r=>{try{return ve.existsSync(le.join(r,n))}catch{return!1}}))}function Hs(){try{let e=ve.readFileSync(le.join(Ee.homedir(),".claude.json"),"utf8"),n=JSON.parse(e)?.mcpServers;if(n&&typeof n=="object")return Object.keys(n).sort()}catch{}return[]}function Pe(e){return ps.createHash("sha1").update(String(e)).digest("hex").slice(0,16)}async function cr(e,t=null){let n=An({cwd:e.cwd}),r=kn({cwd:e.cwd}),o=Gs(),s=Hs(),i=e.syncMemory&&Ze({cwd:e.cwd,memoryDir:e.memoryDir})||null,a=On(e.sharedModels),c={amp:await qs(e)},l=Pe(JSON.stringify({skills:n,commands:r,clis:o,mcpServers:s,memoryRoot:i,sharedModels:a,runtimes:c,codingRoute:!!e.codingCmd,shared:e.share,reach:t||null})),g=Pe(await _n(i)),m=e.syncSkills?Pe(await it({cwd:e.cwd})):null;return{skills:n,commands:r,clis:o,mcpServers:s,memoryRoot:i,sharedModels:a,runtimes:c,codingRoute:!!e.codingCmd,shared:e.share,reach:t||null,capabilitiesHash:l,memoryHash:g,skillsHash:m}}var re=null;async function qs(e){let t=`${e.ampCmd}
|
|
60
|
+
${le.resolve(e.cwd)}`;if(re?.key===t&&Date.now()-re.at<6e4)return re.value??re.pending;let n=Ve({cwd:e.cwd,executable:e.ampCmd});re={key:t,at:Date.now(),pending:n};try{let r=await n;return re={key:t,at:Date.now(),value:r},r}catch(r){throw re?.pending===n&&(re=null),r}}async function be(e,t,n=null){try{let r=await cr(t,n);P(e,{action:"agent_capabilities_sync",workspaceId:t.workspace,agentId:t.agent,skills:r.skills,commands:r.commands,clis:r.clis,mcpServers:r.mcpServers,sharedModels:r.sharedModels,runtimes:r.runtimes,codingRoute:r.codingRoute,shared:r.shared,memoryRoot:r.memoryRoot,reach:r.reach||void 0,hash:r.capabilitiesHash,memoryHash:r.memoryHash,skillsHash:r.skillsHash}),D(`Capabilities synced \u2014 skills:${r.skills.length} commands:${r.commands.length} clis:${r.clis.length} mcp:${r.mcpServers.length}`)}catch(r){D(`Capabilities sync skipped: ${r?.message||r}`)}}function Js(e){let t=Ee.networkInterfaces(),n=[];for(let r of Object.values(t))for(let o of r||[])o.family==="IPv4"&&!o.internal&&n.push({host:o.address,port:e,scope:"lan"});return n.slice(0,4)}async function Zn(e,t){try{if(!t.syncMemory)return;let n=Ze({cwd:t.cwd,memoryDir:t.memoryDir});if(!n)return;let r=await vn(n);P(e,{action:"agent_memory_sync",workspaceId:t.workspace,agentId:t.agent,root:n,files:r}),D(`Synced ${r.length} memory file${r.length===1?"":"s"} from ${n}`)}catch(n){D(`Memory sync skipped: ${n?.message||n}`)}}async function er(e,t){try{if(!t.syncSkills)return;let n=Pe(await it({cwd:t.cwd})),r=await Tn({cwd:t.cwd});P(e,{action:"agent_skill_sync",workspaceId:t.workspace,agentId:t.agent,hash:n,skills:r});let o=r.filter(s=>s.truncated).length;D(`Synced ${r.length} skill document${r.length===1?"":"s"}${o?` (${o} truncated)`:""}`)}catch(n){D(`Skill sync skipped: ${n?.message||n}`)}}function Ks(e){let t=new Set(["--model","-m","--permission-mode","--sandbox","--ask-for-approval","--approval-policy"]),n=new Set(["--dangerously-skip-permissions","--no-sandbox","--yolo","--accept-edits"]),r=[];for(let o=0;o<e.length;o+=1){let s=e[o],[i]=String(s).split("=",1);if(!n.has(s)){if(t.has(i)){String(s).includes("=")||(o+=1);continue}r.push(s)}}return r}function lr(e){return/(^|\/)claude(?:$|\.)/.test(String(e||""))}function ur(e){return/(^|\/)codex(?:$|\.)/.test(String(e||""))}function zs(e){let t=[],n="",r="",o=!1;for(let s of e){if(o){n+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(r){s===r?r="":n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n&&(t.push(n),n="");continue}n+=s}if(n&&t.push(n),!t.length)throw new Error("coding command is empty");return{cmd:t[0],args:t.slice(1)}}function ft(e){try{return JSON.parse(String(e))}catch{return null}}function P(e,t){return!e||e.readyState!==_e.OPEN?!1:(e.send(JSON.stringify(t)),!0)}function Ws(e){return String(e||"").split(/\r?\n/).map(t=>t.trim()).filter(Boolean).slice(-1)[0]||""}function dr(e){return String(e||"").trim().toLowerCase().replace(/^@+/,"").replace(/[^a-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function Ys(e){return e?.code==="EADDRINUSE"||/\bEADDRINUSE\b/.test(String(e?.message||e))}async function Vs(e){let t=new AbortController,n=setTimeout(()=>t.abort(),700);try{let r=await fetch(`http://127.0.0.1:${Number(e||8787)}/cursorbuddy/health`,{cache:"no-store",signal:t.signal}),o=await r.json().catch(()=>({}));return!r.ok||!o?.ok?null:o}catch{return null}finally{clearTimeout(n)}}function D(e){C.stderr.write(`[agensis] ${e}
|
|
61
|
+
`)}function tr(e){if(e instanceof Map)for(let t of e.values())try{t?.abort?.()}catch{}}import Xs from"node:crypto";import ke from"node:fs/promises";import Qs from"node:os";import mr from"node:path";var ue="default",fr=2,Zs=/^[a-zA-Z0-9_.-]{1,64}$/,ei=["url","token","workspace","agent","handle","name","cwd","codingCmd","ampCmd","model","permissionMode","timeoutMs","heartbeatMs","maxConcurrency","share","sharedModelsFile","noCoding","leanCli","fullCliContext","syncMemory","syncSkills","lanListener","primaryDaemon","cursorBuddyBridge","cursorBuddyPort","hostFolders"];function Y(e=ue){let t=String(e||ue).trim();if(!Zs.test(t))throw new Error("Daemon profile names may only contain letters, numbers, dot, dash, and underscore.");return t}function pr(e=ue,t={}){let n=t.homedir||Qs.homedir();return mr.join(n,".agensis","daemon-profiles",`${Y(e)}.json`)}function St(e={}){let t={};for(let n of ei){let r=e[n];r!=null&&r!==""&&(t[n]=r)}return t}function se(e,t,n=[]){for(let r of t)if(String(e?.[r]||"").trim())return!0;for(let r of n)if(String(process.env[r]||"").trim())return!0;return!1}function hr(e={}){return!!(se(e,["url","baseUrl"],["AGENSIS_URL"])||se(e,["token"],["AGENSIS_TOKEN"])||se(e,["workspace","workspaceId"],["AGENSIS_WORKSPACE","AGENSIS_WORKSPACE_ID"])||se(e,["agent","agentId"],["AGENSIS_AGENT","AGENSIS_AGENT_ID"]))}function wt(e={}){return!!(se(e,["url","baseUrl"],["AGENSIS_URL"])&&se(e,["token"],["AGENSIS_TOKEN"])&&se(e,["workspace","workspaceId"],["AGENSIS_WORKSPACE","AGENSIS_WORKSPACE_ID"])&&se(e,["agent","agentId"],["AGENSIS_AGENT","AGENSIS_AGENT_ID"]))}async function bt(e=ue,t={}){let n=pr(e,t),r;try{r=await ke.readFile(n,"utf8")}catch(a){if(a?.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(r)}catch(a){throw new Error(`Daemon profile "${Y(e)}" is unreadable: ${a?.message||a}`)}let s=o?.config;if(!s?.url||!s?.token||!s?.workspace||!s?.agent)return null;let i=St(s);return Number(o.version||1)<fr&&Number(i.maxConcurrency)===8&&(i.maxConcurrency=2),i}async function je(e=ue,t={},n={}){let r=St(t);if(!r.url||!r.token||!r.workspace||!r.agent)return null;let o=pr(e,n),s=mr.dirname(o);await ke.mkdir(s,{recursive:!0,mode:448});let i=`${o}.${process.pid}.${Date.now()}.tmp`,a={version:fr,savedAt:new Date().toISOString(),profile:Y(e),tokenHash:Xs.createHash("sha256").update(r.token).digest("hex"),config:r};return await ke.writeFile(i,`${JSON.stringify(a,null,2)}
|
|
62
|
+
`,{mode:384}),await ke.rename(i,o),await ke.chmod(o,384).catch(()=>{}),o}function gr(e,t={}){let n={...e,...St(t),command:"connect"};return t.fullCliContext===!0&&(n.leanCli=!1),t.codingCmd!==void 0&&t.noCoding===void 0&&(n.noCoding=!1),t.cursorBuddyBridge===void 0&&!n.primaryDaemon&&(n.cursorBuddyBridge=!1),t.once!==void 0&&(n.once=t.once),t.exitOnOnce!==void 0&&(n.exitOnOnce=t.exitOnOnce),n}function _t(e=ue){let t=Y(e);return[`No saved Agensis daemon profile found for "${t}".`,"","To connect the main agent once:","1. Run: agensis setup","2. Sign in or create an account in the browser.","3. Approve this machine as your primary local agent.","","Manual fallback: open Agensis > AI Agents, copy a connection command,","and run that full agensis connect command from the repo folder.","","After the daemon registers successfully, this CLI saves the profile locally.",`Then restart it with: agensis connect${t===ue?"":` --profile ${t}`}`].join(`
|
|
63
|
+
`)}import ti from"node:crypto";import Ae from"node:fs/promises";import yr from"node:os";import vt from"node:path";import Et from"node:process";var ni=/^cbk_[a-z0-9_]+_[A-Z2-9]{18}$/;function ri(e={}){return String(e.url||e.baseUrl||Et.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function Sr(e,t={}){let n=t.homedir||yr.homedir(),r=ti.createHash("sha256").update(String(e)).digest("hex");return vt.join(n,".agensis","cursorbuddy","connection-keys",`${r}.json`)}function oi(){return new Error("Missing or invalid --key. Create a CursorBuddy connection key in Agensis first.")}function kt(e){let t=String(e||"").trim();if(!ni.test(t))throw oi();return t}function si(e,t,n,r){let o=t?.token,s=t?.workspaceId||t?.workspace_id||t?.agent?.workspace_id,i=t?.agentId||t?.agent?.id;if(!o||!s||!i)throw new Error("CursorBuddy key claim did not return a complete daemon connection payload");let{key:a,subcommand:d,...c}=e;return{...c,command:"connect",url:t.baseUrl||n,token:o,workspace:s,agent:i,handle:t.handle||e.handle,name:t.agent?.name||e.name||"CursorBuddy runtime",model:t.model||e.model,permissionMode:t.permissionMode||t.permission_mode||e.permissionMode,cwd:e.cwd||r,cursorBuddyRuntime:!0}}async function ii(e,t={}){kt(e);let n=Sr(e,t),r;try{r=await Ae.readFile(n,"utf8")}catch(i){if(i?.code==="ENOENT")return null;throw i}let o;try{o=JSON.parse(r)}catch(i){throw new Error(`Cached CursorBuddy daemon config is unreadable: ${i?.message||i}`)}let s=o?.daemonArgs;return!s?.token||!s?.workspace||!s?.agent||!s?.url?null:s}async function ai(e,t,n={}){if(kt(e),!t?.token||!t?.workspace||!t?.agent||!t?.url)return;let r=Sr(e,n),o=vt.dirname(r);await Ae.mkdir(o,{recursive:!0,mode:448});let s=`${r}.${Et.pid}.${Date.now()}.tmp`,i={version:1,savedAt:new Date().toISOString(),keyHash:vt.basename(r,".json"),daemonArgs:t};await Ae.writeFile(s,`${JSON.stringify(i,null,2)}
|
|
64
|
+
`,{mode:384}),await Ae.rename(s,r),await Ae.chmod(r,384).catch(()=>{})}function ci(e,t,n){let r={...e,command:"connect"};for(let o of["cwd","codingCmd","model","permissionMode","timeoutMs","heartbeatMs","maxConcurrency","share","sharedModelsFile","noCoding","leanCli","lanListener","once"])t[o]!==void 0&&(r[o]=t[o]);return t.codingCmd!==void 0&&t.noCoding===void 0&&(r.noCoding=!1),r.cwd||(r.cwd=n),r.cursorBuddyRuntime=!0,r}function li(e,t){return t?.error?.message||t?.message||`CursorBuddy key claim failed with HTTP ${e.status}`}async function ui(e){return e.json().catch(()=>({}))}async function wr(e,t={}){let n=kt(e?.key),r=ri(e),o=t.fetchImpl||globalThis.fetch;if(typeof o!="function")throw new Error("This Node.js runtime does not provide fetch; use a current Node.js release.");let s=t.cwd||Et.cwd(),i=t.hostname||yr.hostname(),a=t.version||oe,d={homedir:t.homedir},c=await o(`${r}/backend/cursorbuddy/connection-keys/claim`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:n,baseUrl:r,host:i,cwd:e.cwd||s,name:e.name,surface:e.surface||"local_cli",scope:e.scope||"machine",runtimeKind:"agensis-cli",version:a,permissionMode:e.permissionMode,model:e.model})}),l=await ui(c);if(!c.ok){let m=li(c,l);if(c.status===409||/already been claimed/i.test(m)){let y=await ii(n,d);if(y)return ci(y,e,s);throw new Error(`${m}. No cached daemon config was found on this machine; create a new CursorBuddy key in Agensis or run the full copied agensis connect command.`)}throw new Error(m)}let g=si(e,l?.data||l,r,s);return await ai(n,g,d),g}import di from"node:crypto";import mi from"node:http";import fi from"node:os";import Q from"node:process";import{spawn as pi}from"node:child_process";var hi="https://agensis.io",gi=10*60*1e3;function Fe(e,t,n){e.writeHead(t,{"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"content-type"}),e.end(JSON.stringify(n))}function yi(e){return new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o,r.length>128*1024&&(n(new Error("setup callback body is too large")),e.destroy())}),e.on("error",n),e.on("end",()=>t(r))})}function Si(e){let t=String(e||Q.env.AGENSIS_URL||hi).trim(),n=new URL(t);if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error("Agensis setup URL must be http or https.");return n.search="",n.hash="",n.toString().replace(/\/+$/,"")}function wi(e){let t=Q.platform==="darwin"?"open":Q.platform==="win32"?"cmd":"xdg-open",n=Q.platform==="win32"?["/c","start","",e]:[e],r=pi(t,n,{detached:!0,stdio:"ignore"});r.on("error",()=>{}),r.unref()}function bi(e){let t=e?.daemonArgs||e?.data?.daemonArgs||e?.data||{},r=["url","token","workspace","agent"].filter(o=>!String(t[o]||"").trim());if(r.length)throw new Error(`Setup callback did not include ${r.join(", ")}`);return{...t,command:"connect"}}function _i(e,t,n){let r=new URL(Si(e.url||e.baseUrl));return r.searchParams.set("source","agensis-cli"),r.searchParams.set("referrer","agensis-cli"),r.searchParams.set("intent","setup"),r.searchParams.set("callback",t),r.searchParams.set("state",n),r.searchParams.set("profile",Y(e.profile||"default")),r.searchParams.set("host",fi.hostname()),r.searchParams.set("cwd",String(e.cwd||Q.cwd())),e.handle&&r.searchParams.set("handle",String(e.handle)),e.name&&r.searchParams.set("name",String(e.name)),r.toString()}async function br(e={}){let t=Y(e.profile||"default"),n=di.randomBytes(24).toString("base64url"),r=Number(e.setupTimeoutMs||Q.env.AGENSIS_SETUP_TIMEOUT_MS||gi),o,s=new Promise((c,l)=>{let g=setTimeout(()=>l(new Error("Agensis setup timed out waiting for browser login.")),r);g.unref&&g.unref(),o=mi.createServer(async(m,y)=>{if(y.setHeader("access-control-allow-origin","*"),y.setHeader("access-control-allow-methods","POST, OPTIONS"),y.setHeader("access-control-allow-headers","content-type"),m.method==="OPTIONS"){y.writeHead(204),y.end();return}if(m.method!=="POST"||m.url!=="/agensis/setup-callback"){Fe(y,404,{ok:!1,error:"Unknown Agensis setup callback route"});return}try{let S=JSON.parse(await yi(m)||"{}");if(S?.state!==n){Fe(y,403,{ok:!1,error:"Setup state did not match"});return}let f={...bi(S),primaryDaemon:!0,cursorBuddyBridge:e.cursorBuddyBridge!==!1};await je(t,f),clearTimeout(g),Fe(y,200,{ok:!0,profile:t}),c(f)}catch(S){Fe(y,400,{ok:!1,error:String(S?.message||S)})}}),o.once("error",l)});await new Promise((c,l)=>{o.listen(0,"127.0.0.1",g=>g?l(g):c())});let{port:i}=o.address(),a=`http://127.0.0.1:${i}/agensis/setup-callback`,d=_i(e,a,n);Q.stdout.write(`[agensis] Opening Agensis to sign in and connect this machine.
|
|
65
|
+
`),Q.stdout.write(`[agensis] If the browser did not open, visit:
|
|
66
|
+
${d}
|
|
67
|
+
`),wi(d);try{let c=await s;return Q.stdout.write(`[agensis] Saved daemon profile "${t}". Starting primary agent daemon.
|
|
68
|
+
`),c}finally{await new Promise(c=>o.close(()=>c())).catch(()=>{})}}function Ri(e){let t={command:"connect"},n=[...e],r=n[0];if(r&&!r.startsWith("-")&&(t.command=n.shift(),t.command==="buddy")){let o=n[0];o&&!o.startsWith("-")?t.subcommand=n.shift():t.subcommand="connect"}for(let o=0;o<n.length;o+=1){let s=n[o];if(!s.startsWith("--"))throw new Error(`Unexpected argument: ${s}`);let[i,a]=s.slice(2).split(/=(.*)/s,2),d=i.replace(/-([a-z])/g,(l,g)=>g.toUpperCase());if(d==="help"){t.help=!0;continue}if(d==="version"){t.version=!0;continue}if(d==="once"){t.once=!0;continue}if(d==="lan"){t.lanListener=!0;continue}if(d==="share"){t.share=!0;continue}if(d==="noCoding"){t.noCoding=!0;continue}if(d==="fullCliContext"){t.fullCliContext=!0;continue}if(d==="syncMemory"){t.syncMemory=!0;continue}if(d==="noSyncSkills"){t.syncSkills=!1;continue}if(d==="cursorbuddyBridge"){t.cursorBuddyBridge=!0;continue}if(d==="noCursorbuddyBridge"){t.cursorBuddyBridge=!1;continue}if(d==="yolo"||d==="noSandbox"){t.permissionMode="yolo";continue}if(d==="acceptEdits"){t.permissionMode="accept_edits";continue}if(d==="hostFolder"||d==="hostFolders"||d==="addDir"){let l=a!==void 0?a:n[++o];if(l==null||l.startsWith("--"))throw new Error(`Missing value for --${i}`);t.hostFolders=[...t.hostFolders||[],l];continue}let c=a!==void 0?a:n[++o];if(c==null||c.startsWith("--"))throw new Error(`Missing value for --${i}`);t[d]=c}return t}function Bi(){return`agensis agent daemon
|
|
64
69
|
|
|
65
70
|
Usage:
|
|
66
71
|
agensis --url <workspace-url> --token <token> --workspace <id> --agent <id> [options]
|
|
@@ -83,6 +88,7 @@ Options:
|
|
|
83
88
|
--cwd <path> Folder where the coding CLI runs
|
|
84
89
|
--host-folder <path> Extra folder the coding CLI may read/write (repeatable; passed as --add-dir)
|
|
85
90
|
--coding-cmd <command> Command used for jobs, default: claude -p
|
|
91
|
+
--amp-cmd <path> Amp CLI executable, default: amp
|
|
86
92
|
--no-coding Disable coding jobs; keep presence/shared inference only
|
|
87
93
|
--full-cli-context Load all user CLI skills, plugins, hooks, memory, and MCPs
|
|
88
94
|
(default isolates Claude/Codex to project + Agensis context)
|
|
@@ -118,7 +124,7 @@ agensis supervise [--profile <name>] [--poll-ms <ms>]
|
|
|
118
124
|
"agensis connect" once first). Recommended under a process manager with its
|
|
119
125
|
own restart policy (systemd Restart=always, launchd KeepAlive, pm2) so the
|
|
120
126
|
supervisor itself is recovered if it's ever killed.
|
|
121
|
-
`}async function
|
|
122
|
-
`)}}:e}async function
|
|
123
|
-
`);return}if(e.command==="buddy"){if(e.subcommand!=="connect")throw new Error(`Unknown buddy command "${e.subcommand||""}". Use "agensis buddy connect --key <cbk_...>".`);let n=await
|
|
124
|
-
`),
|
|
127
|
+
`}async function Pi(e){let t=e.profile!==void 0,n=e.handle||e.name,r=Y(e.profile||(wt(e)&&n?n:"default"));if(!hr(e)){let o=await bt(r);if(!o)throw new Error(_t(r));return gr(o,e)}return wt(e)?{...e,cursorBuddyBridge:e.cursorBuddyBridge===!0,onRegistered:async o=>{await je(r,o);let s=t||r!=="default"?`agensis connect --profile ${r}`:"agensis connect";Z.stdout.write(`[agensis] Saved daemon profile "${r}". Restart with: ${s}
|
|
128
|
+
`)}}:e}async function Li(){let e=Ri(Z.argv.slice(2));if(e.help){Z.stdout.write(Bi());return}if(e.version){Z.stdout.write(`${oe}
|
|
129
|
+
`);return}if(e.command==="buddy"){if(e.subcommand!=="connect")throw new Error(`Unknown buddy command "${e.subcommand||""}". Use "agensis buddy connect --key <cbk_...>".`);let n=await wr(e);n.cursorBuddyBridge=e.cursorBuddyBridge!==!1,n.cursorBuddyRuntime=!0,n.exitOnOnce=!0,await Le(n),n.once&&Z.exit(0);return}if(e.command==="supervise"){let n=Y(e.profile||"default"),r=await bt(n);if(!r)throw new Error(_t(n));let{runSupervisor:o}=await Promise.resolve().then(()=>(xr(),Ir)),s=e.pollMs?Number(e.pollMs):void 0;await o({config:r,runningVersion:oe,profileName:n,pollIntervalMs:s});return}if(e.command==="setup"){let n=await br(e);n.exitOnOnce=!0,await Le({...e,...n}),n.once&&Z.exit(0);return}if(e.command!=="connect")throw new Error(`Unknown command "${e.command}". Use "agensis setup", "agensis connect --url ...", "agensis supervise", or "agensis buddy connect --key ...".`);let t=await Pi(e);t.exitOnOnce=!0,await Le(t),t.once&&Z.exit(0)}Li().catch(e=>{Z.stderr.write(`${e?.message||e}
|
|
130
|
+
`),Z.exitCode=1});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agensis/agensis-agent",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.34",
|
|
4
4
|
"description": "Run a local agensis workspace agent daemon. Connects to a workspace, receives @mention jobs, runs a configured coding CLI in the local folder, and posts results back to agensis. Ships as a single minified bundle.",
|
|
5
5
|
"homepage": "https://agensis.io",
|
|
6
6
|
"repository": {
|