@vibecontrols/agent 2026.1201.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
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ht,Er,_e,$e,ye,Vt,Xr,It,zr,nt,ei,_r,yr,st,Sr,ti,w,ri,M,Yt,X,Zt,ii,ni,si,oi,Ct,ai}from"./index-j99tkngg.js";import"./index-7wm4bqx5.js";export{Ht as BUILTIN_PROFILE_SEEDS,Er as NAMED_ENV_PRESETS,Ct as applyAgentConfigToEnv,ai as applyAgentSecretsToEnv,_e as assertValidProfileName,Zt as buildPairedIdentity,_r as buildProfileSeed,ei as deleteProfile,ii as describeGatewayIdentityConflict,si as describeGatewayIdentityMismatch,ni as describeProfileEnvironmentConflict,yr as ensureProfilesInitialized,Sr as getAgentConfigDefaults,st as getAgentConfigPath,ti as getAgentConfigSeed,oi as getEnvPinnedGateways,ri as getOrCreateAgentInstanceId,$e as getProfilePath,Xr as listProfileNames,ye as readActiveProfileName,w as readAgentConfig,X as readAgentConfigWithSecrets,It as readProfile,zr as readProfileStrict,Vt as writeActiveProfileName,M as writeAgentConfig,Yt as writeAgentConfigAwaitSecrets,nt as writeProfile};
2
+ import{Ht,Er,_e,$e,ye,Vt,Xr,It,zr,nt,ei,_r,yr,st,Sr,ti,w,ri,M,Yt,X,Zt,ii,ni,si,oi,Ct,ai}from"./index-30qr1qm3.js";import"./index-nxpw3anc.js";export{Ht as BUILTIN_PROFILE_SEEDS,Er as NAMED_ENV_PRESETS,Ct as applyAgentConfigToEnv,ai as applyAgentSecretsToEnv,_e as assertValidProfileName,Zt as buildPairedIdentity,_r as buildProfileSeed,ei as deleteProfile,ii as describeGatewayIdentityConflict,si as describeGatewayIdentityMismatch,ni as describeProfileEnvironmentConflict,yr as ensureProfilesInitialized,Sr as getAgentConfigDefaults,st as getAgentConfigPath,ti as getAgentConfigSeed,oi as getEnvPinnedGateways,ri as getOrCreateAgentInstanceId,$e as getProfilePath,Xr as listProfileNames,ye as readActiveProfileName,w as readAgentConfig,X as readAgentConfigWithSecrets,It as readProfile,zr as readProfileStrict,Vt as writeActiveProfileName,M as writeAgentConfig,Yt as writeAgentConfigAwaitSecrets,nt as writeProfile};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{i,g,n,c}from"./index-12gb48hg.js";var u={pending:()=>i.gray("\u25CF"),active:()=>i.cyan("\u25B6"),ok:()=>i.green("\u2713"),warn:()=>i.yellow("\u26A0"),fail:()=>i.red("\u2717")};function d(a,t){if(t)console.log(" "+a)}async function P(a,t=2000){let f=new AbortController,h=setTimeout(()=>f.abort(),t);try{let e=await fetch(`${a}/health/ready`,{signal:f.signal});if(e.status!==200&&e.status!==503)return null;return await e.json()}catch{return null}finally{clearTimeout(h)}}function D(a){if(!a?.message)return null;let t=a.message.match(/provider:\s*(\S+)/);return t?t[1]:null}async function I(a,t={}){let f=t.timeoutMs??60000,h=t.pollIntervalMs??500,e=t.verbose!==!1;if(e)g("Waiting for agent to become ready");let o={daemon:!1,awaiting:!1,initializing:!1,db:!1,session:!1,tunnel:!1},S=Date.now(),p="",v=0,A=null;while(Date.now()-S<f){let m=await P(a);if(!m){await C(h);continue}if(!o.daemon)d(`${u.ok()} Daemon listening on ${a}`,e),o.daemon=!0;let s=m.bootState??"unknown",y=m.components??{};if(s!==p){if(p=s,s==="awaiting-config"&&!o.awaiting)d(`${u.warn()} Workspace config: ${i.yellow("awaiting OAuth credentials \u2014 register this agent in the VibeControls UI")}`,e),o.awaiting=!0;else if(s==="initializing"&&!o.initializing)d(`${u.active()} Finalizing: fetching encryption key, opening storage, loading plugins\u2026`,e),o.initializing=!0}if(s==="awaiting-config"){if(v++,v>=2)return{outcome:"awaiting-config",bootState:s,degradedReasons:[],summary:"Agent is awaiting workspace registration. Open the VibeControls UI \u2192 Agents \u2192 Add Agent, paste the API Key and Tunnel URL printed above."}}else v=0;if(y.db?.ok&&!o.db)d(`${u.ok()} Storage encryption key loaded, DB opened`,e),o.db=!0;if(y.session?.ok&&!o.session){let k=y.session.message??"";d(`${u.ok()} Plugins started \u2014 ${k}`,e),o.session=!0}let b=D(y.tunnel);if(b&&b!=="bootstrap"&&b!==A){if(A=b,!o.tunnel)d(`${u.ok()} Tunnel ready (provider: ${b})`,e),o.tunnel=!0}let T=m.status==="degraded";if(s==="ready"&&!T){if(e)c(),n("Status",i.green("ready"));return{outcome:"ready",bootState:s,degradedReasons:[],summary:"Agent ready."}}if(s==="degraded"||s==="ready"&&T){let k=m.degradedReasons??[],w=k;if(k.length===0){let r=[];for(let[R,l]of Object.entries(y)){if(R==="boot"||R==="lifecycle")continue;if(l&&!l.ok&&l.message)r.push({plugin:R,message:l.message})}for(let[R,l]of Object.entries(m.plugins??{}))if(l&&!l.ok&&l.message)r.push({plugin:`plugin:${R}`,message:l.message});w=r}if(e){c(),d(`${u.fail()} Agent boot ${i.red("degraded")} \u2014 investigate before retrying`,e);for(let r of w)d(` ${i.gray("\xB7")} [${r.plugin}] ${r.message}`,e);c()}return{outcome:"degraded",bootState:s,degradedReasons:w,summary:w.length?`Agent degraded: ${w.map((r)=>`[${r.plugin}] ${r.message}`).join("; ")}`:"Agent degraded with no reported reason \u2014 check vibe logs."}}await C(h)}if(e)c(),d(`${u.warn()} Timed out after ${Math.round(f/1000)}s; last bootState=${p||"unknown"}. Check ${i.bold("vibe logs")} for details.`,e),c();return{outcome:"timeout",bootState:p||"unknown",degradedReasons:[],summary:`Timed out waiting for ready. Last bootState=${p||"unknown"}.`}}function C(a){return new Promise((t)=>setTimeout(t,a))}export{I as trackAgentReady};
2
+ import{i,g,n,c}from"./index-j9cg16we.js";var u={pending:()=>i.gray("\u25CF"),active:()=>i.cyan("\u25B6"),ok:()=>i.green("\u2713"),warn:()=>i.yellow("\u26A0"),fail:()=>i.red("\u2717")};function d(a,t){if(t)console.log(" "+a)}async function P(a,t=2000){let f=new AbortController,h=setTimeout(()=>f.abort(),t);try{let e=await fetch(`${a}/health/ready`,{signal:f.signal});if(e.status!==200&&e.status!==503)return null;return await e.json()}catch{return null}finally{clearTimeout(h)}}function D(a){if(!a?.message)return null;let t=a.message.match(/provider:\s*(\S+)/);return t?t[1]:null}async function I(a,t={}){let f=t.timeoutMs??60000,h=t.pollIntervalMs??500,e=t.verbose!==!1;if(e)g("Waiting for agent to become ready");let o={daemon:!1,awaiting:!1,initializing:!1,db:!1,session:!1,tunnel:!1},S=Date.now(),p="",v=0,A=null;while(Date.now()-S<f){let m=await P(a);if(!m){await C(h);continue}if(!o.daemon)d(`${u.ok()} Daemon listening on ${a}`,e),o.daemon=!0;let s=m.bootState??"unknown",y=m.components??{};if(s!==p){if(p=s,s==="awaiting-config"&&!o.awaiting)d(`${u.warn()} Workspace config: ${i.yellow("awaiting OAuth credentials \u2014 register this agent in the VibeControls UI")}`,e),o.awaiting=!0;else if(s==="initializing"&&!o.initializing)d(`${u.active()} Finalizing: fetching encryption key, opening storage, loading plugins\u2026`,e),o.initializing=!0}if(s==="awaiting-config"){if(v++,v>=2)return{outcome:"awaiting-config",bootState:s,degradedReasons:[],summary:"Agent is awaiting workspace registration. Open the VibeControls UI \u2192 Agents \u2192 Add Agent, paste the API Key and Tunnel URL printed above."}}else v=0;if(y.db?.ok&&!o.db)d(`${u.ok()} Storage encryption key loaded, DB opened`,e),o.db=!0;if(y.session?.ok&&!o.session){let k=y.session.message??"";d(`${u.ok()} Plugins started \u2014 ${k}`,e),o.session=!0}let b=D(y.tunnel);if(b&&b!=="bootstrap"&&b!==A){if(A=b,!o.tunnel)d(`${u.ok()} Tunnel ready (provider: ${b})`,e),o.tunnel=!0}let T=m.status==="degraded";if(s==="ready"&&!T){if(e)c(),n("Status",i.green("ready"));return{outcome:"ready",bootState:s,degradedReasons:[],summary:"Agent ready."}}if(s==="degraded"||s==="ready"&&T){let k=m.degradedReasons??[],w=k;if(k.length===0){let r=[];for(let[R,l]of Object.entries(y)){if(R==="boot"||R==="lifecycle")continue;if(l&&!l.ok&&l.message)r.push({plugin:R,message:l.message})}for(let[R,l]of Object.entries(m.plugins??{}))if(l&&!l.ok&&l.message)r.push({plugin:`plugin:${R}`,message:l.message});w=r}if(e){c(),d(`${u.fail()} Agent boot ${i.red("degraded")} \u2014 investigate before retrying`,e);for(let r of w)d(` ${i.gray("\xB7")} [${r.plugin}] ${r.message}`,e);c()}return{outcome:"degraded",bootState:s,degradedReasons:w,summary:w.length?`Agent degraded: ${w.map((r)=>`[${r.plugin}] ${r.message}`).join("; ")}`:"Agent degraded with no reported reason \u2014 check vibe logs."}}await C(h)}if(e)c(),d(`${u.warn()} Timed out after ${Math.round(f/1000)}s; last bootState=${p||"unknown"}. Check ${i.bold("vibe logs")} for details.`,e),c();return{outcome:"timeout",bootState:p||"unknown",degradedReasons:[],summary:`Timed out waiting for ready. Last bootState=${p||"unknown"}.`}}function C(a){return new Promise((t)=>setTimeout(t,a))}export{I as trackAgentReady};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{br}from"./index-xertgyzn.js";import"./index-4qqsx04e.js";import"./index-6xd9k363.js";import"./index-ppxayc0x.js";import"./index-2a1yq04v.js";import"./index-5ygnxt32.js";import"./index-txchzvfc.js";import"./index-zfhmg1gz.js";import"./index-zekdqp0t.js";import"./index-cn4p1ks0.js";import"./index-n3kwtv6f.js";import"./index-pw6aqemr.js";import"./index-x4z055t8.js";import"./index-1t74r13z.js";import"./index-djwa3tm3.js";import"./index-30qr1qm3.js";import"./index-nxpw3anc.js";export{br as createApp};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{tn,kr}from"./index-prp5nvsa.js";import"./index-v77bb0rm.js";import"./index-j9cg16we.js";import"./index-sq5j8bjn.js";import"./index-djwa3tm3.js";import"./index-30qr1qm3.js";import"./index-nxpw3anc.js";export{tn as ensureAutostartConfigured,kr as register};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Tr}from"./index-6g3qhprq.js";import"./index-nxpw3anc.js";export{Tr as bootstrapWorkspace};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ke,ct}from"./index-r1v0yazw.js";export{ke as checkDependencies,ct as installDependencies};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{He,zi}from"./index-bk17490n.js";import"./index-7wm4bqx5.js";export{He as BridgeCommandError,zi as bridgeClient};
2
+ import{He,zi}from"./index-c9q14161.js";import"./index-nxpw3anc.js";export{He as BridgeCommandError,zi as bridgeClient};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import"./index-7wm4bqx5.js";import{He}from"./index-bk17490n.js";import{Ae}from"./index-8jk4a62x.js";var s=new Set(["desk.session"]),c=new Set(["BAD_REQUEST","DESK_OFFLINE"]);async function i(n){try{return await n()}catch(e){let t=typeof e==="object"&&e!==null&&"code"in e?e.code:void 0;if(typeof t==="string"&&c.has(t))throw new He(t,e instanceof Error?e.message:t);throw e}}function p(n,e){let t={publishEvent(o){if(!s.has(o.topic))throw Error(`plugins may not publish '${o.topic}'`);if(typeof o.payload!=="object"||o.payload===null||Array.isArray(o.payload))throw Error("an event payload must be an object");e.publishEvent({topic:o.topic,payload:o.payload})}};n.registerService("agent","bridge",t)}function d(n){if(typeof n!=="object"||n===null)return!1;let e=n;return typeof e.act==="function"&&typeof e.fence==="function"&&typeof e.health==="function"}function a(n){let e=n.getService("desk","remote");if(!d(e))throw new He("DESK_OFFLINE","no desk plugin with remote control is loaded on this agent");return e}function u(n,e){let t=[n.handle("agent.ping",async()=>({pong:!0,version:Ae(),at:new Date().toISOString()})),n.handle("desk.act",(o,r)=>i(()=>a(e).act(o,{signal:r.signal}))),n.handle("desk.fence",(o,r)=>i(()=>a(e).fence(o,{signal:r.signal}))),n.handle("desk.health",(o,r)=>i(()=>a(e).health({signal:r.signal})))];return()=>{for(let o of t)o()}}export{u as registerBridgeCommands,p as registerPluginBridgeService};
2
+ import"./index-nxpw3anc.js";import{He}from"./index-c9q14161.js";import{Ae}from"./index-zfhmg1gz.js";var s=new Set(["desk.session"]),c=new Set(["BAD_REQUEST","DESK_OFFLINE"]);async function i(n){try{return await n()}catch(e){let t=typeof e==="object"&&e!==null&&"code"in e?e.code:void 0;if(typeof t==="string"&&c.has(t))throw new He(t,e instanceof Error?e.message:t);throw e}}function p(n,e){let t={publishEvent(o){if(!s.has(o.topic))throw Error(`plugins may not publish '${o.topic}'`);if(typeof o.payload!=="object"||o.payload===null||Array.isArray(o.payload))throw Error("an event payload must be an object");e.publishEvent({topic:o.topic,payload:o.payload})}};n.registerService("agent","bridge",t)}function d(n){if(typeof n!=="object"||n===null)return!1;let e=n;return typeof e.act==="function"&&typeof e.fence==="function"&&typeof e.health==="function"}function a(n){let e=n.getService("desk","remote");if(!d(e))throw new He("DESK_OFFLINE","no desk plugin with remote control is loaded on this agent");return e}function u(n,e){let t=[n.handle("agent.ping",async()=>({pong:!0,version:Ae(),at:new Date().toISOString()})),n.handle("desk.act",(o,r)=>i(()=>a(e).act(o,{signal:r.signal}))),n.handle("desk.fence",(o,r)=>i(()=>a(e).fence(o,{signal:r.signal}))),n.handle("desk.health",(o,r)=>i(()=>a(e).health({signal:r.signal})))];return()=>{for(let o of t)o()}}export{u as registerBridgeCommands,p as registerPluginBridgeService};
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{Ye}from"./index-xetd52ad.js";import{I,se,e}from"./index-7wm4bqx5.js";import{W}from"./index-8jk4a62x.js";import{Z}from"./index-wxb9dgwq.js";import{Gi}from"./index-12gb48hg.js";import"./index-1t74r13z.js";import"./index-j99tkngg.js";import"./index-x4z055t8.js";import"./index-qzwbctkv.js";import{Br}from"./index-62vfxd90.js";import"./index-sq5j8bjn.js";import"./index-4kf3nr14.js";import"./index-zcnfj1q4.js";import{Pr,Mr}from"./index-q4fht6h2.js";import"./index-dr6rsnpk.js";import"./index-0rmmrrfh.js";import"./index-twtvt4yt.js";import{xe,Ie,Fi,ve}from"./index-br9bakfm.js";import{b}from"./index-w4jqdhc2.js";import"./index-cn4p1ks0.js";import"./index-v77bb0rm.js";import"./index-damc6cvc.js";import{join as m}from"path";if(typeof Bun>"u")console.error(`\x1B[31mError:\x1B[0m VibeControls Agent requires the Bun runtime.
3
+ import{Ye}from"./index-xetd52ad.js";import{I,se,e}from"./index-nxpw3anc.js";import{W}from"./index-zfhmg1gz.js";import{Z}from"./index-zekdqp0t.js";import{Gi}from"./index-j9cg16we.js";import"./index-1t74r13z.js";import"./index-30qr1qm3.js";import"./index-x4z055t8.js";import"./index-pw6aqemr.js";import{Br}from"./index-62vfxd90.js";import"./index-sq5j8bjn.js";import"./index-r1v0yazw.js";import"./index-prp5nvsa.js";import{Pr,Mr}from"./index-r2j1t657.js";import"./index-2a1yq04v.js";import"./index-ep20qw1j.js";import"./index-5ygnxt32.js";import{xe,Ie,Fi,ve}from"./index-txchzvfc.js";import{b}from"./index-w4jqdhc2.js";import"./index-cn4p1ks0.js";import"./index-v77bb0rm.js";import"./index-djwa3tm3.js";import{join as m}from"path";if(typeof Bun>"u")console.error(`\x1B[31mError:\x1B[0m VibeControls Agent requires the Bun runtime.
4
4
  Install Bun: https://bun.sh
5
5
  Then run: bun run vibe ...`),process.exit(1);var a=process.argv.slice(2),l=a.includes("--plain")||a.includes("--json")||process.env.NO_COLOR==="1"||!process.stdout.isTTY;Gi(!l);try{Br()}catch{}var s="1.0.0";try{let t=m(import.meta.dir,"..","package.json");s=(await Bun.file(t).json()).version}catch{}var r=new Ye;r.name("vibe").description("VibeControls Agent CLI \u2014 Remote development environment management").version(s,"-v, --version").option("--provider <name>","Override the default provider for tunnel/session operations").option("-p, --profile <name>","Target a specific profile (one-off; doesn't change the persisted default). See `vibe profile`.").option("--json","Emit machine-readable JSON instead of human output.").option("--plain","Force plain-text output (no interactive UI).").hook("preAction",(t,o)=>{let n=t.opts().profile;if(n)process.env.VIBECONTROLS_PROFILE=n;try{Z.init(),Z.emit("command.executed",{command_name:o.name()})}catch{}});Mr(r);async function g(){let t=new W;try{await t.loadCorePlugins()}catch{}try{await t.loadAll()}catch{}let o=new xe,n={storage:{async get(){return null},async set(){},async delete(){return!1},async list(){return[]},async deleteAll(){return 0}},logger:e().logger,serviceRegistry:o,getProvider:(i)=>o.getProvider(i),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:3005",getAgentVersion:()=>s,broadcast:()=>{},workspaceQuery:async()=>({data:void 0,errors:[{message:"workspaceQuery is not available in CLI mode"}]}),isGatewayConfigured:()=>!1,getAgentRecordId:async()=>null,getWorkspaceId:async()=>null,getConfig:async()=>{return},getPluginRegistry:()=>se(),getDataDir:()=>I(),cliContributors:new Ie,telemetry:{emit:(i,p)=>{try{Z.emit(i,p??{})}catch{}}},os:b(),iframeBridge:ve()};Fi(n.cliContributors);try{await t.dispatchCliSetup(r,n)}catch{}r.configureHelp({formatHelp:()=>Pr(r,!0)}),await r.parseAsync()}g().then(()=>{process.exit(process.exitCode??0)}).catch((t)=>{console.error(`\x1B[31mFatal:\x1B[0m ${t instanceof Error?t.message:t}`),process.exit(1)});
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{D,e,at}from"./index-nxpw3anc.js";export{e as getDaemonProfile,at as getOrCreateProfile,D as profileRegistry};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{e}from"./index-7wm4bqx5.js";var m=[300000,600000,900000,1800000];function p(f){let g=f.backoffsMs??m,n=0,o=!1,i=null,u=null,a=null,t=e();if(t.getBootState()==="ready")return{cancel(){},async forceRetryNow(){return{ok:!0}},getState(){return{attempt:0,cancelled:!0,nextAttemptAt:null}}};function c(){if(i!==null)clearTimeout(i),i=null,u=null}function y(){if(o)return Promise.resolve({ok:!1,error:"retry worker cancelled"});if(t.getBootState()==="ready")return o=!0,c(),Promise.resolve({ok:!0});if(a)return a;return n+=1,f.onAttempt?.(n),t.logger.info("finalize-retry",`Background finalize retry attempt ${n}`),a=(async()=>{try{let r=await f.trigger();if(r.ok)t.logger.info("finalize-retry",`Background finalize succeeded on attempt ${n} \u2014 agent recovered`),o=!0,c();else t.recordFinalizeError(r.error,n),t.logger.warn("finalize-retry",`Background finalize attempt ${n} failed`,{error:r.error});return r}catch(r){let l=r instanceof Error?r.message:String(r);return t.recordFinalizeError(l,n),t.logger.error("finalize-retry",`Background finalize attempt ${n} threw`,{error:l}),{ok:!1,error:l}}finally{a=null}})(),a}function s(){if(o)return;if(t.getBootState()==="ready"){o=!0;return}if(i!==null)return;let r=Math.min(n,g.length-1),l=g[r];u=Date.now()+l,i=setTimeout(async()=>{if(i=null,await y(),!o&&t.getBootState()!=="ready")s()},l)}return s(),{cancel(){o=!0,c()},async forceRetryNow(){if(t.getBootState()==="ready")return{ok:!0};if(o)return{ok:!1,error:"retry worker cancelled"};c();let r=await y();if(!o&&t.getBootState()!=="ready")s();return r},getState(){return{attempt:n,cancelled:o,nextAttemptAt:u?new Date(u).toISOString():null}}}}export{p as startFinalizeRetryWorker};
2
+ import{e}from"./index-nxpw3anc.js";var m=[300000,600000,900000,1800000];function p(f){let g=f.backoffsMs??m,n=0,o=!1,i=null,u=null,a=null,t=e();if(t.getBootState()==="ready")return{cancel(){},async forceRetryNow(){return{ok:!0}},getState(){return{attempt:0,cancelled:!0,nextAttemptAt:null}}};function c(){if(i!==null)clearTimeout(i),i=null,u=null}function y(){if(o)return Promise.resolve({ok:!1,error:"retry worker cancelled"});if(t.getBootState()==="ready")return o=!0,c(),Promise.resolve({ok:!0});if(a)return a;return n+=1,f.onAttempt?.(n),t.logger.info("finalize-retry",`Background finalize retry attempt ${n}`),a=(async()=>{try{let r=await f.trigger();if(r.ok)t.logger.info("finalize-retry",`Background finalize succeeded on attempt ${n} \u2014 agent recovered`),o=!0,c();else t.recordFinalizeError(r.error,n),t.logger.warn("finalize-retry",`Background finalize attempt ${n} failed`,{error:r.error});return r}catch(r){let l=r instanceof Error?r.message:String(r);return t.recordFinalizeError(l,n),t.logger.error("finalize-retry",`Background finalize attempt ${n} threw`,{error:l}),{ok:!1,error:l}}finally{a=null}})(),a}function s(){if(o)return;if(t.getBootState()==="ready"){o=!0;return}if(i!==null)return;let r=Math.min(n,g.length-1),l=g[r];u=Date.now()+l,i=setTimeout(async()=>{if(i=null,await y(),!o&&t.getBootState()!=="ready")s()},l)}return s(),{cancel(){o=!0,c()},async forceRetryNow(){if(t.getBootState()==="ready")return{ok:!0};if(o)return{ok:!1,error:"retry worker cancelled"};c();let r=await y();if(!o&&t.getBootState()!=="ready")s();return r},getState(){return{attempt:n,cancelled:o,nextAttemptAt:u?new Date(u).toISOString():null}}}}export{p as startFinalizeRetryWorker};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ui,T}from"./index-nxpw3anc.js";export{ui as GatewayClient,T as gatewayClient};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Y,Ce,Ue}from"./index-8jk4a62x.js";import{Jt,xt,T,R,I,ne,se,B,e}from"./index-7wm4bqx5.js";import{Z}from"./index-wxb9dgwq.js";import{D}from"./index-twtvt4yt.js";import{b}from"./index-w4jqdhc2.js";import{Fe}from"./index-damc6cvc.js";import{existsSync as q,readFileSync as S,unlinkSync as wt,writeFileSync as U}from"fs";import{join as X}from"path";var Q=".consent.json";function Ze(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.abilities)&&n.abilities.length>0)return new Set(n.abilities)}catch{}return null}function Ot(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.providers))return n.providers.filter((o)=>typeof o==="string")}catch{}return[]}function Ti(t){let r=new Set;for(let n of t.split(",").map((o)=>o.trim()).filter(Boolean)){let o=Ue(n);if(o)r.add(o)}return[...r]}function P(t){return X(t,Q)}function xi(t,r){let n=r??new Set(Y.filter((i)=>i.defaultSelected||i.mandatory).map((i)=>i.key)),o=t.skipPluginInstall?[]:Ce(process.platform,n).filter((i)=>!t.skipPlugins.includes(i.packageName)&&!t.skipPlugins.includes(i.pluginName)).map((i)=>({packageName:i.packageName,pluginName:i.pluginName,reason:i.description}));return{tools:[],plugins:o}}async function nr(){let t=new Set(Y.filter((n)=>n.defaultSelected||n.mandatory).map((n)=>n.key));for(let n of Y)if(n.mandatory)t.add(n.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return t;try{let{interactiveCheckboxes:n}=await import("./interactive-52x9hv6c.js"),o=await n("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}catch(n){process.stdout.write(`
2
+ import{Y,Ce,Ue}from"./index-zfhmg1gz.js";import{Jt,xt,T,R,I,ne,se,B,e}from"./index-nxpw3anc.js";import{Z}from"./index-zekdqp0t.js";import{k}from"./index-5ygnxt32.js";import{b}from"./index-w4jqdhc2.js";import{Fe}from"./index-djwa3tm3.js";import{existsSync as q,readFileSync as x,unlinkSync as wt,writeFileSync as N}from"fs";import{join as X}from"path";var Q=".consent.json";function Ze(t){try{let r=x(v(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.abilities)&&n.abilities.length>0)return new Set(n.abilities)}catch{}return null}function Ot(t){try{let r=x(v(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.providers))return n.providers.filter((o)=>typeof o==="string")}catch{}return[]}function Ti(t){let r=new Set;for(let n of t.split(",").map((o)=>o.trim()).filter(Boolean)){let o=Ue(n);if(o)r.add(o)}return[...r]}function v(t){return X(t,Q)}function xi(t,r){let n=r??new Set(Y.filter((i)=>i.defaultSelected||i.mandatory).map((i)=>i.key)),o=t.skipPluginInstall?[]:Ce(process.platform,n).filter((i)=>!t.skipPlugins.includes(i.packageName)&&!t.skipPlugins.includes(i.pluginName)).map((i)=>({packageName:i.packageName,pluginName:i.pluginName,reason:i.description}));return{tools:[],plugins:o}}async function nr(){let t=new Set(Y.filter((n)=>n.defaultSelected||n.mandatory).map((n)=>n.key));for(let n of Y)if(n.mandatory)t.add(n.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return t;try{let{interactiveCheckboxes:n}=await import("./interactive-52x9hv6c.js"),o=await n("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}catch(n){process.stdout.write(`
3
3
  [vibe] Falling back to plain prompt \u2014 ${n instanceof Error?n.message:String(n)}
4
4
 
5
5
  `);let o=await ee("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}}async function ee(t,r,n){let o=new Set(n);for(let s of r)if(s.mandatory)o.add(s.key);let i=()=>{process.stdout.write(`
@@ -13,5 +13,5 @@ Type numbers to toggle (e.g. '2 4'), 'a' = all, 'n' = none, '?' = help, Enter =
13
13
  `+` \u2022 Type 'a' to select all, 'n' to deselect everything except required rows.
14
14
  `+` \u2022 Press Enter on a blank line to confirm the current selection.
15
15
  `+` \u2022 Press Ctrl-C to cancel and accept the safe defaults (everything on).
16
- `);continue}if(s.toLowerCase()==="a"){for(let c of r)o.add(c.key);continue}if(s.toLowerCase()==="n"){o.clear();for(let c of r)if(c.mandatory)o.add(c.key);continue}let l=s.split(/[\s,]+/u).filter(Boolean);for(let c of l){let d=Number.parseInt(c,10);if(!Number.isFinite(d)||d<1||d>r.length)continue;let u=r[d-1];if(!u||u.mandatory)continue;if(o.has(u.key))o.delete(u.key);else o.add(u.key)}}}finally{process.stdin.pause()}}function bi(t){let r=new Set(Y.map((o)=>o.key)),n=new Set;for(let o of t.split(",").map((i)=>i.trim().toLowerCase()))if(r.has(o))n.add(o);for(let o of Y)if(o.mandatory)n.add(o.key);return n}function sr(){return new Set(Y.filter((t)=>t.defaultSelected||t.mandatory).map((t)=>t.key))}function wi(t,r,n,o,i){let a={acceptedAt:new Date().toISOString(),agentVersion:o,abilities:[...n],providers:i?[...i]:void 0,tools:r.tools.map((s)=>({name:s.name,reason:s.reason})),plugins:r.plugins.map((s)=>({packageName:s.packageName,reason:s.reason}))};U(P(t),JSON.stringify(a,null,2))}function ut(t,r){let n=oe(t),o={acceptedAt:n?.acceptedAt??new Date().toISOString(),agentVersion:r.agentVersion??n?.agentVersion,abilities:r.abilities?[...r.abilities]:n?.abilities,providers:r.providers?[...r.providers]:n?.providers,tools:n?.tools??[],plugins:n?.plugins??[]};U(P(t),JSON.stringify(o,null,2))}function oe(t){try{let r=P(t);if(!q(r))return null;return JSON.parse(S(r,"utf8"))}catch{return null}}import{createHash as ie}from"crypto";import{homedir as le,tmpdir as ce}from"os";import*as f from"path";import{spawn as E}from"child_process";import{createWriteStream as ue,existsSync as de,promises as h}from"fs";import{Readable as pe}from"stream";import{pipeline as ge}from"stream/promises";function fe(){let t=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${t}`}function me(){return f.join(le(),".boff","vibecontrols","tools")}function O(t,r){let n=r??t;if(process.platform==="win32"&&!n.toLowerCase().endsWith(".exe"))return`${n}.exe`;return n}function he(t,r,n){return f.join(n??me(),t,O(t,r))}async function N(t,r){if(!r.versionMatcher)return!0;return new Promise((n)=>{let o=E(t,r.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),i="";o.stdout.on("data",(a)=>i+=a.toString()),o.stderr.on("data",(a)=>i+=a.toString()),o.on("close",()=>{try{n(new RegExp(r.versionMatcher).test(i))}catch{n(!1)}}),o.on("error",()=>n(!1))})}async function ye(t){let r=t.platform??fe(),n=O(t.name,t.binaryName),o=he(t.name,t.binaryName,t.cacheRoot);if(de(o)&&await N(o,t))return o;try{let a=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(t.binaryName??t.name,{PATH:process.env.PATH}):null;if(a&&await N(a,t))return t.log?.info?.(`[install] using PATH binary ${t.name} (${a})`),a}catch{}let i=t.downloads[r];if(!i)throw Error(`[install] no download manifest entry for ${t.name} on ${r}`);return t.log?.info?.(`[install] downloading ${t.name} for ${r}`),await h.mkdir(f.dirname(o),{recursive:!0}),await we(i,o,n,t.name),t.log?.info?.(`[install] installed ${t.name} \u2192 ${o}`),o}async function we(t,r,n,o){f.dirname(r);let i=f.join(ce(),`vibe-install-${o}-${process.pid}`);await h.mkdir(i,{recursive:!0});let a=f.join(i,"artifact");try{let s=await fetch(t.url,{redirect:"follow"});if(!s.ok)throw Error(`download failed (${s.status}) for ${t.url}`);if(!s.body)throw Error(`empty response body for ${t.url}`);if(await ge(pe.fromWeb(s.body),ue(a)),t.sha256){let c=ie("sha256").update(await h.readFile(a)).digest("hex");if(c!==t.sha256)throw Error(`sha256 mismatch for ${o}: expected ${t.sha256}, got ${c}`)}let l=t.archive??(t.url.endsWith(".tar.gz")||t.url.endsWith(".tgz")?"tar.gz":t.url.endsWith(".zip")?"zip":"raw");if(l==="raw")await h.copyFile(a,r);else{if(l==="tar.gz")await x("tar",["-xzf",a,"-C",i]);else await be(a,i);let c=t.binaryWithinArchive??n;await h.copyFile(f.join(i,c),r)}if(process.platform!=="win32")await h.chmod(r,493)}finally{await h.rm(i,{recursive:!0,force:!0})}}async function be(t,r){try{await x("unzip",["-q","-o",t,"-d",r]);return}catch(n){if(process.platform!=="win32")throw n;await x("tar",["-xf",t,"-C",r])}}async function x(t,r){return new Promise((n,o)=>{let i=E(t,r,{stdio:["ignore","ignore","pipe"]}),a="";i.stderr.on("data",(s)=>a+=s.toString()),i.on("close",(s)=>s===0?n():o(Error(`${t} exit ${s}: ${a}`))),i.on("error",o)})}var k="https://github.com/cloudflare/cloudflared/releases/latest/download",Pe={"linux-x64":{url:`${k}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${k}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${k}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${k}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${k}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${k}/cloudflared-windows-arm64.exe`,archive:"raw"}},ve=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function L(t,r){let n=r?.log??{},o;try{o=await ye({name:"cloudflared",downloads:Pe,versionMatcher:"cloudflared version",log:n})}catch(s){return n.warn?.(`quick-tunnel: could not obtain cloudflared: ${String(s)}`),null}let i;try{i=E(o,["tunnel","--url",`http://127.0.0.1:${t}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch(s){return n.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String(s)}`),null}let a=await new Promise((s)=>{let l=!1,c=(g)=>{if(l)return;l=!0,s(g)},d=setTimeout(()=>{n.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),c(null)},r?.timeoutMs??30000),u=(g)=>{let p=g.toString("utf8").match(ve);if(p)clearTimeout(d),c(p[0])};i.stdout?.on("data",u),i.stderr?.on("data",u),i.on("error",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(g)}`),c(null)}),i.on("exit",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared exited (code=${g})`),c(null)})});if(!a)return null;return{url:a,child:i}}import{existsSync as M,mkdirSync as xe,readFileSync as $e,writeFileSync as Re,unlinkSync as Te}from"fs";import{dirname as Ee,join as F}from"path";import{readdirSync as Ae}from"fs";function A(t){return F(t??I(),"tunnel.state.json")}function j(t,r){let n=A(r);try{xe(Ee(n),{recursive:!0}),Re(n,JSON.stringify(t,null,2),"utf8")}catch(o){e().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(o)})}}function te(t){let r=A(t);if(!M(r))return null;try{let n=$e(r,"utf8"),o=JSON.parse(n);if(typeof o.pid!=="number")return null;return o}catch(n){return e().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(n)}),null}}function re(t){let r=A(t);if(!M(r))return;try{Te(r)}catch{}}function ae(t){return b().isProcessAlive(t)}function qi(t){let r=[];if(t?.allProfiles){let o;try{o=ne()}catch{return r}let i;try{i=Ae(o)}catch{return r}for(let a of i){let s=F(o,a),l=te(s);if(l)r.push({...l,alive:ae(l.pid),profileDir:s})}return r}let n=te();if(n)r.push({...n,alive:ae(n.pid),profileDir:I()});return r}function or(t){return t.replace(/[^A-Za-z0-9_]/g,"_")}function v(){return(B()??e()).tunnel}async function Nr(t,r){let n=v();_e(t),Ie();let o=process.env.AGENT_TUNNEL_URL;if(o){let s=xt(o);if(!s)return e().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;n.url=s,n.externalUrl=!0,e().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${s}`);try{Z.emit("tunnel.url_assigned",{provider:"external"})}catch{}return s}let i=r.port,a=await L(i,{log:{info:(s)=>e().logger.info("tunnel-bootstrap",s),warn:(s)=>e().logger.warn("tunnel-bootstrap",s)}});if(!a)return e().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(n.child=a.child,n.url=a.url,n.url){e().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${n.url}`);try{let c=new URL(n.url).hostname.split(".");if(c.length>=2)Jt("."+c.slice(-2).join("."))}catch{}try{Z.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let s=or(R());if(process.env[`AGENT_TUNNEL_URL_${s}`]=n.url,n.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${s}`]=String(n.child.pid),j({pid:n.child.pid,url:n.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:i,cmd:`cloudflared tunnel --url http://127.0.0.1:${i}`})}return n.url}function rn(){let t=v();if(t.externalUrl)return!1;if(!t.child||t.child.killed)return!1;let r=t.child.pid;if(r===void 0)return!1;try{process.kill(r,0)}catch{return!1}return t.child=null,re(),e().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${r}) to plugin \u2014 process kept alive`),!0}function ar(){let t=v();if(t.externalUrl){re();return}let r=t.child;if(t.child=null,re(),!r||r.killed)return;try{r.kill("SIGTERM"),e().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function lt(){return v().url}function Ie(){let t=te();if(!t)return;if(!ae(t.pid)){re();return}try{process.kill(t.pid,"SIGTERM"),e().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:t.pid,provider:t.provider})}catch{}let r=Date.now();while(Date.now()-r<2000&&ae(t.pid))Bun.sleepSync(50);if(ae(t.pid))try{process.kill(t.pid,"SIGKILL")}catch{}re()}function _e(t){let r={name:"bootstrap",async getActiveTunnelUrl(){return v().url}};t.registerProvider("tunnel",r,"bootstrap")}import{existsSync as Oe,mkdirSync as Be,readFileSync as Me,renameSync as De,writeFileSync as je}from"fs";import{dirname as He,join as Ve}from"path";var Ne=["tunnel:read","session:list","session:share:read","session:share:write","plugin:list","plugin:install","plugin:remove","log:read","diagnostics:read","key:mint","mesh:forward","admin"];function z(t){return Ve(t??I(),"agent-network.json")}function y(t){let r=z(t);if(!Oe(r))return{schemaVersion:1,peers:[]};let n=Me(r,"utf8");try{let o=JSON.parse(n);if(!o||!Array.isArray(o.peers))return{schemaVersion:1,peers:[]};return o}catch{return{schemaVersion:1,peers:[]}}}function C(t,r){let n=z(r);Be(He(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;je(o,JSON.stringify(t,null,2),{mode:384}),De(o,n)}function Ri(t){return y(t).peers}function Je(t,r){return y(r).peers.find((n)=>n.id===t)??null}function H(t,r){if(r.workspaceId&&t.workspaceId&&t.workspaceId!==r.workspaceId)return!1;if(r.ownerUserId)return(t.ownerUserId??r.ownerUserId)===r.ownerUserId;return!0}function gt(t,r){return y(r).peers.filter((n)=>H(n,t))}function kr(t,r,n){return y(n).peers.find((o)=>o.agentRecordId===t&&H(o,r))??null}function We(t,r){let n=y(r),o=n.peers.findIndex((i)=>i.id===t.id);if(o>=0)n.peers[o]={...n.peers[o],...t};else n.peers.push(t);return C(n,r),t}function ke(t,r,n){let o=y(n),i=o.peers.findIndex((a)=>a.id===t);if(i<0)return null;return o.peers[i]={...o.peers[i],...r},C(o,n),o.peers[i]}function Bt(t,r){let n=y(r),o=n.peers.length;if(n.peers=n.peers.filter((i)=>i.id!==t),n.peers.length===o)return!1;return C(n,r),!0}function Xe(t){let r=new Set(Ne);return[...t].filter((n)=>r.has(n)).map((n)=>n)}import{join as Ke}from"path";function w(t){let r=b();return r.which(t)??`${t}${r.executableSuffix}`}async function Ar(){let t=["..","../..","../../.."];for(let r of t)try{let n=Ke(import.meta.dir,r,"package.json"),o=await Bun.file(n).json(),{name:i,version:a}=o;if(i&&a){let s=o.publishConfig;return{name:i,version:a,registry:s?.registry??se()}}}catch{}throw Error("package.json not found")}function Ge(t,r,n){try{let o=Bun.spawnSync([w("npm"),"view",`${t}@${r}`,"--json",`--registry=${n}`],{stdout:"pipe",stderr:"pipe"});if(o.exitCode!==0)return null;let i=JSON.parse(o.stdout.toString());return Array.isArray(i)?i[0]??null:i}catch{return null}}function V(t,r){let n=(a)=>a.replace(/^[\^~>=<v]+/,"").split(/[.+-]/).map((s)=>Number(s)||0),o=n(t),i=n(r);for(let a=0;a<Math.max(o.length,i.length);a++){let s=o[a]??0,l=i[a]??0;if(s!==l)return s-l}return 0}function qe(t,r){if(!t)return{ok:!0,message:""};let n=t.replace(/^[\^~]/,"").replace(/^>=?\s*/,"");if(V(r,n)>=0)return{ok:!0,message:`bun ${r} >= ${n}`};return{ok:!1,message:`requires bun ${t}, this process is bun ${r}`}}function Qe(t){try{let r=w("npm"),n=Bun.spawnSync([r,"root","-g"],{stdout:"pipe",stderr:"pipe"});if(n.exitCode!==0)return null;return`${n.stdout.toString().trim()}/${t}`}catch{return null}}function Ye(t){let r=Qe(t);if(!r)return{ok:!0,step:"(skipped, install root unknown)"};let n=`${r}/dist/cli.js`,o=(l,c,d)=>{try{let u=w("bun"),g=Bun.spawnSync([u,n,...l],{stdout:"pipe",stderr:"pipe",timeout:d});if(g.exitCode===0)return{ok:!0,step:c};return{ok:!1,step:c,detail:g.stderr.toString().slice(0,300)||`exit ${g.exitCode}`}}catch(u){return{ok:!1,step:c,detail:String(u)}}},i=o(["--version"],"vibe --version",1e4);if(!i.ok)return i;let a=o(["info"],"vibe info",15000);if(!a.ok)return a;let s=o(["plugin","list","--json"],"vibe plugin list",30000);if(!s.ok)return s;return{ok:!0,step:"all checks passed"}}async function tt(t,r=60000){try{let n=new D,o=await n.getStatus(t);if(!o||o.status!=="running")return{kind:"not-running"};let i=`http://localhost:${o.port}`,a;try{a=await Fe(i)}catch{}let s={};if(a)s["x-agent-api-key"]=a;let l=1000,c=Date.now();while(Date.now()-c<r){try{let d=await fetch(`${i}/api/profiles/${encodeURIComponent(t)}/stats/inflight`,{headers:s,signal:AbortSignal.timeout(2000)});if(d.ok){let u=await d.json();if(typeof u.inflight==="number"&&u.inflight===0){let g=o.config;return await n.restart(t,g),{kind:"restarted"}}}}catch{}await new Promise((d)=>setTimeout(d,l))}return{kind:"still-busy"}}catch(n){return{kind:"error",message:n instanceof Error?n.message:String(n)}}}async function Le(){let t;try{t=await Ar()}catch(n){return{name:"@vibecontrols/agent",registry:se(),current:"unknown",latest:null,hasUpdate:!1,error:n instanceof Error?n.message:String(n)}}let r=null;try{let n=Bun.spawnSync([w("npm"),"view",t.name,"version",`--registry=${t.registry}`],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0)r=n.stdout.toString().trim()||null}catch{}if(!r)return{name:t.name,registry:t.registry,current:t.version,latest:null,hasUpdate:!1,error:"Could not reach the registry to check for updates"};return{name:t.name,registry:t.registry,current:t.version,latest:r,hasUpdate:V(r,t.version)>0}}async function ze(t={}){let r=t.onLog??(()=>{}),n=t.restart!==!1,o=t.name||"default",i;try{i=await Ar()}catch(p){return{ok:!1,updated:!1,current:"unknown",previous:"unknown",latest:null,target:null,restart:"skipped",error:p instanceof Error?p.message:String(p)}}let a=i.version,s=t.targetVersion?.trim(),l=null;if(!s||s==="latest"){try{let p=Bun.spawnSync([w("npm"),"view",i.name,"version",`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode===0)l=p.stdout.toString().trim()||null}catch{}if(!l)return{ok:!1,updated:!1,current:a,previous:a,latest:null,target:null,restart:"skipped",error:"Could not check for updates (registry unreachable)"};s=l}if(s===a)return r(`Already on ${a}; nothing to do.`),{ok:!0,updated:!1,current:a,previous:a,latest:l??a,target:s,restart:"skipped"};let c,d=Ge(i.name,s,i.registry);if(d){let p=typeof Bun<"u"?Bun.version:"0.0.0",m=qe(d.engines?.bun,p);if(c=m.message,!m.ok&&!t.allowIncompatible)return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:m.message,restart:"skipped",error:`Refusing to upgrade: ${m.message}. Pass allowIncompatible to override.`}}r(`Installing ${i.name}@${s}...`);try{let p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${s}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode!==0){let m=p.stderr.toString().slice(0,500);return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install failed: ${m||`exit ${p.exitCode}`}`}}}catch(p){return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install threw: ${p instanceof Error?p.message:String(p)}`}}let u=Ye(i.name);if(!u.ok){r(`Smoke test failed at "${u.step}" \u2014 rolling back to ${a}.`);let p=!1;try{p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${a}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"}).exitCode===0}catch{}return{ok:!1,updated:!1,current:p?a:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:p,restart:"skipped",error:`Post-install smoke test failed at "${u.step}"${u.detail?`: ${u.detail}`:""}. ${p?"Rolled back.":"Rollback FAILED \u2014 reinstall manually."}`}}let g={kind:"skipped"};if(n)r(`Waiting for agent "${o}" to become idle before restart...`),g=await tt(o,t.restartBudgetMs);return r(`Updated to ${s}.`),{ok:!0,updated:!0,current:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:!1,restart:g.kind,restartError:g.kind==="error"?g.message:void 0}}function rt(t){let r=/^(?:ssh:\/\/)?(?:([^@\s]+)@)?([^:/\s]+)(?::(\d+))?$/.exec(t.trim());if(!r)throw Error(`Could not parse SSH target: ${t}`);let n=Boolean(r[1]),o=Boolean(r[3]);if(!n&&!o&&!t.includes(":"))return{alias:r[2],host:r[2]};return{user:r[1],host:r[2],port:r[3]?Number(r[3]):void 0}}class K{mode="ssh";id;target;constructor(t){if(this.target=t,t.alias)this.id=`ssh://${t.alias}`;else{let r=t.user?`${t.user}@`:"",n=t.port?`:${t.port}`:"";this.id=`ssh://${r}${t.host}${n}`}}sshArgv(){let t=["ssh","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];if(this.target.identityFile)t.push("-i",this.target.identityFile);if(this.target.port)t.push("-p",String(this.target.port));return t.push(this.target.alias??(this.target.user?`${this.target.user}@${this.target.host}`:this.target.host)),t}async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=t.map(_).join(" "),o=[...this.sshArgv(),n],i=Bun.spawnSync(o,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:i.exitCode??1,stdout:i.stdout.toString(),stderr:i.stderr.toString()}}async upload(t,r,n){let o=[...this.sshArgv(),`cat > ${_(t)} && chmod ${(n??384).toString(8)} ${_(t)}`],i=Bun.spawn(o,{stdin:"pipe",stdout:"pipe",stderr:"pipe"}),a=i.stdin;a.write(typeof r==="string"?r:Buffer.from(r).toString("binary")),await a.end();let s=await i.exited;if(s!==0){let l=await new Response(i.stderr).text();throw Error(`upload to ${t} failed (exit ${s}): ${l}`)}}async close(){}}function _(t){if(/^[A-Za-z0-9._\-/=:]+$/.test(t))return t;return`'${t.replace(/'/g,"'\\''")}'`}class W{mode="local";id="local";async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=Bun.spawnSync(t,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:n.exitCode??1,stdout:n.stdout.toString(),stderr:n.stderr.toString()}}async upload(t,r,n){await Bun.write(t,r);try{let{chmodSync:o}=await import("fs");o(t,n??384)}catch{}}async close(){}}function et(t,r){let n=/^([a-z]+):\/\//.exec(t)?.[1];if(n==="local"||t.trim()==="local"||t.trim()==="localhost")return new W;if(!n||n==="ssh"){let o=rt(t);if(r?.identityFile)o.identityFile=r.identityFile;return new K(o)}throw Error(`Unsupported install transport scheme: ${n}://. Supported today: ssh:// (and bare host or ssh_config alias). Future: winrm://, ssm://, docker://, k8s://`)}var nt=/^[A-Za-z0-9._+-]+$/,ot=/^(?:@[a-z0-9][a-z0-9._-]{0,127}\/)?[a-z0-9][a-z0-9._-]{0,127}(?:@[A-Za-z0-9][A-Za-z0-9._+-]{0,127})?$/,it=/^\d+[smhdw]?$/,st=/^[a-z0-9:_-]{1,64}$/,at=/[`$;&|<>'"\\]/,ct=/['"`$\s;|&<>()\\]/;function G(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n<=31||n===127)return!0}return!1}function dt(t){if(!t||t.length>128||t.startsWith("-")||!nt.test(t))throw Error(`Invalid agent version: ${t}`);return t}function ht(t){if(!t||t.length>2048||G(t)||ct.test(t))throw Error(`Invalid registry URL: ${t}`);let r;try{r=new URL(t)}catch{throw Error(`Invalid registry URL: ${t}`)}if(r.protocol!=="http:"&&r.protocol!=="https:"||!r.hostname)throw Error(`Invalid registry URL: ${t}`);return t}function ft(t){let r=t.trim();if(!r||r.includes("..")||!ot.test(r))throw Error(`Invalid plugin package name: ${t}`);return r}function pt(t){let r=t.trim();if(!r||r.length>16||!it.test(r))throw Error(`Invalid --expires-in value: ${t}`);return r}function Lr(t){let r=t.split(",").map((n)=>n.trim()).filter(Boolean);if(r.length===0)throw Error(`Invalid --permissions value: ${t}`);for(let n of r)if(!st.test(n))throw Error(`Invalid --permissions value: ${t}`);return r.join(",")}function mt(t){let r=t.trim();if(!r||r.length>128||r.startsWith("-")||G(r)||at.test(r))throw Error(`Invalid --label value: ${t}`);return r}function Pt(t,r){let n=ht(t),o=dt(r);return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; npm_config_registry="$1" bun install -g @vibecontrols/agent@"$2" --no-cache',"_",n,o]}function Mt(t){return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; vibe plugin install "$1"',"_",ft(t)]}function Dt(t){let r=mt(t.label),n=Lr(t.scope),o=t.expiresIn?pt(t.expiresIn):void 0,i=[];if(t.json)i.push("--json");if(t.emitDefaultKey)i.push("--emit-default-key");let a=i.length>0?`${i.join(" ")} `:"";if(o)return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" --expires-in "$3" 2>/dev/null`,"_",r,n,o];return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" 2>/dev/null`,"_",r,n]}async function J(t,r,n){let o=`${t.tunnelUrl.replace(/\/$/,"")}${r}`;try{let i=await fetch(o,{method:n.method??"GET",headers:{"x-agent-api-key":t.apiKey,"content-type":n.body?"application/json":"application/octet-stream"},body:n.body?JSON.stringify(n.body):void 0,signal:AbortSignal.timeout(n.timeoutMs??30000)});if(i.status===200||i.status===201||i.status===204){let s=await i.json().catch(()=>{return});return{ok:!0,status:i.status,data:s}}let a=await i.text().catch(()=>"");return{ok:!1,status:i.status,error:a}}catch(i){return{ok:!1,status:0,error:i instanceof Error?i.message:String(i)}}}async function Se(t,r,n={}){let o=Je(t);if(!o)return{ok:!1,status:0,error:`No peer with id ${t}`};let i=await J(o,r,n);if(i.ok)return ke(o.id,{lastReachable:new Date().toISOString()}),i;if(!(i.status===401||i.status===0||i.status===502||i.status===503||i.status===504))return i;if(!o.agentRecordId||!T.isConfigured())return i;let s=null;try{s=await T.lookupPeerAgent(o.agentRecordId,n.operation??"peer-call")}catch(d){e().logger.warn("peer-client","Backend rotation lookup failed",{peerId:t,error:d instanceof Error?d.message:String(d)})}if(!s)return i;ke(o.id,{tunnelUrl:s.tunnelUrl,apiKey:s.apiKey});let l={...o,tunnelUrl:s.tunnelUrl,apiKey:s.apiKey};return{...await J(l,r,n),rotated:!0}}
17
- export{Ze,Ot,Ti,xi,nr,bi,sr,wi,ut,te,re,ae,qi,or,Nr,rn,ar,lt,Ne,Ri,Je,gt,kr,We,ke,Bt,Xe,Ar,Le,ze,et,dt,ht,ft,pt,Lr,mt,Pt,Mt,Dt,Se};
16
+ `);continue}if(s.toLowerCase()==="a"){for(let c of r)o.add(c.key);continue}if(s.toLowerCase()==="n"){o.clear();for(let c of r)if(c.mandatory)o.add(c.key);continue}let l=s.split(/[\s,]+/u).filter(Boolean);for(let c of l){let d=Number.parseInt(c,10);if(!Number.isFinite(d)||d<1||d>r.length)continue;let u=r[d-1];if(!u||u.mandatory)continue;if(o.has(u.key))o.delete(u.key);else o.add(u.key)}}}finally{process.stdin.pause()}}function bi(t){let r=new Set(Y.map((o)=>o.key)),n=new Set;for(let o of t.split(",").map((i)=>i.trim().toLowerCase()))if(r.has(o))n.add(o);for(let o of Y)if(o.mandatory)n.add(o.key);return n}function sr(){return new Set(Y.filter((t)=>t.defaultSelected||t.mandatory).map((t)=>t.key))}function wi(t,r,n,o,i){let a={acceptedAt:new Date().toISOString(),agentVersion:o,abilities:[...n],providers:i?[...i]:void 0,tools:r.tools.map((s)=>({name:s.name,reason:s.reason})),plugins:r.plugins.map((s)=>({packageName:s.packageName,reason:s.reason}))};N(v(t),JSON.stringify(a,null,2))}function ut(t,r){let n=oe(t),o={acceptedAt:n?.acceptedAt??new Date().toISOString(),agentVersion:r.agentVersion??n?.agentVersion,abilities:r.abilities?[...r.abilities]:n?.abilities,providers:r.providers?[...r.providers]:n?.providers,tools:n?.tools??[],plugins:n?.plugins??[]};N(v(t),JSON.stringify(o,null,2))}function oe(t){try{let r=v(t);if(!q(r))return null;return JSON.parse(x(r,"utf8"))}catch{return null}}import{createHash as ie}from"crypto";import{homedir as le,tmpdir as ce}from"os";import*as f from"path";import{spawn as A}from"child_process";import{createWriteStream as ue,existsSync as de,promises as h}from"fs";import{Readable as pe}from"stream";import{pipeline as ge}from"stream/promises";function fe(){let t=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${t}`}function me(){return f.join(le(),".boff","vibecontrols","tools")}function L(t,r){let n=r??t;if(process.platform==="win32"&&!n.toLowerCase().endsWith(".exe"))return`${n}.exe`;return n}function he(t,r,n){return f.join(n??me(),t,L(t,r))}async function O(t,r){if(!r.versionMatcher)return!0;return new Promise((n)=>{let o=A(t,r.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),i="";o.stdout.on("data",(a)=>i+=a.toString()),o.stderr.on("data",(a)=>i+=a.toString()),o.on("close",()=>{try{n(new RegExp(r.versionMatcher).test(i))}catch{n(!1)}}),o.on("error",()=>n(!1))})}async function ye(t){let r=t.platform??fe(),n=L(t.name,t.binaryName),o=he(t.name,t.binaryName,t.cacheRoot);if(de(o)&&await O(o,t))return o;try{let a=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(t.binaryName??t.name,{PATH:process.env.PATH}):null;if(a&&await O(a,t))return t.log?.info?.(`[install] using PATH binary ${t.name} (${a})`),a}catch{}let i=t.downloads[r];if(!i)throw Error(`[install] no download manifest entry for ${t.name} on ${r}`);return t.log?.info?.(`[install] downloading ${t.name} for ${r}`),await h.mkdir(f.dirname(o),{recursive:!0}),await we(i,o,n,t.name),t.log?.info?.(`[install] installed ${t.name} \u2192 ${o}`),o}async function we(t,r,n,o){f.dirname(r);let i=f.join(ce(),`vibe-install-${o}-${process.pid}`);await h.mkdir(i,{recursive:!0});let a=f.join(i,"artifact");try{let s=await fetch(t.url,{redirect:"follow"});if(!s.ok)throw Error(`download failed (${s.status}) for ${t.url}`);if(!s.body)throw Error(`empty response body for ${t.url}`);if(await ge(pe.fromWeb(s.body),ue(a)),t.sha256){let c=ie("sha256").update(await h.readFile(a)).digest("hex");if(c!==t.sha256)throw Error(`sha256 mismatch for ${o}: expected ${t.sha256}, got ${c}`)}let l=t.archive??(t.url.endsWith(".tar.gz")||t.url.endsWith(".tgz")?"tar.gz":t.url.endsWith(".zip")?"zip":"raw");if(l==="raw")await h.copyFile(a,r);else{if(l==="tar.gz")await E("tar",["-xzf",a,"-C",i]);else await be(a,i);let c=t.binaryWithinArchive??n;await h.copyFile(f.join(i,c),r)}if(process.platform!=="win32")await h.chmod(r,493)}finally{await h.rm(i,{recursive:!0,force:!0})}}async function be(t,r){try{await E("unzip",["-q","-o",t,"-d",r]);return}catch(n){if(process.platform!=="win32")throw n;await E("tar",["-xf",t,"-C",r])}}async function E(t,r){return new Promise((n,o)=>{let i=A(t,r,{stdio:["ignore","ignore","pipe"]}),a="";i.stderr.on("data",(s)=>a+=s.toString()),i.on("close",(s)=>s===0?n():o(Error(`${t} exit ${s}: ${a}`))),i.on("error",o)})}var P="https://github.com/cloudflare/cloudflared/releases/latest/download",ke={"linux-x64":{url:`${P}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${P}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${P}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${P}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${P}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${P}/cloudflared-windows-arm64.exe`,archive:"raw"}},Pe=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function M(t,r){let n=r?.log??{},o;try{o=await ye({name:"cloudflared",downloads:ke,versionMatcher:"cloudflared version",log:n})}catch(s){return n.warn?.(`quick-tunnel: could not obtain cloudflared: ${String(s)}`),null}let i;try{i=A(o,["tunnel","--url",`http://127.0.0.1:${t}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch(s){return n.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String(s)}`),null}let a=await new Promise((s)=>{let l=!1,c=(g)=>{if(l)return;l=!0,s(g)},d=setTimeout(()=>{n.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),c(null)},r?.timeoutMs??30000),u=(g)=>{let p=g.toString("utf8").match(Pe);if(p)clearTimeout(d),c(p[0])};i.stdout?.on("data",u),i.stderr?.on("data",u),i.on("error",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(g)}`),c(null)}),i.on("exit",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared exited (code=${g})`),c(null)})});if(!a)return null;return{url:a,child:i}}import{existsSync as D,mkdirSync as ve,readFileSync as xe,writeFileSync as $e,unlinkSync as Re}from"fs";import{dirname as Te,join as F}from"path";import{readdirSync as Ee}from"fs";function C(t){return F(t??I(),"tunnel.state.json")}function j(t,r){let n=C(r);try{ve(Te(n),{recursive:!0}),$e(n,JSON.stringify(t,null,2),"utf8")}catch(o){e().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(o)})}}function te(t){let r=C(t);if(!D(r))return null;try{let n=xe(r,"utf8"),o=JSON.parse(n);if(typeof o.pid!=="number")return null;return o}catch(n){return e().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(n)}),null}}function re(t){let r=C(t);if(!D(r))return;try{Re(r)}catch{}}function ae(t){return b().isProcessAlive(t)}function qi(t){let r=[];if(t?.allProfiles){let o;try{o=ne()}catch{return r}let i;try{i=Ee(o)}catch{return r}for(let a of i){let s=F(o,a),l=te(s);if(l)r.push({...l,alive:ae(l.pid),profileDir:s})}return r}let n=te();if(n)r.push({...n,alive:ae(n.pid),profileDir:I()});return r}function or(t){return t.replace(/[^A-Za-z0-9_]/g,"_")}function S(){return(B()??e()).tunnel}async function Dr(t,r){let n=S();Ie(t),Ae();let o=process.env.AGENT_TUNNEL_URL;if(o){let s=xt(o);if(!s)return e().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;n.url=s,n.externalUrl=!0,e().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${s}`);try{Z.emit("tunnel.url_assigned",{provider:"external"})}catch{}return s}let i=r.port,a=await M(i,{log:{info:(s)=>e().logger.info("tunnel-bootstrap",s),warn:(s)=>e().logger.warn("tunnel-bootstrap",s)}});if(!a)return e().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(n.child=a.child,n.url=a.url,n.url){e().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${n.url}`);try{let c=new URL(n.url).hostname.split(".");if(c.length>=2)Jt("."+c.slice(-2).join("."))}catch{}try{Z.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let s=or(R());if(process.env[`AGENT_TUNNEL_URL_${s}`]=n.url,n.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${s}`]=String(n.child.pid),j({pid:n.child.pid,url:n.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:i,cmd:`cloudflared tunnel --url http://127.0.0.1:${i}`})}return n.url}function rn(){let t=S();if(t.externalUrl)return!1;if(!t.child||t.child.killed)return!1;let r=t.child.pid;if(r===void 0)return!1;try{process.kill(r,0)}catch{return!1}return t.child=null,re(),e().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${r}) to plugin \u2014 process kept alive`),!0}function ar(){let t=S();if(t.externalUrl){re();return}let r=t.child;if(t.child=null,re(),!r||r.killed)return;try{r.kill("SIGTERM"),e().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function lt(){return S().url}function Ae(){let t=te();if(!t)return;if(!ae(t.pid)){re();return}try{process.kill(t.pid,"SIGTERM"),e().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:t.pid,provider:t.provider})}catch{}let r=Date.now();while(Date.now()-r<2000&&ae(t.pid))Bun.sleepSync(50);if(ae(t.pid))try{process.kill(t.pid,"SIGKILL")}catch{}re()}function Ie(t){let r={name:"bootstrap",async getActiveTunnelUrl(){return S().url}};t.registerProvider("tunnel",r,"bootstrap")}import{existsSync as _e,mkdirSync as Oe,readFileSync as Be,renameSync as Me,writeFileSync as je}from"fs";import{dirname as He,join as Ve}from"path";var De=["tunnel:read","session:list","session:share:read","session:share:write","plugin:list","plugin:install","plugin:remove","log:read","diagnostics:read","key:mint","mesh:forward","admin"];function z(t){return Ve(t??I(),"agent-network.json")}function y(t){let r=z(t);if(!_e(r))return{schemaVersion:1,peers:[]};let n=Be(r,"utf8");try{let o=JSON.parse(n);if(!o||!Array.isArray(o.peers))return{schemaVersion:1,peers:[]};return o}catch{return{schemaVersion:1,peers:[]}}}function _(t,r){let n=z(r);Oe(He(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;je(o,JSON.stringify(t,null,2),{mode:384}),Me(o,n)}function Ri(t){return y(t).peers}function Je(t,r){return y(r).peers.find((n)=>n.id===t)??null}function H(t,r){if(r.workspaceId&&t.workspaceId&&t.workspaceId!==r.workspaceId)return!1;if(r.ownerUserId)return(t.ownerUserId??r.ownerUserId)===r.ownerUserId;return!0}function gt(t,r){return y(r).peers.filter((n)=>H(n,t))}function Nr(t,r,n){return y(n).peers.find((o)=>o.agentRecordId===t&&H(o,r))??null}function We(t,r){let n=y(r),o=n.peers.findIndex((i)=>i.id===t.id);if(o>=0)n.peers[o]={...n.peers[o],...t};else n.peers.push(t);return _(n,r),t}function Ne(t,r,n){let o=y(n),i=o.peers.findIndex((a)=>a.id===t);if(i<0)return null;return o.peers[i]={...o.peers[i],...r},_(o,n),o.peers[i]}function Bt(t,r){let n=y(r),o=n.peers.length;if(n.peers=n.peers.filter((i)=>i.id!==t),n.peers.length===o)return!1;return _(n,r),!0}function Xe(t){let r=new Set(De);return[...t].filter((n)=>r.has(n)).map((n)=>n)}import{join as Ke}from"path";function w(t){let r=b();return r.which(t)??`${t}${r.executableSuffix}`}async function Ar(){let t=["..","../..","../../.."];for(let r of t)try{let n=Ke(import.meta.dir,r,"package.json"),o=await Bun.file(n).json(),{name:i,version:a}=o;if(i&&a){let s=o.publishConfig;return{name:i,version:a,registry:s?.registry??se()}}}catch{}throw Error("package.json not found")}function Ge(t,r,n){try{let o=Bun.spawnSync([w("npm"),"view",`${t}@${r}`,"--json",`--registry=${n}`],{stdout:"pipe",stderr:"pipe"});if(o.exitCode!==0)return null;let i=JSON.parse(o.stdout.toString());return Array.isArray(i)?i[0]??null:i}catch{return null}}function V(t,r){let n=(a)=>a.replace(/^[\^~>=<v]+/,"").split(/[.+-]/).map((s)=>Number(s)||0),o=n(t),i=n(r);for(let a=0;a<Math.max(o.length,i.length);a++){let s=o[a]??0,l=i[a]??0;if(s!==l)return s-l}return 0}function qe(t,r){if(!t)return{ok:!0,message:""};let n=t.replace(/^[\^~]/,"").replace(/^>=?\s*/,"");if(V(r,n)>=0)return{ok:!0,message:`bun ${r} >= ${n}`};return{ok:!1,message:`requires bun ${t}, this process is bun ${r}`}}function Qe(t){try{let r=w("npm"),n=Bun.spawnSync([r,"root","-g"],{stdout:"pipe",stderr:"pipe"});if(n.exitCode!==0)return null;return`${n.stdout.toString().trim()}/${t}`}catch{return null}}function Ye(t){let r=Qe(t);if(!r)return{ok:!0,step:"(skipped, install root unknown)"};let n=`${r}/dist/cli.js`,o=(l,c,d)=>{try{let u=w("bun"),g=Bun.spawnSync([u,n,...l],{stdout:"pipe",stderr:"pipe",timeout:d});if(g.exitCode===0)return{ok:!0,step:c};return{ok:!1,step:c,detail:g.stderr.toString().slice(0,300)||`exit ${g.exitCode}`}}catch(u){return{ok:!1,step:c,detail:String(u)}}},i=o(["--version"],"vibe --version",1e4);if(!i.ok)return i;let a=o(["info"],"vibe info",15000);if(!a.ok)return a;let s=o(["plugin","list","--json"],"vibe plugin list",30000);if(!s.ok)return s;return{ok:!0,step:"all checks passed"}}async function tt(t,r=60000){try{let n=new k,o=await n.getStatus(t);if(!o||o.status!=="running")return{kind:"not-running"};let i=`http://localhost:${o.port}`,a;try{a=await Fe(i)}catch{}let s={};if(a)s["x-agent-api-key"]=a;let l=1000,c=Date.now();while(Date.now()-c<r){try{let d=await fetch(`${i}/api/profiles/${encodeURIComponent(t)}/stats/inflight`,{headers:s,signal:AbortSignal.timeout(2000)});if(d.ok){let u=await d.json();if(typeof u.inflight==="number"&&u.inflight===0){let g=o.config;return await n.restart(t,g),{kind:"restarted"}}}}catch{}await new Promise((d)=>setTimeout(d,l))}return{kind:"still-busy"}}catch(n){return{kind:"error",message:n instanceof Error?n.message:String(n)}}}async function Le(){let t;try{t=await Ar()}catch(n){return{name:"@vibecontrols/agent",registry:se(),current:"unknown",latest:null,hasUpdate:!1,error:n instanceof Error?n.message:String(n)}}let r=null;try{let n=Bun.spawnSync([w("npm"),"view",t.name,"version",`--registry=${t.registry}`],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0)r=n.stdout.toString().trim()||null}catch{}if(!r)return{name:t.name,registry:t.registry,current:t.version,latest:null,hasUpdate:!1,error:"Could not reach the registry to check for updates"};return{name:t.name,registry:t.registry,current:t.version,latest:r,hasUpdate:V(r,t.version)>0}}async function ze(t={}){let r=t.onLog??(()=>{}),n=t.restart!==!1,o=t.name||"default",i;try{i=await Ar()}catch(p){return{ok:!1,updated:!1,current:"unknown",previous:"unknown",latest:null,target:null,restart:"skipped",error:p instanceof Error?p.message:String(p)}}let a=i.version,s=t.targetVersion?.trim(),l=null;if(!s||s==="latest"){try{let p=Bun.spawnSync([w("npm"),"view",i.name,"version",`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode===0)l=p.stdout.toString().trim()||null}catch{}if(!l)return{ok:!1,updated:!1,current:a,previous:a,latest:null,target:null,restart:"skipped",error:"Could not check for updates (registry unreachable)"};s=l}if(s===a)return r(`Already on ${a}; nothing to do.`),{ok:!0,updated:!1,current:a,previous:a,latest:l??a,target:s,restart:"skipped"};let c,d=Ge(i.name,s,i.registry);if(d){let p=typeof Bun<"u"?Bun.version:"0.0.0",m=qe(d.engines?.bun,p);if(c=m.message,!m.ok&&!t.allowIncompatible)return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:m.message,restart:"skipped",error:`Refusing to upgrade: ${m.message}. Pass allowIncompatible to override.`}}r(`Installing ${i.name}@${s}...`);try{let p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${s}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode!==0){let m=p.stderr.toString().slice(0,500);return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install failed: ${m||`exit ${p.exitCode}`}`}}}catch(p){return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install threw: ${p instanceof Error?p.message:String(p)}`}}let u=Ye(i.name);if(!u.ok){r(`Smoke test failed at "${u.step}" \u2014 rolling back to ${a}.`);let p=!1;try{p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${a}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"}).exitCode===0}catch{}return{ok:!1,updated:!1,current:p?a:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:p,restart:"skipped",error:`Post-install smoke test failed at "${u.step}"${u.detail?`: ${u.detail}`:""}. ${p?"Rolled back.":"Rollback FAILED \u2014 reinstall manually."}`}}let g={kind:"skipped"};if(n)r(`Waiting for agent "${o}" to become idle before restart...`),g=await tt(o,t.restartBudgetMs);return r(`Updated to ${s}.`),{ok:!0,updated:!0,current:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:!1,restart:g.kind,restartError:g.kind==="error"?g.message:void 0}}function rt(t){let r=/^(?:ssh:\/\/)?(?:([^@\s]+)@)?([^:/\s]+)(?::(\d+))?$/.exec(t.trim());if(!r)throw Error(`Could not parse SSH target: ${t}`);let n=Boolean(r[1]),o=Boolean(r[3]);if(!n&&!o&&!t.includes(":"))return{alias:r[2],host:r[2]};return{user:r[1],host:r[2],port:r[3]?Number(r[3]):void 0}}class K{mode="ssh";id;target;constructor(t){if(this.target=t,t.alias)this.id=`ssh://${t.alias}`;else{let r=t.user?`${t.user}@`:"",n=t.port?`:${t.port}`:"";this.id=`ssh://${r}${t.host}${n}`}}sshArgv(){let t=["ssh","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];if(this.target.identityFile)t.push("-i",this.target.identityFile);if(this.target.port)t.push("-p",String(this.target.port));return t.push(this.target.alias??(this.target.user?`${this.target.user}@${this.target.host}`:this.target.host)),t}async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=t.map(U).join(" "),o=[...this.sshArgv(),n],i=Bun.spawnSync(o,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:i.exitCode??1,stdout:i.stdout.toString(),stderr:i.stderr.toString()}}async upload(t,r,n){let o=[...this.sshArgv(),`cat > ${U(t)} && chmod ${(n??384).toString(8)} ${U(t)}`],i=Bun.spawn(o,{stdin:"pipe",stdout:"pipe",stderr:"pipe"}),a=i.stdin;a.write(typeof r==="string"?r:Buffer.from(r).toString("binary")),await a.end();let s=await i.exited;if(s!==0){let l=await new Response(i.stderr).text();throw Error(`upload to ${t} failed (exit ${s}): ${l}`)}}async close(){}}function U(t){if(/^[A-Za-z0-9._\-/=:]+$/.test(t))return t;return`'${t.replace(/'/g,"'\\''")}'`}class W{mode="local";id="local";async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=Bun.spawnSync(t,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:n.exitCode??1,stdout:n.stdout.toString(),stderr:n.stderr.toString()}}async upload(t,r,n){await Bun.write(t,r);try{let{chmodSync:o}=await import("fs");o(t,n??384)}catch{}}async close(){}}function et(t,r){let n=/^([a-z]+):\/\//.exec(t)?.[1];if(n==="local"||t.trim()==="local"||t.trim()==="localhost")return new W;if(!n||n==="ssh"){let o=rt(t);if(r?.identityFile)o.identityFile=r.identityFile;return new K(o)}throw Error(`Unsupported install transport scheme: ${n}://. Supported today: ssh:// (and bare host or ssh_config alias). Future: winrm://, ssm://, docker://, k8s://`)}var nt=/^[A-Za-z0-9._+-]+$/,ot=/^(?:@[a-z0-9][a-z0-9._-]{0,127}\/)?[a-z0-9][a-z0-9._-]{0,127}(?:@[A-Za-z0-9][A-Za-z0-9._+-]{0,127})?$/,it=/^\d+[smhdw]?$/,st=/^[a-z0-9:_-]{1,64}$/,at=/[`$;&|<>'"\\]/,ct=/['"`$\s;|&<>()\\]/;function G(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n<=31||n===127)return!0}return!1}function dt(t){if(!t||t.length>128||t.startsWith("-")||!nt.test(t))throw Error(`Invalid agent version: ${t}`);return t}function ht(t){if(!t||t.length>2048||G(t)||ct.test(t))throw Error(`Invalid registry URL: ${t}`);let r;try{r=new URL(t)}catch{throw Error(`Invalid registry URL: ${t}`)}if(r.protocol!=="http:"&&r.protocol!=="https:"||!r.hostname)throw Error(`Invalid registry URL: ${t}`);return t}function ft(t){let r=t.trim();if(!r||r.includes("..")||!ot.test(r))throw Error(`Invalid plugin package name: ${t}`);return r}function pt(t){let r=t.trim();if(!r||r.length>16||!it.test(r))throw Error(`Invalid --expires-in value: ${t}`);return r}function Lr(t){let r=t.split(",").map((n)=>n.trim()).filter(Boolean);if(r.length===0)throw Error(`Invalid --permissions value: ${t}`);for(let n of r)if(!st.test(n))throw Error(`Invalid --permissions value: ${t}`);return r.join(",")}function mt(t){let r=t.trim();if(!r||r.length>128||r.startsWith("-")||G(r)||at.test(r))throw Error(`Invalid --label value: ${t}`);return r}function Pt(t,r){let n=ht(t),o=dt(r);return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; npm_config_registry="$1" bun install -g @vibecontrols/agent@"$2" --no-cache',"_",n,o]}function Mt(t){return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; vibe plugin install "$1"',"_",ft(t)]}function kt(t){let r=mt(t.label),n=Lr(t.scope),o=t.expiresIn?pt(t.expiresIn):void 0,i=[];if(t.json)i.push("--json");if(t.emitDefaultKey)i.push("--emit-default-key");let a=i.length>0?`${i.join(" ")} `:"";if(o)return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" --expires-in "$3" 2>/dev/null`,"_",r,n,o];return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" 2>/dev/null`,"_",r,n]}async function J(t,r,n){let o=`${t.tunnelUrl.replace(/\/$/,"")}${r}`;try{let i=await fetch(o,{method:n.method??"GET",headers:{"x-agent-api-key":t.apiKey,"content-type":n.body?"application/json":"application/octet-stream"},body:n.body?JSON.stringify(n.body):void 0,signal:AbortSignal.timeout(n.timeoutMs??30000)});if(i.status===200||i.status===201||i.status===204){let s=await i.json().catch(()=>{return});return{ok:!0,status:i.status,data:s}}let a=await i.text().catch(()=>"");return{ok:!1,status:i.status,error:a}}catch(i){return{ok:!1,status:0,error:i instanceof Error?i.message:String(i)}}}async function Se(t,r,n={}){let o=Je(t);if(!o)return{ok:!1,status:0,error:`No peer with id ${t}`};let i=await J(o,r,n);if(i.ok)return Ne(o.id,{lastReachable:new Date().toISOString()}),i;if(!(i.status===401||i.status===0||i.status===502||i.status===503||i.status===504))return i;if(!o.agentRecordId||!T.isConfigured())return i;let s=null;try{s=await T.lookupPeerAgent(o.agentRecordId,n.operation??"peer-call")}catch(d){e().logger.warn("peer-client","Backend rotation lookup failed",{peerId:t,error:d instanceof Error?d.message:String(d)})}if(!s)return i;Ne(o.id,{tunnelUrl:s.tunnelUrl,apiKey:s.apiKey});let l={...o,tunnelUrl:s.tunnelUrl,apiKey:s.apiKey};return{...await J(l,r,n),rotated:!0}}
17
+ export{Ze,Ot,Ti,xi,nr,bi,sr,wi,ut,te,re,ae,qi,or,Dr,rn,ar,lt,De,Ri,Je,gt,Nr,We,Ne,Bt,Xe,Ar,Le,ze,et,dt,ht,ft,pt,Lr,mt,Pt,Mt,kt,Se};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{r,E}from"./index-1t74r13z.js";import{oe,Ft}from"./index-ppxayc0x.js";import"./index-7wm4bqx5.js";import"./index-j99tkngg.js";import{s,A,l,o,g,n,F,v,H}from"./index-12gb48hg.js";import{Q}from"./index-sq5j8bjn.js";import{_,y,u}from"./index-v77bb0rm.js";import{f,m,S,q,Te,ge}from"./index-damc6cvc.js";import{promises as b}from"fs";import P from"path";async function I(d){try{let i=await b.readdir(d);if(i.includes("package.json")){try{let t=JSON.parse(await b.readFile(P.join(d,"package.json"),"utf8")),e={...t.dependencies,...t.devDependencies};if(e.react||e["@types/react"])return"react";if(e.vue||e["@vue/cli"])return"vue";if(e.angular||e["@angular/core"])return"angular";if(e.next||e["@types/next"])return"nextjs";if(e.nuxt||e["@nuxt/core"])return"nuxtjs";if(e.svelte||e["@sveltejs/kit"])return"svelte";if(e.express||e.fastify||e.koa)return"nodejs-backend";if(e.electron)return"electron";if(e.vite)return"vite"}catch{}return"nodejs"}if(i.includes("setup.py")||i.includes("requirements.txt")||i.includes("pyproject.toml")||i.includes("Pipfile")){if(i.includes("manage.py"))return"django";if(i.includes("app.py"))return"flask";return"python"}if(i.includes("go.mod"))return"go";if(i.includes("Cargo.toml"))return"rust";if(i.includes("pom.xml"))return"maven";if(i.includes("build.gradle")||i.includes("build.gradle.kts"))return"gradle";if(i.includes("Gemfile"))return"ruby";if(i.includes("composer.json"))return"php";if(i.some((t)=>t.endsWith(".csproj")||t.endsWith(".sln")))return"dotnet";if(i.includes("CMakeLists.txt")||i.includes("Makefile"))return"cpp";if(i.includes("Package.swift"))return"swift";if(i.includes("pubspec.yaml"))return"flutter";if(i.some((t)=>t.endsWith(".tf")))return"terraform";if(i.includes("Dockerfile"))return"docker"}catch{}return}async function G(d){try{let i=["vite.config.ts","vite.config.js"];for(let t of i)try{let a=(await b.readFile(P.join(d,t),"utf-8")).match(/port:\s*(\d+)/);if(a)return parseInt(a[1],10)}catch{}}catch{}return}var O=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),N=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),J=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function C(d,i,t,e={visited:0},a=0){let R=[];if(a>N||e.visited>=J)return R;e.visited+=1;try{let c=await Ft(d);if(c.some((p)=>p.name===".git"&&p.isDirectory())){if(R.push({path:d,name:P.basename(d),parentPath:t,isSubmodule:!!t,projectType:await I(d),vitePort:await G(d)}),!i)return R;t=d}for(let p of c)if(p.isDirectory()&&!p.isSymbolicLink()&&!O.has(p.name)&&!p.name.startsWith(".")){let j=P.join(d,p.name),x=await C(j,i,t,e,a+1);R.push(...x)}}catch{}return R}function T(d){let{db:i}=d;return new E().get("/",async()=>({repositories:await i.getAllGitRepositories()})).get("/:id",async({params:t,set:e})=>{let a=await i.getGitRepository(t.id);if(!a)return e.status=404,{error:"Repository not found"};return{repository:a}}).post("/scan",async({body:t,set:e})=>{try{let a=(await oe(t.directory,{mustExist:!0})).path;if(!(await b.stat(a)).isDirectory())return e.status=400,{error:"Path is not a directory"};let c=await C(a,t.includeSubmodules??!0),h=[];for(let p of c){let j=await i.getGitRepositoryByPath(p.path);if(j)await i.updateGitRepository(j.id,p),h.push({...j,...p});else{let x=await i.createGitRepository({id:globalThis.crypto.randomUUID(),...p});h.push(x)}}return{repositories:h,scannedPath:a,totalFound:h.length}}catch(a){return e.status=500,{error:"Failed to scan directory",details:String(a)}}},{body:r.Object({directory:r.String(),includeSubmodules:r.Optional(r.Boolean())})}).put("/:id",async({params:t,body:e,set:a})=>{if(!await i.getGitRepository(t.id))return a.status=404,{error:"Repository not found"};try{return await i.updateGitRepository(t.id,e),{success:!0}}catch(c){return a.status=500,{error:"Failed to update repository",details:String(c)}}},{body:r.Object({name:r.Optional(r.String()),projectType:r.Optional(r.String()),vitePort:r.Optional(r.Number())})}).delete("/:id",async({params:t,set:e})=>{if(!await i.getGitRepository(t.id))return e.status=404,{error:"Repository not found"};try{return await i.deleteGitRepository(t.id),{success:!0}}catch(R){return e.status=500,{error:"Failed to delete repository",details:String(R)}}}).post("/fix-hierarchy",async({set:t})=>{try{let e=await i.fixGitHierarchy(),a=await i.getAllGitRepositories();return{success:!0,fixed:e.fixed,total:a.length}}catch(e){return t.status=500,{error:"Failed to fix hierarchy",details:String(e)}}})}var w="http://localhost:3005";function k(d){let i=d.command("git").description("Manage git repositories");i.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e));await y({mode:_(e),fetchData:async()=>(await S(a,`/api/profiles/${R}/git`)).repositories||[],plain:(c)=>{if(!c||c.length===0){o("No git repositories found.");return}g("Git Repositories"),F(c.map((h)=>({ID:H(h.id),Name:h.name||"-",Path:h.path||"-",Type:h.type||h.projectType||"-",Submodule:h.isSubmodule?"Yes":"No",Scanned:h.scannedAt?v(h.scannedAt):"-"})))},interactive:async(c)=>{if(!c||c.length===0){g("Git Repositories"),o("No git repositories found.");return}let h=c.map((p)=>({id:String(p.id),label:p.name||H(p.id),hint:p.type||p.projectType||"",detail:[`ID: ${p.id}`,`Name: ${p.name??"-"}`,`Path: ${p.path??"-"}`,`Type: ${p.type??p.projectType??"-"}`,`Submodule: ${p.isSubmodule?"Yes":"No"}`,`Scanned: ${p.scannedAt?v(p.scannedAt):"-"}`].join(`
2
+ import{r,E}from"./index-1t74r13z.js";import{oe,Ft}from"./index-ppxayc0x.js";import"./index-nxpw3anc.js";import"./index-30qr1qm3.js";import{s,A,l,o,g,n,F,v,H}from"./index-j9cg16we.js";import{Q}from"./index-sq5j8bjn.js";import{_,y,u}from"./index-v77bb0rm.js";import{f,m,S,q,Te,ge}from"./index-djwa3tm3.js";import{promises as b}from"fs";import P from"path";async function I(d){try{let i=await b.readdir(d);if(i.includes("package.json")){try{let t=JSON.parse(await b.readFile(P.join(d,"package.json"),"utf8")),e={...t.dependencies,...t.devDependencies};if(e.react||e["@types/react"])return"react";if(e.vue||e["@vue/cli"])return"vue";if(e.angular||e["@angular/core"])return"angular";if(e.next||e["@types/next"])return"nextjs";if(e.nuxt||e["@nuxt/core"])return"nuxtjs";if(e.svelte||e["@sveltejs/kit"])return"svelte";if(e.express||e.fastify||e.koa)return"nodejs-backend";if(e.electron)return"electron";if(e.vite)return"vite"}catch{}return"nodejs"}if(i.includes("setup.py")||i.includes("requirements.txt")||i.includes("pyproject.toml")||i.includes("Pipfile")){if(i.includes("manage.py"))return"django";if(i.includes("app.py"))return"flask";return"python"}if(i.includes("go.mod"))return"go";if(i.includes("Cargo.toml"))return"rust";if(i.includes("pom.xml"))return"maven";if(i.includes("build.gradle")||i.includes("build.gradle.kts"))return"gradle";if(i.includes("Gemfile"))return"ruby";if(i.includes("composer.json"))return"php";if(i.some((t)=>t.endsWith(".csproj")||t.endsWith(".sln")))return"dotnet";if(i.includes("CMakeLists.txt")||i.includes("Makefile"))return"cpp";if(i.includes("Package.swift"))return"swift";if(i.includes("pubspec.yaml"))return"flutter";if(i.some((t)=>t.endsWith(".tf")))return"terraform";if(i.includes("Dockerfile"))return"docker"}catch{}return}async function G(d){try{let i=["vite.config.ts","vite.config.js"];for(let t of i)try{let a=(await b.readFile(P.join(d,t),"utf-8")).match(/port:\s*(\d+)/);if(a)return parseInt(a[1],10)}catch{}}catch{}return}var O=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),N=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),J=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function C(d,i,t,e={visited:0},a=0){let R=[];if(a>N||e.visited>=J)return R;e.visited+=1;try{let c=await Ft(d);if(c.some((p)=>p.name===".git"&&p.isDirectory())){if(R.push({path:d,name:P.basename(d),parentPath:t,isSubmodule:!!t,projectType:await I(d),vitePort:await G(d)}),!i)return R;t=d}for(let p of c)if(p.isDirectory()&&!p.isSymbolicLink()&&!O.has(p.name)&&!p.name.startsWith(".")){let j=P.join(d,p.name),x=await C(j,i,t,e,a+1);R.push(...x)}}catch{}return R}function T(d){let{db:i}=d;return new E().get("/",async()=>({repositories:await i.getAllGitRepositories()})).get("/:id",async({params:t,set:e})=>{let a=await i.getGitRepository(t.id);if(!a)return e.status=404,{error:"Repository not found"};return{repository:a}}).post("/scan",async({body:t,set:e})=>{try{let a=(await oe(t.directory,{mustExist:!0})).path;if(!(await b.stat(a)).isDirectory())return e.status=400,{error:"Path is not a directory"};let c=await C(a,t.includeSubmodules??!0),h=[];for(let p of c){let j=await i.getGitRepositoryByPath(p.path);if(j)await i.updateGitRepository(j.id,p),h.push({...j,...p});else{let x=await i.createGitRepository({id:globalThis.crypto.randomUUID(),...p});h.push(x)}}return{repositories:h,scannedPath:a,totalFound:h.length}}catch(a){return e.status=500,{error:"Failed to scan directory",details:String(a)}}},{body:r.Object({directory:r.String(),includeSubmodules:r.Optional(r.Boolean())})}).put("/:id",async({params:t,body:e,set:a})=>{if(!await i.getGitRepository(t.id))return a.status=404,{error:"Repository not found"};try{return await i.updateGitRepository(t.id,e),{success:!0}}catch(c){return a.status=500,{error:"Failed to update repository",details:String(c)}}},{body:r.Object({name:r.Optional(r.String()),projectType:r.Optional(r.String()),vitePort:r.Optional(r.Number())})}).delete("/:id",async({params:t,set:e})=>{if(!await i.getGitRepository(t.id))return e.status=404,{error:"Repository not found"};try{return await i.deleteGitRepository(t.id),{success:!0}}catch(R){return e.status=500,{error:"Failed to delete repository",details:String(R)}}}).post("/fix-hierarchy",async({set:t})=>{try{let e=await i.fixGitHierarchy(),a=await i.getAllGitRepositories();return{success:!0,fixed:e.fixed,total:a.length}}catch(e){return t.status=500,{error:"Failed to fix hierarchy",details:String(e)}}})}var w="http://localhost:3005";function k(d){let i=d.command("git").description("Manage git repositories");i.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e));await y({mode:_(e),fetchData:async()=>(await S(a,`/api/profiles/${R}/git`)).repositories||[],plain:(c)=>{if(!c||c.length===0){o("No git repositories found.");return}g("Git Repositories"),F(c.map((h)=>({ID:H(h.id),Name:h.name||"-",Path:h.path||"-",Type:h.type||h.projectType||"-",Submodule:h.isSubmodule?"Yes":"No",Scanned:h.scannedAt?v(h.scannedAt):"-"})))},interactive:async(c)=>{if(!c||c.length===0){g("Git Repositories"),o("No git repositories found.");return}let h=c.map((p)=>({id:String(p.id),label:p.name||H(p.id),hint:p.type||p.projectType||"",detail:[`ID: ${p.id}`,`Name: ${p.name??"-"}`,`Path: ${p.path??"-"}`,`Type: ${p.type??p.projectType??"-"}`,`Submodule: ${p.isSubmodule?"Yes":"No"}`,`Scanned: ${p.scannedAt?v(p.scannedAt):"-"}`].join(`
3
3
  `)}));await Q({title:`vibe git list \u2014 ${c.length} repo(s)`,rows:h})},json:(c)=>c.map((h)=>({id:h.id,name:h.name??null,path:h.path??null,type:h.type??h.projectType??null,isSubmodule:!!h.isSubmodule,scannedAt:h.scannedAt??null}))})}catch(a){s(A(a))}}),i.command("scan").description("Scan a directory for git repositories").requiredOption("--dir <directory>","Directory to scan").option("--depth <depth>","Scan depth","3").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c=await q(a,`/api/profiles/${R}/git/scan`,{directory:t.dir,depth:parseInt(t.depth,10)});if(u(e,{ok:!0,found:c?.found??c?.repositories?.length??0}))return;if(l("Git scan completed."),c?.found!==void 0)n("Repositories found",c.found);if(c?.repositories)n("Repositories found",c.repositories.length)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}}),i.command("update").description("Update a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--vite-port <port>","Vite dev server port").option("--project-type <type>","Project type").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c={};if(t.vitePort)c.vitePort=parseInt(t.vitePort,10);if(t.projectType)c.projectType=t.projectType;if(await Te(a,`/api/profiles/${R}/git/${t.id}`,c),u(e,{ok:!0,id:t.id}))return;l(`Repository ${H(t.id)} updated.`)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}}),i.command("delete").description("Delete a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e));if(await ge(a,`/api/profiles/${R}/git/${t.id}`),u(e,{ok:!0,id:t.id}))return;l(`Repository ${H(t.id)} deleted.`)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}}),i.command("fix-hierarchy").description("Fix repository parent-child hierarchy").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c=await q(a,`/api/profiles/${R}/git/fix-hierarchy`,{});if(u(e,{ok:!0,fixed:c?.fixed??null}))return;if(l("Hierarchy fix completed."),c?.fixed!==void 0)n("Fixed",c.fixed)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}})}function D(d,i){k(d)}function te(d){return{name:"git",version:"2.2.0",description:"Git repository scanning, tracking, and hierarchy management",capabilities:{storage:"rw",subprocess:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"git",apiPrefix:"/api/git",createRoutes:(i)=>T(i),onCliSetup:async(i,t)=>{D(i,t)}}}export{te as createPlugin};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{he,R,I,C,e}from"./index-7wm4bqx5.js";import{existsSync as d,mkdirSync as O,readdirSync as Qt,readFileSync as h,renameSync as x,rmSync as te,writeFileSync as S}from"fs";import{dirname as B,join as L}from"path";import{randomUUID as ee}from"crypto";import{existsSync as k,mkdirSync as K,readFileSync as gt,renameSync as ut,unlinkSync as Gt,writeFileSync as _}from"fs";import{dirname as W,join as f}from"path";import{spawnSync as Q}from"child_process";import{hostname as vt,networkInterfaces as _t,platform as dt,userInfo as Ut}from"os";import{createCipheriv as Rt,createDecipheriv as Ot,pbkdf2Sync as xt,randomBytes as Bt}from"crypto";var tt="secrets:fallback",ft="secrets:index",et=10,Lt=100,rt=new Map;function pt(t,n){let r=`${t}:${n}`,i=(rt.get(r)??0)+1;if(rt.set(r,i),i<=et)return!0;return(i-et)%Lt===0}var v="vibecontrols-agent",wt=".libsecret-install-attempted",yt="secrets.json";function $t(){return globalThis.Bun?.secrets??null}class j{api;kind="bun-secrets";constructor(t){this.api=t}async get(t){return this.api.get({service:v,name:t})}async set(t,n){await this.api.set({service:v,name:t,value:n}),await Kt(t)}async delete(t){let n=await this.api.delete({service:v,name:t});return await Jt(t),n}async list(t){return qt(t)}}var mt=".secrets-encrypted-v1",Tt=1e5,Nt=32,Dt="sha256",P=null,it=null;function Ft(){let t=_t();for(let n of Object.values(t)){if(!n)continue;for(let r of n){let i=r?.mac;if(i&&i!=="00:00:00:00:00:00")return i}}return"no-mac"}function ot(){if(it!==null)return it;let t;try{t=Ut().username||"unknown"}catch{t=process.env.USER||process.env.USERNAME||"unknown"}return`${vt()}|${t}|${Ft()}`}function ht(){if(P)return P;let t=`vibecontrols-agent::${ot()}`;return P=xt(t,ot(),Tt,Nt,Dt),P}function at(t){let n=Bt(12),r=Rt("aes-256-gcm",ht(),n),i=Buffer.concat([r.update(t,"utf8"),r.final()]),s=r.getAuthTag();return`${n.toString("hex")}:${s.toString("hex")}:${i.toString("hex")}`}function Mt(t){let n=t.split(":");if(n.length!==3)return!1;let[r,i,s]=n;return/^[0-9a-f]+$/i.test(r)&&r.length===24&&/^[0-9a-f]+$/i.test(i)&&i.length===32&&/^[0-9a-f]*$/i.test(s)}function Wt(t){if(!Mt(t))return null;try{let[n,r,i]=t.split(":"),s=Ot("aes-256-gcm",ht(),Buffer.from(n,"hex"));return s.setAuthTag(Buffer.from(r,"hex")),Buffer.concat([s.update(Buffer.from(i,"hex")),s.final()]).toString("utf8")}catch{return null}}class kt{kind="json-fallback";path;constructor(){this.path=f(C(),yt)}async get(t){let{plain:n}=this.readWithMigration(),r=n[t];return typeof r==="string"?r:null}async set(t,n){await he(tt,async()=>{let{encrypted:r}=this.readWithMigration();r[t]=at(n),this.writeEncrypted(r)})}async delete(t){return he(tt,async()=>{let{encrypted:n}=this.readWithMigration();if(!(t in n))return!1;return delete n[t],this.writeEncrypted(n),!0})}async list(t){let{encrypted:n}=this.readWithMigration(),r=Object.keys(n);return(t?r.filter((s)=>s.startsWith(t)):r).sort().map((s)=>({name:s}))}readWithMigration(){if(!k(this.path))return{encrypted:{},plain:{}};let t;try{t=gt(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let n;try{n=JSON.parse(t)}catch{return{encrypted:{},plain:{}}}if(!n||typeof n!=="object"||Array.isArray(n))return{encrypted:{},plain:{}};let r={},i={},s=!1;for(let[o,a]of Object.entries(n)){if(typeof a!=="string")continue;let g=Wt(a);if(g!==null){r[o]=a,i[o]=g;continue}r[o]=at(a),i[o]=a,s=!0}if(s)try{this.writeEncrypted(r),this.writeMarker()}catch{}return{encrypted:r,plain:i}}writeEncrypted(t){K(W(this.path),{recursive:!0});let n=`${this.path}.${process.pid}.tmp`;if(_(n,`${JSON.stringify(t,null,2)}
2
+ import{he,R,I,C,e}from"./index-nxpw3anc.js";import{existsSync as d,mkdirSync as O,readdirSync as Qt,readFileSync as h,renameSync as x,rmSync as te,writeFileSync as S}from"fs";import{dirname as B,join as L}from"path";import{randomUUID as ee}from"crypto";import{existsSync as k,mkdirSync as K,readFileSync as gt,renameSync as ut,unlinkSync as Gt,writeFileSync as _}from"fs";import{dirname as W,join as f}from"path";import{spawnSync as Q}from"child_process";import{hostname as vt,networkInterfaces as _t,platform as dt,userInfo as Ut}from"os";import{createCipheriv as Rt,createDecipheriv as Ot,pbkdf2Sync as xt,randomBytes as Bt}from"crypto";var tt="secrets:fallback",ft="secrets:index",et=10,Lt=100,rt=new Map;function pt(t,n){let r=`${t}:${n}`,i=(rt.get(r)??0)+1;if(rt.set(r,i),i<=et)return!0;return(i-et)%Lt===0}var v="vibecontrols-agent",wt=".libsecret-install-attempted",yt="secrets.json";function $t(){return globalThis.Bun?.secrets??null}class j{api;kind="bun-secrets";constructor(t){this.api=t}async get(t){return this.api.get({service:v,name:t})}async set(t,n){await this.api.set({service:v,name:t,value:n}),await Kt(t)}async delete(t){let n=await this.api.delete({service:v,name:t});return await Jt(t),n}async list(t){return qt(t)}}var mt=".secrets-encrypted-v1",Tt=1e5,Nt=32,Dt="sha256",P=null,it=null;function Ft(){let t=_t();for(let n of Object.values(t)){if(!n)continue;for(let r of n){let i=r?.mac;if(i&&i!=="00:00:00:00:00:00")return i}}return"no-mac"}function ot(){if(it!==null)return it;let t;try{t=Ut().username||"unknown"}catch{t=process.env.USER||process.env.USERNAME||"unknown"}return`${vt()}|${t}|${Ft()}`}function ht(){if(P)return P;let t=`vibecontrols-agent::${ot()}`;return P=xt(t,ot(),Tt,Nt,Dt),P}function at(t){let n=Bt(12),r=Rt("aes-256-gcm",ht(),n),i=Buffer.concat([r.update(t,"utf8"),r.final()]),s=r.getAuthTag();return`${n.toString("hex")}:${s.toString("hex")}:${i.toString("hex")}`}function Mt(t){let n=t.split(":");if(n.length!==3)return!1;let[r,i,s]=n;return/^[0-9a-f]+$/i.test(r)&&r.length===24&&/^[0-9a-f]+$/i.test(i)&&i.length===32&&/^[0-9a-f]*$/i.test(s)}function Wt(t){if(!Mt(t))return null;try{let[n,r,i]=t.split(":"),s=Ot("aes-256-gcm",ht(),Buffer.from(n,"hex"));return s.setAuthTag(Buffer.from(r,"hex")),Buffer.concat([s.update(Buffer.from(i,"hex")),s.final()]).toString("utf8")}catch{return null}}class kt{kind="json-fallback";path;constructor(){this.path=f(C(),yt)}async get(t){let{plain:n}=this.readWithMigration(),r=n[t];return typeof r==="string"?r:null}async set(t,n){await he(tt,async()=>{let{encrypted:r}=this.readWithMigration();r[t]=at(n),this.writeEncrypted(r)})}async delete(t){return he(tt,async()=>{let{encrypted:n}=this.readWithMigration();if(!(t in n))return!1;return delete n[t],this.writeEncrypted(n),!0})}async list(t){let{encrypted:n}=this.readWithMigration(),r=Object.keys(n);return(t?r.filter((s)=>s.startsWith(t)):r).sort().map((s)=>({name:s}))}readWithMigration(){if(!k(this.path))return{encrypted:{},plain:{}};let t;try{t=gt(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let n;try{n=JSON.parse(t)}catch{return{encrypted:{},plain:{}}}if(!n||typeof n!=="object"||Array.isArray(n))return{encrypted:{},plain:{}};let r={},i={},s=!1;for(let[o,a]of Object.entries(n)){if(typeof a!=="string")continue;let g=Wt(a);if(g!==null){r[o]=a,i[o]=g;continue}r[o]=at(a),i[o]=a,s=!0}if(s)try{this.writeEncrypted(r),this.writeMarker()}catch{}return{encrypted:r,plain:i}}writeEncrypted(t){K(W(this.path),{recursive:!0});let n=`${this.path}.${process.pid}.tmp`;if(_(n,`${JSON.stringify(t,null,2)}
3
3
  `,{mode:384}),ut(n,this.path),!k(this.markerPath()))this.writeMarker()}markerPath(){return f(W(this.path),mt)}writeMarker(){try{_(this.markerPath(),`${new Date().toISOString()}
4
4
  `,{mode:384})}catch{}}}var jt=".secrets-index.json";function Y(){return f(C(),jt)}function q(){let t=Y();if(!k(t))return new Set;try{let n=gt(t,"utf8"),r=JSON.parse(n);if(Array.isArray(r))return new Set(r.filter((i)=>typeof i==="string"))}catch{}return new Set}function At(t){let n=Y();K(W(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;_(r,`${JSON.stringify([...t].sort(),null,2)}
5
5
  `,{mode:384}),ut(r,n)}async function Kt(t){await he(ft,()=>{let n=q();if(n.has(t))return;n.add(t),At(n)})}async function Jt(t){await he(ft,()=>{let n=q();if(!n.delete(t))return;At(n)})}function qt(t){let r=[...q()];return(t?r.filter((s)=>s.startsWith(t)):r).sort().map((s)=>({name:s}))}function zt(){if(dt()!=="linux")return{ok:!1};if(process.env.CI==="true")return{ok:!1,warning:"CI/test environment detected; using JSON fallback"};if(process.env.VIBE_SKIP_LIBSECRET_INSTALL==="1")return{ok:!1,warning:"VIBE_SKIP_LIBSECRET_INSTALL=1 set; using JSON fallback"};let t=C(),n=f(t,wt);if(k(n))return{ok:!1,warning:"previous attempt failed; not retrying"};try{K(t,{recursive:!0}),_(n,`${new Date().toISOString()}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{e}from"./index-7wm4bqx5.js";import{b}from"./index-w4jqdhc2.js";var a=5000,i=new Map,d=1;function c(r){return`${r}#${d++}`}function wr(r){let n=Bun.spawn(r.cmd,{env:r.env,cwd:r.cwd,stdout:r.stdout??"pipe",stderr:r.stderr??"pipe",stdin:r.stdin??"pipe",...b().processGroupSpawnOpts()}),t={id:c(r.owner),owner:r.owner,pid:n.pid??null,startedAt:new Date().toISOString(),proc:n,meta:r.meta};return i.set(t.id,t),n.exited.finally(()=>{i.delete(t.id)}),t}function qr(r){return[...i.values()].filter((n)=>n.owner===r)}async function l(r,n){let t=b(),s=Date.now()+n;while(Date.now()<s){if(!t.isProcessAlive(r))return!0;await new Promise((o)=>setTimeout(o,100))}return!t.isProcessAlive(r)}async function p(r,n="SIGTERM"){let t=r.pid;if(t==null)return;let s=b();if(s.killProcessTree(t,n),await l(t,a))return;s.killProcessTree(t,"SIGKILL")}async function en(){let r=[...i.values()];if(r.length===0)return{reaped:0};return e().logger.info("subprocess",`Reaping ${r.length} tracked child process(es)`,{owners:[...new Set(r.map((n)=>n.owner))]}),await Promise.all(r.map((n)=>p(n))),i.clear(),{reaped:r.length}}
2
+ import{e}from"./index-nxpw3anc.js";import{b}from"./index-w4jqdhc2.js";var a=5000,i=new Map,d=1;function c(r){return`${r}#${d++}`}function wr(r){let n=Bun.spawn(r.cmd,{env:r.env,cwd:r.cwd,stdout:r.stdout??"pipe",stderr:r.stderr??"pipe",stdin:r.stdin??"pipe",...b().processGroupSpawnOpts()}),t={id:c(r.owner),owner:r.owner,pid:n.pid??null,startedAt:new Date().toISOString(),proc:n,meta:r.meta};return i.set(t.id,t),n.exited.finally(()=>{i.delete(t.id)}),t}function qr(r){return[...i.values()].filter((n)=>n.owner===r)}async function l(r,n){let t=b(),s=Date.now()+n;while(Date.now()<s){if(!t.isProcessAlive(r))return!0;await new Promise((o)=>setTimeout(o,100))}return!t.isProcessAlive(r)}async function p(r,n="SIGTERM"){let t=r.pid;if(t==null)return;let s=b();if(s.killProcessTree(t,n),await l(t,a))return;s.killProcessTree(t,"SIGKILL")}async function en(){let r=[...i.values()];if(r.length===0)return{reaped:0};return e().logger.info("subprocess",`Reaping ${r.length} tracked child process(es)`,{owners:[...new Set(r.map((n)=>n.owner))]}),await Promise.all(r.map((n)=>p(n))),i.clear(),{reaped:r.length}}
3
3
  export{wr,qr,en};
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- import{ot,bt,Ji,Oe,Xt,O,I,C}from"./index-7wm4bqx5.js";import{Ae}from"./index-8jk4a62x.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as f,readdirSync as R,readFileSync as h,writeFileSync as m,mkdirSync as y,openSync as P,closeSync as w,unlinkSync as v}from"fs";import{join as l}from"path";import{tmpdir as k}from"os";import{spawn as A}from"child_process";class D{registryPath;logsDir;productDir;constructor(){let t=C();this.productDir=t,this.registryPath=l(t,"agents.json");let s=I();this.logsDir=l(s,"logs"),y(t,{recursive:!0}),y(s,{recursive:!0}),y(this.logsDir,{recursive:!0})}async startDaemon(t){return O(t.name),this.withInstanceLock(t.name,async()=>{let s=await this.findProcessByName(t.name);if(s&&s.status==="running"){let u=s.version,g=Ae();if(u===g){console.log(`\u26A0\uFE0F Agent '${t.name}' is already running on port ${s.port}`);return}console.log(`\uD83D\uDD04 Agent '${t.name}' is running an older build (${u??"unknown"} \u2192 ${g}) \u2014 restarting to apply the update`);try{await this.stopInternal(t.name)}catch(d){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${d instanceof Error?d.message:String(d)}); proceeding to start the new build`)}}let e=l(this.logsDir,`${t.name}.log`),n=P(e,"a"),i=l(import.meta.dir,"index.js"),r=l(import.meta.dir,"..","index.ts"),c=f(i)?i:r,a=A(process.execPath,["run",c],{detached:!0,windowsHide:!0,stdio:["ignore",n,n],env:{...process.env,VIBECONTROLS_PROFILE:t.profile||"default",PORT:t.port.toString(),DB_PATH:t.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:e}});a.on("error",()=>{}),w(n),await new Promise((u)=>setTimeout(u,2000));let o=a.pid;if(!(o!==void 0&&await this.isProcessRunning(o))){let u="";try{u=h(e,"utf8").split(/\r?\n/).filter((S)=>S.trim()).slice(-25).join(`
2
+ import{ot,bt,Ji,Oe,Xt,O,I,C}from"./index-nxpw3anc.js";import{Ae}from"./index-zfhmg1gz.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as f,readdirSync as R,readFileSync as h,writeFileSync as m,mkdirSync as y,openSync as P,closeSync as w,unlinkSync as v}from"fs";import{join as l}from"path";import{tmpdir as D}from"os";import{spawn as A}from"child_process";class k{registryPath;logsDir;productDir;constructor(){let t=C();this.productDir=t,this.registryPath=l(t,"agents.json");let s=I();this.logsDir=l(s,"logs"),y(t,{recursive:!0}),y(s,{recursive:!0}),y(this.logsDir,{recursive:!0})}async startDaemon(t){return O(t.name),this.withInstanceLock(t.name,async()=>{let s=await this.findProcessByName(t.name);if(s&&s.status==="running"){let u=s.version,g=Ae();if(u===g){console.log(`\u26A0\uFE0F Agent '${t.name}' is already running on port ${s.port}`);return}console.log(`\uD83D\uDD04 Agent '${t.name}' is running an older build (${u??"unknown"} \u2192 ${g}) \u2014 restarting to apply the update`);try{await this.stopInternal(t.name)}catch(d){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${d instanceof Error?d.message:String(d)}); proceeding to start the new build`)}}let e=l(this.logsDir,`${t.name}.log`),n=P(e,"a"),i=l(import.meta.dir,"index.js"),r=l(import.meta.dir,"..","index.ts"),c=f(i)?i:r,a=A(process.execPath,["run",c],{detached:!0,windowsHide:!0,stdio:["ignore",n,n],env:{...process.env,VIBECONTROLS_PROFILE:t.profile||"default",PORT:t.port.toString(),DB_PATH:t.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:e}});a.on("error",()=>{}),w(n),await new Promise((u)=>setTimeout(u,2000));let o=a.pid;if(!(o!==void 0&&await this.isProcessRunning(o))){let u="";try{u=h(e,"utf8").split(/\r?\n/).filter((S)=>S.trim()).slice(-25).join(`
3
3
  `)}catch{}let g=`See ${e}`;throw Error(u?`Failed to start agent '${t.name}'. ${g}
4
4
  --- last log lines ---
5
- ${u}`:`Failed to start agent '${t.name}'. ${g}`)}a.unref(),await this.saveProcessInfo(t.name,o,t),console.log(`\uD83D\uDE80 Agent '${t.name}' started (PID: ${o}, Port: ${t.port})`)})}async stop(t){return O(t),this.withInstanceLock(t,()=>this.stopInternal(t))}async stopInternal(t){let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}try{if(process.kill(s.pid,"SIGTERM"),await new Promise((n)=>setTimeout(n,3000)),await this.isProcessRunning(s.pid))process.kill(s.pid,"SIGKILL");await this.updateProcessStatus(t,"stopped"),console.log(`\u2705 Agent '${t}' stopped (tunnel + API key preserved)`)}catch(e){throw Error(`Failed to stop agent '${t}': ${e}`,{cause:e})}}async restart(t,s){O(t),O(s.name);let e=await this.findProcessByName(t);if(e&&e.status==="running")await this.stop(t);await this.startDaemon(s),console.log(`\uD83D\uDD04 Agent '${t}' restarted (tunnel + API key preserved)`)}async kill(t){return O(t),this.withInstanceLock(t,async()=>{let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}let e=l(k(),`.boff-vibecontrols-kill-${s.pid}`);try{await Bun.write(e,"kill")}catch{}try{process.kill(s.pid,"SIGTERM"),await new Promise((i)=>setTimeout(i,5000))}catch{}if(await this.isProcessRunning(s.pid))await this.killProcessTree(s.pid);await this.updateProcessStatus(t,"stopped"),console.log(`\uD83D\uDC80 Agent '${t}' killed (tunnel + state torn down)`)})}async getStatus(t){return O(t),this.findProcessByName(t)}discoverRuntimeInstances(){let t=l(this.productDir,"agents");if(!f(t))return[];let s;try{s=R(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>n.name)}catch{return[]}let e=[];for(let n of s){let i=l(t,n,"runtime.json");if(!f(i))continue;try{let r=JSON.parse(h(i,"utf8"));if(typeof r.pid!=="number"||typeof r.port!=="number")continue;let c=r.profile||n;try{O(c)}catch{continue}e.push({name:c,pid:r.pid,port:r.port,config:{name:c,port:r.port,daemon:!0,dbPath:l(t,n,"agent-db"),host:r.host,profile:c},startTime:r.startedAt??new Date(0).toISOString(),status:"unknown",version:r.version})}catch{}}return e}async getStatusAll(){let t=this.loadRegistry(),s=new Set(t.map((r)=>r.name)),e=[...t];for(let r of this.discoverRuntimeInstances())if(!s.has(r.name))e.push(r);let n=[];for(let r of e){let c=await this.isManagedProcessRunning(r);if(!s.has(r.name)&&!c)continue;n.push({...r,status:c?"running":"stopped"})}let i=n.filter((r)=>r.status==="running"&&!s.has(r.name));if(i.length>0)try{await ot(()=>{let r=this.loadRegistry(),c=new Set(r.map((o)=>o.name)),a=i.filter((o)=>!c.has(o.name));if(a.length>0)this.saveRegistry([...r,...a.map((o)=>({...o,status:"running"}))])})}catch{}return n}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return Oe()}setDefaultProfile(t){Xt(O(t))}async showLogs(t,s){O(t);let e=l(this.logsDir,`${t}.log`);if(!f(e)){console.log(`No logs found for agent '${t}'`);return}if(s.follow)try{let n=async(o)=>{let p=await Bun.file(e).text(),g=p.split(`
5
+ ${u}`:`Failed to start agent '${t.name}'. ${g}`)}a.unref(),await this.saveProcessInfo(t.name,o,t),console.log(`\uD83D\uDE80 Agent '${t.name}' started (PID: ${o}, Port: ${t.port})`)})}async stop(t){return O(t),this.withInstanceLock(t,()=>this.stopInternal(t))}async stopInternal(t){let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}try{if(process.kill(s.pid,"SIGTERM"),await new Promise((n)=>setTimeout(n,3000)),await this.isProcessRunning(s.pid))process.kill(s.pid,"SIGKILL");await this.updateProcessStatus(t,"stopped"),console.log(`\u2705 Agent '${t}' stopped (tunnel + API key preserved)`)}catch(e){throw Error(`Failed to stop agent '${t}': ${e}`,{cause:e})}}async restart(t,s){O(t),O(s.name);let e=await this.findProcessByName(t);if(e&&e.status==="running")await this.stop(t);await this.startDaemon(s),console.log(`\uD83D\uDD04 Agent '${t}' restarted (tunnel + API key preserved)`)}async kill(t){return O(t),this.withInstanceLock(t,async()=>{let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}let e=l(D(),`.boff-vibecontrols-kill-${s.pid}`);try{await Bun.write(e,"kill")}catch{}try{process.kill(s.pid,"SIGTERM"),await new Promise((i)=>setTimeout(i,5000))}catch{}if(await this.isProcessRunning(s.pid))await this.killProcessTree(s.pid);await this.updateProcessStatus(t,"stopped"),console.log(`\uD83D\uDC80 Agent '${t}' killed (tunnel + state torn down)`)})}async getStatus(t){return O(t),this.findProcessByName(t)}discoverRuntimeInstances(){let t=l(this.productDir,"agents");if(!f(t))return[];let s;try{s=R(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>n.name)}catch{return[]}let e=[];for(let n of s){let i=l(t,n,"runtime.json");if(!f(i))continue;try{let r=JSON.parse(h(i,"utf8"));if(typeof r.pid!=="number"||typeof r.port!=="number")continue;let c=r.profile||n;try{O(c)}catch{continue}e.push({name:c,pid:r.pid,port:r.port,config:{name:c,port:r.port,daemon:!0,dbPath:l(t,n,"agent-db"),host:r.host,profile:c},startTime:r.startedAt??new Date(0).toISOString(),status:"unknown",version:r.version})}catch{}}return e}async getStatusAll(){let t=this.loadRegistry(),s=new Set(t.map((r)=>r.name)),e=[...t];for(let r of this.discoverRuntimeInstances())if(!s.has(r.name))e.push(r);let n=[];for(let r of e){let c=await this.isManagedProcessRunning(r);if(!s.has(r.name)&&!c)continue;n.push({...r,status:c?"running":"stopped"})}let i=n.filter((r)=>r.status==="running"&&!s.has(r.name));if(i.length>0)try{await ot(()=>{let r=this.loadRegistry(),c=new Set(r.map((o)=>o.name)),a=i.filter((o)=>!c.has(o.name));if(a.length>0)this.saveRegistry([...r,...a.map((o)=>({...o,status:"running"}))])})}catch{}return n}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return Oe()}setDefaultProfile(t){Xt(O(t))}async showLogs(t,s){O(t);let e=l(this.logsDir,`${t}.log`);if(!f(e)){console.log(`No logs found for agent '${t}'`);return}if(s.follow)try{let n=async(o)=>{let p=await Bun.file(e).text(),g=p.split(`
6
6
  `).slice(-s.tail).join(`
7
7
  `);if(process.stdout.write(o?g:g),o&&!g.endsWith(`
8
8
  `))process.stdout.write(`
@@ -10,4 +10,4 @@ ${u}`:`Failed to start agent '${t.name}'. ${g}`)}a.unref(),await this.saveProces
10
10
  `).slice(-s.tail).join(`
11
11
  `);console.log(r)}catch(n){console.error("Failed to read logs:",n)}}async checkHealth(t){let s=await this.findProcessByName(t);if(!s||s.status!=="running")return{healthy:!1,details:{error:"Process not running"}};try{let e=await fetch(`http://localhost:${s.port}/health`),n=await e.json();return{healthy:e.ok,details:n}}catch(e){return{healthy:!1,details:{error:"Health check failed",message:e.message}}}}async setConfig(t,s){let e=l(C(),"config.json"),n={};if(f(e))n=JSON.parse(h(e,"utf8"));n[t]=s,m(e,JSON.stringify(n,null,2))}async getConfig(t){let s=l(C(),"config.json");if(!f(s))return t?void 0:{};let e=JSON.parse(h(s,"utf8"));return t?e[t]:e}loadRegistry(){return bt()}saveRegistry(t){Ji(t)}async withInstanceLock(t,s){let e=O(t),n=l(this.productDir,`.agent-${e}.lock`),i;try{i=P(n,"wx",384),m(i,`${process.pid}
12
12
  `)}catch(r){if(r.code==="EEXIST"){let a=parseInt(h(n,"utf8"),10);if(!a||!await this.isProcessRunning(a)){try{v(n)}catch{}return this.withInstanceLock(t,s)}throw Error(`Agent '${t}' is already being modified`,{cause:r})}throw r}try{return await s()}finally{try{w(i)}catch{}try{v(n)}catch{}}}async saveProcessInfo(t,s,e){await ot(()=>{let i=this.loadRegistry().filter((r)=>r.name!==t);i.push({name:t,pid:s,port:e.port,config:e,startTime:new Date().toISOString(),status:"running"}),this.saveRegistry(i)})}async updateProcessStatus(t,s){await ot(()=>{let e=this.loadRegistry(),n=e.find((i)=>i.name===t);if(n)n.status=s,this.saveRegistry(e)})}async findProcessByName(t){O(t);let e=this.loadRegistry().find((i)=>i.name===t);if(!e)return null;let n=await this.isManagedProcessRunning(e);return e.status=n?"running":"stopped",e}async isManagedProcessRunning(t){if(!await this.isProcessRunning(t.pid))return!1;try{return(await fetch(`http://127.0.0.1:${t.port}/health/live`,{signal:AbortSignal.timeout(1000)})).ok}catch{return!1}}async isProcessRunning(t){try{return process.kill(t,0),!0}catch{return!1}}killProcessTree(t){try{b().killProcessTree(t,"SIGKILL")}catch{}}}
13
- export{D};
13
+ export{k};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{I,C,e}from"./index-7wm4bqx5.js";import{existsSync as l,mkdirSync as a,readFileSync as p,appendFileSync as m,writeFileSync as u}from"fs";import{join as b,relative as y,resolve as c,isAbsolute as h}from"path";var o=".boff/",S=new Set([".boff",".boff/","/.boff","/.boff/"]);function Tr(){a(I(),{recursive:!0}),w()}function w(){let f=c(C()),i=c(process.cwd()),s=y(i,f);if(s.startsWith("..")||h(s))return;let t=b(i,".gitignore");if(!l(t)){u(t,`${o}
2
+ import{I,C,e}from"./index-nxpw3anc.js";import{existsSync as l,mkdirSync as a,readFileSync as p,appendFileSync as m,writeFileSync as u}from"fs";import{join as b,relative as y,resolve as c,isAbsolute as h}from"path";var o=".boff/",S=new Set([".boff",".boff/","/.boff","/.boff/"]);function Tr(){a(I(),{recursive:!0}),w()}function w(){let f=c(C()),i=c(process.cwd()),s=y(i,f);if(s.startsWith("..")||h(s))return;let t=b(i,".gitignore");if(!l(t)){u(t,`${o}
3
3
  `,{mode:420}),e().logger.info("bootstrap",`Created .gitignore with ${o}`);return}let r=p(t,"utf8");if(r.split(/\r?\n/).some((g)=>{let n=g.trim();if(!n||n.startsWith("#"))return!1;return S.has(n)}))return;let d=r.length>0&&!r.endsWith(`
4
4
  `);m(t,`${d?`
5
5
  `:""}${o}