@vibecontrols/agent 2026.1130.1 → 2026.1202.1

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.
Files changed (71) hide show
  1. package/dist/{agent-config-xwvsmn6b.js → agent-config-mg5dvtm3.js} +1 -1
  2. package/dist/{agent-ready-tracker-7ebr09d9.js → agent-ready-tracker-b1dxkhrt.js} +1 -1
  3. package/dist/app-hvt8zawq.js +2 -0
  4. package/dist/autostart.cmd-4c0rekqt.js +2 -0
  5. package/dist/bootstrap-workspace-wsjzmm9n.js +2 -0
  6. package/dist/bootstrap.service-0m0rcq8d.js +2 -0
  7. package/dist/{bridge-client-9ax1cvj6.js → bridge-client-fcwk5tyk.js} +1 -1
  8. package/dist/{bridge-commands-hc1gvngq.js → bridge-commands-xagq5kq7.js} +1 -1
  9. package/dist/cli.js +1 -1
  10. package/dist/daemon-profile-0bvscqm2.js +2 -0
  11. package/dist/{finalize-retry-worker-c38km3mt.js → finalize-retry-worker-qe7zagk7.js} +1 -1
  12. package/dist/gateway-client-8gfze3jv.js +2 -0
  13. package/dist/{index-dr6rsnpk.js → index-2a1yq04v.js} +3 -3
  14. package/dist/{index-dgbe8jm8.js → index-2nq1tefj.js} +1 -1
  15. package/dist/{index-j99tkngg.js → index-30qr1qm3.js} +1 -1
  16. package/dist/{index-ednz6yz2.js → index-4qqsx04e.js} +1 -1
  17. package/dist/{index-twtvt4yt.js → index-5ygnxt32.js} +3 -3
  18. package/dist/{index-rhn7wy1p.js → index-6g3qhprq.js} +1 -1
  19. package/dist/{index-5tghd67e.js → index-6xd9k363.js} +6 -6
  20. package/dist/{index-j9jwwzq2.js → index-8y4fys3s.js} +7 -7
  21. package/dist/{index-yfk0pb00.js → index-ag2b7yeg.js} +1 -1
  22. package/dist/{index-bk17490n.js → index-c9q14161.js} +1 -1
  23. package/dist/{index-damc6cvc.js → index-djwa3tm3.js} +1 -1
  24. package/dist/{index-0rmmrrfh.js → index-ep20qw1j.js} +1 -1
  25. package/dist/{index-6nv5rdqh.js → index-fm1wjs3r.js} +1 -1
  26. package/dist/{index-12gb48hg.js → index-j9cg16we.js} +1 -1
  27. package/dist/{index-f5nmxa9e.js → index-jhgd7sva.js} +1 -1
  28. package/dist/{index-76vza24h.js → index-mrcjqvnf.js} +1 -1
  29. package/dist/{index-p7fbnfwd.js → index-n3kwtv6f.js} +2 -2
  30. package/dist/{index-e5jdx9c1.js → index-nqa1m94e.js} +2 -2
  31. package/dist/index-nxpw3anc.js +30 -0
  32. package/dist/{index-zcnfj1q4.js → index-prp5nvsa.js} +3 -3
  33. package/dist/{index-qzwbctkv.js → index-pw6aqemr.js} +4 -4
  34. package/dist/{index-4kf3nr14.js → index-r1v0yazw.js} +2 -2
  35. package/dist/{index-q4fht6h2.js → index-r2j1t657.js} +19 -19
  36. package/dist/{index-vhz1c474.js → index-tn2vyz8q.js} +1 -1
  37. package/dist/{index-br9bakfm.js → index-txchzvfc.js} +2 -2
  38. package/dist/{index-85jn7v8t.js → index-xertgyzn.js} +5 -5
  39. package/dist/{index-wxb9dgwq.js → index-zekdqp0t.js} +1 -1
  40. package/dist/{index-8jk4a62x.js → index-zfhmg1gz.js} +6 -6
  41. package/dist/{index-sjs32cgn.js → index-zngtj9re.js} +2 -2
  42. package/dist/index.js +2 -2
  43. package/dist/key.cmd-eevbsknq.js +2 -0
  44. package/dist/log-shipper-h7azf3f8.js +2 -0
  45. package/dist/{path-utils-qgkdkp5j.js → path-utils-3sgj48ta.js} +1 -1
  46. package/dist/plugin-system-e1a3ttpy.js +2 -0
  47. package/dist/prereqs-runner-etehmhk8.js +2 -0
  48. package/dist/profile-mount-rr5kr708.js +2 -0
  49. package/dist/register-core-7kb2k9g3.js +2 -0
  50. package/dist/secondary-profile-attach-2x3dsnn8.js +2 -0
  51. package/dist/subprocess-j0r8hvmc.js +2 -0
  52. package/dist/telemetry-fyced899.js +2 -0
  53. package/dist/tunnel-bootstrap-rm5k7qw4.js +2 -0
  54. package/package.json +1 -1
  55. package/dist/app-ntnpwedw.js +0 -2
  56. package/dist/autostart.cmd-mdyv35dn.js +0 -2
  57. package/dist/bootstrap-workspace-1pt0bwy6.js +0 -2
  58. package/dist/bootstrap.service-gehm65tt.js +0 -2
  59. package/dist/daemon-profile-fnhc7pcf.js +0 -2
  60. package/dist/gateway-client-3zp6kkav.js +0 -2
  61. package/dist/index-7wm4bqx5.js +0 -21
  62. package/dist/key.cmd-y415ngam.js +0 -2
  63. package/dist/log-shipper-02rqvtq8.js +0 -2
  64. package/dist/plugin-system-e690jr6e.js +0 -2
  65. package/dist/prereqs-runner-w7z2dwa6.js +0 -2
  66. package/dist/profile-mount-ga5z1vx9.js +0 -2
  67. package/dist/register-core-n1dy472f.js +0 -2
  68. package/dist/secondary-profile-attach-v7kxsk4z.js +0 -2
  69. package/dist/subprocess-p9bv9nqz.js +0 -2
  70. package/dist/telemetry-1d3t1mbf.js +0 -2
  71. package/dist/tunnel-bootstrap-m51w4d94.js +0 -2
