@agensis/agensis-agent 0.0.5 → 0.1.22
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 +57 -12
- package/package.json +1 -1
package/bin/agensis.mjs
CHANGED
|
@@ -1,40 +1,85 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
${
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import Y from"node:process";import Mt from"node:fs";import ce from"node:path";import ue from"node:os";import Dn from"node:crypto";import k from"node:process";import ae from"ws";import{spawn as Wt}from"node:child_process";function je(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 zt=50*1024*1024;function oe(e){let{cmd:t,args:n=[],cwd:r,timeoutMs:o=0,label:s="working",heartbeatMs:i=15e3,input:c="",now:u=Date.now,log:l=console,signal:p,onData:y}=e||{};return new Promise(S=>{if(p?.aborted){S({status:null,stdout:"",stderr:"",aborted:!0,error:new Error("cancelled")});return}let h;try{h=Wt(t,n,{cwd:r,detached:!0})}catch(a){S({status:null,stdout:"",stderr:"",error:a});return}c?h.stdin?.end(String(c)):h.stdin?.end();let $="",O="";h.stdout?.setEncoding("utf8"),h.stderr?.setEncoding("utf8");let b=(a,g)=>a.length>=zt?a:a+g;h.stdout?.on("data",a=>{if($=b($,a),y)try{y(a)}catch{}}),h.stderr?.on("data",a=>O=b(O,a));let w=u(),A=i>0?setInterval(()=>{l.log(` \u2026 still ${s} (${je(u()-w)}) \u2014 Ctrl+C to cancel`)},i):null;A?.unref&&A.unref();let N=a=>{if(h.pid!=null)try{process.kill(-h.pid,a)}catch{try{h.kill(a)}catch{}}},B=!1,F=o>0?setTimeout(()=>{B=!0,N("SIGKILL")},o):null;F?.unref&&F.unref();let L=!1,d=null,f=()=>{L=!0,N("SIGTERM"),d=setTimeout(()=>N("SIGKILL"),3e3),d?.unref&&d.unref()};p&&p.addEventListener("abort",f,{once:!0});let v=(a,g)=>{A&&clearInterval(A),F&&clearTimeout(F),d&&clearTimeout(d),p&&p.removeEventListener("abort",f),S({status:a,stdout:$,stderr:O,aborted:L,error:g||(L?new Error("cancelled"):B?new Error(`timed out after ${je(o)}`):null)})};h.on("error",a=>v(null,a)),h.on("close",a=>v(a,null))})}function Fe(e={}){let{runJob:t}=e,n=Math.max(1,Number(e.concurrency)||1),r=new Map,o=0,s=[];function i(b){let w=r.get(b);return w||(w={queued:[],active:null},r.set(b,w)),w}function c(b){if(b==null)return!1;for(let w of r.values())if(w.active&&!w.active.cancelled&&w.active.job.key===b||w.queued.some(A=>A.key===b))return!0;return!1}function u(){for(let[b,w]of r){if(o>=n)break;if(w.active||w.queued.length===0)continue;let A=w.queued.shift(),N=new AbortController;w.active={job:A,controller:N,cancelled:!1},o+=1,Promise.resolve().then(()=>N.signal.aborted?void 0:t(A,{signal:N.signal})).catch(()=>{}).finally(()=>{w.active=null,o-=1,w.queued.length===0&&!w.active&&r.delete(b),u(),l()})}}function l(){if(o>0)return;for(let w of r.values())if(w.queued.length)return;let b=s;s=[];for(let w of b)w()}function p(b){if(b&&b.key!=null&&c(b.key))return{accepted:!1,deduped:!0,position:0,startedImmediately:!1};let w=b&&b.lane!=null?String(b.lane):"",A=i(w),N=!A.active&&A.queued.length===0&&o<n;A.queued.push(b);let B=A.queued.length+(A.active?1:0);return u(),{accepted:!0,deduped:!1,position:B,startedImmediately:N}}function y(b,w){let A=!1;for(let[N,B]of r)w!=null&&N!==String(w)||B.active&&(B.active.cancelled=!0,B.active.controller.abort(b||"cancelled"),A=!0);return A}function S(b,w){if(b==null)return!1;let A=!1;for(let[N,B]of[...r]){B.active?.job?.key===b&&(B.active.cancelled=!0,B.active.controller.abort(w||"cancelled"),A=!0);let F=B.queued.length;B.queued=B.queued.filter(L=>L.key!==b),B.queued.length!==F&&(A=!0),!B.active&&B.queued.length===0&&r.delete(N)}return l(),A}function h(){let b=0;for(let w of r.values())b+=w.queued.length;return b}function $(){return o}function O(){return o===0&&h()===0?Promise.resolve():new Promise(b=>s.push(b))}return{enqueue:p,cancel:S,cancelActive:y,has:c,size:h,active:$,idle:O}}import Ke from"node:crypto";import Kt from"node:http";import qe from"node:os";import X from"node:process";var Ge=8787,ke="claude-haiku-4-5",qt=/^cbk_[a-z0-9_]+_[A-Z2-9]{18}$/,Yt=100,Xt=new Set(["say","wave","hush","open","choose"]),pe="x-agensis-bridge-secret";function Vt(){return`cbs_${Ke.randomBytes(24).toString("base64url")}`}function Qt(e){let t=e?.headers||{},n=String(t[pe]||t[pe.toLowerCase()]||"").trim();if(n)return n;let o=String(t.authorization||t.Authorization||"").trim().match(/^Bearer\s+(.+)$/i);return o?o[1].trim():""}function Zt(e,t){let n=String(t||""),r=Qt(e);if(!n||!r)return!1;let o=Buffer.from(r),s=Buffer.from(n);return o.length!==s.length?!1:Ke.timingSafeEqual(o,s)}function en(e={},t={}){let n=String(t.authSecret||"").trim();if(n)return n;let r=String(e.cursorBuddyBridgeSecret||"").trim();if(r)return r;let o=String(X.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim();return o||Vt()}function tn(e,t){return e==="OPTIONS"||e==="GET"&&t==="/cursorbuddy/health"}function U(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 He(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 H(e,t){e.write(`data: ${typeof t=="string"?t:JSON.stringify(t)}
|
|
3
|
+
|
|
4
|
+
`)}function se(e){return new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o,r.length>256*1024&&(n(new Error("request body is too large")),e.destroy())}),e.on("error",n),e.on("end",()=>t(r))})}function nn(e){let t=[],n="",r="",o=!1;for(let s of String(e||"")){if(o){n+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(r){s===r?r="":n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n&&(t.push(n),n="");continue}n+=s}if(n&&t.push(n),!t.length)throw new Error("coding command is empty");return{cmd:t[0],args:t.slice(1)}}function rn(e){return/(^|\/)claude(?:$|\.)/.test(String(e||""))}function me(e,t){return e.some(n=>n===t||String(n).startsWith(`${t}=`))}function Je(e,t){let n=[];t&&n.push("CursorBuddy local runtime context:",JSON.stringify(t,null,2),"");for(let r of Array.isArray(e)?e:[]){let o=String(r?.role||"user"),s=String(r?.content||"");s.trim()&&n.push(`${o.toUpperCase()}:
|
|
5
|
+
${s}`)}return n.join(`
|
|
6
|
+
|
|
7
|
+
`).trim()||"Say that the local Agensis runtime is connected."}function We(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 on(e){let t=Array.isArray(e?.messages)?e.messages:[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(String(r?.role||"user")!=="user")continue;let o=String(r?.content||"").trim();if(o)return o}return""}function sn(e,t=280){let n=on(e).replace(/\s+/g," ").trim();if(!n)return"";if(n.length<=t)return n;let r=[/\b(tell me (?:a )?joke)\b/i,/\b(make (?:him|the buddy|cursorbuddy|avatar) wave|wave(?: hello)?|say hi|say hello)\b/i,/\b(what site|which site|what page|where am i|where are you|current url)\b/i,/\b(are you connected|connected|working|online|there)\b/i,/\b(show|guide|tour|walk|around|sections?|features?|important|highlight|what can i do|what should i do|help me)\b/i,/\b(open|show|bring up|get back|display)\b.{0,80}\b(prompt|bubble|dialog|panel|options|menu)\b/i,/\b(hide|hush|close|dismiss|clear|stop|cancel|be quiet)\b.{0,80}\b(bubble|prompt|dialog|panel|options|menu)?\b/i,/^(hi|hello|hey|yo|sup)\b/i];for(let o of r){let s=n.match(o);if(s?.[0])return s[0].trim()}return n.slice(-t).trim()}function an(e){let t=sn(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 cn(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 Ye(e,t){let n=String(e||"").trim();return!n||cn(n)?t:n}function Xe(e){let t=String(e||"").trim();return!t||t==="haiku-4.5"||t==="claude-haiku-4.5"?ke:t}function ve(e={}){return Xe(e.cursorBuddyModel||X.env.AGENSIS_CURSORBUDDY_MODEL||ke)}function ze(e,t,n,r={}){let{cmd:o,args:s}=nn(e.codingCmd||"claude -p"),i=[...s],c=Xe(Ye(n,ve(e))),u="",l=!1;return rn(o)?(c&&!me(i,"--model")&&i.push("--model",c),r.stream===!0&&!me(i,"--output-format")?(i.push("--output-format","stream-json","--include-partial-messages"),me(i,"--verbose")||i.push("--verbose"),l=!0):(me(i,"--output-format")||i.push("--output-format","json"),l=i.some(y=>String(y).includes("stream-json"))),u=t):i.push(t),{cmd:o,args:i,model:c,stdin:u,streamJson:l}}function un(e=()=>{}){let t="",n="",r=!1,o="",s=null,i=l=>{l&&e(l)},c=l=>{if(!l||typeof l!="object")return;let p=l.event&&l.event.delta||l.delta;if(p&&p.type==="text_delta"&&typeof p.text=="string"){r=!0,n+=p.text,i(p.text);return}if(l.type==="result"&&typeof l.result=="string"){s=l.result;return}if(l.type==="assistant"&&l.message&&Array.isArray(l.message.content)){let y=l.message.content.filter(S=>S&&S.type==="text"&&typeof S.text=="string").map(S=>S.text).join("");y&&(o+=y)}},u=l=>{let p=String(l).trim();if(p)try{c(JSON.parse(p))}catch{}};return{feed(l){t+=String(l||"");let p;for(;(p=t.indexOf(`
|
|
8
|
+
`))>=0;)u(t.slice(0,p)),t=t.slice(p+1)},end(){t&&(u(t),t="")},get live(){return r?n:o},get result(){return s??(r?n:o)}}}function Z(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 fe(e){return`http://127.0.0.1:${e}`}function ln(e={},t={}){return String(t.agensisUrl||t.baseUrl||e.url||X.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function dn(e){return String(e||"").slice(0,18)}function R(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function mn(e={},t={},n={}){let r=R(e.metadata)||{},o=R(e.page)||R(r.page)||{},s=R(e.client)||R(r.client)||{},i=R(r.runtime)||{},c=R(e.manifest)||R(r.manifest)||null;return{url:String(e.url||o.url||r.websiteSource||e.websiteSource||"").slice(0,2048),title:String(e.title||o.title||"").slice(0,300),surface:String(e.surface||i.surface||t.surface||"").slice(0,80),instanceId:String(e.instanceId||i.instanceId||"").slice(0,140),workspaceId:String(t.workspaceId||e.workspaceId||n.workspace||"").slice(0,120),agentId:String(t.agentId||e.agentId||n.agent||"").slice(0,120),runtime:{...i,local:!0,connected:!0,connection:t},page:o,client:s,project:R(e.project)||R(r.project)||null,manifest:c,selection:R(e.selection)||null,updatedAt:new Date().toISOString()}}function fn(e,t){return t?.error?.message||t?.message||`CursorBuddy key claim failed with HTTP ${e.status}`}async function pn(e,t={},n=globalThis.fetch){let r=String(t.key||"").trim();if(!qt.test(r))throw new Error("Connection key format is invalid. Create a fresh CursorBuddy key first.");if(typeof n!="function")throw new Error("This Node.js runtime does not provide fetch; use a current Node.js release.");let o=ln(e,t),s=await n(`${o}/backend/cursorbuddy/connection-keys/claim`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:r,baseUrl:o,host:qe.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:R(t.metadata)||null,websiteSource:t.websiteSource||t.metadata?.websiteSource||"",page:R(t.page)||R(t.metadata?.page)||null,client:R(t.client)||R(t.metadata?.client)||null,manifest:R(t.manifest)||R(t.metadata?.manifest)||null})}),i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(fn(s,i));return{key:r,baseUrl:o,data:i?.data||i}}async function Ve(e,t={}){let n=Number(t.port??e.cursorBuddyPort??X.env.AGENSIS_CURSORBUDDY_PORT??Ge),r=en(e,t),o=new Date().toISOString(),s=[],i=[],c=new Set,u=t.fetchImpl||globalThis.fetch,l=1,p=null,y=n,S=null,h=(d,f={})=>{let v={ts:new Date().toISOString(),event:d,detail:f};return s.push(v),s.length>200&&s.shift(),t.log?.(`CursorBuddy local bridge: ${d}${Object.keys(f).length?` ${JSON.stringify(f)}`:""}`),v},$=()=>({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()}),O=()=>{if(typeof t.connectionProvider!="function")return null;try{let d=t.connectionProvider();return!d||typeof d!="object"||Array.isArray(d)?null:{...$(),...d,connected:d.connected===!0}}catch{return null}},b=()=>{let d=O();return d?.connected===!1?d:S?{...$(),...d||{},...S,connected:!0,updatedAt:d?.updatedAt||S.updatedAt}:d||$()};function w(d={}){if(!d||typeof d!="object"||Array.isArray(d))return null;let f=String(d.action||d.type||"").trim().toLowerCase();if(!Xt.has(f))return null;let v={id:l++,ts:new Date().toISOString(),action:f,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)&&(v.options=d.options.map(a=>({label:String(a?.label||"").slice(0,80),value:String(a?.value||a?.task||"").slice(0,1200)})).filter(a=>a.label).slice(0,6)),v}function A(d){for(i.push(d);i.length>Yt;)i.shift();h("control",{id:d.id,action:d.action,chars:d.text.length});for(let f of[...c])try{H(f,{type:"command",command:d})}catch{c.delete(f)}return d}function N(d){let f=an(d);if(f){let v=w(f.command);return v&&(A(v),h("chat_control",{id:v.id,action:v.action})),{content:f.content,model:"cursorbuddy-local-control",fast:!0}}return null}async function B(d){let f=N(d);if(f)return f;let v=Je(d?.messages,p),a=ze(e,v,d?.model),g=await oe({cmd:a.cmd,args:a.args,cwd:e.cwd,timeoutMs:Math.min(Number(e.timeoutMs||18e5),5*60*1e3),heartbeatMs:e.heartbeatMs,label:"cursorbuddy local chat",input:a.stdin});if(g.error||g.status!==0)throw new Error(g.error?.message||String(g.stderr||"").trim()||`Command exited with status ${g.status}`);return{content:We(g.stdout||g.stderr),model:a.model}}async function F(d,f){let v=`agensis-cursorbuddy-${Date.now()}`,a=N(d);if(a){let C=a.model||"cursorbuddy-local-control";return H(f,Z(v,C,a.content)),H(f,Z(v,C,"","stop")),H(f,"[DONE]"),h("chat_fast",{chars:a.content.length,model:C}),{content:a.content,model:C,fast:!0}}let g=Je(d?.messages,p),M=ze(e,g,d?.model,{stream:!0}),j="",E=C=>{C&&(j+=C,H(f,Z(v,M.model||e.model,C)))},I=M.streamJson?un(E):null,m=await oe({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,onData:C=>{if(I)I.feed(C);else{let P=String(C||"");j+=P,H(f,Z(v,M.model||e.model,P))}}});if(I){I.end();let C=I.result||"";!j&&C?E(C):j=C||j}if(m.error||m.status!==0){let C=m.error?.message||String(m.stderr||"").trim()||`Command exited with status ${m.status}`;throw new Error(C)}let _=I?j:We(j||m.stdout||m.stderr);return!I&&_&&_!==j&&(H(f,Z(v,M.model||e.model,_)),j=_),H(f,Z(v,M.model||e.model,"","stop")),H(f,"[DONE]"),{content:j||_,model:M.model}}let L=Kt.createServer(async(d,f)=>{if(f.setHeader("access-control-allow-origin","*"),f.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),f.setHeader("access-control-allow-headers","content-type, authorization, x-agensis-bridge-secret"),d.method==="OPTIONS"){f.writeHead(204),f.end();return}let v=new URL(d.url||"/",fe(y||Ge));if(!tn(d.method,v.pathname)&&!Zt(d,r)){U(f,401,{ok:!1,error:"Authentication required",code:"bridge_auth_required"});return}if(d.method==="GET"&&v.pathname==="/cursorbuddy/health"){let a=fe(y);U(f,200,{ok:!0,runtime:"agensis-cli",backend:e.codingCmd,model:ve(e),daemonModel:e.model,port:y,host:qe.hostname(),pid:X.pid,bootedAt:o,authRequired:!0,authHeader:pe,stream:!0,streaming:!0,supportsStreaming:!0,chatStream:!0,capabilities:{chatStream:!0,controlStream:!0,fastAvatarReplies:!1,nativeCursorBuddyControl:!0},latestControlId:i.at(-1)?.id||0,connection:b(),context:p,endpoints:{chat:`${a}/v1/chat/completions`,chatStream:`${a}/v1/chat/completions`,edit:`${a}/cursorbuddy/edit`,context:`${a}/cursorbuddy/context`,control:`${a}/cursorbuddy/control`,controlStream:`${a}/cursorbuddy/control/stream`,logs:`${a}/cursorbuddy/logs`}});return}if(d.method==="GET"&&v.pathname==="/cursorbuddy/logs"){U(f,200,{ok:!0,events:s.slice(-100)});return}if(d.method==="GET"&&v.pathname==="/cursorbuddy/context"){U(f,200,{ok:!0,context:p});return}if(d.method==="GET"&&v.pathname==="/cursorbuddy/control"){let a=Number(v.searchParams.get("after")||0),g=i.filter(M=>M.id>a);U(f,200,{ok:!0,commands:g,latestId:i.at(-1)?.id||0});return}if(d.method==="GET"&&v.pathname==="/cursorbuddy/control/stream"){let a=Number(v.searchParams.get("after")||0);He(f),c.add(f),H(f,{type:"ready",latestId:i.at(-1)?.id||0});for(let M of i.filter(j=>j.id>a))H(f,{type:"command",command:M});let g=setInterval(()=>{try{H(f,{type:"ping",ts:new Date().toISOString()})}catch{c.delete(f),clearInterval(g)}},15e3);g.unref&&g.unref(),d.on("close",()=>{c.delete(f),clearInterval(g)});return}if(d.method==="POST"&&v.pathname==="/cursorbuddy/control"){try{let a=JSON.parse(await se(d)||"{}"),g=w(a);if(!g){U(f,400,{ok:!1,error:"unsupported CursorBuddy control command"});return}let M=A(g);U(f,200,{ok:!0,command:M})}catch(a){h("control_error",{error:String(a?.message||a)}),U(f,400,{ok:!1,error:String(a?.message||a)})}return}if(d.method==="POST"&&v.pathname==="/cursorbuddy/context"){try{let a=JSON.parse(await se(d)||"{}");p={url:String(a.url||"").slice(0,2048),title:String(a.title||"").slice(0,300),surface:String(a.surface||"").slice(0,80),instanceId:String(a.instanceId||"").slice(0,140),workspaceId:String(a.workspaceId||e.workspace||"").slice(0,120),agentId:String(a.agentId||e.agent||"").slice(0,120),runtime:a.runtime&&typeof a.runtime=="object"?a.runtime:null,page:a.page&&typeof a.page=="object"?a.page:null,client:a.client&&typeof a.client=="object"?a.client:null,project:a.project&&typeof a.project=="object"?a.project:null,manifest:a.manifest&&typeof a.manifest=="object"?a.manifest:null,selection:a.selection&&typeof a.selection=="object"?a.selection:null,updatedAt:new Date().toISOString()},h("context",{url:p.url,surface:p.surface,instanceId:p.instanceId}),U(f,200,{ok:!0,context:p})}catch(a){h("context_error",{error:String(a?.message||a)}),U(f,400,{ok:!1,error:String(a?.message||a)})}return}if(d.method==="POST"&&v.pathname==="/cursorbuddy/connect"){try{let a=JSON.parse(await se(d)||"{}"),g=await pn(e,a,u),M=g.data||{};S={connected:!0,mode:"agensis-claimed",keyId:dn(g.key),agentId:String(M.agentId||M.agent?.id||e.agent||""),workspaceId:String(M.workspaceId||M.workspace_id||M.agent?.workspace_id||e.workspace||""),agensisUrl:g.baseUrl,handle:String(M.handle||M.agent?.handle||e.handle||""),name:String(M.agent?.name||a.name||e.name||"CursorBuddy runtime"),cwd:String(a.cwd||e.cwd||X.cwd()),surface:String(a.surface||"browser_extension"),command:String(M.command||M.localCommand||""),updatedAt:new Date().toISOString()},p=mn(a,S,e),h("connect",{mode:S.mode,keyId:S.keyId,agentId:S.agentId,workspaceId:S.workspaceId,url:p.url}),U(f,200,{ok:!0,connection:S,claim:M})}catch(a){h("connect_error",{error:String(a?.message||a)}),U(f,400,{ok:!1,error:String(a?.message||a)})}return}if(d.method==="POST"&&v.pathname==="/cursorbuddy/edit"){try{let a=JSON.parse(await se(d)||"{}"),g=[{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(a,null,2)}];h("edit_request",{selector:a?.target?.selector||""});let M=await B({messages:g,model:a?.model});h("edit_done",{chars:M.content.length}),U(f,200,{ok:!0,backend:e.codingCmd,cwd:e.cwd,content:M.content})}catch(a){h("edit_error",{error:String(a?.message||a)}),U(f,500,{ok:!1,error:String(a?.message||a)})}return}if(d.method==="POST"&&v.pathname.endsWith("/chat/completions")){try{let a=JSON.parse(await se(d)||"{}");if(h("chat_request",{messages:Array.isArray(a.messages)?a.messages.length:0,model:Ye(a.model,ve(e))}),a.stream===!0){He(f);let M=await F(a,f);h("chat_done",{chars:M.content.length,stream:!0,fast:M.fast===!0}),f.end();return}let g=await B(a);h("chat_done",{chars:g.content.length,fast:g.fast===!0}),U(f,200,{id:`agensis-cursorbuddy-${Date.now()}`,object:"chat.completion",model:g.model||a.model||e.model,choices:[{index:0,message:{role:"assistant",content:g.content},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}})}catch(a){h("chat_error",{error:String(a?.message||a)}),U(f,500,{error:{message:String(a?.message||a)}})}return}f.writeHead(404),f.end("CursorBuddy local bridge")});return await new Promise((d,f)=>{L.once("error",f),L.listen(n,"127.0.0.1",()=>{y=L.address().port,L.off("error",f),d()})}),h("listening",{url:`${fe(y)}/cursorbuddy/health`}),{port:y,url:fe(y),secret:r,authHeader:pe,close(){return new Promise(d=>L.close(()=>d()))},getContext(){return p}}}import ee from"node:fs/promises";import hn from"node:os";import J from"node:path";var Qe=200,Ze=256*1024,gn=2,yn=new Set([".md",".markdown",".txt"]);function Sn(e){return String(e||"").replace(/[^a-zA-Z0-9]/g,"-")}function _e({cwd:e,memoryDir:t,homedir:n=hn.homedir()}={}){let r=String(t||"").trim();if(r)return r.startsWith("~")?J.join(n,r.slice(1)):J.resolve(r);let o=String(e||"").trim();return o?J.join(n,".claude","projects",Sn(o),"memory"):null}async function Ae(e){if(!e)return null;try{let t=await ee.realpath(e);return(await ee.stat(t)).isDirectory()?t:null}catch{return null}}async function wn(e,t){if(!e)throw new Error("memory root unavailable");let n=J.isAbsolute(String(t))?String(t):J.join(e,String(t)),r=await ee.realpath(n),o=e.endsWith(J.sep)?e:e+J.sep;if(r!==e&&!r.startsWith(o))throw new Error(`path escapes memory root: ${t}`);return r}function bn(e){let t=J.basename(e).toLowerCase();return t==="memory.md"?"index":t==="claude.md"?"instructions":"memory"}async function Ee(e,t,n,r){if(n>gn||r.length>=Qe)return;let o;try{o=await ee.readdir(t,{withFileTypes:!0})}catch{return}for(let s of o){if(r.length>=Qe)break;if(s.name.startsWith("."))continue;let i=J.join(t,s.name);if(s.isDirectory())await Ee(e,i,n+1,r);else if(s.isFile()&&yn.has(J.extname(s.name).toLowerCase())){let c=J.relative(e,i);r.push({path:c,kind:bn(c)})}}}async function kn(e){let t=await Ae(e);if(!t)return[];let n=[];return await Ee(t,t,0,n),n.sort((r,o)=>r.kind==="index"?-1:o.kind==="index"?1:r.path.localeCompare(o.path)),n}async function vn(e,t){let n=await Ae(e),r=await wn(n,t),o=await ee.readFile(r),s=o.length>Ze;return{content:o.subarray(0,Ze).toString("utf8"),byteSize:o.length,truncated:s}}async function et(e){let t=await Ae(e);if(!t)return"";let n=[];await Ee(t,t,0,n),n.sort((o,s)=>o.path.localeCompare(s.path));let r=[];for(let o of n)try{let s=await ee.stat(J.join(t,o.path));r.push(`${o.path}:${s.size}:${Math.floor(s.mtimeMs)}`)}catch{}return r.join("|")}async function tt(e){let t=await kn(e),n=[];for(let r of t)try{let{content:o,byteSize:s}=await vn(e,r.path);n.push({path:r.path,kind:r.kind,content:o,byteSize:s})}catch{}return n}import nt from"node:fs";import te from"node:path";import rt from"node:os";function _n(e){try{return nt.statSync(e).isDirectory()}catch{return!1}}function Ie(e){try{return nt.readdirSync(e,{withFileTypes:!0})}catch{return[]}}function ot({home:e=rt.homedir(),cwd:t=process.cwd()}={}){let n=[e&&te.join(e,".claude","commands"),t&&te.join(t,".claude","commands")].filter(Boolean),r=new Set,o=[],s=(i,c)=>{if(!i)return;let u=c?`${c}:${i}`:i;r.has(u)||(r.add(u),o.push({name:i,parent:c||null}))};for(let i of n)for(let c of Ie(i)){if(c.name.startsWith("."))continue;if(c.name.endsWith(".md")){s(c.name.slice(0,-3),null);continue}let u=te.join(i,c.name);if(c.isDirectory()||c.isSymbolicLink()&&_n(u))for(let l of Ie(u))l.name.startsWith(".")||l.name.endsWith(".md")&&s(l.name.slice(0,-3),c.name)}return o}function st({home:e=rt.homedir(),cwd:t=process.cwd()}={}){let n=[e&&te.join(e,".claude","skills"),e&&te.join(e,".codex","skills"),t&&te.join(t,".claude","skills")].filter(Boolean),r=new Set;for(let o of n)for(let s of Ie(o))s.name.startsWith(".")||(s.name.endsWith(".md")?r.add(s.name.slice(0,-3)):(s.isDirectory()||s.isSymbolicLink())&&r.add(s.name));return[...r].sort()}import{readFile as An}from"node:fs/promises";var En=new Set(["127.0.0.1","localhost","::1","[::1]"]);function it(e,t,n){let r=Number(e);return Number.isFinite(r)?Math.max(1,Math.min(n,Math.trunc(r))):t}function In(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(!En.has(r.hostname))throw new Error(`Shared model '${n}' must use a loopback endpoint.`);if(!["http:","https:"].includes(r.protocol))throw new Error(`Shared model '${n}' must use an HTTP endpoint.`);return{id:n.slice(0,160),name:String(e.name||n).trim().slice(0,160)||n,provider:String(e.provider||"local").trim().slice(0,80)||"local",protocol:"openai-chat",baseUrl:r.toString().replace(/\/$/,""),upstreamModel:String(e.upstreamModel||n).trim().slice(0,200)||n,apiKeyEnv:String(e.apiKeyEnv||"").trim().slice(0,120),capabilities:[...new Set((Array.isArray(e.capabilities)?e.capabilities:["text","streaming"]).map(o=>String(o||"").trim().toLowerCase()).filter(Boolean))].slice(0,16),...e.contextWindow?{contextWindow:it(e.contextWindow,void 0,1e7)}:{},maxConcurrency:it(e.maxConcurrency,1,64),shared:!0}}async function at(e){if(!e)return[];let t=JSON.parse(await An(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(In).filter(Boolean)}function ct(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 ut({models:e,request:t,send:n,signal:r,fetchImpl:o=fetch,env:s=process.env}){let i=String(t?.requestId||"").trim();if(!i)throw new Error("Inference requestId is required.");let c=(Array.isArray(e)?e:[]).find(w=>w.id===t?.model);if(!c)throw new Error(`Shared model '${t?.model||""}' is not available.`);let u={"content-type":"application/json"},l=c.apiKeyEnv?s[c.apiKeyEnv]:"";l&&(u.authorization=`Bearer ${l}`),n({action:"agent_inference_started",requestId:i,model:c.id});let{requestId:p,model:y,type:S,action:h,...$}=t,O=await o(`${c.baseUrl}/chat/completions`,{method:"POST",headers:u,body:JSON.stringify({...$,model:c.upstreamModel,stream:t.stream===!0}),signal:r});if(!O.ok){let w=await O.text().catch(()=>"");throw new Error(w||`Local model returned HTTP ${O.status}.`)}if(t.stream===!0){if(!O.body)throw new Error("Local model returned an empty stream.");let w=O.body.getReader(),A=new TextDecoder,N="",B,F=f=>{let v=f.trim();if(!v.startsWith("data:"))return!1;let a=v.slice(5).trim();if(!a)return!1;if(a==="[DONE]")return!0;try{let g=JSON.parse(a);g?.usage&&(B=g.usage),n({action:"agent_inference_delta",requestId:i,model:c.id,chunk:g})}catch{}return!1},L=!1;for(;!L;){let{done:f,value:v}=await w.read();N+=A.decode(v||new Uint8Array,{stream:!f});let a=N.split(/\r?\n/);N=f?"":a.pop()||"";for(let g of a)if(F(g)){L=!0;break}if(f)break}N&&F(N);let d={action:"agent_inference_result",requestId:i,model:c.id,...B?{usage:B}:{}};return n(d),d}let b=await O.json();return n({action:"agent_inference_result",requestId:i,model:c.id,response:b}),b}import lt from"node:fs";import z from"node:fs/promises";import Cn from"node:os";import W from"node:path";var ft="status.json",pt="heartbeat.json",Ce="heartbeat.md",Mn="agent.json",Bn="soul.md",xn=16*1024,On=`# Heartbeat
|
|
9
|
+
|
|
10
|
+
This file tells you what to do on each heartbeat \u2014 the recurring "still here, still
|
|
11
|
+
working" moment. Edit it freely; the daemon reads it but never overwrites your edits.
|
|
12
|
+
|
|
13
|
+
On each heartbeat:
|
|
14
|
+
|
|
15
|
+
- Keep \`status.json\` fresh \u2014 overwrite it with \`{"status":"...","note":"..."}\` so your
|
|
16
|
+
card reflects what you're actually doing right now.
|
|
17
|
+
- If you're blocked, say so in the note rather than going silent.
|
|
18
|
+
- If you've finished and there's nothing to do, a short idle note is fine.
|
|
19
|
+
|
|
20
|
+
Add your own recurring checks below.
|
|
21
|
+
`,Nn=8*1024,$n=400;function dt(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/\.{2,}/g,".").replace(/^[.-]+/,"").slice(0,96)||t}function ne({workspace:e,agent:t,homedir:n=Cn.homedir()}={}){return W.join(n,".agensis",dt(e,"workspace"),dt(t,"agent"))}function ht(e){return W.join(ne(e),ft)}function gt(e){return W.join(ne(e),Ce)}async function Me(e){let t=ne(e);try{return await z.mkdir(t,{recursive:!0}),t}catch{return null}}async function he(e,t){let n=`${e}.tmp-${process.pid}`;try{return await z.writeFile(n,t),await z.rename(n,e),!0}catch{try{await z.rm(n,{force:!0})}catch{}return!1}}async function Be(e,t){if(!t||typeof t!="object")return!1;let n=await Me(e);if(!n)return!1;let r={id:t.id??e.agent??"",workspace:t.workspace_id??e.workspace??"",name:t.name??e.name??"",handle:t.handle??e.handle??"",model:t.model??e.model??"",permissionMode:t.permissionMode??t.permission_mode??e.permissionMode??"",description:t.description??"",instructions:t.instructions??"",systemPrompt:t.system_prompt??t.systemPrompt??"",tools:Array.isArray(t.tools)?t.tools:[],skills:Array.isArray(t.skills)?t.skills:[],memoryDir:t.memory_dir??t.memoryDir??"",version:Number(t.version||0),updatedAt:new Date().toISOString()},o=await he(W.join(n,Mn),`${JSON.stringify(r,null,2)}
|
|
22
|
+
`),s=String(t.soul??""),i=await he(W.join(n,Bn),s);return o&&i}async function yt(e,t={}){let n=await Me(e);return n?he(W.join(n,pt),wt(e,t)):!1}function St(e,t={}){let n=ne(e);try{return lt.mkdirSync(n,{recursive:!0}),lt.writeFileSync(W.join(n,pt),wt(e,t)),!0}catch{return!1}}function wt(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)}
|
|
23
|
+
`}async function xe(e){let t=W.join(ne(e),ft),n;try{let c=await z.stat(t);if(!c.isFile()||c.size>Nn)return null;n=await z.readFile(t,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let o=mt(r.status),s=mt(r.note??r.message);if(!o&&!s)return null;let i={};return o&&(i.status=o),s&&(i.note=s),r.ts!=null&&Number.isFinite(Number(r.ts))&&(i.ts=Number(r.ts)),i}function mt(e){return e==null?"":String(e).trim().replace(/\s+/g," ").slice(0,$n)}async function bt(e){let t=await Me(e);if(!t)return!1;let n=W.join(t,Ce);try{return await z.access(n),!0}catch{}return he(n,On)}async function kt(e){let t=W.join(ne(e),Ce);try{let n=await z.stat(t);return!n.isFile()||n.size>xn?null:(await z.readFile(t,"utf8")).trim()||null}catch{return null}}var Tn=30*60*1e3,Rn=15*1e3,vt=8,Pn="claude-opus-4-8",re="0.1.22";async function ge(e={}){let t=Ln(e);t.sharedModels=t.share?await at(t.sharedModelsFile):[];let n=!1,r=null,o=null,s=null,i=null,c=0,u=null,l=null,p="",y=null,S=!1,h=null,$=new Map,O=null,b={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"},w=new Map,A=new Map,N=[],B=()=>b,F=()=>({connected:S&&!!t.cursorBuddyRuntime,mode:t.cursorBuddyRuntime?"agensis-cli":"agensis-cli-unclaimed",agentId:h?.agentId||h?.agent_id||t.agent,workspaceId:h?.workspaceId||h?.workspace_id||t.workspace,agensisUrl:t.url,handle:h?.handle||t.handle,name:h?.name||t.name,cwd:t.cwd,updatedAt:new Date().toISOString()}),L=()=>{O||!t.lanListener||(O=new ae.Server({port:0}),O.on("listening",()=>{let{port:E}=O.address();b={transport:"ws",listening:!0,addrs:ir(E),auth:"hub-pairwise"},x(`Agent-mesh LAN listener on port ${E}`),ie(r,t,B())}),O.on("connection",E=>{let I=!1,m=setTimeout(()=>{if(!I)try{E.close(1008,"peer auth required")}catch{}},5e3);E.once("message",_=>{clearTimeout(m);let C=Ne(_),P=C?.type==="peer_auth"?w.get(C.ticket):null;if(!P||P.fromAgentId!==C.fromAgentId||Date.now()>P.exp){try{E.close(1008,"invalid ticket")}catch{}return}w.delete(C.ticket),I=!0,E.on("message",G=>{let D=Ne(G);D?.type==="agent_job"&&D.job?.id&&l.enqueue({...D.job,key:D.job.id,lane:_t(D.job),ws:r}).accepted&&x(`Queued peer-handoff job ${D.job.id} from ${C.fromAgentId}`)})})}),O.on("error",E=>x(`LAN listener error: ${E?.message||E}`)))},d=()=>{if(O){try{O.close()}catch{}O=null}b={transport:"ws",listening:!1,addrs:[],auth:"hub-pairwise"}},f=E=>new Promise((I,m)=>{if(!T(r,{action:"peer_ticket_request",targetAgentId:E})){m(new Error("hub socket not open"));return}let _=A.get(E)||[];_.push({resolve:I,reject:m}),A.set(E,_),setTimeout(()=>{let C=A.get(E)||[],P=C.findIndex(G=>G.resolve===I);P>=0&&(C.splice(P,1),m(new Error("peer ticket request timed out")))},1e4)}),v=()=>new Promise((E,I)=>{if(!T(r,{action:"peer_list_request"})){I(new Error("hub socket not open"));return}N.push(E),setTimeout(()=>{let m=N.indexOf(E);m>=0&&(N.splice(m,1),E([]))},1e4)}),a=async(E,I)=>{let m=null;try{let C=(await v()).find(D=>D.agentId===E&&D.reach?.listening&&D.reach.addrs?.length);if(!C)return!1;let P=await f(E),G=P.peer?.addrs?.[0]||C.reach.addrs[0];return!G?.host||!G?.port?!1:(m=new ae(`ws://${G.host}:${G.port}`),await new Promise((D,be)=>{m.once("open",D),m.once("error",be),setTimeout(()=>be(new Error("peer connect timed out")),5e3)}),T(m,{type:"peer_auth",ticket:P.ticket,fromAgentId:t.agent}),T(m,{type:"agent_job",job:I}),!0)}catch(_){return x(`Peer handoff to ${E} failed, falling back to hub relay: ${_?.message||_}`),!1}finally{try{m?.close()}catch{}}},g=()=>{n=!0,Ct($),o&&clearTimeout(o),s&&clearInterval(s),i&&clearInterval(i),y&&(y.close().catch(()=>{}),y=null),d(),St(t,{status:"stopped",connected:!1});try{r?.close()}catch{}u&&u()};if(l=Fe({concurrency:t.once?1:t.maxConcurrency,runJob:async(E,I)=>{await Zn(t,E,I),t.once&&g()}}),t.cursorBuddyBridge)try{y=await Ve(t,{port:t.cursorBuddyPort,authSecret:t.cursorBuddyBridgeSecret||void 0,log:x,connectionProvider:F}),y?.secret&&(t.cursorBuddyBridgeSecret=y.secret)}catch(E){if(mr(E)){let I=await fr(t.cursorBuddyPort);if(I?.ok){let m=I.pid?` pid ${I.pid}`:"";x(`CursorBuddy local bridge already running on http://127.0.0.1:${t.cursorBuddyPort}${m}`)}else x(`CursorBuddy local bridge port ${t.cursorBuddyPort} is in use but did not answer health`)}else x(`CursorBuddy local bridge unavailable: ${E?.message||E}`);y=null}k.once("SIGINT",g),k.once("SIGTERM",g);let M=()=>{if(n)return;let E=jn(t.url,t.token,t);p="",x(`Connecting to ${E.replace(t.token,"redacted")}`),r=new ae(E),r.on("open",()=>{S=!1,h=null,x(`Connected. Registering @${t.handle||"agent"} from ${t.cwd}`),T(r,{type:"auth",token:t.token}),T(r,{action:"agent_register",workspaceId:t.workspace,agentId:t.agent,handle:t.handle,name:t.name,host:ue.hostname(),cwd:t.cwd,metadata:{codingCmd:t.codingCmd,model:t.model,permissionMode:t.permissionMode,permissionFlags:De(t.permissionMode),once:t.once,runtime:"agensis",version:re}}),s=setInterval(()=>{Promise.all([$t(t,B()).catch(()=>null),xe(t).catch(()=>null)]).then(([I,m])=>{T(r,{action:"agent_heartbeat",...I?{capabilitiesHash:I.capabilitiesHash,memoryHash:I.memoryHash}:{},metadata:Oe(t,l,m,xt(t)?y?.getContext?.():null,$)})})},t.heartbeatMs),s.unref&&s.unref()}),r.on("message",I=>{let m=Ne(I);if(m){if(m.type==="agent_registered"){S=!0,h=m.connection||m.agent||null,At(t,m.agent),x(`Registered as ${m.connection?.name||t.name} on ${m.connection?.host||ue.hostname()}`),t.onRegistered&&Promise.resolve(t.onRegistered(t,m)).catch(_=>{x(`Profile save failed: ${_?.message||_}`)}),Be(t,m.agent).catch(()=>{}),bt(t).catch(()=>{}),It(r,t),L(),ie(r,t,B());return}if(m.type==="agent_config"){At(t,m.agent),x(`Updated config for @${t.handle||"agent"}: model=${t.model}, permission=${t.permissionMode}`),Be(t,m.agent).catch(()=>{});return}if(m.type==="agent_memory_refresh"){It(r,t),ie(r,t,B());return}if(m.type==="agent_capabilities_refresh"){ie(r,t,B());return}if(m.type==="agent_inference_cancel"){$.get(String(m.requestId||""))?.abort();return}if(m.type==="agent_job_cancel"){let _=String(m.jobId||"");_&&l.cancel(_,m.reason||"Cancelled by Agensis")&&x(`Cancelled job ${_}`);return}if(m.type==="agent_inference_request"&&m.requestId){let _=String(m.requestId),C=t.sharedModels.find(D=>D.id===m.model),P=[...$.values()].filter(D=>D.model===m.model).length;if(!C){T(r,{action:"agent_inference_error",requestId:_,error:`Shared model '${m.model||""}' is not available.`});return}if(P>=C.maxConcurrency){T(r,{action:"agent_inference_error",requestId:_,error:"Shared model is at capacity.",code:"capacity_exhausted"});return}let G=new AbortController;$.set(_,{abort:()=>G.abort(),model:C.id}),T(r,{action:"agent_heartbeat",metadata:Oe(t,l,null,null,$)}),ut({models:t.sharedModels,request:m,signal:G.signal,send:D=>T(r,D)}).catch(D=>{T(r,{action:"agent_inference_error",requestId:_,error:G.signal.aborted?"Inference cancelled.":D?.message||String(D),code:G.signal.aborted?"cancelled":"inference_failed"})}).finally(()=>{$.delete(_),T(r,{action:"agent_heartbeat",metadata:Oe(t,l,null,null,$)})});return}if(m.type==="peer_ticket"){let _=m.peer?.agentId,C=A.get(_)||[],P=C.shift();C.length?A.set(_,C):A.delete(_),P&&P.resolve(m);return}if(m.type==="peer_ticket_grant"){w.set(m.ticket,{fromAgentId:m.fromAgentId,exp:m.exp});return}if(m.type==="peer_list"){let _=N.shift();_&&_(Array.isArray(m.peers)?m.peers:[]);return}if(m.type==="agent_reach_disable"){d(),ie(r,t,B());return}if(m.type==="error"){x(`Server rejected request: ${m.message||"unknown error"}`);return}if(m.type==="agent_disabled"){S=!1,h=null,x(`Agent disabled by Agensis: ${m.reason||"deactivated"}`),g();return}if(m.type==="agent_job"&&m.job?.id){let _=l.enqueue({...m.job,key:m.job.id,lane:_t(m.job),ws:r});_.accepted&&(c+=1,x(`Queued job ${m.job.id} at position ${_.position}`),t.once&&l.idle().then(()=>g()))}}}),r.on("close",(I,m)=>{Ct($),S=!1,h=null;let _=String(m||"");if(x(`Socket closed (${I||"no-code"}${_?`: ${_}`:""})`),s&&(clearInterval(s),s=null),I===1008&&/agent deactivated|authentication failed/i.test(_)){x("Stopping daemon because Agensis rejected this agent connection."),g();return}if(p==="ECONNREFUSED"&&Gn(t.url)){x("Local agent backend is not running on 127.0.0.1:3142."),x("Start it in another terminal with: npm run backend"),x("Then rerun this connect command."),g();return}t.once&&c>0&&l.active()===0&&l.size()===0&&g(),!(n||t.once)&&(o=setTimeout(M,2e3),o.unref&&o.unref())}),r.on("error",I=>{p=I?.code||"",x(`Socket error: ${I?.message||I}`)})},j=async()=>{let E=await xe(t).catch(()=>null);await yt(t,{busy:l.active()>0,active:l.active(),queueSize:l.size(),connected:r?.readyState===ae.OPEN,agentStatus:E?.status,agentNote:E?.note}).catch(()=>{})};j(),i=setInterval(()=>{j()},t.heartbeatMs),i.unref&&i.unref(),M(),await new Promise(E=>{let I=setInterval(async()=>{t.once&&c>0&&l.active()===0&&l.size()===0&&g(),n&&g()},500);u=()=>{clearInterval(I),E()}}),u=null,k.off("SIGINT",g),k.off("SIGTERM",g)}function Ln(e){let t=Un(e.cursorBuddyBridge),n=e.noCoding===!0||k.env.AGENSIS_NO_CODING==="1",r={url:String(e.url||e.baseUrl||k.env.AGENSIS_URL||"").trim(),token:String(e.token||k.env.AGENSIS_TOKEN||"").trim(),workspace:String(e.workspace||e.workspaceId||k.env.AGENSIS_WORKSPACE||k.env.AGENSIS_WORKSPACE_ID||"").trim(),agent:String(e.agent||e.agentId||k.env.AGENSIS_AGENT||k.env.AGENSIS_AGENT_ID||"").trim(),handle:Dt(e.handle||k.env.AGENSIS_HANDLE||e.name||k.env.AGENSIS_NAME||"agent"),name:String(e.name||k.env.AGENSIS_NAME||e.handle||k.env.AGENSIS_HANDLE||"agensis Agent").trim(),cwd:String(e.cwd||k.env.AGENSIS_CWD||k.cwd()).trim(),codingCmd:n?"":String(e.codingCmd||k.env.AGENSIS_CODING_CMD||k.env.CODING_CMD||"claude -p").trim(),model:$e(e.model||k.env.AGENSIS_MODEL||k.env.CLAUDE_MODEL||""),permissionMode:ye(e.permissionMode||e.permission_mode||e.permission||k.env.AGENSIS_PERMISSION_MODE||"default"),timeoutMs:Number(e.timeoutMs||k.env.AGENSIS_TIMEOUT_MS||Tn),heartbeatMs:Number(e.heartbeatMs||k.env.AGENSIS_HEARTBEAT_MS||Rn),maxConcurrency:Math.max(1,Number(e.maxConcurrency||k.env.AGENSIS_MAX_CONCURRENCY||vt)||vt),once:!!(e.once||k.env.AGENSIS_ONCE==="1"),exitOnOnce:!!e.exitOnOnce,onRegistered:typeof e.onRegistered=="function"?e.onRegistered:null,primaryDaemon:!!(e.primaryDaemon||k.env.AGENSIS_PRIMARY_DAEMON==="1"),cursorBuddyRuntime:!!(e.cursorBuddyRuntime||k.env.AGENSIS_CURSORBUDDY_RUNTIME==="1"),cursorBuddyBridge:t,cursorBuddyPort:Number(e.cursorBuddyPort||k.env.AGENSIS_CURSORBUDDY_PORT||8787),cursorBuddyBridgeSecret:String(e.cursorBuddyBridgeSecret||k.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim(),cursorBuddyModel:String(e.cursorBuddyModel||k.env.AGENSIS_CURSORBUDDY_MODEL||"haiku-4.5").trim(),lanListener:!!(e.lanListener||e.lan||k.env.AGENSIS_LAN==="1"),share:!!(e.share||k.env.AGENSIS_SHARE==="1"),sharedModelsFile:String(e.sharedModelsFile||k.env.AGENSIS_SHARED_MODELS_FILE||"").trim(),noCoding:n};r.sharedModelsFile&&!ce.isAbsolute(r.sharedModelsFile)&&(r.sharedModelsFile=ce.resolve(r.cwd,r.sharedModelsFile));let o=[];if(r.url||o.push("--url"),r.token||o.push("--token"),r.workspace||o.push("--workspace"),r.agent||o.push("--agent"),r.share&&!r.sharedModelsFile&&o.push("--shared-models-file"),o.length)throw new Error(`Missing required option(s): ${o.join(", ")}`);return r}function Un(e){let t=k.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 jn(e,t,n={}){let r=Bt(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 Bt(e){let t=new URL(e);return Fn(t)&&(t.protocol="http:",t.hostname="127.0.0.1",t.port="3142"),t}function Fn(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 Gn(e){try{let t=Bt(e);return(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="0.0.0.0")&&t.port==="3142"}catch{return!1}}function _t(e){let t=String(e?.sessionId||""),n=String(e?.threadParentId||"");return`${t}::${n}`}var Hn=/\b(cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\b/i,Jn=[/\b(?:make|have|tell)\s+(?:the\s+)?(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\s+(?:say|speak)\s+(.+)$/i];function Wn(e){return String(e||"").trim().replace(/^[`"'“”‘’]+|[`"'“”‘’?.!]+$/g,"").trim().slice(0,1200)}function zn(e){for(let t of Jn){let n=String(e||"").match(t),r=Wn(n?.[1]||"");if(r)return r}return""}function Kn(e){let t=String(e||"").replace(/\s+/g," ").trim();if(!t)return"";let n=/latest user message\s*:\s*/gi,r=null,o=null;for(;r=n.exec(t);)o=r;if(!o)return"";let s=t.slice(o.index+o[0].length).trim(),i=s.search(/\b(Return a useful response|Conversation context follows|Previous user|Previous assistant|Diagnostic notes|System prompt|Developer message)\b/i);return(i>=0?s.slice(0,i):s).trim().replace(/^["'“”‘’]+|["'“”‘’]+$/g,"").trim()}function qn(e){let t=String(e||"").replace(/\s+/g," ").trim(),r=Kn(t)||t;if(!r)return"";if(r.length<=500)return r;let o=[/\b(?:can you\s+)?(?:make|have|tell)\s+(?:the\s+)?(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\s+(?:wave|waves|waving|say|speak)\b.{0,160}/i,/\b(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy)\b.{0,120}\b(?:wave|waves|waving|say|speak|open|show|hide|hush|close|dismiss|clear)\b.{0,160}/i,/\b(?:wave|open|show|hide|hush|close|dismiss|clear)\b.{0,120}\b(?:cursorbuddy|cursor buddy|avatar|buddy|pet|character|him|guy|bubble|prompt|dialog|panel|options|menu)\b/i,/\b(?:say|speak)\s+[`"'“”‘’]?.{1,180}/i];for(let s of o){let i=r.match(s);if(i?.[0])return i[0].trim()}return""}function Yn(e){let t=qn(e);if(!t)return null;let n=/^(open|show|hide|hush|close|dismiss)\b/i.test(t),r=Hn.test(t);if(!n&&!r)return null;let o="agensis-native-control";if(/\b(hide|hush|close|dismiss|clear)\b.*\b(bubble|prompt|dialog|panel|options|menu)\b/i.test(t)||/^hush\b/i.test(t))return{action:"hush",source:o};if(/\b(open|show|bring up|get back|display)\b.*\b(prompt|bubble|dialog|panel|options|menu)\b/i.test(t)||/^open\b/i.test(t))return{action:"open",source:o};let s=zn(t);return s&&r?{action:"say",text:s,source:o}:r&&/\b(wave|waves|waving)\b/i.test(t)?{action:"wave",text:s,source:o}:null}async function Xn(e,t){let r=`http://127.0.0.1:${Number(e.cursorBuddyPort||8787)}/cursorbuddy/control`,o=String(e.cursorBuddyBridgeSecret||k.env.AGENSIS_CURSORBUDDY_BRIDGE_SECRET||"").trim(),s={"content-type":"application/json"};o&&(s.authorization=`Bearer ${o}`,s["x-agensis-bridge-secret"]=o);let i=await fetch(r,{method:"POST",headers:s,body:JSON.stringify(t)}),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 Vn(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 xt(e={}){return e.cursorBuddyBridge===!1?!1:!!(e.cursorBuddyRuntime||e.primaryDaemon)}async function Qn(e,t,n,r){let o="cursorbuddy-control",s="native",i=[],c=(p="")=>{T(t.ws,{action:"agent_job_delta",jobId:t.id,content:p,elapsedMs:Date.now()-r,model:o,permissionMode:s,permissionFlags:i})};c("");let u="",l="";try{await Xn(e,n),u=Vn(n),c(u)}catch(p){l=String(p?.message||p),u=`CursorBuddy control failed: ${l}`,c(u)}T(t.ws,{action:"agent_job_result",jobId:t.id,response:u,error:l,elapsedMs:Date.now()-r,model:o,permissionMode:s,permissionFlags:i}),x(`Finished native CursorBuddy ${n.action} job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s`)}async function Zn(e,t,{signal:n}){let r=Date.now();x(`Starting job ${t.id}`);let o=Yn(t.prompt);if(o&&xt(e)){await Qn(e,t,o,r),e.once&&(x("One-shot CursorBuddy control job complete; exiting."),setTimeout(()=>k.exit(0),150));return}let s=tr(e,t),i=await er(e,t),c="",u="",l=0,p=(A="")=>{T(t.ws,{action:"agent_job_delta",jobId:t.id,content:A,elapsedMs:Date.now()-r,model:s.model,permissionMode:s.permissionMode,permissionFlags:s.permissionFlags})};p("");let y=s.streamJson?nr():null,S=setInterval(()=>p(c),1e3);S.unref&&S.unref();let h=await oe({cmd:s.cmd,args:[...s.args,i],cwd:t.cwd||e.cwd,timeoutMs:e.timeoutMs,heartbeatMs:e.heartbeatMs,label:"agent job",signal:n,onData:A=>{y?(y.feed(A),c=y.live):(c+=String(A||""),u=dr(`${u}
|
|
24
|
+
${A}`));let N=Date.now();N-l>150&&(l=N,p(c))}});clearInterval(S),y&&(y.end(),c=y.live,p(c));let $=String(h.stdout||"").trim(),O=String(h.stderr||"").trim(),b=h.error?h.error.message:h.status===0?"":O||`Command exited with status ${h.status}`,w=y?y.result||(b?"":O):$||(b?"":O)||u||"";T(t.ws,{action:"agent_job_result",jobId:t.id,response:w,error:b,elapsedMs:Date.now()-r,model:s.model,permissionMode:s.permissionMode,permissionFlags:s.permissionFlags}),x(`Finished job ${t.id} in ${Math.round((Date.now()-r)/1e3)}s`),e.once&&(x("One-shot job complete; exiting."),setTimeout(()=>k.exit(0),150))}async function er(e,t){let n=t.agent||{},r=Array.isArray(n.skills)?n.skills.join(", "):String(n.skills||""),o=Array.isArray(n.tools)?n.tools.join(", "):String(n.tools||""),s=Ot(e,t),i=Nt(e,t),c=await kt(e).catch(()=>null),u=c?`Heartbeat (recurring instructions \u2014 edit at ${gt(e)}):
|
|
25
|
+
${c}`:"";return["You are running as a local agensis workspace agent daemon.",`Workspace: ${t.workspaceId||e.workspace}`,`Channel session: ${t.sessionId||""}`,`Agent: ${n.name||e.name} (@${n.handle||e.handle})`,`Requested model: ${s}`,`Permission mode: ${i}`,n.description?`Description:
|
|
26
|
+
${n.description}`:"",n.soul?`Soul:
|
|
27
|
+
${n.soul}`:"",n.system_prompt?`System instructions:
|
|
28
|
+
${n.system_prompt}`:"",n.instructions?`Additional instructions:
|
|
29
|
+
${n.instructions}`:"",o?`Enabled tools:
|
|
8
30
|
${o}`:"",r?`Enabled skills:
|
|
9
|
-
${r}`:"","Respond with a clear channel-ready result. If you changed files, summarize the files and verification. If you cannot complete it, say exactly why.","User message:",String(
|
|
31
|
+
${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 ${ht(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.`,u,"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.","User message:",String(t.prompt||"")].filter(Boolean).join(`
|
|
10
32
|
|
|
11
|
-
`)}function
|
|
12
|
-
`)}
|
|
33
|
+
`)}function tr(e,t){let{cmd:n,args:r}=lr(e.codingCmd),o=Ot(e,t),s=Nt(e,t),i=ar(r),c=De(s);if(cr(n)){let u=[...i];o&&u.push("--model",o),s==="accept_edits"&&u.push("--permission-mode","acceptEdits"),s==="yolo"&&u.push("--dangerously-skip-permissions");let l=i.some(S=>S==="--output-format"||String(S).startsWith("--output-format=")),p=i.includes("-p")||i.includes("--print"),y=!1;return!l&&p?(u.push("--output-format","stream-json","--include-partial-messages"),i.includes("--verbose")||u.push("--verbose"),y=!0):l&&(y=i.some(S=>/stream-json/.test(String(S)))),{cmd:n,args:u,model:o,permissionMode:s,permissionFlags:c,streamJson:y}}if(ur(n)){let u=[...i];return o&&u.push("--model",o),s==="yolo"&&u.push("--sandbox","danger-full-access","--ask-for-approval","never"),{cmd:n,args:u,model:o,permissionMode:s,permissionFlags:c}}return{cmd:n,args:r,model:o,permissionMode:s,permissionFlags:c}}function nr(){let e="",t="",n=!1,r="",o=null,s=c=>{if(!c||typeof c!="object")return;let u=c.event&&c.event.delta||c.delta;if(u&&u.type==="text_delta"&&typeof u.text=="string"){n=!0,t+=u.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 l=c.message.content.filter(p=>p&&p.type==="text"&&typeof p.text=="string").map(p=>p.text).join("");l&&(r+=l)}},i=c=>{let u=String(c).trim();if(u)try{s(JSON.parse(u))}catch{}};return{feed(c){e+=String(c||"");let u;for(;(u=e.indexOf(`
|
|
34
|
+
`))>=0;)i(e.slice(0,u)),e=e.slice(u+1)},end(){e&&(i(e),e="")},get live(){return n?t:r},get result(){return o??(n?t:r)}}}function Ot(e,t){return $e(t?.agent?.model||t?.model||e.model)}function $e(e){let t=String(e||"").trim();return!t||t==="auto"||t==="claude-fable-5"?Pn:t}function Nt(e,t){return ye(t?.agent?.permissionMode||t?.agent?.permission_mode||t?.permissionMode||t?.permission_mode||e.permissionMode)}function ye(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 De(e){return ye(e)==="yolo"?["--no-sandbox","--yolo"]:[]}function Oe(e,t,n,r=null,o=null){let s={busy:t.active()>0,queueSize:t.size(),cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,permissionFlags:De(e.permissionMode),daemon:{runtime:"agensis-cli",version:re,pid:k.pid,node:k.version,platform:k.platform,arch:k.arch,host:ue.hostname(),cwd:e.cwd}};if(o instanceof Map){let i={};for(let c of o.values()){let u=String(c?.model||"");u&&(i[u]=(i[u]||0)+1)}s.activeInferenceByModel=i}return r&&typeof r=="object"&&(s.cursorBuddy=rr(r)),n?.status&&(s.agentStatus=n.status),n?.note&&(s.agentNote=n.note),(n?.status||n?.note)&&(s.agentStatusAt=new Date().toISOString()),s}function rr(e={}){let t=e.client&&typeof e.client=="object"?e.client:{},n=e.page&&typeof e.page=="object"?e.page:{},r=e.runtime&&typeof e.runtime=="object"?e.runtime:{},o=e.manifest&&typeof e.manifest=="object"?e.manifest:{},s=e.project&&typeof e.project=="object"?e.project:{};return{surface:String(e.surface||"").slice(0,80),instanceId:String(e.instanceId||"").slice(0,140),url:String(e.url||"").slice(0,2048),title:String(e.title||"").slice(0,300),origin:String(n.origin||"").slice(0,300),hostname:String(n.hostname||"").slice(0,200),pathname:String(n.pathname||"").slice(0,500),visibilityState:String(n.visibilityState||"").slice(0,40),focused:n.focused===!0,userAgent:String(t.userAgent||"").slice(0,500),platform:String(t.platform||"").slice(0,120),language:String(t.language||"").slice(0,80),viewport:t.viewport&&typeof t.viewport=="object"?{width:Number(t.viewport.width)||0,height:Number(t.viewport.height)||0,devicePixelRatio:Number(t.viewport.devicePixelRatio)||0}:null,runtimeMarker:String(r.marker||"").slice(0,120),extensionMarker:String(r.extensionMarker||"").slice(0,120),manifest:{name:String(o.name||"").slice(0,120),version:String(o.version||"").slice(0,80),source:String(o.source||"").slice(0,500)},project:{name:String(s.name||"").slice(0,120),root:String(s.root||"").slice(0,500),agent:String(s.agent||"").slice(0,80)},updatedAt:String(e.updatedAt||"").slice(0,80)}}function At(e,t){if(!t||typeof t!="object")return;t.name&&(e.name=String(t.name).trim()||e.name),(t.handle||t.name)&&(e.handle=Dt(t.handle||t.name||e.handle)),t.model&&(e.model=$e(t.model));let n=t.permissionMode||t.permission_mode;n&&(e.permissionMode=ye(n)),(t.memory_dir!==void 0||t.memoryDir!==void 0)&&(e.memoryDir=String(t.memory_dir??t.memoryDir??"").trim())}function or(){let e=["claude","codex","gh","node","npm","python3","git","fly","vercel"],t=(k.env.PATH||"").split(ce.delimiter).filter(Boolean);return e.filter(n=>t.some(r=>{try{return Mt.existsSync(ce.join(r,n))}catch{return!1}}))}function sr(){try{let e=Mt.readFileSync(ce.join(ue.homedir(),".claude.json"),"utf8"),n=JSON.parse(e)?.mcpServers;if(n&&typeof n=="object")return Object.keys(n).sort()}catch{}return[]}function Et(e){return Dn.createHash("sha1").update(String(e)).digest("hex").slice(0,16)}async function $t(e,t=null){let n=st({cwd:e.cwd}),r=ot({cwd:e.cwd}),o=or(),s=sr(),i=_e({cwd:e.cwd,memoryDir:e.memoryDir})||null,c=ct(e.sharedModels),u=Et(JSON.stringify({skills:n,commands:r,clis:o,mcpServers:s,memoryRoot:i,sharedModels:c,codingRoute:!!e.codingCmd,shared:e.share,reach:t||null})),l=Et(await et(i));return{skills:n,commands:r,clis:o,mcpServers:s,memoryRoot:i,sharedModels:c,codingRoute:!!e.codingCmd,shared:e.share,reach:t||null,capabilitiesHash:u,memoryHash:l}}async function ie(e,t,n=null){try{let r=await $t(t,n);T(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,codingRoute:r.codingRoute,shared:r.shared,memoryRoot:r.memoryRoot,reach:r.reach||void 0,hash:r.capabilitiesHash,memoryHash:r.memoryHash}),x(`Capabilities synced \u2014 skills:${r.skills.length} commands:${r.commands.length} clis:${r.clis.length} mcp:${r.mcpServers.length}`)}catch(r){x(`Capabilities sync skipped: ${r?.message||r}`)}}function ir(e){let t=ue.networkInterfaces(),n=[];for(let r of Object.values(t))for(let o of r||[])o.family==="IPv4"&&!o.internal&&n.push({host:o.address,port:e,scope:"lan"});return n.slice(0,4)}async function It(e,t){try{let n=_e({cwd:t.cwd,memoryDir:t.memoryDir});if(!n)return;let r=await tt(n);T(e,{action:"agent_memory_sync",workspaceId:t.workspace,agentId:t.agent,root:n,files:r}),x(`Synced ${r.length} memory file${r.length===1?"":"s"} from ${n}`)}catch(n){x(`Memory sync skipped: ${n?.message||n}`)}}function ar(e){let t=new Set(["--model","-m","--permission-mode","--sandbox","--ask-for-approval","--approval-policy"]),n=new Set(["--dangerously-skip-permissions","--no-sandbox","--yolo","--accept-edits"]),r=[];for(let o=0;o<e.length;o+=1){let s=e[o],[i]=String(s).split("=",1);if(!n.has(s)){if(t.has(i)){String(s).includes("=")||(o+=1);continue}r.push(s)}}return r}function cr(e){return/(^|\/)claude(?:$|\.)/.test(String(e||""))}function ur(e){return/(^|\/)codex(?:$|\.)/.test(String(e||""))}function lr(e){let t=[],n="",r="",o=!1;for(let s of e){if(o){n+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(r){s===r?r="":n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n&&(t.push(n),n="");continue}n+=s}if(n&&t.push(n),!t.length)throw new Error("coding command is empty");return{cmd:t[0],args:t.slice(1)}}function Ne(e){try{return JSON.parse(String(e))}catch{return null}}function T(e,t){return!e||e.readyState!==ae.OPEN?!1:(e.send(JSON.stringify(t)),!0)}function dr(e){return String(e||"").split(/\r?\n/).map(t=>t.trim()).filter(Boolean).slice(-1)[0]||""}function Dt(e){return String(e||"").trim().toLowerCase().replace(/^@+/,"").replace(/[^a-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function mr(e){return e?.code==="EADDRINUSE"||/\bEADDRINUSE\b/.test(String(e?.message||e))}async function fr(e){let t=new AbortController,n=setTimeout(()=>t.abort(),700);try{let r=await fetch(`http://127.0.0.1:${Number(e||8787)}/cursorbuddy/health`,{cache:"no-store",signal:t.signal}),o=await r.json().catch(()=>({}));return!r.ok||!o?.ok?null:o}catch{return null}finally{clearTimeout(n)}}function x(e){k.stderr.write(`[agensis] ${e}
|
|
35
|
+
`)}function Ct(e){if(e instanceof Map)for(let t of e.values())try{t?.abort?.()}catch{}}import pr from"node:crypto";import le from"node:fs/promises";import hr from"node:os";import Tt from"node:path";var Q="default",gr=/^[a-zA-Z0-9_.-]{1,64}$/,yr=["url","token","workspace","agent","handle","name","cwd","codingCmd","model","permissionMode","timeoutMs","heartbeatMs","maxConcurrency","share","sharedModelsFile","noCoding","lanListener","primaryDaemon","cursorBuddyBridge","cursorBuddyPort"];function K(e=Q){let t=String(e||Q).trim();if(!gr.test(t))throw new Error("Daemon profile names may only contain letters, numbers, dot, dash, and underscore.");return t}function Rt(e=Q,t={}){let n=t.homedir||hr.homedir();return Tt.join(n,".agensis","daemon-profiles",`${K(e)}.json`)}function Te(e={}){let t={};for(let n of yr){let r=e[n];r!=null&&r!==""&&(t[n]=r)}return t}function V(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 Pt(e={}){return!!(V(e,["url","baseUrl"],["AGENSIS_URL"])||V(e,["token"],["AGENSIS_TOKEN"])||V(e,["workspace","workspaceId"],["AGENSIS_WORKSPACE","AGENSIS_WORKSPACE_ID"])||V(e,["agent","agentId"],["AGENSIS_AGENT","AGENSIS_AGENT_ID"]))}function Re(e={}){return!!(V(e,["url","baseUrl"],["AGENSIS_URL"])&&V(e,["token"],["AGENSIS_TOKEN"])&&V(e,["workspace","workspaceId"],["AGENSIS_WORKSPACE","AGENSIS_WORKSPACE_ID"])&&V(e,["agent","agentId"],["AGENSIS_AGENT","AGENSIS_AGENT_ID"]))}async function Lt(e=Q,t={}){let n=Rt(e,t),r;try{r=await le.readFile(n,"utf8")}catch(i){if(i?.code==="ENOENT")return null;throw i}let o;try{o=JSON.parse(r)}catch(i){throw new Error(`Daemon profile "${K(e)}" is unreadable: ${i?.message||i}`)}let s=o?.config;return!s?.url||!s?.token||!s?.workspace||!s?.agent?null:Te(s)}async function Se(e=Q,t={},n={}){let r=Te(t);if(!r.url||!r.token||!r.workspace||!r.agent)return null;let o=Rt(e,n),s=Tt.dirname(o);await le.mkdir(s,{recursive:!0,mode:448});let i=`${o}.${process.pid}.${Date.now()}.tmp`,c={version:1,savedAt:new Date().toISOString(),profile:K(e),tokenHash:pr.createHash("sha256").update(r.token).digest("hex"),config:r};return await le.writeFile(i,`${JSON.stringify(c,null,2)}
|
|
36
|
+
`,{mode:384}),await le.rename(i,o),await le.chmod(o,384).catch(()=>{}),o}function Ut(e,t={}){let n={...e,...Te(t),command:"connect"};return 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 jt(e=Q){let t=K(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===Q?"":` --profile ${t}`}`].join(`
|
|
37
|
+
`)}import Sr from"node:crypto";import de from"node:fs/promises";import Ft from"node:os";import Pe from"node:path";import Le from"node:process";var wr=/^cbk_[a-z0-9_]+_[A-Z2-9]{18}$/;function br(e={}){return String(e.url||e.baseUrl||Le.env.AGENSIS_URL||"https://agensis.io").trim().replace(/\/+$/,"")}function Gt(e,t={}){let n=t.homedir||Ft.homedir(),r=Sr.createHash("sha256").update(String(e)).digest("hex");return Pe.join(n,".agensis","cursorbuddy","connection-keys",`${r}.json`)}function kr(){return new Error("Missing or invalid --key. Create a CursorBuddy connection key in Agensis first.")}function Ue(e){let t=String(e||"").trim();if(!wr.test(t))throw kr();return t}function vr(e,t,n,r){let o=t?.token,s=t?.workspaceId||t?.workspace_id||t?.agent?.workspace_id,i=t?.agentId||t?.agent?.id;if(!o||!s||!i)throw new Error("CursorBuddy key claim did not return a complete daemon connection payload");let{key:c,subcommand:u,...l}=e;return{...l,command:"connect",url:t.baseUrl||n,token:o,workspace:s,agent:i,handle:t.handle||e.handle,name:t.agent?.name||e.name||"CursorBuddy runtime",model:t.model||e.model,permissionMode:t.permissionMode||t.permission_mode||e.permissionMode,cwd:e.cwd||r,cursorBuddyRuntime:!0}}async function _r(e,t={}){Ue(e);let n=Gt(e,t),r;try{r=await de.readFile(n,"utf8")}catch(i){if(i?.code==="ENOENT")return null;throw i}let o;try{o=JSON.parse(r)}catch(i){throw new Error(`Cached CursorBuddy daemon config is unreadable: ${i?.message||i}`)}let s=o?.daemonArgs;return!s?.token||!s?.workspace||!s?.agent||!s?.url?null:s}async function Ar(e,t,n={}){if(Ue(e),!t?.token||!t?.workspace||!t?.agent||!t?.url)return;let r=Gt(e,n),o=Pe.dirname(r);await de.mkdir(o,{recursive:!0,mode:448});let s=`${r}.${Le.pid}.${Date.now()}.tmp`,i={version:1,savedAt:new Date().toISOString(),keyHash:Pe.basename(r,".json"),daemonArgs:t};await de.writeFile(s,`${JSON.stringify(i,null,2)}
|
|
38
|
+
`,{mode:384}),await de.rename(s,r),await de.chmod(r,384).catch(()=>{})}function Er(e,t,n){let r={...e,command:"connect"};for(let o of["cwd","codingCmd","model","permissionMode","timeoutMs","heartbeatMs","maxConcurrency","share","sharedModelsFile","noCoding","lanListener","once"])t[o]!==void 0&&(r[o]=t[o]);return t.codingCmd!==void 0&&t.noCoding===void 0&&(r.noCoding=!1),r.cwd||(r.cwd=n),r.cursorBuddyRuntime=!0,r}function Ir(e,t){return t?.error?.message||t?.message||`CursorBuddy key claim failed with HTTP ${e.status}`}async function Cr(e){return e.json().catch(()=>({}))}async function Ht(e,t={}){let n=Ue(e?.key),r=br(e),o=t.fetchImpl||globalThis.fetch;if(typeof o!="function")throw new Error("This Node.js runtime does not provide fetch; use a current Node.js release.");let s=t.cwd||Le.cwd(),i=t.hostname||Ft.hostname(),c=t.version||re,u={homedir:t.homedir},l=await o(`${r}/backend/cursorbuddy/connection-keys/claim`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:n,baseUrl:r,host:i,cwd:e.cwd||s,name:e.name,surface:e.surface||"local_cli",scope:e.scope||"machine",runtimeKind:"agensis-cli",version:c,permissionMode:e.permissionMode,model:e.model})}),p=await Cr(l);if(!l.ok){let S=Ir(l,p);if(l.status===409||/already been claimed/i.test(S)){let h=await _r(n,u);if(h)return Er(h,e,s);throw new Error(`${S}. 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(S)}let y=vr(e,p?.data||p,r,s);return await Ar(n,y,u),y}import Mr from"node:crypto";import Br from"node:http";import xr from"node:os";import q from"node:process";import{spawn as Or}from"node:child_process";var Nr="https://agensis.io",$r=10*60*1e3;function we(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 Dr(e){return new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o,r.length>128*1024&&(n(new Error("setup callback body is too large")),e.destroy())}),e.on("error",n),e.on("end",()=>t(r))})}function Tr(e){let t=String(e||q.env.AGENSIS_URL||Nr).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 Rr(e){let t=q.platform==="darwin"?"open":q.platform==="win32"?"cmd":"xdg-open",n=q.platform==="win32"?["/c","start","",e]:[e],r=Or(t,n,{detached:!0,stdio:"ignore"});r.on("error",()=>{}),r.unref()}function Pr(e){let t=e?.daemonArgs||e?.data?.daemonArgs||e?.data||{},r=["url","token","workspace","agent"].filter(o=>!String(t[o]||"").trim());if(r.length)throw new Error(`Setup callback did not include ${r.join(", ")}`);return{...t,command:"connect"}}function Lr(e,t,n){let r=new URL(Tr(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",K(e.profile||"default")),r.searchParams.set("host",xr.hostname()),r.searchParams.set("cwd",String(e.cwd||q.cwd())),e.handle&&r.searchParams.set("handle",String(e.handle)),e.name&&r.searchParams.set("name",String(e.name)),r.toString()}async function Jt(e={}){let t=K(e.profile||"default"),n=Mr.randomBytes(24).toString("base64url"),r=Number(e.setupTimeoutMs||q.env.AGENSIS_SETUP_TIMEOUT_MS||$r),o,s=new Promise((l,p)=>{let y=setTimeout(()=>p(new Error("Agensis setup timed out waiting for browser login.")),r);y.unref&&y.unref(),o=Br.createServer(async(S,h)=>{if(h.setHeader("access-control-allow-origin","*"),h.setHeader("access-control-allow-methods","POST, OPTIONS"),h.setHeader("access-control-allow-headers","content-type"),S.method==="OPTIONS"){h.writeHead(204),h.end();return}if(S.method!=="POST"||S.url!=="/agensis/setup-callback"){we(h,404,{ok:!1,error:"Unknown Agensis setup callback route"});return}try{let $=JSON.parse(await Dr(S)||"{}");if($?.state!==n){we(h,403,{ok:!1,error:"Setup state did not match"});return}let O={...Pr($),primaryDaemon:!0,cursorBuddyBridge:e.cursorBuddyBridge!==!1};await Se(t,O),clearTimeout(y),we(h,200,{ok:!0,profile:t}),l(O)}catch($){we(h,400,{ok:!1,error:String($?.message||$)})}}),o.once("error",p)});await new Promise((l,p)=>{o.listen(0,"127.0.0.1",y=>y?p(y):l())});let{port:i}=o.address(),c=`http://127.0.0.1:${i}/agensis/setup-callback`,u=Lr(e,c,n);q.stdout.write(`[agensis] Opening Agensis to sign in and connect this machine.
|
|
39
|
+
`),q.stdout.write(`[agensis] If the browser did not open, visit:
|
|
40
|
+
${u}
|
|
41
|
+
`),Rr(u);try{let l=await s;return q.stdout.write(`[agensis] Saved daemon profile "${t}". Starting primary agent daemon.
|
|
42
|
+
`),l}finally{await new Promise(l=>o.close(()=>l())).catch(()=>{})}}function Ur(e){let t={command:"connect"},n=[...e],r=n[0];if(r&&!r.startsWith("-")&&(t.command=n.shift(),t.command==="buddy")){let o=n[0];o&&!o.startsWith("-")?t.subcommand=n.shift():t.subcommand="connect"}for(let o=0;o<n.length;o+=1){let s=n[o];if(!s.startsWith("--"))throw new Error(`Unexpected argument: ${s}`);let[i,c]=s.slice(2).split(/=(.*)/s,2),u=i.replace(/-([a-z])/g,(p,y)=>y.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==="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}let l=c!==void 0?c:n[++o];if(l==null||l.startsWith("--"))throw new Error(`Missing value for --${i}`);t[u]=l}return t}function jr(){return`agensis agent daemon
|
|
13
43
|
|
|
14
44
|
Usage:
|
|
15
45
|
agensis --url <workspace-url> --token <token> --workspace <id> --agent <id> [options]
|
|
16
46
|
agensis connect --url <workspace-url> --token <token> --workspace <id> --agent <id> [options]
|
|
47
|
+
agensis connect [--profile <name>]
|
|
48
|
+
agensis setup [--url <agensis-url>] [--profile <name>] [--handle <name>]
|
|
49
|
+
agensis buddy connect --key <cbk_...> [--url <agensis-url>] [options]
|
|
17
50
|
|
|
18
51
|
Required:
|
|
19
52
|
--url <url> agensis app/backend URL, for example https://agensis.io or http://localhost:5173
|
|
20
53
|
--token <token> Agent connection token from agensis
|
|
21
54
|
--workspace <id> Workspace id
|
|
22
55
|
--agent <id> Workspace agent id
|
|
56
|
+
--key <cbk_...> One-time CursorBuddy connection key for buddy connect
|
|
23
57
|
|
|
24
58
|
Options:
|
|
25
59
|
--handle <name> Mention handle used in channels
|
|
26
60
|
--name <name> Display name
|
|
27
61
|
--cwd <path> Folder where the coding CLI runs
|
|
28
62
|
--coding-cmd <command> Command used for jobs, default: claude -p
|
|
63
|
+
--no-coding Disable coding jobs; keep presence/shared inference only
|
|
29
64
|
--model <id> Default model to pass to supported coding CLIs
|
|
30
65
|
--permission-mode <m> default, accept_edits, or yolo
|
|
31
66
|
--yolo Alias for --permission-mode yolo
|
|
32
67
|
--no-sandbox Alias for --permission-mode yolo
|
|
33
68
|
--timeout-ms <ms> Kill a job after this time, default: 1800000
|
|
34
69
|
--heartbeat-ms <ms> Local terminal heartbeat interval, default: 15000
|
|
70
|
+
--cursorbuddy-port <n> Local CursorBuddy discovery/chat port, default: 8787
|
|
71
|
+
--cursorbuddy-bridge Enable local CursorBuddy discovery/chat bridge
|
|
72
|
+
--no-cursorbuddy-bridge Disable local CursorBuddy discovery/chat bridge
|
|
35
73
|
--once Run one queued job then exit
|
|
74
|
+
--lan Opt in to the agent-mesh LAN listener for direct
|
|
75
|
+
daemon-to-daemon job handoff (default: off)
|
|
76
|
+
--share Advertise local inference models to this workspace
|
|
77
|
+
--shared-models-file <path>
|
|
78
|
+
JSON config for loopback OpenAI-compatible models
|
|
79
|
+
--profile <name> Save/reuse a local daemon profile, default: default
|
|
36
80
|
--version Print the CLI version
|
|
37
81
|
--help Show this help
|
|
38
|
-
`}async function
|
|
39
|
-
`)
|
|
40
|
-
`)
|
|
82
|
+
`}async function Fr(e){let t=e.profile!==void 0,n=e.handle||e.name,r=K(e.profile||(Re(e)&&n?n:"default"));if(!Pt(e)){let o=await Lt(r);if(!o)throw new Error(jt(r));return Ut(o,e)}return Re(e)?{...e,cursorBuddyBridge:e.cursorBuddyBridge===!0,onRegistered:async o=>{await Se(r,o);let s=t||r!=="default"?`agensis connect --profile ${r}`:"agensis connect";Y.stdout.write(`[agensis] Saved daemon profile "${r}". Restart with: ${s}
|
|
83
|
+
`)}}:e}async function Gr(){let e=Ur(Y.argv.slice(2));if(e.help){Y.stdout.write(jr());return}if(e.version){Y.stdout.write(`${re}
|
|
84
|
+
`);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 Ht(e);n.cursorBuddyBridge=e.cursorBuddyBridge!==!1,n.cursorBuddyRuntime=!0,n.exitOnOnce=!0,await ge(n),n.once&&Y.exit(0);return}if(e.command==="setup"){let n=await Jt(e);n.exitOnOnce=!0,await ge({...e,...n}),n.once&&Y.exit(0);return}if(e.command!=="connect")throw new Error(`Unknown command "${e.command}". Use "agensis setup", "agensis connect --url ...", or "agensis buddy connect --key ...".`);let t=await Fr(e);t.exitOnOnce=!0,await ge(t),t.once&&Y.exit(0)}Gr().catch(e=>{Y.stderr.write(`${e?.message||e}
|
|
85
|
+
`),Y.exitCode=1});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agensis/agensis-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.22",
|
|
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": {
|