@agensis/agensis-agent 0.1.31 → 0.1.33
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 -38
- package/package.json +1 -1
package/bin/agensis.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),o=String(t.soul??""),i=await
|
|
4
|
-
`}async function
|
|
5
|
-
`)}async function
|
|
2
|
+
var yr=Object.defineProperty;var Ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tt=(e,t)=>{for(var n in t)yr(e,n,{get:t[n],enumerable:!0})};var Ut={};Tt(Ut,{createE2bProvider:()=>$r});function He(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function $r({apiKey:e,anthropicApiKey:t,gitToken:n="",repoUrl:r="",template:s=""}={}){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 o={apiKey:e,envs:t?{ANTHROPIC_API_KEY:t}:{}},i;try{({Sandbox:i}=await import("e2b"))}catch(u){if(u&&(u.code==="ERR_MODULE_NOT_FOUND"||u.code==="MODULE_NOT_FOUND"||/Cannot find package 'e2b'/.test(String(u&&u.message)))){let c=Number(String(process.versions.node).split(".")[0])||0,d=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.${d}`)}throw u}let a=s?await i.create(s,o):await i.create(o);return await a.commands.run("bash -lc 'command -v claude >/dev/null || npm i -g @anthropic-ai/claude-code'"),{sbx:a,dir:Or}},async putRepo(o){let i=n?r.replace(/^https:\/\//,`https://x-access-token:${n}@`):r;try{let a=await o.sbx.commands.run(`git clone ${He(i)} ${He(o.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 u=a&&(a.stderr||a.exitCode!=null)?a.stderr||`exit ${a.exitCode}`:String(a?.message||a);throw new Error(`git clone failed: ${u}`)}},async exec(o,{cmd:i,args:a=[],env:u={},onData:c}){let d=`${i} ${a.map(He).join(" ")}`,f={cwd:o.dir,envs:{...u,IS_SANDBOX:"1",AGENSIS_ALLOW_ROOT_SKIP_PERMISSIONS:"1"},onStdout:y=>{try{c?.(y)}catch{}}};try{let y=await o.sbx.commands.run(d,f);return{status:y.exitCode,stdout:y.stdout||"",stderr:y.stderr||"",error:null}}catch(y){return y&&typeof y.exitCode=="number"?{status:y.exitCode,stdout:y.stdout||"",stderr:y.stderr||"",error:null}:{status:null,stdout:"",stderr:String(y?.message||y),error:y}}},async getResult(o){try{return{patch:(await o.sbx.commands.run("git add -A && git diff --cached",{cwd:o.dir})).stdout||""}}catch(i){return{patch:i&&i.stdout||""}}},async destroy(o){await o.sbx.kill()}}}var Or,Ft=Ae(()=>{Or="/home/user/repo"});import En from"node:fs";import G from"node:fs/promises";import $o from"node:os";import H from"node:path";function kn(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/\.{2,}/g,".").replace(/^[.-]+/,"").slice(0,96)||t}function q({workspace:e,agent:t,homedir:n=$o.homedir()}={}){return H.join(n,".agensis",kn(e,"workspace"),kn(t,"agent"))}function Cn(e){return H.join(q(e),An)}function Mn(e){return H.join(q(e),ot)}async function Ne(e){let t=q(e);try{return await G.mkdir(t,{recursive:!0}),t}catch{return null}}async function ye(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 st(e,t){if(!t||typeof t!="object")return!1;let n=await Ne(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()},s=await ye(H.join(n,Bo),`${JSON.stringify(r,null,2)}
|
|
3
|
+
`),o=String(t.soul??""),i=await ye(H.join(n,Ro),o);return s&&i}async function Tn(e,t={}){let n=await Ne(e);return n?ye(H.join(n,In),On(e,t)):!1}function Nn(e,t={}){let n=q(e);try{return En.mkdirSync(n,{recursive:!0}),En.writeFileSync(H.join(n,In),On(e,t)),!0}catch{return!1}}function On(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 it(e){let t=H.join(q(e),An),n;try{let a=await G.stat(t);if(!a.isFile()||a.size>Ho)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 s=rt(r.status),o=rt(r.note??r.message);if(!s&&!o)return null;let i={};return s&&(i.status=s),o&&(i.note=o),r.ts!=null&&Number.isFinite(Number(r.ts))&&(i.ts=Number(r.ts)),i}function rt(e){return e==null?"":String(e).trim().replace(/\s+/g," ").slice(0,Jo)}function at(e){return H.join(q(e),Do)}async function $n(e){let t=at(e),n;try{let i=await G.stat(t);if(!i.isFile()||i.size>qo)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 s={};for(let i of Ko){let a=i==="description"&&r.description==null?r.profile:r[i];typeof a!="string"||!a.trim()||(s[i]=a.trim())}let o=Wo(r.voice,r.attitude);return o&&(s.voice=o),Object.keys(s).length>0?s:null}function Wo(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r={};for(let s of zo){let o=n[s];typeof o=="string"&&o.trim()?r[s]=o.trim():s==="speed"&&typeof o=="number"&&Number.isFinite(o)&&(r.speed=o)}return!r.emotion&&!r.attitude&&typeof t=="string"&&t.trim()&&(r.attitude=t.trim()),Object.keys(r).length>0?r:null}function Dn(e){return H.join(q(e),Po)}function Yo(e){return H.join(q(e),xn)}async function Bn(e){let t=Dn(e),n;try{let a=await G.stat(t);if(!a.isFile()||a.size>Lo)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 s=String(r.targetVersion||"").trim();if(!Fo.test(s))return null;let o={targetVersion:s},i=rt(r.note);return i&&(o.note=i),typeof r.requestedAt=="string"&&(o.requestedAt=r.requestedAt),o}async function Rn(e){try{return await G.rm(Dn(e),{force:!0}),!0}catch{return!1}}async function Oe(e){let t=Yo(e),n;try{let r=await G.stat(t);if(!r.isFile()||r.size>Uo)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 ie(e,t={}){let n=await Ne(e);if(!n)return!1;let r={...t,updatedAt:new Date().toISOString()};return ye(H.join(n,xn),`${JSON.stringify(r,null,2)}
|
|
5
|
+
`)}async function Pn(e){let t=await Ne(e);if(!t)return!1;let n=H.join(t,ot);try{return await G.access(n),!0}catch{}return ye(n,Go)}async function Ln(e){let t=H.join(q(e),ot);try{let n=await G.stat(t);return!n.isFile()||n.size>jo?null:(await G.readFile(t,"utf8")).trim()||null}catch{return null}}var An,Do,In,ot,Bo,Ro,Po,xn,Lo,Uo,Fo,jo,Go,Ho,Jo,qo,Ko,zo,$e=Ae(()=>{An="status.json",Do="identity.json",In="heartbeat.json",ot="heartbeat.md",Bo="agent.json",Ro="soul.md",Po="update-request.json",xn="update.json",Lo=4*1024,Uo=16*1024,Fo=/^[a-zA-Z0-9._+-]{1,64}$/,jo=16*1024,Go=`# 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,49 +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 u=n.slice(0,
|
|
26
|
-
`)})},notify(i,
|
|
27
|
-
`)},respond(i,
|
|
28
|
-
`)},respondError(i,
|
|
29
|
-
`)},onMessage(i){return s.add(i),()=>s.delete(i)}}}function
|
|
18
|
+
`,Ho=8*1024,Jo=400;qo=16*1024,Ko=["name","avatar","accent_color","description","soul"],zo=["cartesia_voice_id","voice_id","id","speed","emotion","attitude"]});import{spawn as oi,execFile as si}from"node:child_process";import _t from"node:fs";import ke from"node:fs/promises";import ii from"node:os";import he from"node:path";import{promisify as ai}from"node:util";function Et({homedir:e=ii.homedir()}={}){return he.join(e,".agensis","versions")}function Ue(e,t){return he.join(e,t)}function kt(e){return he.join(e,ui)}function pe(e){return he.join(e,"node_modules",vt,"bin","agensis.mjs")}async function lr(e,t){await ke.mkdir(he.dirname(e),{recursive:!0}),await ke.rm(e,{force:!0}),await ke.symlink(t,e)}async function At({root:e,version:t,log:n=()=>{}}){let r=Ue(e,t),s=pe(r);if(_t.existsSync(s))return n(`[self-update] ${t} already installed at ${r}`),r;if(await ke.mkdir(r,{recursive:!0}),n(`[self-update] installing ${vt}@${t} into ${r}`),await ci("npm",["install","--prefix",r,`${vt}@${t}`,"--no-audit","--no-fund","--no-save","--omit=dev"]),!_t.existsSync(s))throw new Error(`npm install reported success but ${s} is missing`);return r}function It({entry:e,profileName:t,extraArgs:n=[],env:r=process.env}){let s=["connect","--profile",t,...n],o=oi(process.execPath,[e,...s],{detached:!0,stdio:"inherit",env:r});return o.unref(),o}async function xt(e,{graceMs:t=5e3}={}){return!e||e.exitCode!==null||e.killed||await new Promise(n=>{let r=!1,s=()=>{r||(r=!0,clearTimeout(o),n())},o=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},t);o.unref?.(),e.once("exit",s);try{e.kill("SIGTERM")}catch{s()}}),!0}async function Ct({config:e,pid:t,timeoutMs:n=dr}){let r=he.join(q(e),"heartbeat.json"),s=Date.now()+n;for(;Date.now()<s;){try{let o=await ke.readFile(r,"utf8"),i=JSON.parse(o);if(Number.isFinite(i.ts)&&Date.now()-i.ts<=di&&i.connected&&(t==null||i.pid===t))return!0}catch{}await new Promise(o=>setTimeout(o,li))}return!1}async function mr({config:e,targetVersion:t,currentVersion:n,root:r=Et({}),profileName:s="default",runningChild:o=null,installFn:i=At,spawnFn:a=It,stopFn:u=xt,healthCheckFn:c=Ct,healthTimeoutMs:d=dr,log:f=()=>{}}={}){let y=await Oe(e)||{},p=n||y.currentVersion||null,h=kt(r),v={version:t,startedAt:new Date().toISOString()};if(t===p){let l={currentVersion:p,previousVersion:y.previousVersion||null,lastAttempt:{...v,result:"noop_already_current"}};return await ie(e,l),{...l,child:o}}let S;try{S=await i({root:r,version:t,log:f})}catch(l){let w={currentVersion:p,previousVersion:y.previousVersion||null,lastAttempt:{...v,result:"install_failed",error:String(l?.message||l)}};return await ie(e,w),{...w,child:o}}o&&await u(o),await lr(h,S);let g=pe(S),_=a({entry:g,profileName:s});if(await c({config:e,pid:_.pid,timeoutMs:d})){let l={currentVersion:t,previousVersion:p,lastAttempt:{...v,result:"ok"}};return await ie(e,l),{...l,child:_}}f(`[self-update] ${t} failed its health check within ${d}ms \u2014 rolling back to ${p||"(no known previous version)"}`),await u(_);let A=!1,T=null;if(p){let l=Ue(r,p);_t.existsSync(pe(l))&&(await lr(h,l),T=a({entry:pe(l),profileName:s}),A=!0)}let B={currentVersion:A?p:y.currentVersion||p,previousVersion:p,lastAttempt:{...v,result:A?"rolled_back":"failed_no_fallback"}};return await ie(e,B),{...B,child:T}}var ci,vt,ui,dr,li,di,fr=Ae(()=>{$e();ci=ai(si),vt="@agensis/agensis-agent",ui="current",dr=3e4,li=1e3,di=1e4});var hr={};Tt(hr,{runSupervisor:()=>gi});import mi from"node:fs";import Mt from"node:fs/promises";import fi from"node:path";async function hi({root:e,runningVersion:t,installFn:n,log:r}){let s=kt(e);if(mi.existsSync(s))return;r(`[supervise] no current version linked yet \u2014 adopting the running version ${t}`);let o=await n({root:e,version:t,log:r});await Mt.mkdir(fi.dirname(s),{recursive:!0}),await Mt.rm(s,{force:!0}),await Mt.symlink(o,s)}async function gi({config:e,runningVersion:t,profileName:n="default",pollIntervalMs:r=pi,root:s=Et({}),log:o=y=>process.stdout.write(`${y}
|
|
19
|
+
`),signal:i,installFn:a=At,spawnFn:u=It,stopFn:c=xt,healthCheckFn:d=Ct,maxIterations:f=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 hi({root:s,runningVersion:t,installFn:a,log:o});let y=await Oe(e);y?.currentVersion||(y={currentVersion:t,previousVersion:null,lastAttempt:null},await ie(e,y));let p=null,h=!1,v=0,S=()=>{let k=Ue(s,y.currentVersion);return p=u({entry:pe(k),profileName:n}),p.on?.("exit",(A,T)=>{if(h)return;o(`[supervise] daemon (version ${y.currentVersion}) exited (code=${A} signal=${T}); respawning`);let B=pr[Math.min(v,pr.length-1)];v+=1,setTimeout(()=>{h||S()},B).unref?.()}),p.on?.("spawn",()=>{v=0}),p};S();let g=async()=>{h=!0,p&&await c(p)};i?.addEventListener("abort",()=>{g()}),process.once("SIGTERM",()=>{g().then(()=>process.exit(0))}),process.once("SIGINT",()=>{g().then(()=>process.exit(0))});let _=0;for(;!h&&!i?.aborted&&_<f&&(_+=1,await new Promise(T=>setTimeout(T,r)),!(h||i?.aborted));){let k=await Bn(e);if(!k||k.targetVersion===y.currentVersion)continue;o(`[supervise] update requested: ${y.currentVersion} -> ${k.targetVersion}${k.note?` (${k.note})`:""}`);let A=await mr({config:e,targetVersion:k.targetVersion,currentVersion:y.currentVersion,root:s,profileName:n,runningChild:p,installFn:a,spawnFn:u,stopFn:c,healthCheckFn:d,log:o});await Rn(e),y=A,p=A.child||p,v=0,o(`[supervise] update attempt "${k.targetVersion}" -> ${A.lastAttempt?.result} (running ${A.currentVersion})`)}return{state:y,child:p}}var pi,pr,gr=Ae(()=>{fr();$e();pi=5e3,pr=[1e3,5e3,15e3,3e4]});import Q from"node:process";import be from"node:fs";import ce from"node:path";import _e from"node:os";import Vo from"node:crypto";import x from"node:process";import we from"ws";import{spawn as Sr}from"node:child_process";function Nt(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 wr=50*1024*1024;function Y(e){let{cmd:t,args:n=[],env:r={},cwd:s,timeoutMs:o=0,label:i="working",heartbeatMs:a=15e3,input:u="",now:c=Date.now,log:d=console,signal:f,onData:y}=e||{};return new Promise(p=>{if(f?.aborted){p({status:null,stdout:"",stderr:"",aborted:!0,error:new Error("cancelled")});return}let h;try{let b=n.some(M=>M==="--dangerously-skip-permissions"),I=typeof process.getuid=="function"&&process.getuid()===0,R={...process.env,...r};delete R.AGENSIS_TOKEN,delete R.ANTHROPIC_API_KEY,delete R.ANTHROPIC_AUTH_TOKEN,b&&I&&(R.IS_SANDBOX="1"),h=Sr(t,n,{cwd:s,detached:!0,env:R})}catch(b){p({status:null,stdout:"",stderr:"",error:b});return}u?h.stdin?.end(String(u)):h.stdin?.end();let v="",S="";h.stdout?.setEncoding("utf8"),h.stderr?.setEncoding("utf8");let g=(b,I)=>b.length>=wr?b:b+I;h.stdout?.on("data",b=>{if(v=g(v,b),y)try{y(b)}catch{}}),h.stderr?.on("data",b=>S=g(S,b));let _=c(),k=a>0?setInterval(()=>{d.log(` \u2026 still ${i} (${Nt(c()-_)}) \u2014 Ctrl+C to cancel`)},a):null;k?.unref&&k.unref();let A=b=>{if(h.pid!=null)try{process.kill(-h.pid,b)}catch{try{h.kill(b)}catch{}}},T=!1,B=o>0?setTimeout(()=>{T=!0,A("SIGKILL")},o):null;B?.unref&&B.unref();let l=!1,w=null,C=()=>{l=!0,A("SIGTERM"),w=setTimeout(()=>A("SIGKILL"),3e3),w?.unref&&w.unref()};f&&f.addEventListener("abort",C,{once:!0});let m=(b,I)=>{k&&clearInterval(k),B&&clearTimeout(B),w&&clearTimeout(w),f&&f.removeEventListener("abort",C),p({status:b,stdout:v,stderr:S,aborted:l,error:I||(l?new Error("cancelled"):T?new Error(`timed out after ${Nt(o)}`):null)})};h.on("error",b=>m(null,b)),h.on("close",b=>m(b,null))})}import{spawn as br}from"node:child_process";var $t=10*60*1e3;function Dt(e={}){let t={...process.env,...e};return delete t.AGENSIS_TOKEN,delete t.ANTHROPIC_API_KEY,delete t.ANTHROPIC_AUTH_TOKEN,t}var je=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 Bt(){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 _r=["mcp__agensis"],vr=["Grep","Glob"];function Er(e){return e==="yolo"?{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0}:e==="accept_edits"?{permissionMode:"acceptEdits"}:{permissionMode:"default"}}function kr(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 Ar(e){return`${JSON.stringify({type:"stream_event",event:{type:"content_block_delta",delta:{type:"text_delta",text:e}}})}
|
|
20
|
+
`}function Ir(e){return`${JSON.stringify({type:"result",result:e})}
|
|
21
|
+
`}function xr(e){return`${JSON.stringify({type:"agensis_step",step:e})}
|
|
22
|
+
`}function Cr(e){return`${JSON.stringify({type:"agensis_segment",segment:e})}
|
|
23
|
+
`}var Mr=["file_path","path","pattern","command","description","prompt"],Ot=120;function Ge(e){if(!e||typeof e!="object")return"";for(let t of Mr){let n=e[t];if(typeof n!="string")continue;let r=n.replace(/\s+/g," ").trim();if(r)return r.length>Ot?`${r.slice(0,Ot)}\u2026`:r}return""}function Rt(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||""})}function Pt({queryFn:e,idleCloseMs:t=$t}={}){let n=new Map,r=Bt(),s=(u,c,d)=>{let f=n.get(u);if(!(!f||c&&f!==c))if(n.delete(u),clearTimeout(f.idleTimer),f.closed=!0,f.queue.close(),d&&f.activeTurn&&f.activeTurn.finish(d),typeof f.query.close=="function")try{f.query.close()}catch{}else Promise.resolve(f.query.return?.()).catch(()=>{})},o=u=>{let c=n.get(u);c&&(clearTimeout(c.idleTimer),c.idleTimer=setTimeout(()=>s(u),t),c.idleTimer.unref?.())},i=async(u,c)=>{let d=n.get(u),f=Rt(c);if(d&&d.fingerprint===f&&!d.closed)return d;d&&s(u,d),e||(e=(await import("@anthropic-ai/claude-agent-sdk")).query);let y=new je,p=Er(c.permissionMode),h=c.leanCli&&c.mcp?{agensis:{type:"http",url:c.mcp.url,headers:{Authorization:"Bearer ${AGENSIS_MCP_TOKEN}"}}}:void 0,v=e({prompt:y,options:{cwd:c.cwd,model:c.model,...p,allowedTools:[..._r,...vr],additionalDirectories:c.hostFolders&&c.hostFolders.length?c.hostFolders:void 0,mcpServers:h,strictMcpConfig:c.leanCli?!0:void 0,settingSources:c.leanCli?[]:void 0,persistSession:c.leanCli?!1:void 0,includePartialMessages:!0,env:Dt(c.mcp?.env)}});return d={query:v,queue:y,sessionId:"",idleTimer:null,activeTurn:null,closed:!1,terminalError:null,fingerprint:f},n.set(u,d),d.pump=(async()=>{let S=null;try{for await(let g of v){g.session_id&&(d.sessionId=g.session_id);let _=d.activeTurn;if(_){if(g.type==="stream_event"){let k=kr(g.event);k&&(_.streamed+=k,_.onData?.(Ar(k)))}else if(g.type==="result")if(g.subtype==="success"){let k=g.result==null?_.text:String(g.result);_.onData?.(Ir(k)),_.finish({status:0,stdout:k,stderr:"",error:null})}else{let k=Array.isArray(g.errors)?g.errors.filter(Boolean).join(`
|
|
24
|
+
`):g.result,A=new Error(k||`claude-agent-sdk result error: ${g.subtype}`);_.finish({status:1,stdout:_.text,stderr:A.message,error:A})}else if(g.type==="assistant"){let k=g.message?.content;if(Array.isArray(k)){let A=k.filter(T=>T&&T.type==="text"&&typeof T.text=="string").map(T=>T.text).join("");A&&(_.onData?.(Cr({text:A})),_.flushed+=_.streamed,_.streamed="");for(let T of k)!T||T.type!=="tool_use"||!T.name||_.onData?.(xr({kind:"tool",name:String(T.name),detail:Ge(T.input)}))}}}}S=new Error("claude-agent-sdk connection closed")}catch(g){S=g}finally{d.closed=!0,d.terminalError=S,clearTimeout(d.idleTimer),d.queue.close(),n.get(u)===d&&n.delete(u),d.activeTurn&&d.activeTurn.finish({status:null,stdout:d.activeTurn.text,stderr:String(S?.message||S||""),error:S})}})(),d};return{run:u=>r(u.sessionKey||"default",async()=>{let{sessionKey:c="default",prompt:d,signal:f,onData:y,timeoutMs:p=0}=u;if(f?.aborted)return{status:null,stdout:"",stderr:"",aborted:!0,error:new Error("cancelled")};let h;try{h=await i(c,u)}catch(S){return{status:null,stdout:"",stderr:"",error:S}}if(h.closed){let S=h.terminalError||new Error("claude-agent-sdk connection closed");return{status:null,stdout:"",stderr:String(S.message||S),error:S}}clearTimeout(h.idleTimer);let v=await new Promise(S=>{let g=!1,_=null,k={streamed:"",flushed:"",get text(){return this.flushed+this.streamed},onData:y,finish(T){g||(g=!0,h.activeTurn===k&&(h.activeTurn=null),f&&f.removeEventListener("abort",A),_&&clearTimeout(_),S(T))}},A=()=>{let T={status:null,stdout:k.text,stderr:"",aborted:!0,error:new Error("cancelled")};Promise.resolve(h.query.interrupt?.()).catch(()=>{}),s(c,h,T)};h.activeTurn=k,f&&f.addEventListener("abort",A,{once:!0}),p>0&&(_=setTimeout(()=>{let T=new Error(`timed out after ${p}ms`);Promise.resolve(h.query.interrupt?.()).catch(()=>{}),s(c,h,{status:null,stdout:k.text,stderr:T.message,error:T})},p),_.unref?.()),h.queue.push({type:"user",message:{role:"user",content:d},parent_tool_use_id:null,session_id:h.sessionId})});return n.get(c)===h&&o(c),v}),shutdown:()=>{for(let u of[...n.keys()])s(u)}}}function Tr(e){let t=1,n="",r=new Map,s=new Set;e.stdout.setEncoding("utf8"),e.stdout.on("data",i=>{n+=i;let a;for(;(a=n.indexOf(`
|
|
25
|
+
`))>=0;){let u=n.slice(0,a);if(n=n.slice(a+1),!u.trim())continue;let c;try{c=JSON.parse(u)}catch{continue}if(c.id!==void 0&&r.has(c.id)){let{resolve:d,reject:f}=r.get(c.id);r.delete(c.id),c.error?f(new Error(c.error.message||"codex app-server error")):d(c.result)}else if(c.method)for(let d of s)d(c.method,c.params,c.id)}});let o=i=>{for(let{reject:a}of r.values())a(i);r.clear()};return e.on("exit",()=>o(new Error("codex app-server exited"))),e.on("error",i=>o(i)),{request(i,a){let u=t++;return new Promise((c,d)=>{r.set(u,{resolve:c,reject:d}),e.stdin.write(`${JSON.stringify({id:u,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 s.add(i),()=>s.delete(i)}}}function Nr(e){return e==="yolo"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{}}function Lt({spawnFn:e=br,idleCloseMs:t=$t}={}){let n=new Map,r=Bt(),s=u=>{let c=n.get(u);if(c){n.delete(u),clearTimeout(c.idleTimer);try{c.child.kill("SIGTERM")}catch{}}},o=u=>{let c=n.get(u);c&&(clearTimeout(c.idleTimer),c.idleTimer=setTimeout(()=>s(u),t),c.idleTimer.unref?.())},i=async(u,c)=>{let d=n.get(u),f=Rt(c);if(d&&d.fingerprint===f)return d;d&&s(u);let y=e("codex",["app-server"],{cwd:c.cwd,env:Dt(c.mcp?.env),stdio:["pipe","pipe","pipe"]}),p=Tr(y);await p.request("initialize",{clientInfo:{name:"agensis-agent",version:c.clientVersion||"unknown"}}),p.notify("initialized");let h=c.leanCli&&c.mcp?{mcp_servers:{agensis:{url:c.mcp.url,bearer_token_env_var:"AGENSIS_MCP_TOKEN"}}}:void 0,v=await p.request("thread/start",{cwd:c.cwd,ephemeral:c.leanCli||void 0,model:c.model,config:h,...Nr(c.permissionMode)}),S={child:y,rpc:p,threadId:v.thread.id,fingerprint:f,idleTimer:null};return n.set(u,S),S};return{run:u=>r(u.sessionKey||"default",async()=>{let{sessionKey:c="default",prompt:d,signal:f,onData:y,timeoutMs:p=0}=u;if(f?.aborted)return{status:null,stdout:"",stderr:"",aborted:!0,error:new Error("cancelled")};let h;try{h=await i(c,u)}catch(A){return{status:null,stdout:"",stderr:"",error:A}}let v="",S="",g=null,_=!1,k=await new Promise(A=>{let T=!1,B=b=>{T||(T=!0,m(),A(b))},l=h.rpc.onMessage((b,I,R)=>{if(R!==void 0){if(b==="item/commandExecution/requestApproval"){let M=u.permissionMode==="yolo"?"acceptForSession":"decline";h.rpc.respond(R,{decision:M})}else if(b==="item/fileChange/requestApproval"){let M=u.permissionMode==="yolo"||u.permissionMode==="accept_edits"?"acceptForSession":"decline";h.rpc.respond(R,{decision:M})}else h.rpc.respondError(R,`Agensis daemon cannot handle Codex request ${b}`);return}if(!(!I||I.threadId!==h.threadId)){if(b==="turn/started"){g=I.turn?.id??g;return}if(!(g&&I.turnId&&I.turnId!==g)){if(b==="item/agentMessage/delta")v+=I.delta||"",y?.(I.delta||"");else if(b==="item/completed"&&I.item?.type==="agentMessage")S=I.item.text||S;else if(b==="turn/completed"){let M=I.turn?.status==="failed"||I.turn?.error;B({status:M?1:0,stdout:S||v,stderr:M?String(I.turn?.error?.message||I.turn?.error||""):"",error:M?new Error(String(I.turn?.error?.message||I.turn?.error||"codex turn failed")):null})}}}}),w=()=>{_=!0,h.rpc.request("turn/interrupt",{threadId:h.threadId}).catch(()=>{});let b={status:null,stdout:v,stderr:"",aborted:!0,error:new Error("cancelled")};B(b),s(c)};f&&f.addEventListener("abort",w,{once:!0});let C=p>0?setTimeout(()=>{let b=new Error(`timed out after ${p}ms`);h.rpc.request("turn/interrupt",{threadId:h.threadId}).catch(()=>{}),B({status:null,stdout:v,stderr:b.message,error:b}),s(c)},p):null;C?.unref?.();function m(){l(),f&&f.removeEventListener("abort",w),C&&clearTimeout(C)}h.rpc.request("turn/start",{threadId:h.threadId,input:[{type:"text",text:d}]}).then(b=>{g=b?.turn?.id||g}).catch(b=>B({status:null,stdout:"",stderr:"",error:b}))});return _||o(c),k}),shutdown:()=>{for(let u of[...n.keys()])s(u)}}}function Gt({run:e=Y}={}){return{run:t=>e(t)}}var Dr=null,Br=null,jt=new Set;function Rr(e){let t=String(e&&e.message||e||"");return/Cannot find module|ERR_MODULE_NOT_FOUND|ENOENT|command not found/i.test(t)}function Pr(e,{local:t,pooled:n,log:r=console}={}){let s=t||Gt(),o=n||(e==="claude"?Dr||=Pt():e==="codex"?Br||=Lt():null);return o?{async run(i){if(jt.has(e))return s.run(i);let a=await o.run(i);return a.error&&Rr(a.error)?(jt.add(e),r.log?.(`[executor] ${e} fast connection unavailable (${a.error.message}); falling back to subprocess mode for this and future jobs.`),s.run(i)):a}}:s}function Lr(e){return{async run({cmd:t,args:n=[],env:r={},onData:s,signal:o,job:i}){let a=null;try{a=await e.ensureEnv({job:i,signal:o}),await e.putRepo(a,{job:i,signal:o});let u=await e.exec(a,{cmd:t,args:n,env:r,onData:s,signal:o}),c=await e.getResult(a,{job:i}).catch(()=>({})),d=c&&c.patch?String(c.patch).trim():"",f=d?`${u.stdout||""}
|
|
30
30
|
|
|
31
31
|
\`\`\`diff
|
|
32
|
-
${
|
|
33
|
-
\`\`\``:u.stdout||"";return{status:u.status,stdout:
|
|
32
|
+
${d}
|
|
33
|
+
\`\`\``:u.stdout||"";return{status:u.status,stdout:f,stderr:u.stderr||"",error:u.error||null}}catch(u){return{status:null,stdout:"",stderr:"",error:u}}finally{if(a)try{await e.destroy(a)}catch{}}}}}function Ht(e,{makeProvider:t,family:n}={}){return(e&&e.agent&&e.agent.run_mode)==="sandbox"?Lr((t||Ur)(e)):n==="claude"||n==="codex"?Pr(n):Gt()}function Ur(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 jr({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 Fr(e=process.versions.node){let[t,n,r]=String(e).split(".").map(s=>Number(s)||0);return t===21?!1:t>=22?!0:t!==20?!1:n>18?!0:n<18?!1:r>=1}function jr(e){let t=null,n=async()=>{if(!t){if(!Fr())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(()=>(Ft(),Ut))).createE2bProvider(e)}return t};return{ensureEnv:async r=>(await n()).ensureEnv(r),putRepo:async(r,s)=>(await n()).putRepo(r,s),exec:async(r,s)=>(await n()).exec(r,s),getResult:async(r,s)=>(await n()).getResult(r,s),destroy:async r=>(await n()).destroy(r)}}import Jt from"node:fs/promises";import Ie from"node:path";var qe="amp",Gr=/^T-[A-Za-z0-9-]{20,100}$/,Je={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 V(e,t=""){let n=new Error(Je[e]||Je.amp_cli_crashed);return n.code=e,t&&(n.detail=String(t).slice(0,1e3)),n}function qt(e){return String(e?.agent?.metadata?.runtime||"").trim().toLowerCase()===qe}function le(e){let t=String(e||"").trim();return Gr.test(t)?t:""}function Hr(e){let t=le(e);return t?`https://ampcode.com/threads/${t}`:""}function Kt({prompt:e,threadId:t="",executable:n="amp"}={}){let r=le(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 zt(){let e="",t="",n=r=>{try{let s=JSON.parse(String(r).trim()),o=le(s?.session_id||s?.sessionId||s?.thread_id||s?.threadId);o&&(t=o)}catch{}};return{feed(r){e+=String(r||"");let s;for(;(s=e.indexOf(`
|
|
34
|
+
`))>=0;)n(e.slice(0,s)),e=e.slice(s+1)},end(){e&&n(e),e=""},get threadId(){return t},get threadUrl(){return Hr(t)}}}function xe(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:Je[n],detail:t.slice(0,1e3)}}async function Wt({cwd:e,allowedRoots:t=[]}={}){let n=Ie.resolve(String(e||""));if(!t.map(o=>String(o||"").trim()).filter(Boolean).map(o=>Ie.resolve(o)).includes(n))throw V("amp_repo_not_allowed");try{await Jt.access(Ie.join(n,".git"))}catch{throw V("amp_repo_not_allowed","cwd is not a Git repository root")}let s=Ie.join(n,".agents","setup");try{let o=await Jt.stat(s);if(o.isFile()&&!(o.mode&73))throw V("amp_setup_failed")}catch(o){if(o?.code!=="ENOENT")throw o}return n}function se(e,t){return{id:qe,available:!1,version:e,reason:t,project:null}}function Jr(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 Ke({cwd:e,executable:t="amp",run:n=Y,signal:r}={}){let s=(y,p=1e4)=>n({cmd:t,args:y,cwd:e,timeoutMs:p,heartbeatMs:0,label:"checking Amp",signal:r}),o=await s(["version"],5e3);if(o?.status!==0){let y=xe(o);return se("",y.code)}let i=String(o.stdout||o.stderr||"").trim().split(/\r?\n/).at(-1)?.slice(0,120)||"",a=await s(["--help"],5e3),u=`${a?.stdout||""}
|
|
37
|
+
${a?.stderr||""}`;if(a?.status!==0||!/--stream-json/.test(u)||!/threads[\s\S]*continue/i.test(u)||!/\borb\b/i.test(u))return se(i,"amp_version_unsupported");let c=await s(["usage"]);if(c?.status!==0){let y=xe(c);return se(i,y.code)}let d=await s(["projects","status","--json"]);if(d?.status!==0){let y=xe(d);return se(i,y.code)}let f;try{f=JSON.parse(String(d.stdout||""))}catch{return se(i,"amp_version_unsupported")}return["forbidden","permission_denied","access_denied"].includes(String(f?.status||"").toLowerCase())?se(i,"amp_project_forbidden"):f?.status!=="matched"||!f?.project?se(i,"amp_project_not_found"):{id:qe,available:!0,version:i,reason:null,project:Jr(f.project)}}function Yt(e){let t=xe(e);return V(t.code,t.detail)}function Vt(e={}){let{runJob:t}=e,n=Math.max(1,Number(e.concurrency)||1),r=new Map,s=0,o=[];function i(S){let g=r.get(S);return g||(g={queued:[],active:null},r.set(S,g)),g}function a(S){if(S==null)return!1;for(let g of r.values())if(g.active&&!g.active.cancelled&&g.active.job.key===S||g.queued.some(_=>_.key===S))return!0;return!1}function u(){for(let[S,g]of r){if(s>=n)break;if(g.active||g.queued.length===0)continue;let _=g.queued.shift(),k=new AbortController;g.active={job:_,controller:k,cancelled:!1},s+=1,Promise.resolve().then(()=>k.signal.aborted?void 0:t(_,{signal:k.signal})).catch(()=>{}).finally(()=>{g.active=null,s-=1,g.queued.length===0&&!g.active&&r.delete(S),u(),c()})}}function c(){if(s>0)return;for(let g of r.values())if(g.queued.length)return;let S=o;o=[];for(let g of S)g()}function d(S){if(S&&S.key!=null&&a(S.key))return{accepted:!1,deduped:!0,position:0,startedImmediately:!1};let g=S&&S.lane!=null?String(S.lane):"",_=i(g),k=!_.active&&_.queued.length===0&&s<n;_.queued.push(S);let A=_.queued.length+(_.active?1:0);return u(),{accepted:!0,deduped:!1,position:A,startedImmediately:k}}function f(S,g){let _=!1;for(let[k,A]of r)g!=null&&k!==String(g)||A.active&&(A.active.cancelled=!0,A.active.controller.abort(S||"cancelled"),_=!0);return _}function y(S,g){if(S==null)return!1;let _=!1;for(let[k,A]of[...r]){A.active?.job?.key===S&&(A.active.cancelled=!0,A.active.controller.abort(g||"cancelled"),_=!0);let T=A.queued.length;A.queued=A.queued.filter(B=>B.key!==S),A.queued.length!==T&&(_=!0),!A.active&&A.queued.length===0&&r.delete(k)}return c(),_}function p(){let S=0;for(let g of r.values())S+=g.queued.length;return S}function h(){return s}function v(){return s===0&&p()===0?Promise.resolve():new Promise(S=>o.push(S))}return{enqueue:d,cancel:y,cancelActive:f,has:a,size:p,active:h,idle:v}}import nn from"node:crypto";import qr from"node:http";import rn from"node:os";import Z from"node:process";var Xt=8787,ze="claude-haiku-4-5",Kr=/^cbk_[a-z0-9_]+_[A-Z2-9]{18}$/,zr=100,Wr=new Set(["say","wave","hush","open","choose"]),Te="x-agensis-bridge-secret";function Yr(){return`cbs_${nn.randomBytes(24).toString("base64url")}`}function Vr(e){let t=e?.headers||{},n=String(t[Te]||t[Te.toLowerCase()]||"").trim();if(n)return n;let s=String(t.authorization||t.Authorization||"").trim().match(/^Bearer\s+(.+)$/i);return s?s[1].trim():""}function Xr(e,t){let n=String(t||""),r=Vr(e);if(!n||!r)return!1;let s=Buffer.from(r),o=Buffer.from(n);return s.length!==o.length?!1:nn.timingSafeEqual(s,o)}function Qr(e={},t={}){let n=String(t.authSecret||"").trim();if(n)return n;let r=String(e.cursorBuddyBridgeSecret||"").trim();if(r)return r;let s=String(Z.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim();return s||Yr()}function Zr(e,t){return e==="OPTIONS"||e==="GET"&&t==="/cursorbuddy/health"}function j(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 Qt(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 K(e,t){e.write(`data: ${typeof t=="string"?t:JSON.stringify(t)}
|
|
34
38
|
|
|
35
|
-
`)}function
|
|
39
|
+
`)}function ge(e){return new Promise((t,n)=>{let r="";e.on("data",s=>{r+=s,r.length>256*1024&&(n(new Error("request body is too large")),e.destroy())}),e.on("error",n),e.on("end",()=>t(r))})}function eo(e){let t=[],n="",r="",s=!1;for(let o of String(e||"")){if(s){n+=o,s=!1;continue}if(o==="\\"){s=!0;continue}if(r){o===r?r="":n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n&&(t.push(n),n="");continue}n+=o}if(n&&t.push(n),!t.length)throw new Error("coding command is empty");return{cmd:t[0],args:t.slice(1)}}function to(e){return/(^|\/)claude(?:$|\.)/.test(String(e||""))}function Ce(e,t){return e.some(n=>n===t||String(n).startsWith(`${t}=`))}function Zt(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 s=String(r?.role||"user"),o=String(r?.content||"");o.trim()&&n.push(`${s.toUpperCase()}:
|
|
36
40
|
${o}`)}return n.join(`
|
|
37
41
|
|
|
38
|
-
`).trim()||"Say that the local Agensis runtime is connected."}function
|
|
39
|
-
`))>=0;)u(t.slice(0,l)),t=t.slice(l+1)},end(){t&&(u(t),t="")},get live(){return r?n:s},get result(){return o??(r?n:s)}}}function re(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 ve(e){return`http://127.0.0.1:${e}`}function $r(e={},t={}){return String(t.agensisUrl||t.baseUrl||e.url||X.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function Dr(e){return String(e||"").slice(0,18)}function U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Br(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 Rr(e,t){return t?.error?.message||t?.message||`CursorBuddy key claim failed with HTTP ${e.status}`}async function Pr(e,t={},n=globalThis.fetch){let r=String(t.key||"").trim();if(!Sr.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=$r(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:Rt.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(Rr(o,i));return{key:r,baseUrl:s,data:i?.data||i}}async function Ut(e,t={}){let n=Number(t.port??e.cursorBuddyPort??X.env.AGENSIS_CURSORBUDDY_PORT??Tt),r=kr(e,t),s=new Date().toISOString(),o=[],i=[],c=new Set,u=t.fetchImpl||globalThis.fetch,a=1,l=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()}),_=()=>{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=_();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(!br.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 v(d){for(i.push(d);i.length>wr;)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=Tr(d);if(b){let M=p(b.command);return M&&(v(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=Nt(d?.messages,l),m=Dt(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:$t(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,re(M,$,m.content)),K(b,re(M,$,"","stop")),K(b,"[DONE]"),f("chat_fast",{chars:m.content.length,model:$}),{content:m.content,model:$,fast:!0}}let y=Nt(d?.messages,l),I=Dt(e,y,d?.model,{stream:!0}),R="",C=$=>{$&&(R+=$,K(b,re(M,I.model||e.model,$)))},N=I.streamJson?Nr(C):null,E=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(N)N.feed($);else{let F=String($||"");R+=F,K(b,re(M,I.model||e.model,F))}}});if(N){N.end();let $=N.result||"";!R&&$?C($):R=$||R}if(E.error||E.status!==0){let $=E.error?.message||String(E.stderr||"").trim()||`Command exited with status ${E.status}`;throw new Error($)}let O=N?R:$t(R||E.stdout||E.stderr);return!N&&O&&O!==R&&(K(b,re(M,I.model||e.model,O)),R=O),K(b,re(M,I.model||e.model,"","stop")),K(b,"[DONE]"),{content:R||O,model:I.model}}let B=yr.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||"/",ve(g||Tt));if(!Ar(d.method,M.pathname)&&!Er(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=ve(g);j(b,200,{ok:!0,runtime:"agensis-cli",backend:e.codingCmd,model:Pe(e),daemonModel:e.model,port:g,host:Rt.hostname(),pid:X.pid,bootedAt:s,authRequired:!0,authHeader:Ee,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:l,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:l});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);Ot(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 le(d)||"{}"),y=p(m);if(!y){j(b,400,{ok:!1,error:"unsupported CursorBuddy control command"});return}let I=v(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 le(d)||"{}");l={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:l.url,surface:l.surface,instanceId:l.instanceId}),j(b,200,{ok:!0,context:l})}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 le(d)||"{}"),y=await Pr(e,m,u),I=y.data||{};w={connected:!0,mode:"agensis-claimed",keyId:Dr(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()},l=Br(m,w,e),f("connect",{mode:w.mode,keyId:w.keyId,agentId:w.agentId,workspaceId:w.workspaceId,url:l.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 le(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 le(d)||"{}");if(f("chat_request",{messages:Array.isArray(m.messages)?m.messages.length:0,model:Pt(m.model,Pe(e))}),m.stream===!0){Ot(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:`${ve(g)}/cursorbuddy/health`}),{port:g,url:ve(g),secret:r,authHeader:Ee,close(){return new Promise(d=>B.close(()=>d()))},getContext(){return l}}}import oe from"node:fs/promises";import Lr from"node:os";import z from"node:path";var Ft=200,jt=256*1024,Ur=2,Fr=new Set([".md",".markdown",".txt"]);function jr(e){return String(e||"").replace(/[^a-zA-Z0-9]/g,"-")}function Le({cwd:e,memoryDir:t,homedir:n=Lr.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",jr(s),"memory"):null}async function Ue(e){if(!e)return null;try{let t=await oe.realpath(e);return(await oe.stat(t)).isDirectory()?t:null}catch{return null}}async function Gr(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 oe.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 Hr(e){let t=z.basename(e).toLowerCase();return t==="memory.md"?"index":t==="claude.md"?"instructions":"memory"}async function Fe(e,t,n,r){if(n>Ur||r.length>=Ft)return;let s;try{s=await oe.readdir(t,{withFileTypes:!0})}catch{return}for(let o of s){if(r.length>=Ft)break;if(o.name.startsWith("."))continue;let i=z.join(t,o.name);if(o.isDirectory())await Fe(e,i,n+1,r);else if(o.isFile()&&Fr.has(z.extname(o.name).toLowerCase())){let c=z.relative(e,i);r.push({path:c,kind:Hr(c)})}}}async function Jr(e){let t=await Ue(e);if(!t)return[];let n=[];return await Fe(t,t,0,n),n.sort((r,s)=>r.kind==="index"?-1:s.kind==="index"?1:r.path.localeCompare(s.path)),n}async function qr(e,t){let n=await Ue(e),r=await Gr(n,t),s=await oe.readFile(r),o=s.length>jt;return{content:s.subarray(0,jt).toString("utf8"),byteSize:s.length,truncated:o}}async function Gt(e){let t=await Ue(e);if(!t)return"";let n=[];await Fe(t,t,0,n),n.sort((s,o)=>s.path.localeCompare(o.path));let r=[];for(let s of n)try{let o=await oe.stat(z.join(t,s.path));r.push(`${s.path}:${o.size}:${Math.floor(o.mtimeMs)}`)}catch{}return r.join("|")}async function Ht(e){let t=await Jr(e),n=[];for(let r of t)try{let{content:s,byteSize:o}=await qr(e,r.path);n.push({path:r.path,kind:r.kind,content:s,byteSize:o})}catch{}return n}import Jt from"node:fs";import se from"node:path";import qt from"node:os";function Kr(e){try{return Jt.statSync(e).isDirectory()}catch{return!1}}function je(e){try{return Jt.readdirSync(e,{withFileTypes:!0})}catch{return[]}}function Kt({home:e=qt.homedir(),cwd:t=process.cwd()}={}){let n=[e&&se.join(e,".claude","commands"),t&&se.join(t,".claude","commands")].filter(Boolean),r=new Set,s=[],o=(i,c)=>{if(!i)return;let u=c?`${c}:${i}`:i;r.has(u)||(r.add(u),s.push({name:i,parent:c||null}))};for(let i of n)for(let c of je(i)){if(c.name.startsWith("."))continue;if(c.name.endsWith(".md")){o(c.name.slice(0,-3),null);continue}let u=se.join(i,c.name);if(c.isDirectory()||c.isSymbolicLink()&&Kr(u))for(let a of je(u))a.name.startsWith(".")||a.name.endsWith(".md")&&o(a.name.slice(0,-3),c.name)}return s}function zt({home:e=qt.homedir(),cwd:t=process.cwd()}={}){let n=[e&&se.join(e,".claude","skills"),e&&se.join(e,".codex","skills"),t&&se.join(t,".claude","skills")].filter(Boolean),r=new Set;for(let s of n)for(let o of je(s))o.name.startsWith(".")||(o.name.endsWith(".md")?r.add(o.name.slice(0,-3)):(o.isDirectory()||o.isSymbolicLink())&&r.add(o.name));return[...r].sort()}import{readFile as zr}from"node:fs/promises";var Wr=new Set(["127.0.0.1","localhost","::1","[::1]"]);function Wt(e,t,n){let r=Number(e);return Number.isFinite(r)?Math.max(1,Math.min(n,Math.trunc(r))):t}function Yr(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(!Wr.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:Wt(e.contextWindow,void 0,1e7)}:{},maxConcurrency:Wt(e.maxConcurrency,1,64),shared:!0}}async function Yt(e){if(!e)return[];let t=JSON.parse(await zr(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(Yr).filter(Boolean)}function Vt(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 Xt({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 u={"content-type":"application/json"},a=c.apiKeyEnv?o[c.apiKeyEnv]:"";a&&(u.authorization=`Bearer ${a}`),n({action:"agent_inference_started",requestId:i,model:c.id});let{requestId:l,model:g,type:w,action:f,...h}=t,_=await s(`${c.baseUrl}/chat/completions`,{method:"POST",headers:u,body:JSON.stringify({...h,model:c.upstreamModel,stream:t.stream===!0}),signal:r});if(!_.ok){let p=await _.text().catch(()=>"");throw new Error(p||`Local model returned HTTP ${_.status}.`)}if(t.stream===!0){if(!_.body)throw new Error("Local model returned an empty stream.");let p=_.body.getReader(),v=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+=v.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 _.json();return n({action:"agent_inference_result",requestId:i,model:c.id,response:S}),S}Ie();var ho=30*60*1e3,go=15*1e3,hn=2,yo=10*1024,So="claude-opus-4-8",Q="0.1.31";async function xe(e={}){let t=wo(e);t.sharedModels=t.share?await Yt(t.sharedModelsFile):[];let n=!1,r=null,s=null,o=null,i=null,c=0,u=null,a=null,l="",g=null,w=!1,f=null,h=new Map,_=null,S={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"},p=new Map,v=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=()=>{_||!t.lanListener||(_=new fe.Server({port:0}),_.on("listening",()=>{let{port:C}=_.address();S={transport:"ws",listening:!0,addrs:Jo(C),auth:"hub-pairwise"},D(`Agent-mesh LAN listener on port ${C}`),me(r,t,A())}),_.on("connection",C=>{let N=!1,E=setTimeout(()=>{if(!N)try{C.close(1008,"peer auth required")}catch{}},5e3);C.once("message",O=>{clearTimeout(E);let $=We(O),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),N=!0,C.on("message",J=>{let P=We(J);P?.type==="agent_job"&&P.job?.id&&a.enqueue({...P.job,key:P.job.id,lane:gn(P.job),ws:r}).accepted&&D(`Queued peer-handoff job ${P.job.id} from ${$.fromAgentId}`)})})}),_.on("error",C=>D(`LAN listener error: ${C?.message||C}`)))},d=()=>{if(_){try{_.close()}catch{}_=null}S={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"}},b=C=>new Promise((N,E)=>{if(!L(r,{action:"peer_ticket_request",targetAgentId:C})){E(new Error("hub socket not open"));return}let O=v.get(C)||[];O.push({resolve:N,reject:E}),v.set(C,O),setTimeout(()=>{let $=v.get(C)||[],F=$.findIndex(J=>J.resolve===N);F>=0&&($.splice(F,1),E(new Error("peer ticket request timed out")))},1e4)}),M=()=>new Promise((C,N)=>{if(!L(r,{action:"peer_list_request"})){N(new Error("hub socket not open"));return}k.push(C),setTimeout(()=>{let E=k.indexOf(C);E>=0&&(k.splice(E,1),C([]))},1e4)}),m=async(C,N)=>{let E=null;try{let $=(await M()).find(P=>P.agentId===C&&P.reach?.listening&&P.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:(E=new fe(`ws://${J.host}:${J.port}`),await new Promise((P,Ne)=>{E.once("open",P),E.once("error",Ne),setTimeout(()=>Ne(new Error("peer connect timed out")),5e3)}),L(E,{type:"peer_auth",ticket:F.ticket,fromAgentId:t.agent}),L(E,{type:"agent_job",job:N}),!0)}catch(O){return D(`Peer handoff to ${C} failed, falling back to hub relay: ${O?.message||O}`),!1}finally{try{E?.close()}catch{}}},y=()=>{n=!0,bn(h),s&&clearTimeout(s),o&&clearInterval(o),i&&clearInterval(i),g&&(g.close().catch(()=>{}),g=null),d(),an(t,{status:"stopped",connected:!1});try{r?.close()}catch{}u&&u()};if(a=Mt({concurrency:t.once?1:t.maxConcurrency,runJob:async(C,N)=>{await Do(t,C,N),t.once&&y()}}),t.cursorBuddyBridge)try{g=await Ut(t,{port:t.cursorBuddyPort,authSecret:t.cursorBuddyBridgeSecret||void 0,log:D,connectionProvider:T}),g?.secret&&(t.cursorBuddyBridgeSecret=g.secret)}catch(C){if(Wo(C)){let N=await Yo(t.cursorBuddyPort);if(N?.ok){let E=N.pid?` pid ${N.pid}`:"";D(`CursorBuddy local bridge already running on http://127.0.0.1:${t.cursorBuddyPort}${E}`)}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=_o(t.url,t.token,t);l="",D(`Connecting to ${C.replace(t.token,"redacted")}`),r=new fe(C),r.on("open",async()=>{w=!1,f=null,D(`Connected. Registering @${t.handle||"agent"} from ${t.cwd}`),L(r,{type:"auth",token:t.token});let N=await un(t);L(r,{action:"agent_register",workspaceId:t.workspace,agentId:t.agent,handle:t.handle,name:t.name,host:ge.hostname(),cwd:t.cwd,...N?{identity:N}:{},metadata:{codingCmd:t.codingCmd,model:t.model,permissionMode:t.permissionMode,permissionFlags:Qe(t.permissionMode),once:t.once,runtime:"agensis",version:Q}}),o=setInterval(()=>{Promise.all([In(t,A()).catch(()=>null),qe(t).catch(()=>null)]).then(([E,O])=>{L(r,{action:"agent_heartbeat",...E?{capabilitiesHash:E.capabilitiesHash,memoryHash:E.memoryHash}:{},metadata:ze(t,a,O,_n(t)?g?.getContext?.():null,h)})})},t.heartbeatMs),o.unref&&o.unref()}),r.on("message",N=>{let E=We(N);if(E){if(E.type==="agent_registered"){w=!0,f=E.connection||E.agent||null,yn(t,E.agent),D(`Registered as ${E.connection?.name||t.name} on ${E.connection?.host||ge.hostname()}`),t.onRegistered&&Promise.resolve(t.onRegistered(t,E)).catch(O=>{D(`Profile save failed: ${O?.message||O}`)}),Je(t,E.agent).catch(()=>{}),fn(t).catch(()=>{}),wn(r,t),B(),me(r,t,A());return}if(E.type==="agent_config"){yn(t,E.agent),D(`Updated config for @${t.handle||"agent"}: model=${t.model}, permission=${t.permissionMode}`),Je(t,E.agent).catch(()=>{});return}if(E.type==="agent_memory_refresh"){wn(r,t),me(r,t,A());return}if(E.type==="agent_capabilities_refresh"){me(r,t,A());return}if(E.type==="agent_inference_cancel"){h.get(String(E.requestId||""))?.abort();return}if(E.type==="agent_job_cancel"){let O=String(E.jobId||"");O&&a.cancel(O,E.reason||"Cancelled by Agensis")&&D(`Cancelled job ${O}`);return}if(E.type==="agent_inference_request"&&E.requestId){let O=String(E.requestId),$=t.sharedModels.find(P=>P.id===E.model),F=[...h.values()].filter(P=>P.model===E.model).length;if(!$){L(r,{action:"agent_inference_error",requestId:O,error:`Shared model '${E.model||""}' is not available.`});return}if(F>=$.maxConcurrency){L(r,{action:"agent_inference_error",requestId:O,error:"Shared model is at capacity.",code:"capacity_exhausted"});return}let J=new AbortController;h.set(O,{abort:()=>J.abort(),model:$.id}),L(r,{action:"agent_heartbeat",metadata:ze(t,a,null,null,h)}),Xt({models:t.sharedModels,request:E,signal:J.signal,send:P=>L(r,P)}).catch(P=>{L(r,{action:"agent_inference_error",requestId:O,error:J.signal.aborted?"Inference cancelled.":P?.message||String(P),code:J.signal.aborted?"cancelled":"inference_failed"})}).finally(()=>{h.delete(O),L(r,{action:"agent_heartbeat",metadata:ze(t,a,null,null,h)})});return}if(E.type==="peer_ticket"){let O=E.peer?.agentId,$=v.get(O)||[],F=$.shift();$.length?v.set(O,$):v.delete(O),F&&F.resolve(E);return}if(E.type==="peer_ticket_grant"){p.set(E.ticket,{fromAgentId:E.fromAgentId,exp:E.exp});return}if(E.type==="peer_list"){let O=k.shift();O&&O(Array.isArray(E.peers)?E.peers:[]);return}if(E.type==="agent_reach_disable"){d(),me(r,t,A());return}if(E.type==="error"){D(`Server rejected request: ${E.message||"unknown error"}`);return}if(E.type==="agent_disabled"){w=!1,f=null,D(`Agent disabled by Agensis: ${E.reason||"deactivated"}`),y();return}if(E.type==="agent_job"&&E.job?.id){let O=a.enqueue({...E.job,key:E.job.id,lane:gn(E.job),ws:r});O.accepted&&(c+=1,D(`Queued job ${E.job.id} at position ${O.position}`),t.once&&a.idle().then(()=>y()))}}}),r.on("close",(N,E)=>{bn(h),w=!1,f=null;let O=String(E||"");if(D(`Socket closed (${N||"no-code"}${O?`: ${O}`:""})`),o&&(clearInterval(o),o=null),N===1008&&/agent deactivated|authentication failed/i.test(O)){D("Stopping daemon because Agensis rejected this agent connection."),y();return}if(l==="ECONNREFUSED"&&Eo(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",N=>{l=N?.code||"",D(`Socket error: ${N?.message||N}`)})},R=async()=>{let C=await qe(t).catch(()=>null);await sn(t,{busy:a.active()>0,active:a.active(),queueSize:a.size(),connected:r?.readyState===fe.OPEN,agentStatus:C?.status,agentNote:C?.note}).catch(()=>{})};R(),i=setInterval(()=>{R()},t.heartbeatMs),i.unref&&i.unref(),I(),await new Promise(C=>{let N=setInterval(async()=>{t.once&&c>0&&a.active()===0&&a.size()===0&&y(),n&&y()},500);u=()=>{clearInterval(N),C()}}),u=null,x.off("SIGINT",y),x.off("SIGTERM",y)}function wo(e){let t=bo(e.cursorBuddyBridge),n=e.noCoding===!0||x.env.AGENSIS_NO_CODING==="1",s=!ie(e.fullCliContext,ie(x.env.AGENSIS_FULL_CLI_CONTEXT,!1))&&ie(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:Mn(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:Xe(e.model||x.env.AGENSIS_MODEL||x.env.CLAUDE_MODEL||""),permissionMode:Ce(e.permissionMode||e.permission_mode||e.permission||x.env.AGENSIS_PERMISSION_MODE||"default"),timeoutMs:Number(e.timeoutMs||x.env.AGENSIS_TIMEOUT_MS||ho),heartbeatMs:Number(e.heartbeatMs||x.env.AGENSIS_HEARTBEAT_MS||go),maxConcurrency:Math.max(1,Number(e.maxConcurrency||x.env.AGENSIS_MAX_CONCURRENCY||hn)||hn),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:ie(e.fastConnection,ie(x.env.AGENSIS_FAST_CONNECTION,!0)),syncMemory:ie(e.syncMemory,x.env.AGENSIS_SYNC_MEMORY==="1"),hostFolders:kn(e.hostFolders??e.host_folders??x.env.AGENSIS_HOST_FOLDERS)};o.sharedModelsFile&&!he.isAbsolute(o.sharedModelsFile)&&(o.sharedModelsFile=he.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 ie(e,t){return e==null||e===""?t:typeof e=="boolean"?e:!/^(0|false|off|no)$/i.test(String(e).trim())}function bo(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 _o(e,t,n={}){let r=Ve(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 Ve(e){let t=new URL(e);return vo(t)&&(t.protocol="http:",t.hostname="127.0.0.1",t.port="3142"),t}function vo(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 Eo(e){try{let t=Ve(e);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="0.0.0.0")&&t.port==="3142"}catch{return!1}}function gn(e){let t=String(e?.sessionId||""),n=String(e?.threadParentId||"");return`${t}::${n}`}var ko=/\b(cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\b/i,Ao=[/\b(?:make|have|tell)\s+(?:the\s+)?(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\s+(?:say|speak)\s+(.+)$/i];function Io(e){return String(e||"").trim().replace(/^[`"'“”‘’]+|[`"'“”‘’?.!]+$/g,"").trim().slice(0,1200)}function xo(e){for(let t of Ao){let n=String(e||"").match(t),r=Io(n?.[1]||"");if(r)return r}return""}function Co(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 Mo(e){let t=String(e||"").replace(/\s+/g," ").trim(),r=Co(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 To(e){let t=Mo(e);if(!t)return null;let n=/^(open|show|hide|hush|close|dismiss)\b/i.test(t),r=ko.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=xo(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 Oo(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 No(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 _n(e={}){return e.cursorBuddyBridge===!1?!1:!!(e.cursorBuddyRuntime||e.primaryDaemon)}async function $o(e,t,n,r){let s="cursorbuddy-control",o="native",i=[],c=(l="")=>{L(t.ws,{action:"agent_job_delta",jobId:t.id,content:l,elapsedMs:Date.now()-r,model:s,permissionMode:o,permissionFlags:i})};c("");let u="",a="";try{await Oo(e,n),u=No(n),c(u)}catch(l){a=String(l?.message||l),u=`CursorBuddy control failed: ${a}`,c(u)}L(t.ws,{action:"agent_job_result",jobId:t.id,response:u,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 Do(e,t,{signal:n}){let r=Date.now();D(`Starting job ${t.id}`);let s=To(t.prompt);if(s&&_n(e)){await $o(e,t,s,r),e.once&&(D("One-shot CursorBuddy control job complete; exiting."),setTimeout(()=>x.exit(0),150));return}let o=Po(e,t),i=await Bo(e,t),c="",u="",a=0,l=(d="")=>{L(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=>{L(t.ws,{action:"agent_job_step",jobId:t.id,kind:d.kind,name:d.name,detail:d.detail,elapsedMs:Date.now()-r})},w=d=>{L(t.ws,{action:"agent_job_segment",jobId:t.id,text:d.text,elapsedMs:Date.now()-r})};l("");let f=o.streamJson?Lo({onStep:g,onSegment:w}):null,h=setInterval(()=>l(c),1e3);h.unref&&h.unref();let _=!/[\\/]/.test(o.cmd),S=e.fastConnection&&_?xn(o.cmd)?"claude":Cn(o.cmd)?"codex":null:null,v=await Ct(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:An(e,t),leanCli:e.leanCli,mcp:e.leanCli?Ye(e):null,sessionKey:`${t.workspaceId||e.workspace||""}:${e.agent||e.handle||""}`,clientVersion:Q,onData:d=>{f?(f.feed(d),c=f.live):(c+=String(d||""),u=zo(`${u}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
+
`).trim()||"Say that the local Agensis runtime is connected."}function en(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 no(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 s=String(r?.content||"").trim();if(s)return s}return""}function ro(e,t=280){let n=no(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 s of r){let o=n.match(s);if(o?.[0])return o[0].trim()}return n.slice(-t).trim()}function oo(e){let t=ro(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 so(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 on(e,t){let n=String(e||"").trim();return!n||so(n)?t:n}function sn(e){let t=String(e||"").trim();return!t||t==="haiku-4.5"||t==="claude-haiku-4.5"?ze:t}function We(e={}){return sn(e.cursorBuddyModel||Z.env.AGENSIS_CURSORBUDDY_MODEL||ze)}function tn(e,t,n,r={}){let{cmd:s,args:o}=eo(e.codingCmd||"claude -p"),i=[...o],a=sn(on(n,We(e))),u="",c=!1;return to(s)?(a&&!Ce(i,"--model")&&i.push("--model",a),r.stream===!0&&!Ce(i,"--output-format")?(i.push("--output-format","stream-json","--include-partial-messages"),Ce(i,"--verbose")||i.push("--verbose"),c=!0):(Ce(i,"--output-format")||i.push("--output-format","json"),c=i.some(f=>String(f).includes("stream-json"))),u=t):i.push(t),{cmd:s,args:i,model:a,stdin:u,streamJson:c}}function io(e=()=>{}){let t="",n="",r=!1,s="",o=null,i=c=>{c&&e(c)},a=c=>{if(!c||typeof c!="object")return;let d=c.event&&c.event.delta||c.delta;if(d&&d.type==="text_delta"&&typeof d.text=="string"){r=!0,n+=d.text,i(d.text);return}if(c.type==="result"&&typeof c.result=="string"){o=c.result;return}if(c.type==="assistant"&&c.message&&Array.isArray(c.message.content)){let f=c.message.content.filter(y=>y&&y.type==="text"&&typeof y.text=="string").map(y=>y.text).join("");f&&(s+=f)}},u=c=>{let d=String(c).trim();if(d)try{a(JSON.parse(d))}catch{}};return{feed(c){t+=String(c||"");let d;for(;(d=t.indexOf(`
|
|
43
|
+
`))>=0;)u(t.slice(0,d)),t=t.slice(d+1)},end(){t&&(u(t),t="")},get live(){return r?n:s},get result(){return o??(r?n:s)}}}function de(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 Me(e){return`http://127.0.0.1:${e}`}function ao(e={},t={}){return String(t.agensisUrl||t.baseUrl||e.url||Z.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function co(e){return String(e||"").slice(0,18)}function U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function uo(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)||{},a=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:a,selection:U(e.selection)||null,updatedAt:new Date().toISOString()}}function lo(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(!Kr.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=ao(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:rn.hostname(),cwd:t.cwd||e.cwd||Z.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||Z.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(lo(o,i));return{key:r,baseUrl:s,data:i?.data||i}}async function an(e,t={}){let n=Number(t.port??e.cursorBuddyPort??Z.env.AGENSIS_CURSORBUDDY_PORT??Xt),r=Qr(e,t),s=new Date().toISOString(),o=[],i=[],a=new Set,u=t.fetchImpl||globalThis.fetch,c=1,d=null,f=n,y=null,p=(l,w={})=>{let C={ts:new Date().toISOString(),event:l,detail:w};return o.push(C),o.length>200&&o.shift(),t.log?.(`CursorBuddy local bridge: ${l}${Object.keys(w).length?` ${JSON.stringify(w)}`:""}`),C},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 l=t.connectionProvider();return!l||typeof l!="object"||Array.isArray(l)?null:{...h(),...l,connected:l.connected===!0}}catch{return null}},S=()=>{let l=v();return l?.connected===!1?l:y?{...h(),...l||{},...y,connected:!0,updatedAt:l?.updatedAt||y.updatedAt}:l||h()};function g(l={}){if(!l||typeof l!="object"||Array.isArray(l))return null;let w=String(l.action||l.type||"").trim().toLowerCase();if(!Wr.has(w))return null;let C={id:c++,ts:new Date().toISOString(),action:w,text:String(l.text||l.say||l.message||"").slice(0,1200),label:String(l.label||"").slice(0,80),value:String(l.value||l.prompt||"").slice(0,1200),holdMs:Number.isFinite(l.holdMs)?Math.max(0,Math.min(6e4,l.holdMs)):void 0,source:String(l.source||"agensis-daemon").slice(0,80)};return l.options&&Array.isArray(l.options)&&(C.options=l.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)),C}function _(l){for(i.push(l);i.length>zr;)i.shift();p("control",{id:l.id,action:l.action,chars:l.text.length});for(let w of[...a])try{K(w,{type:"command",command:l})}catch{a.delete(w)}return l}function k(l){let w=oo(l);if(w){let C=g(w.command);return C&&(_(C),p("chat_control",{id:C.id,action:C.action})),{content:w.content,model:"cursorbuddy-local-control",fast:!0}}return null}async function A(l){let w=k(l);if(w)return w;let C=Zt(l?.messages,d),m=tn(e,C,l?.model),b=await Y({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(b.error||b.status!==0)throw new Error(b.error?.message||String(b.stderr||"").trim()||`Command exited with status ${b.status}`);return{content:en(b.stdout||b.stderr),model:m.model}}async function T(l,w){let C=`agensis-cursorbuddy-${Date.now()}`,m=k(l);if(m){let D=m.model||"cursorbuddy-local-control";return K(w,de(C,D,m.content)),K(w,de(C,D,"","stop")),K(w,"[DONE]"),p("chat_fast",{chars:m.content.length,model:D}),{content:m.content,model:D,fast:!0}}let b=Zt(l?.messages,d),I=tn(e,b,l?.model,{stream:!0}),R="",M=D=>{D&&(R+=D,K(w,de(C,I.model||e.model,D)))},$=I.streamJson?io(M):null,E=await Y({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:D=>{if($)$.feed(D);else{let F=String(D||"");R+=F,K(w,de(C,I.model||e.model,F))}}});if($){$.end();let D=$.result||"";!R&&D?M(D):R=D||R}if(E.error||E.status!==0){let D=E.error?.message||String(E.stderr||"").trim()||`Command exited with status ${E.status}`;throw new Error(D)}let N=$?R:en(R||E.stdout||E.stderr);return!$&&N&&N!==R&&(K(w,de(C,I.model||e.model,N)),R=N),K(w,de(C,I.model||e.model,"","stop")),K(w,"[DONE]"),{content:R||N,model:I.model}}let B=qr.createServer(async(l,w)=>{if(w.setHeader("access-control-allow-origin","*"),w.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),w.setHeader("access-control-allow-headers","content-type, authorization, x-agensis-bridge-secret"),l.method==="OPTIONS"){w.writeHead(204),w.end();return}let C=new URL(l.url||"/",Me(f||Xt));if(!Zr(l.method,C.pathname)&&!Xr(l,r)){j(w,401,{ok:!1,error:"Authentication required",code:"bridge_auth_required"});return}if(l.method==="GET"&&C.pathname==="/cursorbuddy/health"){let m=Me(f);j(w,200,{ok:!0,runtime:"agensis-cli",backend:e.codingCmd,model:We(e),daemonModel:e.model,port:f,host:rn.hostname(),pid:Z.pid,bootedAt:s,authRequired:!0,authHeader:Te,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:d,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(l.method==="GET"&&C.pathname==="/cursorbuddy/logs"){j(w,200,{ok:!0,events:o.slice(-100)});return}if(l.method==="GET"&&C.pathname==="/cursorbuddy/context"){j(w,200,{ok:!0,context:d});return}if(l.method==="GET"&&C.pathname==="/cursorbuddy/control"){let m=Number(C.searchParams.get("after")||0),b=i.filter(I=>I.id>m);j(w,200,{ok:!0,commands:b,latestId:i.at(-1)?.id||0});return}if(l.method==="GET"&&C.pathname==="/cursorbuddy/control/stream"){let m=Number(C.searchParams.get("after")||0);Qt(w),a.add(w),K(w,{type:"ready",latestId:i.at(-1)?.id||0});for(let I of i.filter(R=>R.id>m))K(w,{type:"command",command:I});let b=setInterval(()=>{try{K(w,{type:"ping",ts:new Date().toISOString()})}catch{a.delete(w),clearInterval(b)}},15e3);b.unref&&b.unref(),l.on("close",()=>{a.delete(w),clearInterval(b)});return}if(l.method==="POST"&&C.pathname==="/cursorbuddy/control"){try{let m=JSON.parse(await ge(l)||"{}"),b=g(m);if(!b){j(w,400,{ok:!1,error:"unsupported CursorBuddy control command"});return}let I=_(b);j(w,200,{ok:!0,command:I})}catch(m){p("control_error",{error:String(m?.message||m)}),j(w,400,{ok:!1,error:String(m?.message||m)})}return}if(l.method==="POST"&&C.pathname==="/cursorbuddy/context"){try{let m=JSON.parse(await ge(l)||"{}");d={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()},p("context",{url:d.url,surface:d.surface,instanceId:d.instanceId}),j(w,200,{ok:!0,context:d})}catch(m){p("context_error",{error:String(m?.message||m)}),j(w,400,{ok:!1,error:String(m?.message||m)})}return}if(l.method==="POST"&&C.pathname==="/cursorbuddy/connect"){try{let m=JSON.parse(await ge(l)||"{}"),b=await mo(e,m,u),I=b.data||{};y={connected:!0,mode:"agensis-claimed",keyId:co(b.key),agentId:String(I.agentId||I.agent?.id||e.agent||""),workspaceId:String(I.workspaceId||I.workspace_id||I.agent?.workspace_id||e.workspace||""),agensisUrl:b.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||Z.cwd()),surface:String(m.surface||"browser_extension"),command:String(I.command||I.localCommand||""),updatedAt:new Date().toISOString()},d=uo(m,y,e),p("connect",{mode:y.mode,keyId:y.keyId,agentId:y.agentId,workspaceId:y.workspaceId,url:d.url}),j(w,200,{ok:!0,connection:y,claim:I})}catch(m){p("connect_error",{error:String(m?.message||m)}),j(w,400,{ok:!1,error:String(m?.message||m)})}return}if(l.method==="POST"&&C.pathname==="/cursorbuddy/edit"){try{let m=JSON.parse(await ge(l)||"{}"),b=[{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)}];p("edit_request",{selector:m?.target?.selector||""});let I=await A({messages:b,model:m?.model});p("edit_done",{chars:I.content.length}),j(w,200,{ok:!0,backend:e.codingCmd,cwd:e.cwd,content:I.content})}catch(m){p("edit_error",{error:String(m?.message||m)}),j(w,500,{ok:!1,error:String(m?.message||m)})}return}if(l.method==="POST"&&C.pathname.endsWith("/chat/completions")){try{let m=JSON.parse(await ge(l)||"{}");if(p("chat_request",{messages:Array.isArray(m.messages)?m.messages.length:0,model:on(m.model,We(e))}),m.stream===!0){Qt(w);let I=await T(m,w);p("chat_done",{chars:I.content.length,stream:!0,fast:I.fast===!0}),w.end();return}let b=await A(m);p("chat_done",{chars:b.content.length,fast:b.fast===!0}),j(w,200,{id:`agensis-cursorbuddy-${Date.now()}`,object:"chat.completion",model:b.model||m.model||e.model,choices:[{index:0,message:{role:"assistant",content:b.content},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}})}catch(m){p("chat_error",{error:String(m?.message||m)}),j(w,500,{error:{message:String(m?.message||m)}})}return}w.writeHead(404),w.end("CursorBuddy local bridge")});return await new Promise((l,w)=>{B.once("error",w),B.listen(n,"127.0.0.1",()=>{f=B.address().port,B.off("error",w),l()})}),p("listening",{url:`${Me(f)}/cursorbuddy/health`}),{port:f,url:Me(f),secret:r,authHeader:Te,close(){return new Promise(l=>B.close(()=>l()))},getContext(){return d}}}import me from"node:fs/promises";import fo from"node:os";import z from"node:path";var cn=200,un=256*1024,po=2,ho=new Set([".md",".markdown",".txt"]);function go(e){return String(e||"").replace(/[^a-zA-Z0-9]/g,"-")}function Ye({cwd:e,memoryDir:t,homedir:n=fo.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",go(s),"memory"):null}async function Ve(e){if(!e)return null;try{let t=await me.realpath(e);return(await me.stat(t)).isDirectory()?t:null}catch{return null}}async function yo(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 me.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 So(e){let t=z.basename(e).toLowerCase();return t==="memory.md"?"index":t==="claude.md"?"instructions":"memory"}async function Xe(e,t,n,r){if(n>po||r.length>=cn)return;let s;try{s=await me.readdir(t,{withFileTypes:!0})}catch{return}for(let o of s){if(r.length>=cn)break;if(o.name.startsWith("."))continue;let i=z.join(t,o.name);if(o.isDirectory())await Xe(e,i,n+1,r);else if(o.isFile()&&ho.has(z.extname(o.name).toLowerCase())){let a=z.relative(e,i);r.push({path:a,kind:So(a)})}}}async function wo(e){let t=await Ve(e);if(!t)return[];let n=[];return await Xe(t,t,0,n),n.sort((r,s)=>r.kind==="index"?-1:s.kind==="index"?1:r.path.localeCompare(s.path)),n}async function bo(e,t){let n=await Ve(e),r=await yo(n,t),s=await me.readFile(r),o=s.length>un;return{content:s.subarray(0,un).toString("utf8"),byteSize:s.length,truncated:o}}async function ln(e){let t=await Ve(e);if(!t)return"";let n=[];await Xe(t,t,0,n),n.sort((s,o)=>s.path.localeCompare(o.path));let r=[];for(let s of n)try{let o=await me.stat(z.join(t,s.path));r.push(`${s.path}:${o.size}:${Math.floor(o.mtimeMs)}`)}catch{}return r.join("|")}async function dn(e){let t=await wo(e),n=[];for(let r of t)try{let{content:s,byteSize:o}=await bo(e,r.path);n.push({path:r.path,kind:r.kind,content:s,byteSize:o})}catch{}return n}import Ze from"node:fs";import ee from"node:path";import mn from"node:os";function _o(e){try{return Ze.statSync(e).isDirectory()}catch{return!1}}function vo(e){try{return Ze.statSync(e).isFile()}catch{return!1}}function Qe(e){try{return Ze.readdirSync(e,{withFileTypes:!0})}catch{return[]}}function fn({home:e=mn.homedir(),cwd:t=process.cwd()}={}){let n=[e&&ee.join(e,".claude","commands"),t&&ee.join(t,".claude","commands")].filter(Boolean),r=new Set,s=[],o=(i,a)=>{if(!i)return;let u=a?`${a}:${i}`:i;r.has(u)||(r.add(u),s.push({name:i,parent:a||null}))};for(let i of n)for(let a of Qe(i)){if(a.name.startsWith("."))continue;if(a.name.endsWith(".md")){o(a.name.slice(0,-3),null);continue}let u=ee.join(i,a.name);if(a.isDirectory()||a.isSymbolicLink()&&_o(u))for(let c of Qe(u))c.name.startsWith(".")||c.name.endsWith(".md")&&o(c.name.slice(0,-3),a.name)}return s}function et({home:e=mn.homedir(),cwd:t=process.cwd()}={}){let n=[e&&ee.join(e,".claude","skills"),e&&ee.join(e,".codex","skills"),t&&ee.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 Qe(o)){if(i.name.startsWith("."))continue;let a=ee.join(o,i.name);if(i.name.endsWith(".md"))s(i.name.slice(0,-3),a);else if(i.isDirectory()||i.isSymbolicLink()){let u=ee.join(a,"SKILL.md");s(i.name,vo(u)?u:"")}}return[...r.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function pn(e={}){return et(e).map(t=>t.name)}import tt from"node:fs/promises";var fe=64*1024,Eo=200,gn=4*1024*1024,ko=2e3,Ao=512;function hn(e,t,n=fe){let r=`
|
|
44
|
+
|
|
45
|
+
... [truncated by agensis-agent: ${t}]
|
|
46
|
+
`,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 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()==="---"),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,ko)}function yn(e){try{return et(e).slice(0,Eo)}catch{return[]}}async function xo(e){let t;try{t=await tt.open(e,"r")}catch{return null}try{let n=Buffer.alloc(fe+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 xo(e.file);if(!n)return null;let r=n.toString("utf8"),s=Io(r),o=n.length>fe,i=Math.min(fe,Math.max(0,t)),a=Buffer.byteLength(r)>i;if(!o&&!a)return{skill:e.name,path:e.file,summary:s,content:r,truncated:!1};let u=o?await Mo(e.file):0,c=o&&!a?`the file is ${u?`${u} bytes`:`over ${fe} bytes`}; only the first ${fe} were synced`:`this sync reached its ${gn}-byte ceiling`,d=i<Ao?hn("",c,Number.MAX_SAFE_INTEGER):hn(r,c,i);return{skill:e.name,path:e.file,summary:s,content:d,truncated:!0}}async function Mo(e){try{return(await tt.stat(e)).size}catch{return 0}}async function nt(e={}){let t=[];for(let n of yn(e)){if(!n.file){t.push(`${n.name}:-`);continue}try{let r=await tt.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 Sn(e={}){let t=[],n=0;for(let r of yn(e))if(r.file)try{let s=await Co(r,gn-n);if(!s)continue;n+=Buffer.byteLength(s.content),t.push(s)}catch{}return t}import{readFile as To}from"node:fs/promises";var No=new Set(["127.0.0.1","localhost","::1","[::1]"]);function wn(e,t,n){let r=Number(e);return Number.isFinite(r)?Math.max(1,Math.min(n,Math.trunc(r))):t}function Oo(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(!No.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:wn(e.contextWindow,void 0,1e7)}:{},maxConcurrency:wn(e.maxConcurrency,1,64),shared:!0}}async function bn(e){if(!e)return[];let t=JSON.parse(await To(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(Oo).filter(Boolean)}function _n(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 vn({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 a=(Array.isArray(e)?e:[]).find(g=>g.id===t?.model);if(!a)throw new Error(`Shared model '${t?.model||""}' is not available.`);let u={"content-type":"application/json"},c=a.apiKeyEnv?o[a.apiKeyEnv]:"";c&&(u.authorization=`Bearer ${c}`),n({action:"agent_inference_started",requestId:i,model:a.id});let{requestId:d,model:f,type:y,action:p,...h}=t,v=await s(`${a.baseUrl}/chat/completions`,{method:"POST",headers:u,body:JSON.stringify({...h,model:a.upstreamModel,stream:t.stream===!0}),signal:r});if(!v.ok){let g=await v.text().catch(()=>"");throw new Error(g||`Local model returned HTTP ${v.status}.`)}if(t.stream===!0){if(!v.body)throw new Error("Local model returned an empty stream.");let g=v.body.getReader(),_=new TextDecoder,k="",A,T=w=>{let C=w.trim();if(!C.startsWith("data:"))return!1;let m=C.slice(5).trim();if(!m)return!1;if(m==="[DONE]")return!0;try{let b=JSON.parse(m);b?.usage&&(A=b.usage),n({action:"agent_inference_delta",requestId:i,model:a.id,chunk:b})}catch{}return!1},B=!1;for(;!B;){let{done:w,value:C}=await g.read();k+=_.decode(C||new Uint8Array,{stream:!w});let m=k.split(/\r?\n/);k=w?"":m.pop()||"";for(let b of m)if(T(b)){B=!0;break}if(w)break}k&&T(k);let l={action:"agent_inference_result",requestId:i,model:a.id,...A?{usage:A}:{}};return n(l),l}let S=await v.json();return n({action:"agent_inference_result",requestId:i,model:a.id,response:S}),S}$e();var Xo=30*60*1e3,Qo=15*1e3,Un=2,Zo=10*1024,es="claude-opus-4-8",re="0.1.33";async function Be(e={}){let t=ts(e);t.sharedModels=t.share?await bn(t.sharedModelsFile):[];let n=!1,r=null,s=null,o=null,i=null,a=0,u=null,c=null,d="",f=null,y=!1,p=null,h=new Map,v=null,S={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"},g=new Map,_=new Map,k=[],A=()=>S,T=()=>({connected:y&&!!t.cursorBuddyRuntime,mode:t.cursorBuddyRuntime?"agensis-cli":"agensis-cli-unclaimed",agentId:p?.agentId||p?.agent_id||t.agent,workspaceId:p?.workspaceId||p?.workspace_id||t.workspace,agensisUrl:t.url,handle:p?.handle||t.handle,name:p?.name||t.name,cwd:t.cwd,updatedAt:new Date().toISOString()}),B=()=>{v||!t.lanListener||(v=new we.Server({port:0}),v.on("listening",()=>{let{port:M}=v.address();S={transport:"ws",listening:!0,addrs:xs(M),auth:"hub-pairwise"},O(`Agent-mesh LAN listener on port ${M}`),Se(r,t,A())}),v.on("connection",M=>{let $=!1,E=setTimeout(()=>{if(!$)try{M.close(1008,"peer auth required")}catch{}},5e3);M.once("message",N=>{clearTimeout(E);let D=ut(N),F=D?.type==="peer_auth"?g.get(D.ticket):null;if(!F||F.fromAgentId!==D.fromAgentId||Date.now()>F.exp){try{M.close(1008,"invalid ticket")}catch{}return}g.delete(D.ticket),$=!0,M.on("message",J=>{let L=ut(J);L?.type==="agent_job"&&L.job?.id&&c.enqueue({...L.job,key:L.job.id,lane:Fn(L.job),ws:r}).accepted&&O(`Queued peer-handoff job ${L.job.id} from ${D.fromAgentId}`)})})}),v.on("error",M=>O(`LAN listener error: ${M?.message||M}`)))},l=()=>{if(v){try{v.close()}catch{}v=null}S={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"}},w=M=>new Promise(($,E)=>{if(!P(r,{action:"peer_ticket_request",targetAgentId:M})){E(new Error("hub socket not open"));return}let N=_.get(M)||[];N.push({resolve:$,reject:E}),_.set(M,N),setTimeout(()=>{let D=_.get(M)||[],F=D.findIndex(J=>J.resolve===$);F>=0&&(D.splice(F,1),E(new Error("peer ticket request timed out")))},1e4)}),C=()=>new Promise((M,$)=>{if(!P(r,{action:"peer_list_request"})){$(new Error("hub socket not open"));return}k.push(M),setTimeout(()=>{let E=k.indexOf(M);E>=0&&(k.splice(E,1),M([]))},1e4)}),m=async(M,$)=>{let E=null;try{let D=(await C()).find(L=>L.agentId===M&&L.reach?.listening&&L.reach.addrs?.length);if(!D)return!1;let F=await w(M),J=F.peer?.addrs?.[0]||D.reach.addrs[0];return!J?.host||!J?.port?!1:(E=new we(`ws://${J.host}:${J.port}`),await new Promise((L,Fe)=>{E.once("open",L),E.once("error",Fe),setTimeout(()=>Fe(new Error("peer connect timed out")),5e3)}),P(E,{type:"peer_auth",ticket:F.ticket,fromAgentId:t.agent}),P(E,{type:"agent_job",job:$}),!0)}catch(N){return O(`Peer handoff to ${M} failed, falling back to hub relay: ${N?.message||N}`),!1}finally{try{E?.close()}catch{}}},b=()=>{n=!0,Jn(h),s&&clearTimeout(s),o&&clearInterval(o),i&&clearInterval(i),f&&(f.close().catch(()=>{}),f=null),l(),Nn(t,{status:"stopped",connected:!1});try{r?.close()}catch{}u&&u()};if(c=Vt({concurrency:t.once?1:t.maxConcurrency,runJob:async(M,$)=>{await gs(t,M,$),t.once&&b()}}),t.cursorBuddyBridge)try{f=await an(t,{port:t.cursorBuddyPort,authSecret:t.cursorBuddyBridgeSecret||void 0,log:O,connectionProvider:T}),f?.secret&&(t.cursorBuddyBridgeSecret=f.secret)}catch(M){if(Ns(M)){let $=await Os(t.cursorBuddyPort);if($?.ok){let E=$.pid?` pid ${$.pid}`:"";O(`CursorBuddy local bridge already running on http://127.0.0.1:${t.cursorBuddyPort}${E}`)}else O(`CursorBuddy local bridge port ${t.cursorBuddyPort} is in use but did not answer health`)}else O(`CursorBuddy local bridge unavailable: ${M?.message||M}`);f=null}x.once("SIGINT",b),x.once("SIGTERM",b);let I=()=>{if(n)return;let M=rs(t.url,t.token,t);d="",O(`Connecting to ${M.replace(t.token,"redacted")}`),r=new we(M),r.on("open",async()=>{y=!1,p=null,O(`Connected. Registering @${t.handle||"agent"} from ${t.cwd}`),P(r,{type:"auth",token:t.token});let $=await $n(t);P(r,{action:"agent_register",workspaceId:t.workspace,agentId:t.agent,handle:t.handle,name:t.name,host:_e.hostname(),cwd:t.cwd,...$?{identity:$}:{},metadata:{codingCmd:t.codingCmd,model:t.model,permissionMode:t.permissionMode,permissionFlags:ft(t.permissionMode),once:t.once,runtime:"agensis",version:re}}),o=setInterval(()=>{Promise.all([Xn(t,A()).catch(()=>null),it(t).catch(()=>null)]).then(([E,N])=>{P(r,{action:"agent_heartbeat",...E?{capabilitiesHash:E.capabilitiesHash,memoryHash:E.memoryHash}:{},...E?.skillsHash?{skillsHash:E.skillsHash}:{},metadata:ct(t,c,N,qn(t)?f?.getContext?.():null,h)})})},t.heartbeatMs),o.unref&&o.unref()}),r.on("message",$=>{let E=ut($);if(E){if(E.type==="agent_registered"){y=!0,p=E.connection||E.agent||null,jn(t,E.agent),O(`Registered as ${E.connection?.name||t.name} on ${E.connection?.host||_e.hostname()}`),t.onRegistered&&Promise.resolve(t.onRegistered(t,E)).catch(N=>{O(`Profile save failed: ${N?.message||N}`)}),st(t,E.agent).catch(()=>{}),Pn(t).catch(()=>{}),Gn(r,t),Hn(r,t),B(),Se(r,t,A());return}if(E.type==="agent_config"){jn(t,E.agent),O(`Updated config for @${t.handle||"agent"}: model=${t.model}, permission=${t.permissionMode}`),st(t,E.agent).catch(()=>{});return}if(E.type==="agent_memory_refresh"){Gn(r,t),Se(r,t,A());return}if(E.type==="agent_capabilities_refresh"){Se(r,t,A());return}if(E.type==="agent_skills_refresh"){Hn(r,t);return}if(E.type==="agent_inference_cancel"){h.get(String(E.requestId||""))?.abort();return}if(E.type==="agent_job_cancel"){let N=String(E.jobId||"");N&&c.cancel(N,E.reason||"Cancelled by Agensis")&&O(`Cancelled job ${N}`);return}if(E.type==="agent_inference_request"&&E.requestId){let N=String(E.requestId),D=t.sharedModels.find(L=>L.id===E.model),F=[...h.values()].filter(L=>L.model===E.model).length;if(!D){P(r,{action:"agent_inference_error",requestId:N,error:`Shared model '${E.model||""}' is not available.`});return}if(F>=D.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:D.id}),P(r,{action:"agent_heartbeat",metadata:ct(t,c,null,null,h)}),vn({models:t.sharedModels,request:E,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:ct(t,c,null,null,h)})});return}if(E.type==="peer_ticket"){let N=E.peer?.agentId,D=_.get(N)||[],F=D.shift();D.length?_.set(N,D):_.delete(N),F&&F.resolve(E);return}if(E.type==="peer_ticket_grant"){g.set(E.ticket,{fromAgentId:E.fromAgentId,exp:E.exp});return}if(E.type==="peer_list"){let N=k.shift();N&&N(Array.isArray(E.peers)?E.peers:[]);return}if(E.type==="agent_reach_disable"){l(),Se(r,t,A());return}if(E.type==="error"){O(`Server rejected request: ${E.message||"unknown error"}`);return}if(E.type==="agent_disabled"){y=!1,p=null,O(`Agent disabled by Agensis: ${E.reason||"deactivated"}`),b();return}if(E.type==="agent_job"&&E.job?.id){let N=c.enqueue({...E.job,key:E.job.id,lane:Fn(E.job),ws:r});N.accepted&&(a+=1,O(`Queued job ${E.job.id} at position ${N.position}`),t.once&&c.idle().then(()=>b()))}}}),r.on("close",($,E)=>{Jn(h),y=!1,p=null;let N=String(E||"");if(O(`Socket closed (${$||"no-code"}${N?`: ${N}`:""})`),o&&(clearInterval(o),o=null),$===1008&&/agent deactivated|authentication failed/i.test(N)){O("Stopping daemon because Agensis rejected this agent connection."),b();return}if(d==="ECONNREFUSED"&&ss(t.url)){O("Local agent backend is not running on 127.0.0.1:3142."),O("Start it in another terminal with: npm run backend"),O("Then rerun this connect command."),b();return}t.once&&a>0&&c.active()===0&&c.size()===0&&b(),!(n||t.once)&&(s=setTimeout(I,2e3),s.unref&&s.unref())}),r.on("error",$=>{d=$?.code||"",O(`Socket error: ${$?.message||$}`)})},R=async()=>{let M=await it(t).catch(()=>null);await Tn(t,{busy:c.active()>0,active:c.active(),queueSize:c.size(),connected:r?.readyState===we.OPEN,agentStatus:M?.status,agentNote:M?.note}).catch(()=>{})};R(),i=setInterval(()=>{R()},t.heartbeatMs),i.unref&&i.unref(),I(),await new Promise(M=>{let $=setInterval(async()=>{t.once&&a>0&&c.active()===0&&c.size()===0&&b(),n&&b()},500);u=()=>{clearInterval($),M()}}),u=null,x.off("SIGINT",b),x.off("SIGTERM",b)}function ts(e){let t=ns(e.cursorBuddyBridge),n=e.noCoding===!0||x.env.AGENSIS_NO_CODING==="1",s=!te(e.fullCliContext,te(x.env.AGENSIS_FULL_CLI_CONTEXT,!1))&&te(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:er(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(),ampCmd:String(e.ampCmd||x.env.AGENSIS_AMP_CMD||"amp").trim()||"amp",model:mt(e.model||x.env.AGENSIS_MODEL||x.env.CLAUDE_MODEL||""),permissionMode:Re(e.permissionMode||e.permission_mode||e.permission||x.env.AGENSIS_PERMISSION_MODE||"default"),timeoutMs:Number(e.timeoutMs||x.env.AGENSIS_TIMEOUT_MS||Xo),heartbeatMs:Number(e.heartbeatMs||x.env.AGENSIS_HEARTBEAT_MS||Qo),maxConcurrency:Math.max(1,Number(e.maxConcurrency||x.env.AGENSIS_MAX_CONCURRENCY||Un)||Un),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:te(e.fastConnection,te(x.env.AGENSIS_FAST_CONNECTION,!0)),syncMemory:te(e.syncMemory,x.env.AGENSIS_SYNC_MEMORY==="1"),syncSkills:te(e.syncSkills,te(x.env.AGENSIS_SYNC_SKILLS,!0)),hostFolders:Yn(e.hostFolders??e.host_folders??x.env.AGENSIS_HOST_FOLDERS)};o.sharedModelsFile&&!ce.isAbsolute(o.sharedModelsFile)&&(o.sharedModelsFile=ce.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 te(e,t){return e==null||e===""?t:typeof e=="boolean"?e:!/^(0|false|off|no)$/i.test(String(e).trim())}function ns(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 rs(e,t,n={}){let r=dt(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 dt(e){let t=new URL(e);return os(t)&&(t.protocol="http:",t.hostname="127.0.0.1",t.port="3142"),t}function os(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 ss(e){try{let t=dt(e);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="0.0.0.0")&&t.port==="3142"}catch{return!1}}function Fn(e){let t=String(e?.sessionId||""),n=String(e?.threadParentId||"");return`${t}::${n}`}var is=/\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 cs(e){return String(e||"").trim().replace(/^[`"'“”‘’]+|[`"'“”‘’?.!]+$/g,"").trim().slice(0,1200)}function us(e){for(let t of as){let n=String(e||"").match(t),r=cs(n?.[1]||"");if(r)return r}return""}function ls(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 ds(e){let t=String(e||"").replace(/\s+/g," ").trim(),r=ls(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 ms(e){let t=ds(e);if(!t)return null;let n=/^(open|show|hide|hush|close|dismiss)\b/i.test(t),r=is.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=us(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 fs(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)}),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 ps(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 qn(e={}){return e.cursorBuddyBridge===!1?!1:!!(e.cursorBuddyRuntime||e.primaryDaemon)}async function hs(e,t,n,r){let s="cursorbuddy-control",o="native",i=[],a=(d="")=>{P(t.ws,{action:"agent_job_delta",jobId:t.id,content:d,elapsedMs:Date.now()-r,model:s,permissionMode:o,permissionFlags:i})};a("");let u="",c="";try{await fs(e,n),u=ps(n),a(u)}catch(d){c=String(d?.message||d),u=`CursorBuddy control failed: ${c}`,a(u)}P(t.ws,{action:"agent_job_result",jobId:t.id,response:u,error:c,elapsedMs:Date.now()-r,model:s,permissionMode:o,permissionFlags:i}),O(`Finished native CursorBuddy ${n.action} job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s`)}async function gs(e,t,{signal:n}){let r=Date.now();if(O(`Starting job ${t.id}`),qt(t)){await ys(e,t,{signal:n,started:r}),e.once&&(O("One-shot Amp job complete; exiting."),setTimeout(()=>x.exit(0),150));return}let s=ms(t.prompt);if(s&&qn(e)){await hs(e,t,s,r),e.once&&(O("One-shot CursorBuddy control job complete; exiting."),setTimeout(()=>x.exit(0),150));return}let o=bs(e,t),i=await Ss(e,t),a="",u="",c=0,d=(l="")=>{P(t.ws,{action:"agent_job_delta",jobId:t.id,content:l,elapsedMs:Date.now()-r,model:o.model,permissionMode:o.permissionMode,permissionFlags:o.permissionFlags})},f=l=>{P(t.ws,{action:"agent_job_step",jobId:t.id,kind:l.kind,name:l.name,detail:l.detail,elapsedMs:Date.now()-r})},y=l=>{P(t.ws,{action:"agent_job_segment",jobId:t.id,text:l.text,elapsedMs:Date.now()-r})};d("");let p=o.streamJson?Kn({onStep:f,onSegment:y}):null,h=setInterval(()=>d(a),1e3);h.unref&&h.unref();let v=!/[\\/]/.test(o.cmd),S=e.fastConnection&&v?Qn(o.cmd)?"claude":Zn(o.cmd)?"codex":null:null,_=await Ht(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:Vn(e,t),leanCli:e.leanCli,mcp:e.leanCli?lt(e):null,sessionKey:`${t.workspaceId||e.workspace||""}:${e.agent||e.handle||""}`,clientVersion:re,onData:l=>{p?(p.feed(l),a=p.live):(a+=String(l||""),u=Ts(`${u}
|
|
47
|
+
${l}`));let w=Date.now();w-c>150&&(c=w,d(a))}});clearInterval(h),p&&(p.end(),a=p.live,d(a));let k=String(_.stdout||"").trim(),A=String(_.stderr||"").trim(),T=_.error?_.error.message:_.status===0?"":A||`Command exited with status ${_.status}`,B=p?p.result||(T?"":A):k||(T?"":A)||u||"";P(t.ws,{action:"agent_job_result",jobId:t.id,response:B,error:T,elapsedMs:Date.now()-r,model:o.model,permissionMode:o.permissionMode,permissionFlags:o.permissionFlags}),O(`Finished job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s`),e.once&&(O("One-shot job complete; exiting."),setTimeout(()=>x.exit(0),150))}async function ys(e,t,{signal:n,started:r=Date.now()}={}){let s="amp-orb",o="amp-managed",i=[],a=(l="")=>P(t.ws,{action:"agent_job_delta",jobId:t.id,content:l,elapsedMs:Date.now()-r,model:s,permissionMode:o,permissionFlags:i}),u=l=>P(t.ws,{action:"agent_job_step",jobId:t.id,kind:l.kind,name:l.name,detail:l.detail,elapsedMs:Date.now()-r}),c=l=>P(t.ws,{action:"agent_job_segment",jobId:t.id,text:l.text,elapsedMs:Date.now()-r}),d=({response:l="",error:w="",errorCode:C="",threadId:m=""}={})=>{let b=le(m);P(t.ws,{action:"agent_job_result",jobId:t.id,response:l,error:w,errorCode:C||void 0,elapsedMs:Date.now()-r,model:s,permissionMode:o,permissionFlags:i,metadata:{runtime:"amp",...b?{ampThreadId:b,ampThreadUrl:`https://ampcode.com/threads/${b}`}:{},...C?{ampErrorCode:C}:{}}})};a("");let f=ce.resolve(String(t.cwd||e.cwd)),y=[e.cwd,...e.hostFolders||[]];try{await Wt({cwd:f,allowedRoots:y});let l=await Ke({cwd:f,executable:e.ampCmd,signal:n});if(!l.available)throw V(l.reason||"amp_cli_crashed")}catch(l){let w=n?.aborted?"amp_turn_cancelled":String(l?.code||"amp_cli_crashed");d({error:l?.message||V(w).message,errorCode:w}),O(`Amp job ${t.id} refused: ${w}`);return}let p=String(t?.runtime?.threadId||t?.ampThreadId||t?.metadata?.ampThreadId||"").trim(),h=le(p);if(t?.runtime?.continuationRequired===!0&&!h||p&&!h){let l=V("amp_thread_not_found");d({error:l.message,errorCode:l.code}),O(`Amp job ${t.id} refused: ${l.code}`);return}let v=Kt({executable:e.ampCmd,prompt:String(t.prompt||""),threadId:h}),S=Kn({onStep:u,onSegment:c}),g=zt(),_="",k=0,A=setInterval(()=>a(_),1e3);A.unref&&A.unref();let T=await Y({cmd:v.cmd,args:v.args,cwd:f,timeoutMs:e.timeoutMs,heartbeatMs:e.heartbeatMs,label:"Amp orb turn",signal:n,onData:l=>{S.feed(l),g.feed(l),_=S.live;let w=Date.now();w-k>150&&(k=w,a(_))}});clearInterval(A),S.end(),g.end(),_=S.live,a(_);let B=g.threadId||h;if(T.status!==0||T.error){let l=Yt(T);d({error:l.message,errorCode:l.code,threadId:B}),O(`Amp job ${t.id} failed: ${l.code}`);return}if(!B){let l=V("amp_stream_invalid");d({error:l.message,errorCode:l.code}),O(`Amp job ${t.id} failed: ${l.code}`);return}d({response:S.result||"",threadId:B}),O(`Finished Amp job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s (${B})`)}async function Ss(e,t){let n=t.agent||{},r=Array.isArray(n.skills)?n.skills.join(", "):String(n.skills||""),s=Array.isArray(n.tools)?n.tools.join(", "):String(n.tools||""),o=zn(e,t),i=Wn(e,t),a=await Ln(e).catch(()=>null),u=a?`Heartbeat (recurring instructions \u2014 edit at ${Mn(e)}):
|
|
48
|
+
${a}`:"",d=["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: ${o}`,`Permission mode: ${i}`,n.description?`Description:
|
|
42
49
|
${n.description}`:"",n.soul?`Soul:
|
|
43
50
|
${n.soul}`:"",n.system_prompt?`System instructions:
|
|
44
51
|
${n.system_prompt}`:"",n.instructions?`Additional instructions:
|
|
45
52
|
${n.instructions}`:"",s?`Enabled tools:
|
|
46
53
|
${s}`:"",r?`Enabled skills:
|
|
47
|
-
${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 ${
|
|
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 ${Cn(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 ${at(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.`,u,"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(`
|
|
48
55
|
|
|
49
|
-
`);return e.leanCli?
|
|
56
|
+
`);return e.leanCli?ws(d,Zo):d}function ws(e,t){let n=String(e||"");if(Buffer.byteLength(n,"utf8")<=t)return n;let r=`[... older or optional Agensis context omitted ...]
|
|
50
57
|
|
|
51
|
-
`,s=Math.max(0,t-Buffer.byteLength(r,"utf8")),o=[...n],i=0,
|
|
52
|
-
`))>=0;)h(n.slice(0,S)),n=n.slice(S+1)},end(){n&&(h(n),n="")},get live(){return s?r:o},get result(){return
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
`,s=Math.max(0,t-Buffer.byteLength(r,"utf8")),o=[...n],i=0,a=o.length;for(;i<a;){let u=Math.ceil((i+a)/2),c=o.slice(o.length-u).join("");Buffer.byteLength(c,"utf8")<=s?i=u:a=u-1}return r+o.slice(o.length-i).join("")}function bs(e,t){let{cmd:n,args:r}=Ms(e.codingCmd),s=zn(e,t),o=Wn(e,t),i=Cs(r),a=ft(o),u=Vn(e,t);if(Qn(n)){let c=[...i];s&&c.push("--model",s);let d;if(e.leanCli){let h=lt(e);c.push("--no-session-persistence","--safe-mode","--mcp-config",JSON.stringify({mcpServers:{agensis:{type:"http",url:h.url,headers:{Authorization:"Bearer ${AGENSIS_MCP_TOKEN}"}}}}),"--strict-mcp-config"),d=h.env}if(o==="accept_edits"&&c.push("--permission-mode","acceptEdits"),o==="yolo"){let h=t&&t.agent&&t.agent.run_mode==="sandbox",v=typeof x.getuid=="function"&&x.getuid()===0,S=h||vs(),g=x.env.AGENSIS_ALLOW_ROOT_SKIP_PERMISSIONS==="1";S||!v||g?c.push("--dangerously-skip-permissions"):(a=[],O("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 f=i.some(h=>h==="--output-format"||String(h).startsWith("--output-format=")),y=i.includes("-p")||i.includes("--print"),p=!1;!f&&y?(c.push("--output-format","stream-json","--include-partial-messages"),i.includes("--verbose")||c.push("--verbose"),p=!0):f&&(p=i.some(h=>/stream-json/.test(String(h))));for(let h of u)c.push("--add-dir",h);return{cmd:n,args:c,model:s,permissionMode:o,permissionFlags:a,streamJson:p,env:d}}if(Zn(n)){let c=[...i];s&&c.push("--model",s);let d;if(e.leanCli&&i.includes("exec")){let f=lt(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(f.url)}`,"-c",'mcp_servers.agensis.bearer_token_env_var="AGENSIS_MCP_TOKEN"'),d=f.env}return o==="yolo"&&c.push("--sandbox","danger-full-access","--ask-for-approval","never"),{cmd:n,args:c,model:s,permissionMode:o,permissionFlags:a,env:d}}return{cmd:n,args:r,model:s,permissionMode:o,permissionFlags:a}}function lt(e){let t=dt(e.url);return t.pathname="/backend/mcp",t.search="",t.hash="",{url:t.toString(),env:{AGENSIS_MCP_TOKEN:e.token}}}function Kn({onStep:e,onSegment:t}={}){let n="",r="",s=!1,o="",i="",a=null,u=!1,c=!1,d=new Set,f=v=>{if(!(typeof e!="function"||!v.name))try{e(v)}catch{}},y=v=>{if(typeof t=="function"){i+=s?r:o,r="",o="";try{t(v)}catch{}}},p=v=>{if(!v||typeof v!="object")return;if(v.type==="agensis_step"){let g=v.step;g&&typeof g=="object"&&(u=!0,f({kind:g.kind||"tool",name:String(g.name||""),detail:String(g.detail||"")}));return}if(v.type==="agensis_segment"){let g=v.segment;g&&typeof g=="object"&&(c=!0,y({text:String(g.text||"")}));return}let S=v.event&&v.event.delta||v.delta;if(S&&S.type==="text_delta"&&typeof S.text=="string"){s=!0,r+=S.text;return}if(v.type==="result"&&typeof v.result=="string"){a=v.result;return}if(v.type==="assistant"&&v.message&&Array.isArray(v.message.content)){let g=v.message.content.filter(_=>_&&_.type==="text"&&typeof _.text=="string").map(_=>_.text).join("");if(g&&(o+=g),g&&!c&&y({text:g}),!u)for(let _ of v.message.content){if(!_||_.type!=="tool_use")continue;let k=typeof _.id=="string"?_.id:"";if(k){if(d.has(k))continue;d.add(k)}f({kind:"tool",name:String(_.name||""),detail:Ge(_.input)})}}},h=v=>{let S=String(v).trim();if(S)try{p(JSON.parse(S))}catch{}};return{feed(v){n+=String(v||"");let S;for(;(S=n.indexOf(`
|
|
59
|
+
`))>=0;)h(n.slice(0,S)),n=n.slice(S+1)},end(){n&&(h(n),n="")},get live(){return s?r:o},get result(){return a??i+(s?r:o)}}}function zn(e,t){return mt(t?.agent?.model||t?.model||e.model)}function mt(e){let t=String(e||"").trim();return!t||t==="auto"||t==="claude-fable-5"?es:t}function Wn(e,t){return Re(t?.agent?.permissionMode||t?.agent?.permission_mode||t?.permissionMode||t?.permission_mode||e.permissionMode)}function Re(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 ft(e){return Re(e)==="yolo"?["--no-sandbox","--yolo"]:[]}function Yn(e){let t=Array.isArray(e)?e:String(e||"").split(/[,\n]/),n=new Set,r=[];for(let s of t){let o=String(s||"").trim();!o||n.has(o)||(n.add(o),r.push(o))}return r}function _s(e,t){let n=t?.agent?.metadata?.host_folders??t?.agent?.hostFolders??t?.hostFolders??t?.host_folders,r=Yn(n);return r.length>0?r:e.hostFolders||[]}function Vn(e,t){let n=_s(e,t),r=q({workspace:e.workspace,agent:e.agent});return r&&!n.includes(r)?[...n,r]:n}var ae;function vs(){if(ae!==void 0)return ae;let e=x.env;if(e.AGENSIS_ALLOW_ROOT_SKIP_PERMISSIONS==="1"||e.AGENSIS_SANDBOX_HOST==="1"||e.IS_SANDBOX==="1")return ae=!0;if(e.AGENSIS_NO_SANDBOX_AUTODETECT==="1")return ae=!1;try{if(be.existsSync("/.dockerenv")||be.existsSync("/run/.containerenv"))return ae=!0}catch{}try{let t=be.readFileSync("/proc/1/cgroup","utf8");if(/docker|kubepods|containerd|lxc|podman/i.test(t))return ae=!0}catch{}return ae=!1}function ct(e,t,n,r=null,s=null){let o={busy:t.active()>0,queueSize:t.size(),cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,permissionFlags:ft(e.permissionMode),daemon:{runtime:"agensis-cli",version:re,pid:x.pid,node:x.version,platform:x.platform,arch:x.arch,host:_e.hostname(),cwd:e.cwd}};if(s instanceof Map){let i={};for(let a of s.values()){let u=String(a?.model||"");u&&(i[u]=(i[u]||0)+1)}o.activeInferenceByModel=i}return r&&typeof r=="object"&&(o.cursorBuddy=Es(r)),n?.status&&(o.agentStatus=n.status),n?.note&&(o.agentNote=n.note),(n?.status||n?.note)&&(o.agentStatusAt=new Date().toISOString()),o}function Es(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:{},s=e.manifest&&typeof e.manifest=="object"?e.manifest:{},o=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(s.name||"").slice(0,120),version:String(s.version||"").slice(0,80),source:String(s.source||"").slice(0,500)},project:{name:String(o.name||"").slice(0,120),root:String(o.root||"").slice(0,500),agent:String(o.agent||"").slice(0,80)},updatedAt:String(e.updatedAt||"").slice(0,80)}}function jn(e,t){if(!t||typeof t!="object")return;t.name&&(e.name=String(t.name).trim()||e.name),(t.handle||t.name)&&(e.handle=er(t.handle||t.name||e.handle)),t.model&&(e.model=mt(t.model));let n=t.permissionMode||t.permission_mode;n&&(e.permissionMode=Re(n)),(t.memory_dir!==void 0||t.memoryDir!==void 0)&&(e.memoryDir=String(t.memory_dir??t.memoryDir??"").trim())}function ks(){let e=["amp","claude","codex","gh","node","npm","python3","git","fly","vercel"],t=(x.env.PATH||"").split(ce.delimiter).filter(Boolean);return e.filter(n=>t.some(r=>{try{return be.existsSync(ce.join(r,n))}catch{return!1}}))}function As(){try{let e=be.readFileSync(ce.join(_e.homedir(),".claude.json"),"utf8"),n=JSON.parse(e)?.mcpServers;if(n&&typeof n=="object")return Object.keys(n).sort()}catch{}return[]}function De(e){return Vo.createHash("sha1").update(String(e)).digest("hex").slice(0,16)}async function Xn(e,t=null){let n=pn({cwd:e.cwd}),r=fn({cwd:e.cwd}),s=ks(),o=As(),i=e.syncMemory&&Ye({cwd:e.cwd,memoryDir:e.memoryDir})||null,a=_n(e.sharedModels),c={amp:await Is(e)},d=De(JSON.stringify({skills:n,commands:r,clis:s,mcpServers:o,memoryRoot:i,sharedModels:a,runtimes:c,codingRoute:!!e.codingCmd,shared:e.share,reach:t||null})),f=De(await ln(i)),y=e.syncSkills?De(await nt({cwd:e.cwd})):null;return{skills:n,commands:r,clis:s,mcpServers:o,memoryRoot:i,sharedModels:a,runtimes:c,codingRoute:!!e.codingCmd,shared:e.share,reach:t||null,capabilitiesHash:d,memoryHash:f,skillsHash:y}}var ne=null;async function Is(e){let t=`${e.ampCmd}
|
|
60
|
+
${ce.resolve(e.cwd)}`;if(ne?.key===t&&Date.now()-ne.at<6e4)return ne.value??ne.pending;let n=Ke({cwd:e.cwd,executable:e.ampCmd});ne={key:t,at:Date.now(),pending:n};try{let r=await n;return ne={key:t,at:Date.now(),value:r},r}catch(r){throw ne?.pending===n&&(ne=null),r}}async function Se(e,t,n=null){try{let r=await Xn(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}),O(`Capabilities synced \u2014 skills:${r.skills.length} commands:${r.commands.length} clis:${r.clis.length} mcp:${r.mcpServers.length}`)}catch(r){O(`Capabilities sync skipped: ${r?.message||r}`)}}function xs(e){let t=_e.networkInterfaces(),n=[];for(let r of Object.values(t))for(let s of r||[])s.family==="IPv4"&&!s.internal&&n.push({host:s.address,port:e,scope:"lan"});return n.slice(0,4)}async function Gn(e,t){try{if(!t.syncMemory)return;let n=Ye({cwd:t.cwd,memoryDir:t.memoryDir});if(!n)return;let r=await dn(n);P(e,{action:"agent_memory_sync",workspaceId:t.workspace,agentId:t.agent,root:n,files:r}),O(`Synced ${r.length} memory file${r.length===1?"":"s"} from ${n}`)}catch(n){O(`Memory sync skipped: ${n?.message||n}`)}}async function Hn(e,t){try{if(!t.syncSkills)return;let n=De(await nt({cwd:t.cwd})),r=await Sn({cwd:t.cwd});P(e,{action:"agent_skill_sync",workspaceId:t.workspace,agentId:t.agent,hash:n,skills:r});let s=r.filter(o=>o.truncated).length;O(`Synced ${r.length} skill document${r.length===1?"":"s"}${s?` (${s} truncated)`:""}`)}catch(n){O(`Skill sync skipped: ${n?.message||n}`)}}function Cs(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 s=0;s<e.length;s+=1){let o=e[s],[i]=String(o).split("=",1);if(!n.has(o)){if(t.has(i)){String(o).includes("=")||(s+=1);continue}r.push(o)}}return r}function Qn(e){return/(^|\/)claude(?:$|\.)/.test(String(e||""))}function Zn(e){return/(^|\/)codex(?:$|\.)/.test(String(e||""))}function Ms(e){let t=[],n="",r="",s=!1;for(let o of e){if(s){n+=o,s=!1;continue}if(o==="\\"){s=!0;continue}if(r){o===r?r="":n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n&&(t.push(n),n="");continue}n+=o}if(n&&t.push(n),!t.length)throw new Error("coding command is empty");return{cmd:t[0],args:t.slice(1)}}function ut(e){try{return JSON.parse(String(e))}catch{return null}}function P(e,t){return!e||e.readyState!==we.OPEN?!1:(e.send(JSON.stringify(t)),!0)}function Ts(e){return String(e||"").split(/\r?\n/).map(t=>t.trim()).filter(Boolean).slice(-1)[0]||""}function er(e){return String(e||"").trim().toLowerCase().replace(/^@+/,"").replace(/[^a-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function Ns(e){return e?.code==="EADDRINUSE"||/\bEADDRINUSE\b/.test(String(e?.message||e))}async function Os(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}),s=await r.json().catch(()=>({}));return!r.ok||!s?.ok?null:s}catch{return null}finally{clearTimeout(n)}}function O(e){x.stderr.write(`[agensis] ${e}
|
|
61
|
+
`)}function Jn(e){if(e instanceof Map)for(let t of e.values())try{t?.abort?.()}catch{}}import $s from"node:crypto";import ve from"node:fs/promises";import Ds from"node:os";import tr from"node:path";var ue="default",nr=2,Bs=/^[a-zA-Z0-9_.-]{1,64}$/,Rs=["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 W(e=ue){let t=String(e||ue).trim();if(!Bs.test(t))throw new Error("Daemon profile names may only contain letters, numbers, dot, dash, and underscore.");return t}function rr(e=ue,t={}){let n=t.homedir||Ds.homedir();return tr.join(n,".agensis","daemon-profiles",`${W(e)}.json`)}function pt(e={}){let t={};for(let n of Rs){let r=e[n];r!=null&&r!==""&&(t[n]=r)}return t}function oe(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 or(e={}){return!!(oe(e,["url","baseUrl"],["AGENSIS_URL"])||oe(e,["token"],["AGENSIS_TOKEN"])||oe(e,["workspace","workspaceId"],["AGENSIS_WORKSPACE","AGENSIS_WORKSPACE_ID"])||oe(e,["agent","agentId"],["AGENSIS_AGENT","AGENSIS_AGENT_ID"]))}function ht(e={}){return!!(oe(e,["url","baseUrl"],["AGENSIS_URL"])&&oe(e,["token"],["AGENSIS_TOKEN"])&&oe(e,["workspace","workspaceId"],["AGENSIS_WORKSPACE","AGENSIS_WORKSPACE_ID"])&&oe(e,["agent","agentId"],["AGENSIS_AGENT","AGENSIS_AGENT_ID"]))}async function gt(e=ue,t={}){let n=rr(e,t),r;try{r=await ve.readFile(n,"utf8")}catch(a){if(a?.code==="ENOENT")return null;throw a}let s;try{s=JSON.parse(r)}catch(a){throw new Error(`Daemon profile "${W(e)}" is unreadable: ${a?.message||a}`)}let o=s?.config;if(!o?.url||!o?.token||!o?.workspace||!o?.agent)return null;let i=pt(o);return Number(s.version||1)<nr&&Number(i.maxConcurrency)===8&&(i.maxConcurrency=2),i}async function Pe(e=ue,t={},n={}){let r=pt(t);if(!r.url||!r.token||!r.workspace||!r.agent)return null;let s=rr(e,n),o=tr.dirname(s);await ve.mkdir(o,{recursive:!0,mode:448});let i=`${s}.${process.pid}.${Date.now()}.tmp`,a={version:nr,savedAt:new Date().toISOString(),profile:W(e),tokenHash:$s.createHash("sha256").update(r.token).digest("hex"),config:r};return await ve.writeFile(i,`${JSON.stringify(a,null,2)}
|
|
62
|
+
`,{mode:384}),await ve.rename(i,s),await ve.chmod(s,384).catch(()=>{}),s}function sr(e,t={}){let n={...e,...pt(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 yt(e=ue){let t=W(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 Ps from"node:crypto";import Ee from"node:fs/promises";import ir from"node:os";import St from"node:path";import wt from"node:process";var Ls=/^cbk_[a-z0-9_]+_[A-Z2-9]{18}$/;function Us(e={}){return String(e.url||e.baseUrl||wt.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function ar(e,t={}){let n=t.homedir||ir.homedir(),r=Ps.createHash("sha256").update(String(e)).digest("hex");return St.join(n,".agensis","cursorbuddy","connection-keys",`${r}.json`)}function Fs(){return new Error("Missing or invalid --key. Create a CursorBuddy connection key in Agensis first.")}function bt(e){let t=String(e||"").trim();if(!Ls.test(t))throw Fs();return t}function js(e,t,n,r){let s=t?.token,o=t?.workspaceId||t?.workspace_id||t?.agent?.workspace_id,i=t?.agentId||t?.agent?.id;if(!s||!o||!i)throw new Error("CursorBuddy key claim did not return a complete daemon connection payload");let{key:a,subcommand:u,...c}=e;return{...c,command:"connect",url:t.baseUrl||n,token:s,workspace:o,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 Gs(e,t={}){bt(e);let n=ar(e,t),r;try{r=await Ee.readFile(n,"utf8")}catch(i){if(i?.code==="ENOENT")return null;throw i}let s;try{s=JSON.parse(r)}catch(i){throw new Error(`Cached CursorBuddy daemon config is unreadable: ${i?.message||i}`)}let o=s?.daemonArgs;return!o?.token||!o?.workspace||!o?.agent||!o?.url?null:o}async function Hs(e,t,n={}){if(bt(e),!t?.token||!t?.workspace||!t?.agent||!t?.url)return;let r=ar(e,n),s=St.dirname(r);await Ee.mkdir(s,{recursive:!0,mode:448});let o=`${r}.${wt.pid}.${Date.now()}.tmp`,i={version:1,savedAt:new Date().toISOString(),keyHash:St.basename(r,".json"),daemonArgs:t};await Ee.writeFile(o,`${JSON.stringify(i,null,2)}
|
|
64
|
+
`,{mode:384}),await Ee.rename(o,r),await Ee.chmod(r,384).catch(()=>{})}function Js(e,t,n){let r={...e,command:"connect"};for(let s of["cwd","codingCmd","model","permissionMode","timeoutMs","heartbeatMs","maxConcurrency","share","sharedModelsFile","noCoding","leanCli","lanListener","once"])t[s]!==void 0&&(r[s]=t[s]);return t.codingCmd!==void 0&&t.noCoding===void 0&&(r.noCoding=!1),r.cwd||(r.cwd=n),r.cursorBuddyRuntime=!0,r}function qs(e,t){return t?.error?.message||t?.message||`CursorBuddy key claim failed with HTTP ${e.status}`}async function Ks(e){return e.json().catch(()=>({}))}async function cr(e,t={}){let n=bt(e?.key),r=Us(e),s=t.fetchImpl||globalThis.fetch;if(typeof s!="function")throw new Error("This Node.js runtime does not provide fetch; use a current Node.js release.");let o=t.cwd||wt.cwd(),i=t.hostname||ir.hostname(),a=t.version||re,u={homedir:t.homedir},c=await s(`${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||o,name:e.name,surface:e.surface||"local_cli",scope:e.scope||"machine",runtimeKind:"agensis-cli",version:a,permissionMode:e.permissionMode,model:e.model})}),d=await Ks(c);if(!c.ok){let y=qs(c,d);if(c.status===409||/already been claimed/i.test(y)){let p=await Gs(n,u);if(p)return Js(p,e,o);throw new Error(`${y}. 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(y)}let f=js(e,d?.data||d,r,o);return await Hs(n,f,u),f}import zs from"node:crypto";import Ws from"node:http";import Ys from"node:os";import X from"node:process";import{spawn as Vs}from"node:child_process";var Xs="https://agensis.io",Qs=10*60*1e3;function Le(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 Zs(e){return new Promise((t,n)=>{let r="";e.on("data",s=>{r+=s,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 ei(e){let t=String(e||X.env.AGENSIS_URL||Xs).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 ti(e){let t=X.platform==="darwin"?"open":X.platform==="win32"?"cmd":"xdg-open",n=X.platform==="win32"?["/c","start","",e]:[e],r=Vs(t,n,{detached:!0,stdio:"ignore"});r.on("error",()=>{}),r.unref()}function ni(e){let t=e?.daemonArgs||e?.data?.daemonArgs||e?.data||{},r=["url","token","workspace","agent"].filter(s=>!String(t[s]||"").trim());if(r.length)throw new Error(`Setup callback did not include ${r.join(", ")}`);return{...t,command:"connect"}}function ri(e,t,n){let r=new URL(ei(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",W(e.profile||"default")),r.searchParams.set("host",Ys.hostname()),r.searchParams.set("cwd",String(e.cwd||X.cwd())),e.handle&&r.searchParams.set("handle",String(e.handle)),e.name&&r.searchParams.set("name",String(e.name)),r.toString()}async function ur(e={}){let t=W(e.profile||"default"),n=zs.randomBytes(24).toString("base64url"),r=Number(e.setupTimeoutMs||X.env.AGENSIS_SETUP_TIMEOUT_MS||Qs),s,o=new Promise((c,d)=>{let f=setTimeout(()=>d(new Error("Agensis setup timed out waiting for browser login.")),r);f.unref&&f.unref(),s=Ws.createServer(async(y,p)=>{if(p.setHeader("access-control-allow-origin","*"),p.setHeader("access-control-allow-methods","POST, OPTIONS"),p.setHeader("access-control-allow-headers","content-type"),y.method==="OPTIONS"){p.writeHead(204),p.end();return}if(y.method!=="POST"||y.url!=="/agensis/setup-callback"){Le(p,404,{ok:!1,error:"Unknown Agensis setup callback route"});return}try{let h=JSON.parse(await Zs(y)||"{}");if(h?.state!==n){Le(p,403,{ok:!1,error:"Setup state did not match"});return}let v={...ni(h),primaryDaemon:!0,cursorBuddyBridge:e.cursorBuddyBridge!==!1};await Pe(t,v),clearTimeout(f),Le(p,200,{ok:!0,profile:t}),c(v)}catch(h){Le(p,400,{ok:!1,error:String(h?.message||h)})}}),s.once("error",d)});await new Promise((c,d)=>{s.listen(0,"127.0.0.1",f=>f?d(f):c())});let{port:i}=s.address(),a=`http://127.0.0.1:${i}/agensis/setup-callback`,u=ri(e,a,n);X.stdout.write(`[agensis] Opening Agensis to sign in and connect this machine.
|
|
65
|
+
`),X.stdout.write(`[agensis] If the browser did not open, visit:
|
|
58
66
|
${u}
|
|
59
|
-
`),
|
|
60
|
-
`),
|
|
67
|
+
`),ti(u);try{let c=await o;return X.stdout.write(`[agensis] Saved daemon profile "${t}". Starting primary agent daemon.
|
|
68
|
+
`),c}finally{await new Promise(c=>s.close(()=>c())).catch(()=>{})}}function yi(e){let t={command:"connect"},n=[...e],r=n[0];if(r&&!r.startsWith("-")&&(t.command=n.shift(),t.command==="buddy")){let s=n[0];s&&!s.startsWith("-")?t.subcommand=n.shift():t.subcommand="connect"}for(let s=0;s<n.length;s+=1){let o=n[s];if(!o.startsWith("--"))throw new Error(`Unexpected argument: ${o}`);let[i,a]=o.slice(2).split(/=(.*)/s,2),u=i.replace(/-([a-z])/g,(d,f)=>f.toUpperCase());if(u==="help"){t.help=!0;continue}if(u==="version"){t.version=!0;continue}if(u==="once"){t.once=!0;continue}if(u==="lan"){t.lanListener=!0;continue}if(u==="share"){t.share=!0;continue}if(u==="noCoding"){t.noCoding=!0;continue}if(u==="fullCliContext"){t.fullCliContext=!0;continue}if(u==="syncMemory"){t.syncMemory=!0;continue}if(u==="noSyncSkills"){t.syncSkills=!1;continue}if(u==="cursorbuddyBridge"){t.cursorBuddyBridge=!0;continue}if(u==="noCursorbuddyBridge"){t.cursorBuddyBridge=!1;continue}if(u==="yolo"||u==="noSandbox"){t.permissionMode="yolo";continue}if(u==="acceptEdits"){t.permissionMode="accept_edits";continue}if(u==="hostFolder"||u==="hostFolders"||u==="addDir"){let d=a!==void 0?a:n[++s];if(d==null||d.startsWith("--"))throw new Error(`Missing value for --${i}`);t.hostFolders=[...t.hostFolders||[],d];continue}let c=a!==void 0?a:n[++s];if(c==null||c.startsWith("--"))throw new Error(`Missing value for --${i}`);t[u]=c}return t}function Si(){return`agensis agent daemon
|
|
61
69
|
|
|
62
70
|
Usage:
|
|
63
71
|
agensis --url <workspace-url> --token <token> --workspace <id> --agent <id> [options]
|
|
@@ -80,11 +88,14 @@ Options:
|
|
|
80
88
|
--cwd <path> Folder where the coding CLI runs
|
|
81
89
|
--host-folder <path> Extra folder the coding CLI may read/write (repeatable; passed as --add-dir)
|
|
82
90
|
--coding-cmd <command> Command used for jobs, default: claude -p
|
|
91
|
+
--amp-cmd <path> Amp CLI executable, default: amp
|
|
83
92
|
--no-coding Disable coding jobs; keep presence/shared inference only
|
|
84
93
|
--full-cli-context Load all user CLI skills, plugins, hooks, memory, and MCPs
|
|
85
94
|
(default isolates Claude/Codex to project + Agensis context)
|
|
86
95
|
--sync-memory Opt in to mirroring this project's Claude memory files
|
|
87
96
|
to the connected Agensis workspace (default: off)
|
|
97
|
+
--no-sync-skills Stop mirroring the text of this machine's skills to the
|
|
98
|
+
workspace; only their names are advertised (default: on)
|
|
88
99
|
--model <id> Default model to pass to supported coding CLIs
|
|
89
100
|
--permission-mode <m> default, accept_edits, or yolo
|
|
90
101
|
--yolo Alias for --permission-mode yolo
|
|
@@ -113,7 +124,7 @@ agensis supervise [--profile <name>] [--poll-ms <ms>]
|
|
|
113
124
|
"agensis connect" once first). Recommended under a process manager with its
|
|
114
125
|
own restart policy (systemd Restart=always, launchd KeepAlive, pm2) so the
|
|
115
126
|
supervisor itself is recovered if it's ever killed.
|
|
116
|
-
`}async function
|
|
117
|
-
`)}}:e}async function
|
|
118
|
-
`);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
|
|
119
|
-
`),
|
|
127
|
+
`}async function wi(e){let t=e.profile!==void 0,n=e.handle||e.name,r=W(e.profile||(ht(e)&&n?n:"default"));if(!or(e)){let s=await gt(r);if(!s)throw new Error(yt(r));return sr(s,e)}return ht(e)?{...e,cursorBuddyBridge:e.cursorBuddyBridge===!0,onRegistered:async s=>{await Pe(r,s);let o=t||r!=="default"?`agensis connect --profile ${r}`:"agensis connect";Q.stdout.write(`[agensis] Saved daemon profile "${r}". Restart with: ${o}
|
|
128
|
+
`)}}:e}async function bi(){let e=yi(Q.argv.slice(2));if(e.help){Q.stdout.write(Si());return}if(e.version){Q.stdout.write(`${re}
|
|
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 cr(e);n.cursorBuddyBridge=e.cursorBuddyBridge!==!1,n.cursorBuddyRuntime=!0,n.exitOnOnce=!0,await Be(n),n.once&&Q.exit(0);return}if(e.command==="supervise"){let n=W(e.profile||"default"),r=await gt(n);if(!r)throw new Error(yt(n));let{runSupervisor:s}=await Promise.resolve().then(()=>(gr(),hr)),o=e.pollMs?Number(e.pollMs):void 0;await s({config:r,runningVersion:re,profileName:n,pollIntervalMs:o});return}if(e.command==="setup"){let n=await ur(e);n.exitOnOnce=!0,await Be({...e,...n}),n.once&&Q.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 wi(e);t.exitOnOnce=!0,await Be(t),t.once&&Q.exit(0)}bi().catch(e=>{Q.stderr.write(`${e?.message||e}
|
|
130
|
+
`),Q.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.33",
|
|
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": {
|