@@ -0,0 +1,30 @@
1
+ // @bun
2
+ import{join as Ft}from"path";import{AsyncLocalStorage as lt}from"async_hooks";import{mkdirSync as ct}from"fs";import{join as le}from"path";import{appendFileSync as de,existsSync as L,mkdirSync as me,readFileSync as ye,readdirSync as we,statSync as ke,unlinkSync as Y}from"fs";import{join as k}from"path";var Te=30,Se=104857600,ve=/secret|password|token|key|email/i,J=/^audit-(\d{4}-\d{2}-\d{2})\.log$/;function X(t=new Date){let r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${r}-${n}-${i}`}function P(t){if(Array.isArray(t))return t.map(P);if(t&&typeof t==="object"){let r={};for(let[n,i]of Object.entries(t)){if(ve.test(n)){r[n]="[redacted]";continue}r[n]=P(i)}return r}return t}function Re(t,r){if(!r)return!0;if(r.includes("*"))return new RegExp(`^${r.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`).test(t);return t.includes(r)}class _{profile;auditDir;constructor(t,r){this.profile=t,this.auditDir=k(r,"audit")}ensureDir(){if(!L(this.auditDir))me(this.auditDir,{recursive:!0});return this.auditDir}activeFilePath(){return k(this.ensureDir(),`audit-${X()}.log`)}emit(t,r,n={}){let i=P(n),o={timestamp:new Date().toISOString(),source:t,event:r,payload:{...i,profile:this.profile}};try{de(this.activeFilePath(),`${JSON.stringify(o)}
3
+ `,{mode:384})}catch{}}listLogFiles(){if(!L(this.auditDir))return[];return we(this.auditDir).filter((t)=>J.test(t)).sort()}listEvents(t={}){let r=Math.max(1,Math.min(t.limit??200,5000)),n=t.since?Date.parse(t.since):null,i=t.event??"",o=this.listLogFiles(),a=[];for(let s=o.length-1;s>=0&&a.length<r;s--){let l=o[s],c;try{c=ye(k(this.auditDir,l),"utf8")}catch{continue}let u=c.split(`
4
+ `);for(let g=u.length-1;g>=0&&a.length<r;g--){let p=u[g];if(!p)continue;let f;try{f=JSON.parse(p)}catch{continue}if(n!==null&&Number.isFinite(n)&&Date.parse(f.timestamp)<n)continue;if(!Re(f.event,i))continue;a.push(f)}}return a}runRetention(t=new Date){if(!L(this.auditDir))return;let r=t.getTime()-Te*24*60*60*1000,n=this.listLogFiles(),i=[];for(let s of n){let l=J.exec(s);if(!l)continue;let c=Date.parse(`${l[1]}T00:00:00Z`),u=k(this.auditDir,s);try{let g=ke(u);if(Number.isFinite(c)&&c<r){Y(u);continue}i.push({name:s,size:g.size,mtime:g.mtimeMs})}catch{}}let o=i.reduce((s,l)=>s+l.size,0),a=`audit-${X(t)}.log`;i.sort((s,l)=>s.name.localeCompare(l.name));for(let s of i){if(o<=Se)break;if(s.name===a)continue;try{Y(k(this.auditDir,s.name)),o-=s.size}catch{}}}__getAuditDirForTests(){return this.auditDir}}class G{profile;cryptoKey=null;apiKeyHash=null;constructor(t){this.profile=t}async load(t){if(t.byteLength!==32)throw Error(`KeyVault expects 32-byte key, got ${t.byteLength}`);let r=new Uint8Array(t);try{this.cryptoKey=await crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{t.fill(0),r.fill(0)}}async bindApiKey(t){let r=new TextEncoder().encode(t);this.apiKeyHash=await crypto.subtle.digest("SHA-256",r),r.fill(0)}async match(t){if(!this.apiKeyHash)return!1;let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return r.fill(0),be(this.apiKeyHash,n)}hasKey(){return this.cryptoKey!==null}getCryptoKey(){return this.cryptoKey}shutdown(){this.cryptoKey=null,this.apiKeyHash=null}}function be(t,r){if(t.byteLength!==r.byteLength)return!1;let n=new Uint8Array(t),i=new Uint8Array(r),o=0;for(let a=0;a<n.length;a++)o|=(n[a]??0)^(i[a]??0);return o===0}import{existsSync as y,mkdirSync as Le,statSync as Pe,copyFileSync as Ie,truncateSync as _e,renameSync as Ce,unlinkSync as Ge,createReadStream as De}from"fs";import{join as Fe}from"path";import{EventEmitter as Ue}from"events";import{createInterface as $e}from"readline";import{AsyncLocalStorage as Ee}from"async_hooks";var Z=new Ee,xe=/^[A-Za-z0-9._:-]{8,128}$/;function Ai(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let r=new Uint8Array(16);return t?.getRandomValues?.(r),[...r].map((n)=>n.toString(16).padStart(2,"0")).join("")}function Hi(t){let r=(i)=>{if(t instanceof Headers)return t.get(i)??void 0;return t[i]??t[i.toLowerCase()]??t[i.toUpperCase()]},n=r("x-request-id")??r("X-Request-Id");if(!n)return;return xe.test(n)?n:void 0}function Vi(t){Z.enterWith(t)}function Tt(){return Z.getStore()?.requestId}function Ae(){let t=process.env.VIBECONTROLS_LOG_SHIP_URL;if(!t)return null;return{url:t,apiKey:process.env.VIBECONTROLS_LOG_SHIP_API_KEY,batchSize:Number.parseInt(process.env.VIBECONTROLS_LOG_SHIP_BATCH??"",10)||100,intervalMs:Number.parseInt(process.env.VIBECONTROLS_LOG_SHIP_INTERVAL_MS??"",10)||1e4,sampleRate:Number.parseFloat(process.env.VIBECONTROLS_LOG_SHIP_SAMPLE??"1")}}var te=1000;class re{config=null;queue=[];timer=null;inFlight=!1;dropped=0;init(){if(this.config)return;if(this.config=Ae(),!this.config)return;if(this.timer=setInterval(()=>{this.flush()},this.config.intervalMs),this.timer&&typeof this.timer.unref==="function")this.timer.unref()}enqueue(t){if(!this.config)return;if(t.level==="debug"&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate)return;if(this.queue.length>=te)this.dropped+=1,this.queue.shift();this.queue.push(t)}async flush(){if(!this.config||this.inFlight||this.queue.length===0)return;this.inFlight=!0;let t=this.queue.splice(0,this.config.batchSize);try{await fetch(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey?{Authorization:`Bearer ${this.config.apiKey}`}:{}},body:JSON.stringify({entries:t,dropped:this.dropped}),signal:AbortSignal.timeout(5000)}),this.dropped=0}catch{this.queue=[...t,...this.queue].slice(0,te)}finally{this.inFlight=!1}}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;this.flush()}}var Yi=new re;var Ne=10485760,ie=7,Be=60000,E={debug:0,info:1,warn:2,error:3},Me={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"},qe="\x1B[0m";class F extends Ue{logDir;logFile;currentDay="";minLevel;isDaemon;emitOutput;prettyOutput;rotationTimer=null;constructor(t){super();this.setMaxListeners(100),this.logDir=t.logDir;let r=process.env.AGENT_LOG_FILE;this.logFile=r&&r.length>0?r:t.logFile??Fe(this.logDir,"default.log"),this.minLevel=process.env.LOG_LEVEL??"info",this.isDaemon=Boolean(process.env.AGENT_LOG_FILE);let n=process.env.VIBE_FOREGROUND==="1"||process.argv.some((i)=>i==="-f"||i==="--foreground");if(this.emitOutput=this.isDaemon||n||process.env.LOG_CONSOLE==="true"||!1,this.prettyOutput=this.emitOutput&&!this.isDaemon&&Boolean(process.stdout.isTTY),this.ensureLogDir(),this.currentDay=new Date().toISOString().split("T")[0]??"",this.isDaemon)this.rotationTimer=setInterval(()=>this.checkRotation(),Be),this.rotationTimer.unref?.()}debug(t,r,n){this.log("debug",t,r,n)}info(t,r,n){this.log("info",t,r,n)}warn(t,r,n){this.log("warn",t,r,n)}error(t,r,n){this.log("error",t,r,n)}setLevel(t){this.minLevel=t}async readHistory(t){let{level:r,source:n,from:i,to:o,limit:a=200,offset:s=0}=t??{},l=[];if(!y(this.logFile))return l;return new Promise((c)=>{let u=$e({input:De(this.logFile,"utf8")}),g=0;u.on("line",(p)=>{if(l.length>=a){u.close();return}try{let f=JSON.parse(p);if(r&&E[f.level]<E[r])return;if(n&&!f.source.includes(n))return;if(i&&f.timestamp<i)return;if(o&&f.timestamp>o)return;if(g<s){g++;return}l.push(f)}catch{}}),u.on("close",()=>c(l)),u.on("error",()=>c(l))})}close(){if(this.rotationTimer)clearInterval(this.rotationTimer),this.rotationTimer=null}log(t,r,n,i){if(E[t]<E[this.minLevel])return;let o=Tt(),a=o!==void 0?{requestId:o,...i??{}}:i,s={timestamp:new Date().toISOString(),level:t,source:r,message:n,...a&&Object.keys(a).length>0?{metadata:a}:{}};if(this.emitOutput)if(this.prettyOutput){let l=Me[t],c=t.toUpperCase().padEnd(5),u=r?` [${r}]`:"",g=a&&Object.keys(a).length>0?` ${JSON.stringify(a)}`:"",p=s.timestamp.split("T")[1]?.slice(0,12)??s.timestamp;process.stdout.write(`${l}${p} ${c}${qe}${u} ${n}${g}
5
+ `)}else process.stdout.write(JSON.stringify(s)+`
6
+ `);this.emit("log",s),Yi.enqueue(s)}checkRotation(){let t=new Date().toISOString().split("T")[0];if(this.currentDay&&this.currentDay!==t){this.rotate(),this.currentDay=t;return}this.currentDay=t;try{if(y(this.logFile)){if(Pe(this.logFile).size>=Ne)this.rotate()}}catch{}}rotate(){try{for(let t=ie-1;t>=1;t--){let r=`${this.logFile}.${t}`,n=`${this.logFile}.${t+1}`;if(y(r)){if(t+1>ie&&y(n))Ge(n);Ce(r,n)}}if(y(this.logFile))Ie(this.logFile,`${this.logFile}.1`),_e(this.logFile,0)}catch{}}ensureLogDir(){if(!y(this.logDir))Le(this.logDir,{recursive:!0})}}var x=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]","host.docker.internal"]),We=new Set(["4000","4001","4002","4003"]),Ke=new Set(["gw-global.local.burdenoff.com","gw-global-int.local.burdenoff.com","gw-wspace.local.burdenoff.com","gw-wspace-int.local.burdenoff.com"]),ze=new Set(["graphql.burdenoff.com","graphqlworkspaces.burdenoff.com","alphagraphql.burdenoff.com","alphagraphqlworkspaces.burdenoff.com"]);function d(t){return t.toLowerCase().replace(/^\[|\]$/g,"")}function oe(t){let r=d(t.hostname);if(!x.has(r))return!1;if(process.env.VIBECONTROLS_ALLOW_UNTRUSTED_GATEWAYS==="1")return!0;return We.has(t.port)}function ae(t){try{let r=new URL(t.trim());if(r.protocol!=="https:"&&r.protocol!=="http:")return!1;if(oe(r))return!0;let n=d(r.hostname);if(Ke.has(n))return r.protocol==="https:";if(r.protocol!=="https:")return!1;return ze.has(n)}catch{return!1}}function z(t,r){let n=t.trim();if(!ae(n))throw Error(`${r} is not an allowed gateway URL. Use a trusted Burdenoff gateway, approved gw-*.local.burdenoff.com host, or localhost gateway ports 4000-4003.`);return n.replace(/\/+$/,"")}var U=new Set([".vibecontrols.com"]);function Jt(t){let r=t.trim().toLowerCase();if(!r)return;U.add(r.startsWith(".")?r:`.${r}`)}function Ve(t){try{let r=new URL(t.trim()),n=d(r.hostname);if(x.has(n))return r.protocol==="http:"||r.protocol==="https:";if(r.protocol!=="https:")return!1;for(let i of U)if(n.endsWith(i))return!0;return!1}catch{return!1}}function ci(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return Ve(r)?r:null}function Wt(t){if(!t)return null;let r=ci(t);if(r)return r;let n=process.env.AGENT_TUNNEL_URL;if(n&&t.trim().replace(/\/+$/,"")===n.trim().replace(/\/+$/,""))return xt(t);return null}var Qe=new Set([".trycloudflare.com"]);function je(t){try{let r=new URL(t.trim()),n=d(r.hostname);if(x.has(n))return r.protocol==="http:"||r.protocol==="https:";if(r.protocol!=="https:")return!1;for(let i of U)if(n.endsWith(i))return!0;for(let i of Qe)if(n.endsWith(i))return!0;return!1}catch{return!1}}function Ir(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return je(r)?r:null}function He(t){try{let r=new URL(t.trim()),n=d(r.hostname);if(x.has(n))return r.protocol==="http:"||r.protocol==="https:";return r.protocol==="https:"}catch{return!1}}function xt(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return He(r)?r:null}function Zi(t,r){try{let n=new URL(t.trim());if(n.protocol!=="https:"&&!oe(n))return!1;let i=d(n.hostname);for(let o of r){if(!o)continue;let a=new URL(o);if(i===d(a.hostname))return!0}return ae(t)}catch{return!1}}class S extends Error{status;constructor(t,r){super(t);this.status=r;this.name="GatewayHttpError"}}var Ye=/(?:\/(?:global|workspaces))?\/graphql$/i,Je=1048576,Xe=60000,Ze=600000,et=30000,tt="WORKSPACE_SESSION_UNRESOLVED",rt=`
7
+ mutation IssueAgentWorkspaceToken($input: IssueWorkspaceTokenInput!) {
8
+ issueWorkspaceToken(input: $input) {
9
+ success
10
+ token
11
+ expiresAt
12
+ error { code message }
13
+ }
14
+ }
15
+ `;function nt(t,r){if(r)return r instanceof S&&r.status===401;if(!t||t.data)return!1;return t.errors?.some((n)=>n.extensions?.authFailure===tt)??!1}function it(t,r){let n=t?Date.parse(t):Number.NaN;return Number.isFinite(n)&&n>r?n:r+Ze}function W(t){return t.trim().replace(/\/+$/,"").replace(Ye,"")}function N(t,r){return`${W(t)}/${r}/graphql`}function M(t){return t instanceof Error?t.message:String(t)}async function st(t,r){let n=t.headers.get("content-length");if(n){let c=Number.parseInt(n,10);if(Number.isInteger(c)&&c>r)throw Error(`Gateway response is too large (${c} bytes)`)}if(!t.body)return"";let i=t.body.getReader(),o=[],a=0;try{while(!0){let{done:c,value:u}=await i.read();if(c)break;if(!u)continue;if(a+=u.byteLength,a>r)throw await i.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${r} bytes`);o.push(u)}}finally{i.releaseLock()}let s=new Uint8Array(a),l=0;for(let c of o)s.set(c,l),l+=c.byteLength;return new TextDecoder().decode(s)}class ui{config=null;token=null;authInFlight=null;configGeneration=0;workspaceToken=null;workspaceTokenBackoff=null;workspaceTokenInFlight=null;configure(t){let r=W(z(t.globalGatewayUrl,"globalGatewayUrl")),n=t.workspaceGatewayUrl?W(z(t.workspaceGatewayUrl,"workspaceGatewayUrl")):void 0,i=t.clientId.trim(),o=t.clientSecret.trim();if(!r)throw Error("globalGatewayUrl is required");if(!i)throw Error("clientId is required");if(!o)throw Error("clientSecret is required");this.configGeneration+=1,this.config={...t,globalGatewayUrl:r,workspaceGatewayUrl:n,clientId:i,clientSecret:o,scopes:t.scopes?.map((a)=>a.trim()).filter(Boolean),workspaceId:t.workspaceId?.trim()||void 0,organizationId:t.organizationId?.trim()||void 0},this.token=null,this.authInFlight=null,this.workspaceToken=null,this.workspaceTokenInFlight=null,this.workspaceTokenBackoff=null,e().logger.info("gateway-client","Gateway client configured",{globalGatewayUrl:this.config.globalGatewayUrl,workspaceGatewayUrl:this.config.workspaceGatewayUrl,clientId:this.config.clientId})}isConfigured(){return this.config!==null}getConfig(){if(!this.config)return null;let{clientSecret:t,...r}=this.config;return r}async getAccessToken(){let{token:t,config:r}=await this.ensureToken();return{token:t,workspaceGatewayUrl:r.workspaceGatewayUrl??"",globalGatewayUrl:r.globalGatewayUrl??"",workspaceId:r.workspaceId??""}}async globalQuery(t,r){return this.executeQuery("global",t,r)}async workspaceQuery(t,r){return this.executeQuery("workspaces",t,r)}async lookupPeerAgent(t,r){if(!this.isConfigured())return null;try{let i=(await this.workspaceQuery(`query AgentNetworkLookup($targetAgentRecordId: ID!, $operation: String!) {
16
+ vibecontrolsAgentNetworkLookup(targetAgentRecordId: $targetAgentRecordId, operation: $operation) {
17
+ tunnelUrl
18
+ peerApiKey
19
+ }
20
+ }`,{targetAgentRecordId:t,operation:r})).data?.vibecontrolsAgentNetworkLookup;if(!i)return null;return{tunnelUrl:i.tunnelUrl,apiKey:i.peerApiKey}}catch(n){return e().logger.warn("gateway-client","Peer agent lookup failed",{targetAgentRecordId:t,error:n instanceof Error?n.message:String(n)}),null}}async executeQuery(t,r,n){let{token:i,config:o,generation:a}=await this.ensureToken(),s=t==="workspaces"?o.workspaceGatewayUrl??o.globalGatewayUrl:o.globalGatewayUrl,l=N(s,t);e().logger.debug("gateway-client",`GraphQL ${t} request`,{url:l,queryLength:r.length});let c=Boolean(o.workspaceId&&t==="workspaces"),u=async(p,f,h)=>{let m={"Content-Type":"application/json",Authorization:`Bearer ${p}`};if(c&&f.workspaceId)m["x-workspace-id"]=f.workspaceId;if(h)m["X-Workspace-Authorization"]=`Bearer ${h}`;let H=Tt();if(H)m["X-Request-Id"]=H;return this.postGraphQL(l,m,{query:r,variables:n})},g;if(!c)g=await u(i,o,null);else{let p=await this.ensureWorkspaceToken(i,o),f=null,h=null;try{f=await u(i,o,p)}catch(m){h=m}if(nt(f,h))g=await this.retryRefusedWorkspaceCall({token:i,generation:a,workspaceToken:p,first:f,firstError:h},u);else if(h)throw h;else g=f??{}}if(g.errors?.length)e().logger.warn("gateway-client","GraphQL errors",{supergraph:t,errors:g.errors.map((p)=>p.message)});return g}async retryRefusedWorkspaceCall(t,r){let{token:n,generation:i,workspaceToken:o,first:a,firstError:s}=t,l=()=>{if(s)throw s;return a??{}},c=s instanceof S&&s.status===401;if(e().logger.warn("gateway-client","The gateway refused the workspace session",{hadWorkspaceToken:o!==null,error:s instanceof Error?s.message:a?.errors?.[0]?.message}),o)this.invalidateWorkspaceToken(o);if(c&&this.token?.accessToken===n)this.token=null;if(!o&&!c)return l();let u=await this.ensureToken();if(u.generation!==i)return l();let g=await this.ensureWorkspaceToken(u.token,u.config);if(!g&&!c)return l();return r(u.token,u.config,g)}async ensureWorkspaceToken(t,r){let n=r.workspaceId;if(!n)return null;let i=this.workspaceToken;if(i&&i.appToken===t&&i.workspaceId===n&&i.expiresAt>Date.now()+Xe)return i.token;let o=`${this.configGeneration}:${n}:${t}`,a=this.workspaceTokenBackoff;if(a&&a.key===o&&a.until>Date.now())return null;if(this.workspaceTokenInFlight?.key===o)return this.workspaceTokenInFlight.promise;let s={key:o,promise:this.issueWorkspaceToken(t,r,n)};this.workspaceTokenInFlight=s;try{return await s.promise}finally{if(this.workspaceTokenInFlight===s)this.workspaceTokenInFlight=null}}invalidateWorkspaceToken(t){if(this.workspaceToken?.token===t)this.workspaceToken=null}async issueWorkspaceToken(t,r,n){let i=this.configGeneration,o=N(r.workspaceGatewayUrl??r.globalGatewayUrl,"workspaces"),a;try{a=await this.postGraphQL(o,{"Content-Type":"application/json",Authorization:`Bearer ${t}`},{query:rt,variables:{input:r.organizationId?{workspaceId:n,organizationId:r.organizationId}:{workspaceId:n}}})}catch(c){return this.backOffWorkspaceToken(i,n,t),e().logger.warn("gateway-client","Could not mint a workspace token; sending the call without one",{error:M(c)}),null}let s=a.data?.issueWorkspaceToken;if(a.errors?.length||!s?.success||!s.token)return this.backOffWorkspaceToken(i,n,t),e().logger.warn("gateway-client","The platform did not issue a workspace token; sending the call without one",{error:a.errors?.[0]?.message??s?.error?.message??"no workspace token returned",code:s?.error?.code}),null;if(i!==this.configGeneration)return null;let l=Date.now();return this.workspaceToken={token:s.token,expiresAt:it(s.expiresAt,l),appToken:t,workspaceId:n},s.token}backOffWorkspaceToken(t,r,n){if(t!==this.configGeneration)return;this.workspaceTokenBackoff={key:`${t}:${r}:${n}`,until:Date.now()+et}}async ensureToken(){if(!this.config)throw Error("Gateway client not configured. Call configure() first.");let t=this.config,r=this.configGeneration;if(this.token&&this.token.expiresAt>Date.now()+60000)return{token:this.token.accessToken,config:t,generation:r};if(this.authInFlight?.generation===r){let i=await this.authInFlight.promise;if(r!==this.configGeneration||t!==this.config)return this.ensureToken();return{token:i,config:t,generation:r}}let n={generation:r,promise:this.authenticate(t,r)};this.authInFlight=n;try{let i=await n.promise;if(r!==this.configGeneration||t!==this.config)return this.ensureToken();return{token:i,config:t,generation:r}}finally{if(this.authInFlight===n)this.authInFlight=null}}async authenticate(t,r){e().logger.info("gateway-client","Authenticating with gateway",{clientId:t.clientId});let n=N(t.globalGatewayUrl,"global"),i=await this.postGraphQL(n,{"Content-Type":"application/json"},{query:`
21
+ mutation AuthenticateApp($input: AuthenticateAppInput!) {
22
+ authenticateApp(input: $input) {
23
+ accessToken
24
+ tokenType
25
+ expiresIn
26
+ scopes
27
+ }
28
+ }
29
+ `,variables:{input:{clientId:t.clientId,clientSecret:t.clientSecret,scopes:t.scopes??[]}}});if(i.errors?.length||!i.data?.authenticateApp){let s=i.errors?.[0]?.message??"Authentication failed";throw e().logger.error("gateway-client",`Authentication failed: ${s}`),Error(`Gateway authentication failed: ${s}`)}let o=i.data.authenticateApp,a={accessToken:o.accessToken,expiresAt:Date.now()+o.expiresIn*1000,scopes:o.scopes};if(r!==this.configGeneration||t!==this.config)throw Error("Gateway configuration changed during authentication");return this.token=a,e().logger.info("gateway-client","Authenticated successfully",{expiresIn:o.expiresIn,scopes:o.scopes}),a.accessToken}async postGraphQL(t,r,n){let i;try{i=await fetch(t,{method:"POST",headers:r,body:JSON.stringify(n),signal:AbortSignal.timeout(15000)})}catch(o){throw Error(`Could not reach gateway at ${t}: ${M(o)}`,{cause:o})}try{let o=await st(i,Je),a={};if(o)try{a=JSON.parse(o)}catch{let s=o.slice(0,240).replace(/\s+/g," "),l=`Gateway returned a non-JSON response (${i.status} ${i.statusText}) from ${t}${s?`: ${s}`:""}`;if(!i.ok)throw new S(l,i.status);throw Error(l)}if(!i.ok){let s=a.errors?.[0]?.message??`${i.status} ${i.statusText}`;throw new S(`Gateway request failed at ${t}: ${s} (${i.status})`,i.status)}return a}catch(o){if(o instanceof Error)throw o;throw Error(`Failed to process gateway response from ${t}: ${M(o)}`,{cause:o})}}}function q(){let t=B();if(t)return t.gatewayClient;return e().gatewayClient}var T=new Proxy({},{get(t,r,n){let i=q(),o=i[r];return typeof o==="function"?o.bind(i):o},set(t,r,n){let i=q();return i[r]=n,!0},has(t,r){return r in q()}});var ut={maxFileDescriptors:4096,maxChildProcesses:256,maxMemoryMB:4096},K=new lt;function wt(t){K.enterWith(t)}class V{name;dataDir;spawnOwnerKey;keyVault;audit;logger;budget;db=null;serviceRegistry=null;pluginManager=null;lifecycle=null;hostServices=null;tunnel={url:null,child:null,externalUrl:!1};_gatewayClient=null;state="awaiting-config";degradedReasons=[];listeners=new Set;lastFinalizeError=null;constructor(t){this.name=t.name,this.dataDir=t.dataDir,this.spawnOwnerKey=`profile/${t.name}`,this.budget=t.budget??ut,ct(this.dataDir,{recursive:!0}),this.keyVault=new G(t.name),this.audit=new _(t.name,t.dataDir),this.logger=new F({logDir:le(t.dataDir,"logs")})}run(t){return K.run(this,t)}get gatewayClient(){if(!this._gatewayClient)this._gatewayClient=new ui;return this._gatewayClient}attachServices(t){this.db=t.db,this.serviceRegistry=t.serviceRegistry,this.pluginManager=t.pluginManager,this.lifecycle=t.lifecycle,this.hostServices=t.hostServices}getBootState(){return this.state}setBootState(t){if(this.state===t)return;if(this.state=t,t!=="degraded")this.degradedReasons.length=0;for(let r of this.listeners)try{r(t)}catch{}}recordDegradedReason(t,r){if(this.degradedReasons.push({plugin:t,message:r}),this.state==="ready")this.setBootState("degraded");(async()=>{try{let{telemetryService:n}=await import("./telemetry-fyced899.js");n.emit("health.degraded",{reason_class:gt(r)})}catch{}})()}getDegradedReasons(){return this.degradedReasons.slice()}recordFinalizeError(t,r){this.lastFinalizeError={message:t,at:new Date().toISOString(),attempt:r}}clearFinalizeError(){this.lastFinalizeError=null}getLastFinalizeError(){return this.lastFinalizeError}onBootStateChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}async shutdown(){this.setBootState("shutting-down");try{let{unmountProfileRoutes:t}=await import("./profile-mount-rr5kr708.js");t(this.name)}catch{}try{if(this.pluginManager)await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch{}try{if(this.db)await this.db.close()}catch{}this.lifecycle=null,this.pluginManager=null,this.hostServices=null,this.serviceRegistry=null,this.db=null,this._gatewayClient=null,this.tunnel={url:null,child:null,externalUrl:!1},this.keyVault.shutdown(),this.listeners.clear()}subdir(t){return le(this.dataDir,t)}}function B(){return K.getStore()??null}function gt(t){let r=t.toLowerCase();if(r.includes("timeout"))return"timeout";if(r.includes("econn")||r.includes("network"))return"network";if(r.includes("permission")||r.includes("eacces"))return"permission";if(r.includes("not found")||r.includes("enoent"))return"not_found";if(r.includes("plugin"))return"plugin";return"other"}class Q{profiles=new Map;create(t){if(this.profiles.has(t.name))throw Error(`profile already registered: ${t.name}`);let r=new V(t);return this.profiles.set(t.name,r),this.refreshProcessTitle(),r}refreshProcessTitle(){try{let r=[...this.profiles.keys()].sort().join(","),n=r.length>96?`${r.slice(0,93)}...`:r;process.title=`vibe-daemon[${n}]`}catch{}}get(t){return this.profiles.get(t)}list(){return[...this.profiles.values()]}names(){return[...this.profiles.keys()]}has(t){return this.profiles.has(t)}size(){return this.profiles.size}async destroy(t){let r=this.profiles.get(t);if(!r)return;await r.shutdown(),this.profiles.delete(t),this.refreshProcessTitle()}async destroyAll(){let t=[...this.profiles.keys()];for(let r of t)await this.destroy(r)}}import{isAbsolute as Lt,join as v,relative as Pt,resolve as j}from"path";import{existsSync as It,readFileSync as _t}from"fs";import{homedir as Ct}from"os";import{existsSync as ft,mkdirSync as pt,readFileSync as ht,renameSync as dt,writeFileSync as mt}from"fs";import{homedir as yt}from"os";import{dirname as kt,join as ce,resolve as St}from"path";var w=new Map;async function he(t,r){let n=w.get(t)??Promise.resolve(),i,o=new Promise((a)=>{i=a});w.set(t,n.then(()=>o));try{return await n,await r()}finally{if(i(),w.get(t)===n.then(()=>o));queueMicrotask(()=>{let a=w.get(t);if(!a)return;Promise.race([a,new Promise((s)=>{s(void 0)})]).then(()=>{if(w.get(t)===a)w.delete(t)})})}}var vt="agents-registry";async function ot(t){return he(vt,t)}function Rt(){return St(process.env.VIBECONTROLS_HOME??ce(yt(),".boff","vibecontrols"))}var ue=2,Et="default";function ge(){return ce(Rt(),"agents.json")}function At(){let t=ge();if(!ft(t))return null;try{let r=JSON.parse(ht(t,"utf8"));if(r&&typeof r==="object"&&!Array.isArray(r)&&"instances"in r)return r;return null}catch{return null}}function A(){let t=At();if(!t)return{schemaVersion:ue,instances:[]};return t}function fe(t){let r=ge();pt(kt(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`,i={...t,schemaVersion:ue};mt(n,`${JSON.stringify(i,null,2)}
30
+ `,{encoding:"utf8",mode:384}),dt(n,r)}function bt(){return A().instances}function Ji(t){let r=A();fe({...r,instances:t})}function Oe(){try{let r=A().defaultProfile;if(r&&typeof r==="string"&&r.length>0)return r}catch{}return Et}function Xt(t){if(!t||typeof t!=="string")throw Error("setDefaultProfile: name is required");let r=A();fe({...r,defaultProfile:t})}var Ot=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Gt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function pe(t){if(!Ot.test(t))throw Error("Invalid VIBECONTROLS_PROFILE. Use 1-128 characters: letters, numbers, dot, underscore, or dash.");return t}function R(){let t=process.env.VIBECONTROLS_PROFILE;if(t)return pe(t);let r=Oe();return pe(r)}function O(t){if(!Gt.test(t))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return t}function li(t,r){let n=Pt(j(t),j(r));return n===""||!!n&&!n.startsWith("..")&&!Lt(n)}function I(){let t=C(),r=R();return v(t,"agents",r)}function ne(){return v(C(),"agents")}function ee(){return v(I(),"agent-db")}function C(){return j(process.env.VIBECONTROLS_HOME??v(Ct(),".boff","vibecontrols"))}var Dt="https://registry.npmjs.org/";function se(){if(process.env.VIBECONTROLS_REGISTRY)return process.env.VIBECONTROLS_REGISTRY;try{let t=v(I(),"config.json");if(It(t)){let r=JSON.parse(_t(t,"utf8"));if(r.registry)return r.registry}}catch{}return Dt}var D=new Q,b=null;function Ut(){if(b)return b;let t=R(),r=D.get(t);if(r)return b=r,r;return b=D.create({name:t,dataDir:I()}),b}function e(){return Ut()}function at(t){let r=O(t),n=D.get(r);if(n)return n;return D.create({name:r,dataDir:Ft(C(),"agents",r)})}export{Ai,Hi,Vi,Tt,Yi,z,Jt,ci,Wt,Ir,xt,Zi,ui,T,he,ot,bt,Ji,Oe,Xt,R,O,li,I,ne,ee,C,se,wt,B,D,e,at};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{I,ee}from"./index-7wm4bqx5.js";import{s,l,p,o,g,n,c}from"./index-12gb48hg.js";import{b}from"./index-w4jqdhc2.js";import{u}from"./index-v77bb0rm.js";import{existsSync as L,mkdirSync as T,writeFileSync as U,unlinkSync as H,readFileSync as q}from"fs";import{join as v}from"path";import{homedir as A,platform as x}from"os";import{isAbsolute as J,resolve as K}from"path";function W(){return I()}function w(){return v(W(),"logs")}function B(){if(process.execPath&&process.execPath.includes("bun"))return process.execPath;let t=b().which("bun");if(t)return t;throw Error("Could not find bun binary. Ensure bun is installed and in PATH.")}function D(){return import.meta.dir.endsWith("/dist")||import.meta.dir.includes("/dist/")?v(import.meta.dir,"index.js"):v(import.meta.dir,"..","..","index.ts")}function R(t,e){if(/[\0\r\n]/.test(t))throw Error(`${e} contains invalid control characters`)}function C(t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(t))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return t}function Y(t){let e=parseInt(t,10);if(!Number.isInteger(e)||e<1||e>65535)throw Error("Port must be an integer between 1 and 65535");return e}function y(t){return R(t,"systemd value"),`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function tt(t){if(R(t,"systemd path"),!J(t))throw Error(`systemd path must be absolute, got: ${t}`);return t}function d(t){let e=String(t);return R(e,"plist value"),e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function V(t){let e=v(A(),".config","systemd","user");return T(e,{recursive:!0}),v(e,`vibecontrols-agent-${t}.service`)}function X(t){return`[Unit]
2
+ import{I,ee}from"./index-nxpw3anc.js";import{s,l,p,o,g,n,c}from"./index-j9cg16we.js";import{b}from"./index-w4jqdhc2.js";import{u}from"./index-v77bb0rm.js";import{existsSync as L,mkdirSync as T,writeFileSync as U,unlinkSync as H,readFileSync as q}from"fs";import{join as v}from"path";import{homedir as A,platform as x}from"os";import{isAbsolute as J,resolve as K}from"path";function W(){return I()}function w(){return v(W(),"logs")}function B(){if(process.execPath&&process.execPath.includes("bun"))return process.execPath;let t=b().which("bun");if(t)return t;throw Error("Could not find bun binary. Ensure bun is installed and in PATH.")}function D(){return import.meta.dir.endsWith("/dist")||import.meta.dir.includes("/dist/")?v(import.meta.dir,"index.js"):v(import.meta.dir,"..","..","index.ts")}function R(t,e){if(/[\0\r\n]/.test(t))throw Error(`${e} contains invalid control characters`)}function C(t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(t))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return t}function Y(t){let e=parseInt(t,10);if(!Number.isInteger(e)||e<1||e>65535)throw Error("Port must be an integer between 1 and 65535");return e}function y(t){return R(t,"systemd value"),`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function tt(t){if(R(t,"systemd path"),!J(t))throw Error(`systemd path must be absolute, got: ${t}`);return t}function d(t){let e=String(t);return R(e,"plist value"),e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function V(t){let e=v(A(),".config","systemd","user");return T(e,{recursive:!0}),v(e,`vibecontrols-agent-${t}.service`)}function X(t){return`[Unit]
3
3
  Description=VibeControls Agent (${t.name})
4
4
  After=network.target
5
5
 
@@ -129,5 +129,5 @@ WantedBy=default.target
129
129
  <WorkingDirectory>${d(t.configDir)}</WorkingDirectory>
130
130
  </Exec>
131
131
  </Actions>
132
- </Task>`}async function lt(t,e,r,i={}){let a=M(t),f=Q(t),h=W(),m=w();T(h,{recursive:!0}),T(m,{recursive:!0});let P=B(),k=D(),S=at({name:t,port:e,host:i.host,dbPath:r,bunPath:P,entryPoint:k,configDir:h,logsDir:m}),N=Buffer.concat([Buffer.from([255,254]),Buffer.from(S,"utf16le")]);if(U(f,N),n("Task XML",f),Bun.spawnSync(["schtasks","/Create","/TN",a,"/XML",f,"/F"],{stdout:"inherit",stderr:"inherit"}).exitCode!==0)throw Error("schtasks /Create failed. Run from an elevated shell if your user lacks scheduler permission.");c(),l(`Autostart installed for agent '${t}' (Task: ${a})`),o("To start now without rebooting:"),o(` schtasks /Run /TN ${a}`)}async function ut(t){let e=M(t),r=Q(t),i=Bun.spawnSync(["schtasks","/Delete","/TN",e,"/F"],{stdout:"pipe",stderr:"pipe"});if(i.exitCode!==0)p(`schtasks /Delete returned non-zero (${i.exitCode}). Task may not have existed.`);else l(`Removed scheduled task ${e}`);if(L(r))try{H(r)}catch{}}async function ct(t){let e=M(t),r=Bun.spawnSync(["schtasks","/Query","/TN",e,"/V","/FO","LIST"],{stdout:"pipe",stderr:"pipe"});if(r.exitCode!==0){o(`Autostart is NOT configured for agent '${t}'`),n("Expected task",e);return}g(`Autostart Status \u2014 ${t}`),n("Task",e),c(),console.log(r.stdout.toString())}function G(t,e,r){if(!L(e))return!1;try{let i=r({bunPath:B(),entryPoint:D(),logFile:v(w(),`${t.name}.log`)});return q(e,"utf8")===i}catch{return!0}}function gt(t){try{let e=Bun.spawnSync(["systemctl","--user","is-enabled",`vibecontrols-agent-${t}.service`]);if(e.exitCode===0)return!0;let r=e.stdout.toString().trim();return!["disabled","masked","linked",""].includes(r)}catch{return!0}}var Z={linux:{label:"systemd",install:(t,e,r,i)=>et(t,e,r??"./agent-db",i),uninstall:nt,status:rt,isCurrent:(t)=>G(t,V(t.name),(e)=>X({...t,...e}))&&gt(t.name),autoConfigurable:!0},darwin:{label:"launchd",install:(t,e,r,i)=>st(t,e,r??"./agent-db",i),uninstall:it,status:ot,isCurrent:(t)=>G(t,F(t.name),(e)=>z({...t,...e})),autoConfigurable:!0},win32:{label:"Task Scheduler",install:lt,uninstall:ut,status:ct,isCurrent:()=>!0,autoConfigurable:!1}};function _(){let t=Z[x()];if(!t)throw Error(`Autostart is not supported on ${x()}. Supported: linux (systemd), darwin (launchd), win32 (Task Scheduler).`);return t}async function tn(t){let e=process.env.VIBECONTROLS_PROFILES||void 0,r=process.env.VIBECONTROLS_HOME||void 0,i=process.env.VIBE_ISOLATE_PLUGINS||void 0;if(process.env.VIBE_NO_AUTOSTART==="1"||process.env.VIBE_AUTOSTART==="0")return{installed:!1,reason:"opted out via env"};let a=Z[x()];if(!a)return{installed:!1,reason:`unsupported platform ${x()}`};if(!a.autoConfigurable)return{installed:!1,reason:`${a.label} must be configured manually \u2014 run \`vibe autostart install\``};try{let f={name:t.name,port:t.port,dbPath:t.dbPath??"./agent-db",host:t.host,profile:t.profile,profiles:e,home:r,isolatePlugins:i};if(a.isCurrent(f))return{installed:!1,reason:"already configured"};return await a.install(t.name,t.port,t.dbPath,{skipStart:!0,host:t.host,profile:t.profile,profiles:e,home:r,isolatePlugins:i}),{installed:!0,serviceLabel:a.label}}catch(f){return{installed:!1,failed:!0,reason:f instanceof Error?f.message:String(f)}}}function Dr(t){let e=t.command("autostart").description("Configure agent to auto-start on system boot");e.command("install").description("Generate and enable system service for auto-start on reboot").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on","3005").option("--db-path <path>","Agent storage directory (absolute path; default: ~/.boff/vibecontrols/agents/<profile>/agent-db)").option("--json","Emit JSON").action(async function(r){let i={...t.opts(),...r};try{let a=_(),f=C(r.name),h=Y(r.port),m=r.dbPath??null,P=ee(),k=(()=>{if(!m)return P;if(J(m))return m;let S=K(P,"..",m);return p(`--db-path is relative; resolved to ${S}. Pass an absolute path to silence this warning.`),S})();if(!i.json)g("Installing Autostart"),n("Platform",`${x()} (${a.label})`),n("Agent",f),n("Port",String(h)),n("Database",k),c();await a.install(f,h,k),u(i,{ok:!0,enabled:!0,name:f,port:h})}catch(a){if(i.json)u(i,{ok:!1,error:String(a)}),process.exit(1);s(`Failed to install autostart: ${a}`),process.exit(1)}}),e.command("uninstall").description("Stop and remove the system service").option("-n, --name <name>","Agent instance name","default").option("--json","Emit JSON").action(async function(r){let i={...t.opts(),...r};try{let a=_(),f=C(r.name);if(!i.json)g("Removing Autostart");await a.uninstall(f),u(i,{ok:!0,enabled:!1,name:f})}catch(a){if(i.json)u(i,{ok:!1,error:String(a)}),process.exit(1);s(`Failed to uninstall autostart: ${a}`),process.exit(1)}}),e.command("status").description("Check if autostart is configured and running").option("-n, --name <name>","Agent instance name","default").action(async(r)=>{try{let i=_(),a=C(r.name);await i.status(a)}catch(i){s(`Failed to check autostart status: ${i}`),process.exit(1)}})}
133
- export{tn,Dr};
132
+ </Task>`}async function lt(t,e,r,i={}){let a=M(t),f=Q(t),h=W(),m=w();T(h,{recursive:!0}),T(m,{recursive:!0});let P=B(),k=D(),S=at({name:t,port:e,host:i.host,dbPath:r,bunPath:P,entryPoint:k,configDir:h,logsDir:m}),N=Buffer.concat([Buffer.from([255,254]),Buffer.from(S,"utf16le")]);if(U(f,N),n("Task XML",f),Bun.spawnSync(["schtasks","/Create","/TN",a,"/XML",f,"/F"],{stdout:"inherit",stderr:"inherit"}).exitCode!==0)throw Error("schtasks /Create failed. Run from an elevated shell if your user lacks scheduler permission.");c(),l(`Autostart installed for agent '${t}' (Task: ${a})`),o("To start now without rebooting:"),o(` schtasks /Run /TN ${a}`)}async function ut(t){let e=M(t),r=Q(t),i=Bun.spawnSync(["schtasks","/Delete","/TN",e,"/F"],{stdout:"pipe",stderr:"pipe"});if(i.exitCode!==0)p(`schtasks /Delete returned non-zero (${i.exitCode}). Task may not have existed.`);else l(`Removed scheduled task ${e}`);if(L(r))try{H(r)}catch{}}async function ct(t){let e=M(t),r=Bun.spawnSync(["schtasks","/Query","/TN",e,"/V","/FO","LIST"],{stdout:"pipe",stderr:"pipe"});if(r.exitCode!==0){o(`Autostart is NOT configured for agent '${t}'`),n("Expected task",e);return}g(`Autostart Status \u2014 ${t}`),n("Task",e),c(),console.log(r.stdout.toString())}function G(t,e,r){if(!L(e))return!1;try{let i=r({bunPath:B(),entryPoint:D(),logFile:v(w(),`${t.name}.log`)});return q(e,"utf8")===i}catch{return!0}}function gt(t){try{let e=Bun.spawnSync(["systemctl","--user","is-enabled",`vibecontrols-agent-${t}.service`]);if(e.exitCode===0)return!0;let r=e.stdout.toString().trim();return!["disabled","masked","linked",""].includes(r)}catch{return!0}}var Z={linux:{label:"systemd",install:(t,e,r,i)=>et(t,e,r??"./agent-db",i),uninstall:nt,status:rt,isCurrent:(t)=>G(t,V(t.name),(e)=>X({...t,...e}))&&gt(t.name),autoConfigurable:!0},darwin:{label:"launchd",install:(t,e,r,i)=>st(t,e,r??"./agent-db",i),uninstall:it,status:ot,isCurrent:(t)=>G(t,F(t.name),(e)=>z({...t,...e})),autoConfigurable:!0},win32:{label:"Task Scheduler",install:lt,uninstall:ut,status:ct,isCurrent:()=>!0,autoConfigurable:!1}};function _(){let t=Z[x()];if(!t)throw Error(`Autostart is not supported on ${x()}. Supported: linux (systemd), darwin (launchd), win32 (Task Scheduler).`);return t}async function tn(t){let e=process.env.VIBECONTROLS_PROFILES||void 0,r=process.env.VIBECONTROLS_HOME||void 0,i=process.env.VIBE_ISOLATE_PLUGINS||void 0;if(process.env.VIBE_NO_AUTOSTART==="1"||process.env.VIBE_AUTOSTART==="0")return{installed:!1,reason:"opted out via env"};let a=Z[x()];if(!a)return{installed:!1,reason:`unsupported platform ${x()}`};if(!a.autoConfigurable)return{installed:!1,reason:`${a.label} must be configured manually \u2014 run \`vibe autostart install\``};try{let f={name:t.name,port:t.port,dbPath:t.dbPath??"./agent-db",host:t.host,profile:t.profile,profiles:e,home:r,isolatePlugins:i};if(a.isCurrent(f))return{installed:!1,reason:"already configured"};return await a.install(t.name,t.port,t.dbPath,{skipStart:!0,host:t.host,profile:t.profile,profiles:e,home:r,isolatePlugins:i}),{installed:!0,serviceLabel:a.label}}catch(f){return{installed:!1,failed:!0,reason:f instanceof Error?f.message:String(f)}}}function kr(t){let e=t.command("autostart").description("Configure agent to auto-start on system boot");e.command("install").description("Generate and enable system service for auto-start on reboot").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on","3005").option("--db-path <path>","Agent storage directory (absolute path; default: ~/.boff/vibecontrols/agents/<profile>/agent-db)").option("--json","Emit JSON").action(async function(r){let i={...t.opts(),...r};try{let a=_(),f=C(r.name),h=Y(r.port),m=r.dbPath??null,P=ee(),k=(()=>{if(!m)return P;if(J(m))return m;let S=K(P,"..",m);return p(`--db-path is relative; resolved to ${S}. Pass an absolute path to silence this warning.`),S})();if(!i.json)g("Installing Autostart"),n("Platform",`${x()} (${a.label})`),n("Agent",f),n("Port",String(h)),n("Database",k),c();await a.install(f,h,k),u(i,{ok:!0,enabled:!0,name:f,port:h})}catch(a){if(i.json)u(i,{ok:!1,error:String(a)}),process.exit(1);s(`Failed to install autostart: ${a}`),process.exit(1)}}),e.command("uninstall").description("Stop and remove the system service").option("-n, --name <name>","Agent instance name","default").option("--json","Emit JSON").action(async function(r){let i={...t.opts(),...r};try{let a=_(),f=C(r.name);if(!i.json)g("Removing Autostart");await a.uninstall(f),u(i,{ok:!0,enabled:!1,name:f})}catch(a){if(i.json)u(i,{ok:!1,error:String(a)}),process.exit(1);s(`Failed to uninstall autostart: ${a}`),process.exit(1)}}),e.command("status").description("Check if autostart is configured and running").option("-n, --name <name>","Agent instance name","default").action(async(r)=>{try{let i=_(),a=C(r.name);await i.status(a)}catch(i){s(`Failed to check autostart status: ${i}`),process.exit(1)}})}
133
+ export{tn,kr};
@@ -1,16 +1,16 @@
1
1
  // @bun
2
- import{E}from"./index-1t74r13z.js";import{R,B,N,e}from"./index-7wm4bqx5.js";import{J,de,w,M}from"./index-j99tkngg.js";import{ji}from"./index-x4z055t8.js";import{randomBytes as P,createHmac as X,timingSafeEqual as ke}from"crypto";var F=600,ie=600,H=P(32),x="p2.";function S(t){if(!t.startsWith("/"))return`/${t}`;return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}var Ee=/^\/terminal\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,_e=/^\/ui\/[a-z0-9-]{1,64}(?:\/.*)?$/,Ie=/^\/plan\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,xe=/^\/git(?:\/.*)?$/,Pe="/ws/logs",Se=/^\/code-server(?:\/.*)?$/,Te=/^\/api\/plugins\/[a-z0-9-]{1,64}\/ui(?:\/.*)?$/;function se(t){if(typeof t!=="string"||t.length===0)return!1;if(t.includes("\x00")||t.includes(`
2
+ import{E}from"./index-1t74r13z.js";import{R,B,D,e}from"./index-nxpw3anc.js";import{J,de,w,M}from"./index-30qr1qm3.js";import{ji}from"./index-x4z055t8.js";import{randomBytes as P,createHmac as X,timingSafeEqual as ke}from"crypto";var F=600,ie=600,H=P(32),x="p2.";function S(t){if(!t.startsWith("/"))return`/${t}`;return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}var Ee=/^\/terminal\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,_e=/^\/ui\/[a-z0-9-]{1,64}(?:\/.*)?$/,Ie=/^\/plan\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,xe=/^\/git(?:\/.*)?$/,Pe="/ws/logs",Se=/^\/code-server(?:\/.*)?$/,Te=/^\/api\/plugins\/[a-z0-9-]{1,64}\/ui(?:\/.*)?$/;function se(t){if(typeof t!=="string"||t.length===0)return!1;if(t.includes("\x00")||t.includes(`
3
3
  `)||t.includes("|"))return!1;if(t.includes(".."))return!1;if(new Set(["/","/api","/api/agent","/api/plugins","/api/profiles","/health","/metrics","/ws","/api/ai","/api/logs"]).has(t))return!1;if(Ee.test(t))return!0;if(_e.test(t))return!0;if(Ie.test(t))return!0;if(xe.test(t))return!0;if(t===Pe)return!0;if(Se.test(t))return!0;if(Te.test(t))return!0;return!1}var be=new Set(["*","GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);function ve(t){if(!t||t.length===0)return["*"];let n=new Set,r=[];for(let i of t){if(typeof i!=="string")continue;let s=i.toUpperCase();if(!be.has(s))throw Error(`invalid method: ${i}`);if(!n.has(s))n.add(s),r.push(s)}if(r.length===0)return["*"];return r.sort()}function oe(t,n){if(t.includes("*"))return!0;return t.includes(n.toUpperCase())}var $e=/^[A-Za-z0-9_-]{1,128}$/;function we(t){return typeof t==="string"&&$e.test(t)}function Z(t,n,r){return X("sha256",H).update(`${t}
4
4
  ${n}
5
- ${r}`).digest("hex")}var C=new Map;function Fe(t){for(let[n,r]of C)if(r<=t)C.delete(n)}function ae(t,n){let r=Date.parse(n);if(!Number.isFinite(r))return;C.set(t,r)}function ue(t){return Fe(Date.now()),C.has(t)}function j(t,n,r,i){return X("sha256",H).update(`v2
5
+ ${r}`).digest("hex")}var N=new Map;function Fe(t){for(let[n,r]of N)if(r<=t)N.delete(n)}function ae(t,n){let r=Date.parse(n);if(!Number.isFinite(r))return;N.set(t,r)}function ue(t){return Fe(Date.now()),N.has(t)}function j(t,n,r,i){return X("sha256",H).update(`v2
6
6
  ${t}
7
7
  ${n}
8
8
  ${r}
9
- ${i}`).digest("hex")}function O(t){return Buffer.from(t,"utf8").toString("base64").replace(/=+$/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function D(t){try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n.length%4===0?n:n+"=".repeat(4-n.length%4);return Buffer.from(r,"base64").toString("utf8")}catch{return null}}var re=16;function Ke(t){if(t.length>re)throw Error(`pathPrefixes exceeds maximum count (${t.length} > ${re})`);let n=new Set,r=[];for(let i of t){if(!i||typeof i!=="string")continue;if(i.includes("..")||i.includes("\x00"))throw Error("invalid pathPrefix");let s=S(i);if(!se(s))throw Error(`pathPrefix '${s}' is not an allowed iframe surface`);if(!n.has(s))n.add(s),r.push(s)}return r.sort()}function fr(t,n=F){if(!t||typeof t!=="string")throw Error("pathPrefix is required");if(t.includes("..")||t.includes("\x00"))throw Error("invalid pathPrefix");let r=Math.min(Math.max(1,Math.floor(n||F)),ie),i=S(t);if(!se(i))throw Error(`pathPrefix '${i}' is not an allowed iframe surface`);let s=new Date(Date.now()+r*1000).toISOString(),o=P(16).toString("hex"),a=Z(i,s,o);return{token:`${s}|${o}|${a}`,expiresAt:s}}function Ut(t,n=F){if(!t||!Array.isArray(t.pathPrefixes)||t.pathPrefixes.length===0)throw Error("pathPrefixes is required");let r=Ke(t.pathPrefixes);if(r.length===0)throw Error("pathPrefixes is required");let i=ve(t.methods),s=Math.min(Math.max(1,Math.floor(n||F)),ie),o=new Date(Date.now()+s*1000).toISOString(),a=P(16).toString("hex"),c=O(JSON.stringify(r)),u=O(JSON.stringify(i)),f=`${x}${c}.${u}`,l=j(c,u,o,a);return{token:`${o}|${a}|${f}|${l}`,expiresAt:o}}function k(t,n){if(t.length!==n.length)return!1;try{return ke(Buffer.from(t,"hex"),Buffer.from(n,"hex"))}catch{return!1}}function U(t,n){let r=S(n);return t===r||t.startsWith(`${r}/`)}function je(t,n,r="*"){return Hr(t,n,r).ok}function Hr(t,n,r="*"){if(!t||typeof t!=="string")return{ok:!1,reason:"missing"};let i=t.split("|");if(i.length===3)return Ne(i,n);if(i.length===4)return Ce(i,n,r);return{ok:!1,reason:"malformed"}}function Ne(t,n){let[r,i,s]=t;if(!r||!i||!s)return{ok:!1,reason:"malformed"};if(!_(r))return{ok:!1,reason:"expired"};let o=n.split("/").filter(Boolean),a=["/"],c="";for(let u of o)c+=`/${u}`,a.push(c);for(let u of a){let f=Z(S(u),r,i);if(k(f,s)){if(!U(n,u))return{ok:!1,reason:"path_mismatch"};if(ue(i))return{ok:!1,reason:"replayed"};return ae(i,r),{ok:!0}}}return{ok:!1,reason:"bad_signature"}}function Ce(t,n,r){let[i,s,o,a]=t;if(!i||!s||!o||!a)return{ok:!1,reason:"malformed"};if(!o.startsWith(x))return{ok:!1,reason:"malformed"};if(!_(i))return{ok:!1,reason:"expired"};let u=o.slice(x.length).split("."),f=u[0]??"",l=u[1]??O(JSON.stringify(["*"]));if(!f)return{ok:!1,reason:"malformed"};let h=j(f,l,i,s);if(!k(h,a))return{ok:!1,reason:"bad_signature"};let v=D(f);if(v===null)return{ok:!1,reason:"malformed"};let y;try{y=JSON.parse(v)}catch{return{ok:!1,reason:"malformed"}}if(!Array.isArray(y))return{ok:!1,reason:"malformed"};let A=D(l),I=["*"];if(A!==null)try{let g=JSON.parse(A);if(Array.isArray(g)&&g.every((d)=>typeof d==="string"))I=g}catch{return{ok:!1,reason:"malformed"}}if(r!=="*"&&!oe(I,r))return{ok:!1,reason:"method_mismatch"};for(let g of y){if(typeof g!=="string")continue;if(U(n,g)){if(ue(s))return{ok:!1,reason:"replayed"};return ae(s,i),{ok:!0}}}return{ok:!1,reason:"path_mismatch"}}function qe(t,n,r="*"){if(!t||typeof t!=="string")return!1;let i=t.split("|");if(i.length===3){let[s,o,a]=i;if(!s||!o||!a)return!1;if(!_(s))return!1;let c=n.split("/").filter(Boolean),u=["/"],f="";for(let l of c)f+=`/${l}`,u.push(f);for(let l of u){let h=Z(S(l),s,o);if(k(h,a))return U(n,l)}return!1}if(i.length===4){let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(!a.startsWith(x))return!1;if(!_(s))return!1;let f=a.slice(x.length).split("."),l=f[0]??"",h=f[1]??O(JSON.stringify(["*"]));if(!l)return!1;let v=j(l,h,s,o);if(!k(v,c))return!1;let y=D(l);if(y===null)return!1;let A;try{A=JSON.parse(y)}catch{return!1}if(!Array.isArray(A))return!1;let I=D(h),g=["*"];if(I!==null)try{let d=JSON.parse(I);if(Array.isArray(d)&&d.every((Ae)=>typeof Ae==="string"))g=d}catch{return!1}if(r!=="*"&&!oe(g,r))return!1;for(let d of A){if(typeof d!=="string")continue;if(U(n,d))return!0}return!1}return!1}function _(t){let n=Date.parse(t);return Number.isFinite(n)&&Date.now()<n}function Kt(t,n){let r=t.headers.get("x-vibe-iframe-token")??t.headers.get("X-Vibe-Iframe-Token");if(r)return r;try{let i=new URL(t.url).searchParams.get("vt");if(i)return i}catch{}return null}var q="tc1|",z=600,Oe=600;function ce(t,n,r){return X("sha256",H).update(`tc1
9
+ ${i}`).digest("hex")}function C(t){return Buffer.from(t,"utf8").toString("base64").replace(/=+$/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function O(t){try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n.length%4===0?n:n+"=".repeat(4-n.length%4);return Buffer.from(r,"base64").toString("utf8")}catch{return null}}var re=16;function Ke(t){if(t.length>re)throw Error(`pathPrefixes exceeds maximum count (${t.length} > ${re})`);let n=new Set,r=[];for(let i of t){if(!i||typeof i!=="string")continue;if(i.includes("..")||i.includes("\x00"))throw Error("invalid pathPrefix");let s=S(i);if(!se(s))throw Error(`pathPrefix '${s}' is not an allowed iframe surface`);if(!n.has(s))n.add(s),r.push(s)}return r.sort()}function fr(t,n=F){if(!t||typeof t!=="string")throw Error("pathPrefix is required");if(t.includes("..")||t.includes("\x00"))throw Error("invalid pathPrefix");let r=Math.min(Math.max(1,Math.floor(n||F)),ie),i=S(t);if(!se(i))throw Error(`pathPrefix '${i}' is not an allowed iframe surface`);let s=new Date(Date.now()+r*1000).toISOString(),o=P(16).toString("hex"),a=Z(i,s,o);return{token:`${s}|${o}|${a}`,expiresAt:s}}function Ut(t,n=F){if(!t||!Array.isArray(t.pathPrefixes)||t.pathPrefixes.length===0)throw Error("pathPrefixes is required");let r=Ke(t.pathPrefixes);if(r.length===0)throw Error("pathPrefixes is required");let i=ve(t.methods),s=Math.min(Math.max(1,Math.floor(n||F)),ie),o=new Date(Date.now()+s*1000).toISOString(),a=P(16).toString("hex"),c=C(JSON.stringify(r)),u=C(JSON.stringify(i)),f=`${x}${c}.${u}`,l=j(c,u,o,a);return{token:`${o}|${a}|${f}|${l}`,expiresAt:o}}function k(t,n){if(t.length!==n.length)return!1;try{return ke(Buffer.from(t,"hex"),Buffer.from(n,"hex"))}catch{return!1}}function U(t,n){let r=S(n);return t===r||t.startsWith(`${r}/`)}function je(t,n,r="*"){return Hr(t,n,r).ok}function Hr(t,n,r="*"){if(!t||typeof t!=="string")return{ok:!1,reason:"missing"};let i=t.split("|");if(i.length===3)return Ne(i,n);if(i.length===4)return Ce(i,n,r);return{ok:!1,reason:"malformed"}}function Ne(t,n){let[r,i,s]=t;if(!r||!i||!s)return{ok:!1,reason:"malformed"};if(!_(r))return{ok:!1,reason:"expired"};let o=n.split("/").filter(Boolean),a=["/"],c="";for(let u of o)c+=`/${u}`,a.push(c);for(let u of a){let f=Z(S(u),r,i);if(k(f,s)){if(!U(n,u))return{ok:!1,reason:"path_mismatch"};if(ue(i))return{ok:!1,reason:"replayed"};return ae(i,r),{ok:!0}}}return{ok:!1,reason:"bad_signature"}}function Ce(t,n,r){let[i,s,o,a]=t;if(!i||!s||!o||!a)return{ok:!1,reason:"malformed"};if(!o.startsWith(x))return{ok:!1,reason:"malformed"};if(!_(i))return{ok:!1,reason:"expired"};let u=o.slice(x.length).split("."),f=u[0]??"",l=u[1]??C(JSON.stringify(["*"]));if(!f)return{ok:!1,reason:"malformed"};let h=j(f,l,i,s);if(!k(h,a))return{ok:!1,reason:"bad_signature"};let v=O(f);if(v===null)return{ok:!1,reason:"malformed"};let y;try{y=JSON.parse(v)}catch{return{ok:!1,reason:"malformed"}}if(!Array.isArray(y))return{ok:!1,reason:"malformed"};let A=O(l),I=["*"];if(A!==null)try{let g=JSON.parse(A);if(Array.isArray(g)&&g.every((d)=>typeof d==="string"))I=g}catch{return{ok:!1,reason:"malformed"}}if(r!=="*"&&!oe(I,r))return{ok:!1,reason:"method_mismatch"};for(let g of y){if(typeof g!=="string")continue;if(U(n,g)){if(ue(s))return{ok:!1,reason:"replayed"};return ae(s,i),{ok:!0}}}return{ok:!1,reason:"path_mismatch"}}function qe(t,n,r="*"){if(!t||typeof t!=="string")return!1;let i=t.split("|");if(i.length===3){let[s,o,a]=i;if(!s||!o||!a)return!1;if(!_(s))return!1;let c=n.split("/").filter(Boolean),u=["/"],f="";for(let l of c)f+=`/${l}`,u.push(f);for(let l of u){let h=Z(S(l),s,o);if(k(h,a))return U(n,l)}return!1}if(i.length===4){let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(!a.startsWith(x))return!1;if(!_(s))return!1;let f=a.slice(x.length).split("."),l=f[0]??"",h=f[1]??C(JSON.stringify(["*"]));if(!l)return!1;let v=j(l,h,s,o);if(!k(v,c))return!1;let y=O(l);if(y===null)return!1;let A;try{A=JSON.parse(y)}catch{return!1}if(!Array.isArray(A))return!1;let I=O(h),g=["*"];if(I!==null)try{let d=JSON.parse(I);if(Array.isArray(d)&&d.every((Ae)=>typeof Ae==="string"))g=d}catch{return!1}if(r!=="*"&&!oe(g,r))return!1;for(let d of A){if(typeof d!=="string")continue;if(U(n,d))return!0}return!1}return!1}function _(t){let n=Date.parse(t);return Number.isFinite(n)&&Date.now()<n}function Kt(t,n){let r=t.headers.get("x-vibe-iframe-token")??t.headers.get("X-Vibe-Iframe-Token");if(r)return r;try{let i=new URL(t.url).searchParams.get("vt");if(i)return i}catch{}return null}var q="tc1|",z=600,Oe=600;function ce(t,n,r){return X("sha256",H).update(`tc1
10
10
  ${t}
11
11
  ${n}
12
12
  ${r}`).digest("hex")}function Li(t,n=z){if(!we(t))throw Error("invalid sid");let r=Math.min(Math.max(1,Math.floor(n||z)||z),Oe),i=new Date(Date.now()+r*1000).toISOString(),s=P(16).toString("hex"),o=ce(t,i,s);return{token:`${q}${i}|${t}|${s}|${o}`,expiresAt:i}}function pr(t,n){if(!t||typeof t!=="string")return!1;if(!t.startsWith(q))return!1;let i=t.slice(q.length).split("|");if(i.length!==4)return!1;let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(o!==n)return!1;if(!_(s))return!1;let u=ce(o,s,a);return k(u,c)}function Vr(t,n){let r;if(t instanceof Headers)r=t.get("cookie")??t.get("Cookie")??void 0;else r=t.cookie??t.Cookie??void 0;if(!r)return null;let i=`vt_term_${n}`;for(let s of r.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()!==i)continue;return s.slice(o+1).trim()||null}return null}function Yr(t,n){return Vr(t.headers,n)}var Y="uc1|",W=600,De=600,Me=/^[a-z0-9-]{1,64}$/;function me(t){return typeof t==="string"&&Me.test(t)}function fe(t,n,r){return X("sha256",H).update(`uc1
13
13
  ${t}
14
14
  ${n}
15
- ${r}`).digest("hex")}function yt(t,n=W){if(!me(t))throw Error("invalid plugin name");let r=Math.min(Math.max(1,Math.floor(n||W)||W),De),i=new Date(Date.now()+r*1000).toISOString(),s=P(16).toString("hex"),o=fe(t,i,s);return{token:`${Y}${i}|${t}|${s}|${o}`,expiresAt:i}}function rt(t,n){if(!t||typeof t!=="string")return!1;if(!t.startsWith(Y))return!1;let i=t.slice(Y.length).split("|");if(i.length!==4)return!1;let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(o!==n)return!1;if(!_(s))return!1;let u=fe(o,s,a);return k(u,c)}function Ue(t,n){let r;if(t instanceof Headers)r=t.get("cookie")??t.get("Cookie")??void 0;else r=t.cookie??t.Cookie??void 0;if(!r)return null;let i=`vt_ui_${n}`;for(let s of r.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()!==i)continue;return s.slice(o+1).trim()||null}return null}function it(t,n){return Ue(t.headers,n)}import{timingSafeEqual as Ge}from"crypto";var Le=["/api/agent/api-key","/api/agent/reset-key","/api/agent/iframe-token","/api/agent/aliases","/api/agent/alias","/api/agent/commands","/api/agent/lifecycle","/api/agent/nuke","/api/agent/uninstall","/api/agent/gateway-auth","/api/agent/storage-key","/api/agent/sessions/share","/api/config","/api/security","/api/tasks","/api/editor","/api/code-server","/api/logs","/api/maintenance"],Xe=["/api/plugins/install","/api/plugins/prereqs"],Be=["/api/plugins/remove","/api/plugins/remove-all"],Ve=["/api/agent/update","/api/plugins/update","/api/plugins/update-all"];var Q=new Set(["GET","HEAD","OPTIONS"]);function ee(t,n){return t===n||t.startsWith(`${n}/`)}function G(t,n){return n.some((r)=>ee(t,r))}function He(t){let n=new URL(t,"http://agent.local").pathname,r=/^\/api\/profiles\/[^/]+\/(.+)$/.exec(n);if(r?.[1])return`/api/${r[1]}`;return n}function hr(t,n,r){if(t.has("admin"))return!0;let i=He(r),s=n.toUpperCase();if(i==="/api/profiles"||/^\/api\/profiles\/[^/]+$/.test(i))return Q.has(s)&&t.has("read");if(G(i,Le))return!1;if(G(i,Xe)&&t.has("plugin:install"))return!0;if(G(i,Be)&&t.has("plugin:remove"))return!0;if(G(i,Ve)&&t.has("update"))return!0;if(ee(i,"/api/mesh"))return!0;if(ee(i,"/api/plugins")&&!Q.has(s))return!1;if(Q.has(s))return t.has("read")||t.has("mutate");return t.has("mutate")}var ze=["/health","/ui","/code-server","/terminal","/plan","/git","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/terminal-exchange","/api/agent/ui-exchange","/api/agent/ui-exchange-plugin","/metrics"];function le(t,n){if(!n||n==="/")return!1;let r=n.endsWith("/")?n.slice(0,-1):n;return t===r||t.startsWith(`${r}/`)}function We(t){let n=t.replace(/^\/api\/profiles\/[^/]+/,"/api");return n==="/api"?"/":n}function Je(t){let n=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(t);if(!n)return null;let r=n[1];if(!r)return null;return r}function ge(t,n){let r=[t],i=We(t);if(i!==t)r.push(i);for(let s of r){if(ze.some((o)=>le(s,o)))return!0;if(n.some((o)=>le(s,o)))return!0}return!1}function ye(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`vcak_${Buffer.from(t).toString("base64url")}`}var p=null;function ne(){return`${R()}:static-api-key`}async function Re(){let t=process.env.AGENT_API_KEY;if(t)return p=t,t;let n=ne(),r=await J(n);if(r)return p=r,r;let i=w({dir:e().dataDir})["static-api-key"];if(i){try{await de(n,i)}catch(o){e().logger.warn("auth","could not persist legacy api key into secrets backend",{error:String(o)})}return p=i,i}let s=ye();return await de(n,s),p=s,e().logger.info("auth","Generated and persisted new agent API key"),e().audit.emit("agent","apikey.minted",{profile:R(),via:"loadAgentApiKey"}),s}function K(){let t=process.env.AGENT_API_KEY;if(t)return t;if(p!==null)return p;let n=w()["static-api-key"];if(n)return p=n,n;let r=ye();p=r;try{M({"static-api-key":r},{dir:e().dataDir,scope:e().name})}catch{}return de(ne(),r).catch(()=>{}),r}async function vi(t){if(process.env.AGENT_API_KEY)throw Error("AGENT_API_KEY is pinned via the environment \u2014 cannot rotate the key at runtime. Update the env var and restart.");let n=(t??"").trim();if(!/^vcak_[A-Za-z0-9_-]{16,}$/.test(n))throw Error("Invalid agent API key format (expected vcak_<base64url>).");p=n,await de(ne(),n);try{M({"static-api-key":n},{dir:e().dataDir,scope:e().name})}catch{}e().audit.emit("agent","apikey.rotated",{profile:R(),via:"reset-key"})}function L(t){let n=t["x-agent-api-key"]??t["X-Agent-Api-Key"];if(n)return n;let r=t.authorization??t.Authorization;if(r?.startsWith("Bearer "))return r.slice(7);return null}function Ye(t){return!1}function Ze(t,n){let r=L(Object.fromEntries(t.headers.entries()));if(r)return r;if(!Ye(n))return null;try{let i=new URL(t.url).searchParams.get("apiKey");if(i)return i}catch{}return null}function b(t,n){let r=Buffer.from(t),i=Buffer.from(n);if(r.length!==i.length)return!1;try{return Ge(r,i)}catch{return!1}}function V(t){if(!t)return!1;return b(t,K())}var T={name:"default",scopes:new Set(["admin"])};async function Qe(t,n){if(!t)return null;let r=Je(n);if(r){let i=N.get(r);if(i){try{if(await i.keyVault.match(t))return T}catch{}if(r===e().name){try{if(await e().keyVault.match(t))return T}catch{}if(b(t,K()))return T;return pe(t)}return null}}try{if(await e().keyVault.match(t))return T}catch{}if(b(t,K()))return T;return pe(t)}function pe(t){let n=mr(t);return n?{name:n.name,scopes:n.scopes}:null}function mr(t){if(!t)return null;if(b(t,K()))return{name:"default",scopes:new Set(["admin"])};let n=B()??e(),r=w({dir:n.dataDir}),i=Date.now();for(let s of r.apiKeys??[]){if(!b(t,s.key))continue;if(s.notBefore){let o=Date.parse(s.notBefore);if(Number.isFinite(o)&&i<o)return null}if(s.expiresAt){let o=Date.parse(s.expiresAt);if(Number.isFinite(o)&&i>=o)return null}return{name:s.name,scopes:new Set(s.scopes)}}return null}function Ui(t,n){if(!t)return!1;if(t.scopes.has("admin"))return!0;return n.some((r)=>t.scopes.has(r))}var m=null;function te(t,n){try{e().audit.emit("auth",t,n)}catch{e().logger.warn("auth.audit",t,n)}}function et(t){let n=new Set(t());if(m===null)for(let r of n)te("plugin.public_path.declared",{path:r});else{for(let r of n)if(!m.has(r))te("plugin.public_path.added",{path:r});for(let r of m)if(!n.has(r))te("plugin.public_path.removed",{path:r})}return m=n,n}function Ki(){m=null}function he(t){if(!t)return[];if(m===null)return[...et(t)];return[...m]}function Qi(t){let n=K();return e().logger.info("auth",`Agent API key: ${n.substring(0,8)}****${n.substring(n.length-4)}`),new E({name:"plugin/auth"}).decorate("apiKey",n).derive(async({request:r,path:i})=>{let s=he(t),o;if(ge(i,s))o=!0;else if(ji(r.headers))o=!0;else{let a=Kt(r,i);if(a&&je(a,i,r.method))o=!0;else{let c=Ze(r,i),u=await Qe(c,i);if(o=u!==null,u&&!hr(u.scopes,r.method,i))return{isAuthenticated:o,scopeDenied:u.name}}}return{isAuthenticated:o,scopeDenied:null}}).onBeforeHandle(({isAuthenticated:r,scopeDenied:i,request:s,path:o,set:a})=>{if(i){try{e().audit.emit("auth","scoped_key.denied",{key:i,method:s.method,path:o})}catch{}return a.status=403,{error:"Forbidden",message:"This API key's scopes do not allow this operation"}}let c=he(t);if(!r&&!ge(o,c)){if(Kt(s,o))return a.status=401,{error:"invalid iframe token"};return a.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}}).as("global")}
15
+ ${r}`).digest("hex")}function yt(t,n=W){if(!me(t))throw Error("invalid plugin name");let r=Math.min(Math.max(1,Math.floor(n||W)||W),De),i=new Date(Date.now()+r*1000).toISOString(),s=P(16).toString("hex"),o=fe(t,i,s);return{token:`${Y}${i}|${t}|${s}|${o}`,expiresAt:i}}function rt(t,n){if(!t||typeof t!=="string")return!1;if(!t.startsWith(Y))return!1;let i=t.slice(Y.length).split("|");if(i.length!==4)return!1;let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(o!==n)return!1;if(!_(s))return!1;let u=fe(o,s,a);return k(u,c)}function Ue(t,n){let r;if(t instanceof Headers)r=t.get("cookie")??t.get("Cookie")??void 0;else r=t.cookie??t.Cookie??void 0;if(!r)return null;let i=`vt_ui_${n}`;for(let s of r.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()!==i)continue;return s.slice(o+1).trim()||null}return null}function it(t,n){return Ue(t.headers,n)}import{timingSafeEqual as Ge}from"crypto";var Le=["/api/agent/api-key","/api/agent/reset-key","/api/agent/iframe-token","/api/agent/aliases","/api/agent/alias","/api/agent/commands","/api/agent/lifecycle","/api/agent/nuke","/api/agent/uninstall","/api/agent/gateway-auth","/api/agent/storage-key","/api/agent/sessions/share","/api/config","/api/security","/api/tasks","/api/editor","/api/code-server","/api/logs","/api/maintenance"],Xe=["/api/plugins/install","/api/plugins/prereqs"],Be=["/api/plugins/remove","/api/plugins/remove-all"],Ve=["/api/agent/update","/api/plugins/update","/api/plugins/update-all"];var Q=new Set(["GET","HEAD","OPTIONS"]);function ee(t,n){return t===n||t.startsWith(`${n}/`)}function G(t,n){return n.some((r)=>ee(t,r))}function He(t){let n=new URL(t,"http://agent.local").pathname,r=/^\/api\/profiles\/[^/]+\/(.+)$/.exec(n);if(r?.[1])return`/api/${r[1]}`;return n}function hr(t,n,r){if(t.has("admin"))return!0;let i=He(r),s=n.toUpperCase();if(i==="/api/profiles"||/^\/api\/profiles\/[^/]+$/.test(i))return Q.has(s)&&t.has("read");if(G(i,Le))return!1;if(G(i,Xe)&&t.has("plugin:install"))return!0;if(G(i,Be)&&t.has("plugin:remove"))return!0;if(G(i,Ve)&&t.has("update"))return!0;if(ee(i,"/api/mesh"))return!0;if(ee(i,"/api/plugins")&&!Q.has(s))return!1;if(Q.has(s))return t.has("read")||t.has("mutate");return t.has("mutate")}var ze=["/health","/ui","/code-server","/terminal","/plan","/git","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/terminal-exchange","/api/agent/ui-exchange","/api/agent/ui-exchange-plugin","/metrics"];function le(t,n){if(!n||n==="/")return!1;let r=n.endsWith("/")?n.slice(0,-1):n;return t===r||t.startsWith(`${r}/`)}function We(t){let n=t.replace(/^\/api\/profiles\/[^/]+/,"/api");return n==="/api"?"/":n}function Je(t){let n=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(t);if(!n)return null;let r=n[1];if(!r)return null;return r}function ge(t,n){let r=[t],i=We(t);if(i!==t)r.push(i);for(let s of r){if(ze.some((o)=>le(s,o)))return!0;if(n.some((o)=>le(s,o)))return!0}return!1}function ye(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`vcak_${Buffer.from(t).toString("base64url")}`}var p=null;function ne(){return`${R()}:static-api-key`}async function Re(){let t=process.env.AGENT_API_KEY;if(t)return p=t,t;let n=ne(),r=await J(n);if(r)return p=r,r;let i=w({dir:e().dataDir})["static-api-key"];if(i){try{await de(n,i)}catch(o){e().logger.warn("auth","could not persist legacy api key into secrets backend",{error:String(o)})}return p=i,i}let s=ye();return await de(n,s),p=s,e().logger.info("auth","Generated and persisted new agent API key"),e().audit.emit("agent","apikey.minted",{profile:R(),via:"loadAgentApiKey"}),s}function K(){let t=process.env.AGENT_API_KEY;if(t)return t;if(p!==null)return p;let n=w()["static-api-key"];if(n)return p=n,n;let r=ye();p=r;try{M({"static-api-key":r},{dir:e().dataDir,scope:e().name})}catch{}return de(ne(),r).catch(()=>{}),r}async function vi(t){if(process.env.AGENT_API_KEY)throw Error("AGENT_API_KEY is pinned via the environment \u2014 cannot rotate the key at runtime. Update the env var and restart.");let n=(t??"").trim();if(!/^vcak_[A-Za-z0-9_-]{16,}$/.test(n))throw Error("Invalid agent API key format (expected vcak_<base64url>).");p=n,await de(ne(),n);try{M({"static-api-key":n},{dir:e().dataDir,scope:e().name})}catch{}e().audit.emit("agent","apikey.rotated",{profile:R(),via:"reset-key"})}function L(t){let n=t["x-agent-api-key"]??t["X-Agent-Api-Key"];if(n)return n;let r=t.authorization??t.Authorization;if(r?.startsWith("Bearer "))return r.slice(7);return null}function Ye(t){return!1}function Ze(t,n){let r=L(Object.fromEntries(t.headers.entries()));if(r)return r;if(!Ye(n))return null;try{let i=new URL(t.url).searchParams.get("apiKey");if(i)return i}catch{}return null}function b(t,n){let r=Buffer.from(t),i=Buffer.from(n);if(r.length!==i.length)return!1;try{return Ge(r,i)}catch{return!1}}function V(t){if(!t)return!1;return b(t,K())}var T={name:"default",scopes:new Set(["admin"])};async function Qe(t,n){if(!t)return null;let r=Je(n);if(r){let i=D.get(r);if(i){try{if(await i.keyVault.match(t))return T}catch{}if(r===e().name){try{if(await e().keyVault.match(t))return T}catch{}if(b(t,K()))return T;return pe(t)}return null}}try{if(await e().keyVault.match(t))return T}catch{}if(b(t,K()))return T;return pe(t)}function pe(t){let n=mr(t);return n?{name:n.name,scopes:n.scopes}:null}function mr(t){if(!t)return null;if(b(t,K()))return{name:"default",scopes:new Set(["admin"])};let n=B()??e(),r=w({dir:n.dataDir}),i=Date.now();for(let s of r.apiKeys??[]){if(!b(t,s.key))continue;if(s.notBefore){let o=Date.parse(s.notBefore);if(Number.isFinite(o)&&i<o)return null}if(s.expiresAt){let o=Date.parse(s.expiresAt);if(Number.isFinite(o)&&i>=o)return null}return{name:s.name,scopes:new Set(s.scopes)}}return null}function Ui(t,n){if(!t)return!1;if(t.scopes.has("admin"))return!0;return n.some((r)=>t.scopes.has(r))}var m=null;function te(t,n){try{e().audit.emit("auth",t,n)}catch{e().logger.warn("auth.audit",t,n)}}function et(t){let n=new Set(t());if(m===null)for(let r of n)te("plugin.public_path.declared",{path:r});else{for(let r of n)if(!m.has(r))te("plugin.public_path.added",{path:r});for(let r of m)if(!n.has(r))te("plugin.public_path.removed",{path:r})}return m=n,n}function Ki(){m=null}function he(t){if(!t)return[];if(m===null)return[...et(t)];return[...m]}function Qi(t){let n=K();return e().logger.info("auth",`Agent API key: ${n.substring(0,8)}****${n.substring(n.length-4)}`),new E({name:"plugin/auth"}).decorate("apiKey",n).derive(async({request:r,path:i})=>{let s=he(t),o;if(ge(i,s))o=!0;else if(ji(r.headers))o=!0;else{let a=Kt(r,i);if(a&&je(a,i,r.method))o=!0;else{let c=Ze(r,i),u=await Qe(c,i);if(o=u!==null,u&&!hr(u.scopes,r.method,i))return{isAuthenticated:o,scopeDenied:u.name}}}return{isAuthenticated:o,scopeDenied:null}}).onBeforeHandle(({isAuthenticated:r,scopeDenied:i,request:s,path:o,set:a})=>{if(i){try{e().audit.emit("auth","scoped_key.denied",{key:i,method:s.method,path:o})}catch{}return a.status=403,{error:"Forbidden",message:"This API key's scopes do not allow this operation"}}let c=he(t);if(!r&&!ge(o,c)){if(Kt(s,o))return a.status=401,{error:"invalid iframe token"};return a.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}}).as("global")}
16
16
  export{hr,we,fr,Ut,je,Hr,qe,Kt,Li,pr,Vr,Yr,me,yt,rt,it,Re,K,vi,L,V,mr,Ui,Ki,Qi};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
2
  function c(e){let r=[["--version"],["-V"],["version"]];for(let t of r)try{let n=Bun.spawnSync([e,...t],{timeout:5000,stdout:"pipe",stderr:"pipe"});if(n.exitCode===0){let s=n.stdout.toString().trim(),o=n.stderr.toString().trim();return{installed:!0,version:(s||o).split(`
3
- `)[0]||void 0}}}catch{}try{if(Bun.which(e,{PATH:process.env.PATH}))return{installed:!0}}catch{}return{installed:!1}}var a=[{name:"bun",cmd:"bun",required:!0,category:"runtime"}];function De(e){let r=a.map((t)=>{let{installed:n,version:s}=c(t.cmd);return{name:t.name,installed:n,version:s,required:t.required,category:t.category}});if(e!==void 0){let t=e instanceof Set?e:new Set(e);for(let n of t){if(r.some((i)=>i.name===n))continue;let{installed:s,version:o}=c(n);r.push({name:n,installed:s,version:o,required:!1,category:"tool"})}}return r}async function ct(e){return{success:!0,installed:[],failed:[],skipped:e??[]}}
4
- export{De,ct};
3
+ `)[0]||void 0}}}catch{}try{if(Bun.which(e,{PATH:process.env.PATH}))return{installed:!0}}catch{}return{installed:!1}}var a=[{name:"bun",cmd:"bun",required:!0,category:"runtime"}];function ke(e){let r=a.map((t)=>{let{installed:n,version:s}=c(t.cmd);return{name:t.name,installed:n,version:s,required:t.required,category:t.category}});if(e!==void 0){let t=e instanceof Set?e:new Set(e);for(let n of t){if(r.some((i)=>i.name===n))continue;let{installed:s,version:o}=c(n);r.push({name:n,installed:s,version:o,required:!1,category:"tool"})}}return r}async function ct(e){return{success:!0,installed:[],failed:[],skipped:e??[]}}
4
+ export{ke,ct};