@vibecontrols/agent 2026.1125.2 → 2026.1127.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-config-xwvsmn6b.js +2 -0
- package/dist/{agent-ready-tracker-mewxehg9.js → agent-ready-tracker-7ebr09d9.js} +1 -1
- package/dist/app-4t875vbv.js +2 -0
- package/dist/autostart.cmd-mdyv35dn.js +2 -0
- package/dist/bootstrap-workspace-1pt0bwy6.js +2 -0
- package/dist/bootstrap.service-gehm65tt.js +2 -0
- package/dist/bridge-client-9ax1cvj6.js +2 -0
- package/dist/bridge-commands-xhzhghxt.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/daemon-profile-fnhc7pcf.js +2 -0
- package/dist/{finalize-retry-worker-az74f2qv.js → finalize-retry-worker-c38km3mt.js} +1 -1
- package/dist/gateway-client-3zp6kkav.js +2 -0
- package/dist/{getMachineId-bsd-4w1wmcjv.js → getMachineId-bsd-qjqk66se.js} +1 -1
- package/dist/{getMachineId-darwin-kejwz8w5.js → getMachineId-darwin-tqhg8pqb.js} +1 -1
- package/dist/{getMachineId-linux-mpm53wat.js → getMachineId-linux-ygfapc26.js} +1 -1
- package/dist/{getMachineId-unsupported-54seyw5v.js → getMachineId-unsupported-87w3cred.js} +1 -1
- package/dist/{getMachineId-win-cva7ghz9.js → getMachineId-win-jrtkq63e.js} +1 -1
- package/dist/{index-0gmhd3hs.js → index-0rmmrrfh.js} +3 -3
- package/dist/{index-7s7ee1y9.js → index-0vbsve3v.js} +4 -4
- package/dist/{index-7f2k4g6q.js → index-12gb48hg.js} +4 -4
- package/dist/{index-4rasb3ph.js → index-12rehjp4.js} +9 -9
- package/dist/{index-7wben1jx.js → index-164mtd7z.js} +2 -2
- package/dist/index-1smr1csg.js +116 -0
- package/dist/{index-w0m3jm0s.js → index-1t74r13z.js} +2 -2
- package/dist/{index-9xrhb68w.js → index-31ssvzw8.js} +2 -2
- package/dist/{index-652f9scs.js → index-4kf3nr14.js} +2 -2
- package/dist/{index-qe3xpt41.js → index-5s4mtrqb.js} +2 -2
- package/dist/{index-jmx5awkj.js → index-62vfxd90.js} +2 -2
- package/dist/{index-5ccmrpb5.js → index-6b9vh0gq.js} +48 -48
- package/dist/{index-7gk1x74m.js → index-6nv5rdqh.js} +2 -2
- package/dist/{index-er5k6qtr.js → index-6wfd7cv3.js} +4 -4
- package/dist/{index-t6p4szqx.js → index-76vza24h.js} +3 -3
- package/dist/{index-76m37yd8.js → index-7bm1kptr.js} +3 -3
- package/dist/{index-0qjbnyg4.js → index-7wm4bqx5.js} +5 -5
- package/dist/{index-akk3rxnn.js → index-90gn0b6x.js} +3 -3
- package/dist/{index-2r6cmxxz.js → index-axkwyajz.js} +1 -1
- package/dist/index-bk17490n.js +3 -0
- package/dist/{index-2vcxt38h.js → index-bpzk441p.js} +2 -2
- package/dist/{index-4z1y39jt.js → index-cn4p1ks0.js} +2 -2
- package/dist/{index-byerrz46.js → index-damc6cvc.js} +2 -2
- package/dist/{index-xtd0j8ve.js → index-dgbe8jm8.js} +2 -2
- package/dist/index-dtxd2xmg.js +158 -0
- package/dist/index-e5jdx9c1.js +3 -0
- package/dist/{index-tahaxp6n.js → index-ednz6yz2.js} +2 -2
- package/dist/{index-hsrt2v87.js → index-f5nmxa9e.js} +1 -1
- package/dist/{index-thm1bzpj.js → index-j8j1h00a.js} +9 -9
- package/dist/{index-kwhx023z.js → index-j99tkngg.js} +10 -10
- package/dist/{index-fqz9n560.js → index-nz7mhjjn.js} +3 -3
- package/dist/index-p1b10hs1.js +11 -0
- package/dist/{index-qfxwk38p.js → index-p7fbnfwd.js} +2 -2
- package/dist/{index-jnxjjx2y.js → index-ppxayc0x.js} +2 -2
- package/dist/index-qzwbctkv.js +16 -0
- package/dist/{index-a0vx2zyx.js → index-rae5bn1c.js} +2 -2
- package/dist/{index-8rbhm4g8.js → index-rhn7wy1p.js} +2 -2
- package/dist/index-sd5bt3g5.js +2 -0
- package/dist/{index-vtsd74g0.js → index-sq5j8bjn.js} +6 -6
- package/dist/{index-t5cfkz1e.js → index-v77bb0rm.js} +3 -3
- package/dist/{index-v16qz1fa.js → index-vhz1c474.js} +2 -2
- package/dist/{index-ywnfz6nm.js → index-wxb9dgwq.js} +1 -1
- package/dist/index-x4z055t8.js +3 -0
- package/dist/{index-haww9jpq.js → index-xetd52ad.js} +2 -2
- package/dist/{index-d59kp6zr.js → index-yfk0pb00.js} +2 -2
- package/dist/{index-cy97asyh.js → index-zcnfj1q4.js} +3 -3
- package/dist/{index-c4whjk5r.js → index-zn9snqbg.js} +2 -2
- package/dist/index.js +3 -3
- package/dist/interactive-52x9hv6c.js +2 -0
- package/dist/key.cmd-y415ngam.js +2 -0
- package/dist/log-shipper-02rqvtq8.js +2 -0
- package/dist/{path-utils-r4df8d3w.js → path-utils-qgkdkp5j.js} +1 -1
- package/dist/plugin-system-7qjqrq7s.js +2 -0
- package/dist/prereqs-runner-w7z2dwa6.js +2 -0
- package/dist/profile-mount-ga5z1vx9.js +2 -0
- package/dist/prune-stale-shims-vejvb1rj.js +2 -0
- package/dist/register-core-vv5pddxj.js +2 -0
- package/dist/secondary-profile-attach-222s85md.js +2 -0
- package/dist/subprocess-p9bv9nqz.js +2 -0
- package/dist/telemetry-1d3t1mbf.js +2 -0
- package/dist/tunnel-bootstrap-20vwak7q.js +2 -0
- package/package.json +1 -1
- package/dist/agent-config-v9d7gcz0.js +0 -2
- package/dist/app-xc9c1d71.js +0 -2
- package/dist/autostart.cmd-ahet7b1t.js +0 -2
- package/dist/bootstrap-workspace-3pb8qjsh.js +0 -2
- package/dist/bootstrap.service-9m7m1ksa.js +0 -2
- package/dist/bridge-client-xvqy3n15.js +0 -2
- package/dist/daemon-profile-sg8fp50z.js +0 -2
- package/dist/gateway-client-ermpz52n.js +0 -2
- package/dist/index-5021rk8n.js +0 -3
- package/dist/index-b3v08awy.js +0 -3
- package/dist/index-mmx2kp76.js +0 -16
- package/dist/index-ss5gez2p.js +0 -2
- package/dist/index-tts92sdm.js +0 -5
- package/dist/index-x83tcr8f.js +0 -158
- package/dist/index-zcmhy3jv.js +0 -116
- package/dist/interactive-vbz68zh5.js +0 -2
- package/dist/key.cmd-f6rjvjy8.js +0 -2
- package/dist/log-shipper-0erbwn0q.js +0 -2
- package/dist/plugin-system-byzwda4c.js +0 -2
- package/dist/prereqs-runner-gca0bytz.js +0 -2
- package/dist/profile-mount-s4mc1x18.js +0 -2
- package/dist/prune-stale-shims-4nqtv0xt.js +0 -2
- package/dist/register-core-ws2axmcf.js +0 -2
- package/dist/secondary-profile-attach-em1tq7vq.js +0 -2
- package/dist/subprocess-4gg77skg.js +0 -2
- package/dist/telemetry-nmtywcba.js +0 -2
- package/dist/tunnel-bootstrap-tjwz90pb.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import"./index-7wm4bqx5.js";import{Z}from"./index-wxb9dgwq.js";import"./index-j99tkngg.js";import{i,d,s,A,l,o,g,n,c,F}from"./index-12gb48hg.js";import"./index-sq5j8bjn.js";import{vt,be,Di}from"./index-e5jdx9c1.js";import"./index-cn4p1ks0.js";import{_,y,u}from"./index-v77bb0rm.js";import{f,m,S,Te,ge}from"./index-damc6cvc.js";function R(C,t){if(C==="telemetry.enabled")Z.setEnabled(t==="true")}function P(C){return Object.entries(C).map(([t,e])=>({key:t,value:e}))}function j(C){let{db:t}=C;return new E().get("/",async()=>{let e=await t.getAllConfig(),p=Di(e);return{config:p,configs:P(p)}}).get("/status",async()=>await t.getConfigStatus()).get("/:key",async({params:e,set:p})=>{let k=await t.getConfig(e.key);if(k===void 0)return p.status=404,{error:"Configuration key not found"};return{key:e.key,value:be(e.key,k)}}).put("/:key",async({params:e,body:p,set:k})=>{if(vt(e.key))return k.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await t.setConfig(e.key,p.value),R(e.key,p.value),{success:!0}}catch(a){return k.status=500,{error:"Failed to set configuration",details:String(a)}}},{body:r.Object({value:r.String()})}).delete("/:key",async({params:e,set:p})=>{if(vt(e.key))return p.status=403,{error:"Configuration key is managed by a dedicated endpoint"};if(await t.getConfig(e.key)===void 0)return p.status=404,{error:"Configuration key not found"};try{return await t.deleteConfig(e.key),{success:!0}}catch(a){return p.status=500,{error:"Failed to delete configuration",details:String(a)}}}).post("/",async({body:e,set:p})=>{if(vt(e.key))return p.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await t.setConfig(e.key,e.value),R(e.key,e.value),{success:!0,key:e.key}}catch(k){return p.status=500,{error:"Failed to set configuration",details:String(k)}}},{body:r.Object({key:r.String(),value:r.String()})}).post("/bulk",async({body:e,set:p})=>{let k=Object.keys(e.configs).filter(vt);if(k.length>0)return p.status=403,{error:"One or more configuration keys are managed by dedicated endpoints",keys:k};try{await t.bulkSetConfig(e.configs);for(let[a,v]of Object.entries(e.configs))R(a,v);return{success:!0}}catch(a){return p.status=500,{error:"Failed to set configuration",details:String(a)}}},{body:r.Object({configs:r.Record(r.String(),r.String())})})}var x="http://localhost:3005";function h(C){C.command("config").description("Manage VibeControls agent configuration").option("--set <key=value>","Set a configuration value").option("--get <key>","Get a configuration value").option("--delete <key>","Delete a configuration value").option("--list","List all configuration values",!1).option("--value <value>","Value used with `--set <key>` (alternative to `--set key=value`)").option("--agent-url <url>","Agent URL",x).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let e={...C.opts(),...t};try{let p=f(t),k=encodeURIComponent(m(e));if(t.set){let a=t.set.indexOf("="),v,b;if(a===-1){if(t.value===void 0){if(e.json){u(e,{ok:!1,error:"Invalid format: use key=value or --set key --value v"});return}s(`Invalid format. Use ${i.bold("--set key=value")} or ${i.bold("--set key --value value")}`);return}v=t.set.trim(),b=String(t.value).trim()}else v=t.set.slice(0,a).trim(),b=t.set.slice(a+1).trim();if(!v){if(e.json){u(e,{ok:!1,error:"Configuration key cannot be empty"});return}s("Configuration key cannot be empty.");return}if(await Te(p,`/api/profiles/${k}/config/${encodeURIComponent(v)}`,{value:b}),u(e,{ok:!0,key:v}))return;l(`${d.success} Set ${i.bold(v)} = ${i.cyan(String(be(v,b)))}`)}else if(t.get)await y({mode:_(e),fetchData:()=>S(p,`/api/profiles/${k}/config/${encodeURIComponent(t.get)}`),plain:(a)=>{g("Configuration"),c(),n(a.key,i.bold(String(be(a.key,a.value)))),c()},json:(a)=>({key:a.key,value:be(a.key,a.value)})});else if(t.delete){if(await ge(p,`/api/profiles/${k}/config/${encodeURIComponent(t.delete)}`),u(e,{ok:!0,key:t.delete}))return;l(`${d.success} Deleted configuration key: ${i.bold(t.delete)}`)}else if(t.list)await y({mode:_(e),fetchData:()=>S(p,`/api/profiles/${k}/config/`),plain:(a)=>{if(g("Agent Configuration"),c(),!a.configs||a.configs.length===0){o(`${d.info} No configuration entries found.`);return}let v=a.configs.map((b)=>({Key:b.key,Value:String(be(b.key,b.value))}));F(v),c(),o(`${d.info} ${a.configs.length} configuration(s) found.`)},json:(a)=>(a.configs??[]).map((v)=>({key:v.key,value:be(v.key,v.value)}))});else{if(e.json){u(e,{ok:!1,error:"No operation specified"});return}o(`${d.info} Usage:`),o(` ${i.bold("vibe config --list")} List all config values`),o(` ${i.bold("vibe config --get <key>")} Get a config value`),o(` ${i.bold("vibe config --set <key=value>")} Set a config value`),o(` ${i.bold("vibe config --delete <key>")} Delete a config value`)}}catch(p){if(e.json){u(e,{ok:!1,error:A(p)});return}s(`Config operation failed: ${A(p)}`)}})}function w(C,t){h(C)}function J(C){return{name:"config",version:"2.2.0",description:"Agent configuration key-value store",capabilities:{storage:"rw",audit:!0},tags:["backend","cli"],cliCommand:"config",apiPrefix:"/api/config",createRoutes:(t)=>j(t),onCliSetup:async(t,e)=>{w(t,e)}}}export{J as createPlugin};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-
|
|
3
|
-
`);return}if(w)await w(C);if(t)C.telemetry?.emit(t,{plugin:O})},onServerStop:async(P)=>{if(a)await a(P)},onNuke:async(P,C)=>{if(p)return p(P,C)}}}var ie=class{logger;source;constructor(b,O){this.logger=b,this.source=O}info(b,O){this.logger?.info?.(this.source,b,O)}warn(b,O){this.logger?.warn?.(this.source,b,O)}error(b,O){this.logger?.error?.(this.source,b,O)}debug(b,O){this.logger?.debug?.(this.source,b,O)}};import{existsSync as qe,rmSync as Je,statSync as We}from"fs";import{resolve as ze}from"path";function ae(b=I()){let O=[],w=ze(b),a=ne();if(!si(a,w))throw Error("Refusing to reset a path outside the agents directory");if(qe(w)&&We(w).isDirectory())Je(w,{recursive:!0,force:!0}),O.push(w);return{removed:O,agentDir:w}}var X="alias",ce=/^[a-zA-Z0-9_-]{1,64}$/,le=16384,ue=256,me=1024,Ye=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class H extends Error{code;constructor(b,O){super(O);this.code=b,this.name="AliasValidationError"}}class Q extends Error{constructor(b){super(`alias '${b}' already exists`);this.name="AliasConflictError"}}class W extends Error{constructor(b){super(`alias '${b}' not found`);this.name="AliasNotFoundError"}}function Xe(b){if(typeof b!=="string"||!ce.test(b))throw new H("invalid_name",`alias name must match ${ce} (got '${b}')`);if(Ye.has(b))throw new H("reserved_name",`alias name '${b}' is reserved`)}function ge(b){if(typeof b!=="string"||b.length===0)throw new H("invalid_command","alias command must be a non-empty string");if(b.length>le)throw new H("command_too_long",`alias command exceeds ${le} bytes`)}function pe(b){if(b===void 0)return;if(typeof b!=="string")throw new H("invalid_description","alias description must be a string");if(b.length>ue)throw new H("description_too_long",`alias description exceeds ${ue} chars`)}function fe(b){if(b===void 0||b===null||b==="")return;if(typeof b!=="string")throw new H("invalid_cwd","alias cwd must be a string");if(b.length>me)throw new H("cwd_too_long",`alias cwd exceeds ${me} chars`);if(b.includes("\x00"))throw new H("invalid_cwd","alias cwd must not contain NUL bytes")}function Ze(b){if(!b)return;try{return JSON.parse(b)}catch{return}}async function se(b){let O=await b.getAllPluginState(X),w=[];for(let a of O){let p=Ze(a.value);if(p)w.push(p)}return w.sort((a,p)=>a.name.localeCompare(p.name)),w}async function z(b,O){return(await se(b)).find((a)=>a.name===O)}function de(b){if(b===void 0||b===null)return null;let O=b.trim();return O===""?null:O}async function he(b,O){if(Xe(O.name),ge(O.command),pe(O.description),fe(O.cwd),await z(b,O.name))throw new Q(O.name);let a=new Date().toISOString(),p={id:crypto.randomUUID(),name:O.name,command:O.command,description:O.description,cwd:de(O.cwd),profile:R(),createdAt:a,updatedAt:a};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ye(b,O,w){let a=await z(b,O);if(!a)throw new W(O);if(w.command!==void 0)ge(w.command);if(w.description!==void 0)pe(w.description);if(w.cwd!==void 0)fe(w.cwd);let p={...a,command:w.command??a.command,description:w.description!==void 0?w.description:a.description,cwd:w.cwd!==void 0?de(w.cwd):a.cwd,updatedAt:new Date().toISOString()};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function we(b,O){let w=await z(b,O);if(!w)throw new W(O);await b.deletePluginState(X,w.id)}function Z(){let b=B()??e();return{dir:b.dataDir,scope:b.name}}function Se(b){let{serviceRegistry:O,db:w}=b;return new E().get("/api-key",({request:a,set:p})=>{if(Ge(a))return p.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let t=k(Object.fromEntries(a.headers.entries()));if(!V(t))return p.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/reset-key",async({body:a,set:p})=>{let t=a.apiKey;if(!t||typeof t!=="string")return p.status=400,{error:"Missing required field: apiKey"};try{return await Mi(t),await e().keyVault.bindApiKey(t),e().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(h){return p.status=400,{error:"reset-key failed",message:h instanceof Error?h.message:String(h)}}},{body:r.Object({apiKey:r.String()})}).get("/audit",({query:a})=>{let p=a,t=p.limit?Math.min(5000,Math.max(1,Number.parseInt(p.limit,10)||100)):100,h=e().audit.listEvents({since:p.since,limit:t,event:p.event});return{events:h,count:h.length}},{query:r.Object({since:r.Optional(r.String()),limit:r.Optional(r.String()),event:r.Optional(r.String())})}).get("/setup/check",()=>{let a=Me();return{ready:a.filter((t)=>t.required).every((t)=>t.installed),dependencies:a}}).post("/setup/install",async({request:a,server:p,set:t})=>{let h=await Pe(a,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",p);if(h)return t.status=403,{error:"Forbidden",message:h};return await st()}).get("/url",async()=>{let a=O.getProvider("tunnel"),p=a&&a.getActiveTunnelUrl?await a.getActiveTunnelUrl():null,t=`http://localhost:${process.env.PORT||3005}`;return{url:p||t,tunnelUrl:p,localUrl:t,source:p?"tunnel":"local"}}).get("/lifecycle/state",()=>({state:O.getService("agent","lifecycle")?.getState()??"running"})).post("/lifecycle/stop",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.start(),{state:"running"}}).post("/lifecycle/kill",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>p.kill(),100),{state:"killing"}}).post("/log-level",async({body:a,request:p,server:t,set:h})=>{let P=await Pe(p,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=String(a.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(C))return h.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return e().logger.setLevel(C),e().logger.info("agent",`Log level set to ${C} via API`),{ok:!0,level:C}},{body:r.Object({level:r.String()})}).post("/reset",async({body:a,request:p,server:t,set:h})=>{if(!a.confirm)return h.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let P=await Pe(p,"VIBECONTROLS_ALLOW_REMOTE_RESET",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=O.getService("agent","lifecycle");try{if(C)await C.prepareForReset()}catch(Y){e().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(Y)})}try{T.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:x,agentDir:N}=ae();e().logger.info("agent","Reset wiped local agent state",{agentDir:N,removed:x});let j=new Uint8Array(32);crypto.getRandomValues(j);let J=`vcak_${Buffer.from(j).toString("base64url")}`;return M({"static-api-key":J},Z()),e().setBootState("awaiting-config"),h.status=200,{success:!0,state:"awaiting-config",...Be(p,t)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:J}:{},agentDir:N,removed:x}},{body:r.Object({confirm:r.Boolean()})}).post("/sessions/:sessionId/share",async({params:a,body:p,server:t,request:h,set:P})=>{if(!Be(h,t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return P.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!be(a.sessionId))return P.status=400,{error:"BadRequest",message:"invalid sessionId"};let C=et(p?.expiresIn)??1800000,x=crypto.randomUUID(),N=new Uint8Array(32);crypto.getRandomValues(N);let j=`vcak_${Buffer.from(N).toString("base64url")}`,J=new Date(Date.now()+C).toISOString(),oe=[...(await import("./agent-config-v9d7gcz0.js")).readAgentConfig({dir:Z().dir}).apiKeys??[],{id:x,name:`session-share:${a.sessionId}:${p?.label??"viewer"}`,key:j,scopes:["read"],expiresAt:J,createdAt:new Date().toISOString()}];(await import("./agent-config-v9d7gcz0.js")).writeAgentConfig({apiKeys:oe},Z());let Y=O.getProvider("tunnel"),_e=(Y&&Y.getActiveTunnelUrl?await Y.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,je=Nt({pathPrefixes:[`/terminal/${a.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(C/1000))),He=`${_e.replace(/\/$/,"")}/terminal/${encodeURIComponent(a.sessionId)}/#vt=${encodeURIComponent(je.token)}`;return e().logger.info("session-share","Minted share credential",{sessionId:a.sessionId,keyId:x,expiresAt:J}),{ok:!0,keyId:x,apiKey:j,joinUrl:He,sessionId:a.sessionId,expiresAt:J}},{params:r.Object({sessionId:r.String()}),body:r.Optional(r.Object({permissions:r.Optional(r.Array(r.String())),expiresIn:r.Optional(r.String()),label:r.Optional(r.String())}))}).get("/aliases",async()=>({aliases:await se(w)})).get("/aliases/:name",async({params:a,set:p})=>{let t=await z(w,a.name);if(!t)return p.status=404,{error:"Alias not found"};return t},{params:r.Object({name:r.String()})}).post("/aliases",async({body:a,set:p})=>{try{let t=await he(w,a);return p.status=201,t}catch(t){if(t instanceof Q)return p.status=409,{error:"Alias already exists",message:t.message};if(t instanceof H)return p.status=400,{error:t.code,message:t.message};throw t}},{body:r.Object({name:r.String(),command:r.String(),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).put("/aliases/:name",async({params:a,body:p,set:t})=>{try{return await ye(w,a.name,p)}catch(h){if(h instanceof W)return t.status=404,{error:"Alias not found"};if(h instanceof H)return t.status=400,{error:h.code,message:h.message};throw h}},{params:r.Object({name:r.String()}),body:r.Object({command:r.Optional(r.String()),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).delete("/aliases/:name",async({params:a,set:p})=>{try{return await we(w,a.name),p.status=204,null}catch(t){if(t instanceof W)return p.status=404,{error:"Alias not found"};throw t}},{params:r.Object({name:r.String()})}).post("/aliases/:name/execute",async({params:a,body:p,set:t})=>{let h=await z(w,a.name);if(!h)return t.status=404,{error:"Alias not found"};let P=p?.args??[],C=await mi(h,P);e().audit.emit("agent","alias.executed",{exit_code:C.exit_code});let x=ve("alias.executed",{exit_code:C.exit_code});if(!x.ok)e().logger.debug("alias",`telemetry validate failed: ${x.reason}`);if(C.timed_out)t.status=408;return{exit_code:C.exit_code,stdout:C.stdout,stderr:C.stderr,duration_ms:C.duration_ms,truncated:C.truncated,cwd:C.cwd}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({args:r.Optional(r.Array(r.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:a,server:p,request:t,set:h})=>{if(!Be(t,p)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return h.status=403,{error:"Forbidden"};let P=await import("./agent-config-v9d7gcz0.js"),C=Z(),x=P.readAgentConfig({dir:C.dir}),N=(x.apiKeys??[]).length,j=(x.apiKeys??[]).filter((J)=>J.id!==a.keyId);if(j.length===N)return h.status=404,{error:"No such share key"};return P.writeAgentConfig({apiKeys:j},C),{ok:!0,revoked:a.keyId}},{params:r.Object({keyId:r.String()})})}function et(b){if(!b)return null;let O=/^(\d+)([smhdw]?)$/.exec(b.trim());if(!O)return null;let w=Number(O[1]),a=O[2]||"m";return a==="s"?w*1000:a==="m"?w*60000:a==="h"?w*3600000:a==="d"?w*86400000:w*7*86400000}var tt="http://localhost:3005";function Ae(b){b.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",tt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O};await y({mode:_(w),fetchData:async()=>{if(w.name){let t=await new D().checkHealth(w.name);return{mode:"named",agentUrl:f(w),name:w.name,healthy:t.healthy,details:t.details??{}}}let a=f(w);try{let p=await S(a,"/health");return{mode:"url",agentUrl:a,healthy:!0,details:p}}catch(p){return{mode:"url",agentUrl:a,healthy:!1,details:{status:"unhealthy",...p instanceof Error?{error:A(p)}:{}}}}},plain:(a)=>{if(g("Agent Health"),c(),a.mode==="named"){if(!a.healthy){s(`Agent instance ${i.bold(a.name??"")} is not responding.`);return}let p=a.details;if(n("Instance",a.name??""),n("Status",G(p.status??"healthy")),p.uptime!==void 0)n("Uptime",`${p.uptime}s`);if(p.checks){c(),o(`${d.info} Health checks:`);for(let[t,h]of Object.entries(p.checks)){let P=h.status==="healthy"?d.success:d.error;n(` ${P} ${t}`,G(h.status))}}}else{if(n("URL",a.agentUrl),n("Status",G(a.details.status??"unhealthy")),a.details.version)n("Version",a.details.version);if(a.details.uptime!==void 0)n("Uptime",`${a.details.uptime}s`);if(a.details.timestamp)n("Timestamp",a.details.timestamp);if(a.details.checks){c(),o(`${d.info} Health checks:`);for(let[p,t]of Object.entries(a.details.checks)){let h=t.status==="healthy"?d.success:d.error;n(` ${h} ${p}`,G(t.status))}}}if(c(),a.healthy)l(`${d.success} Agent is healthy.`)},interactive:async(a)=>{let p=[];if(a.mode==="named")p.push(`Instance: ${a.name??""}`);else p.push(`URL: ${a.agentUrl}`);if(p.push(`Status: ${G(a.details.status??(a.healthy?"healthy":"unhealthy"))}`),a.details.version)p.push(`Version: ${a.details.version}`);if(a.details.uptime!==void 0)p.push(`Uptime: ${a.details.uptime}s`);if(a.details.timestamp)p.push(`Time: ${a.details.timestamp}`);if(a.details.checks){p.push(""),p.push("Checks:");for(let[t,h]of Object.entries(a.details.checks))p.push(` ${t}: ${h.status}`)}await U({title:"Agent Health",body:p.join(`
|
|
4
|
-
`),footer:"press q to exit"})},json:(a)=>({mode:a.mode,agentUrl:a.agentUrl,name:a.name??null,healthy:a.healthy,details:a.details})})}catch(w){s(`Health check failed: ${A(w)}`)}})}import{platform as nt,arch as rt,release as it,hostname as
|
|
5
|
-
`),footer:"press q to exit"})},json:(t)=>({local:t.local,agentUrl:t.agentUrl,remote:t.remote,remoteError:t.remoteError??null})})}catch(w){s(`Failed to get info: ${A(w)}`)}})}var ut="http://localhost:3005";function
|
|
6
|
-
`),footer:"press q to exit"})}})}catch(w){s(`Failed to get system info: ${A(w)}`)}})}var mt="http://localhost:3005";async function
|
|
7
|
-
`)}async function ft(b,O){let w={agentUrl:O},a=b.jsonKey??b.title.toLowerCase(),p;try{p=await b.render(w)}catch(h){p=i.red(`error (${h.message})`)}let t=null;if(b.json)try{t=await b.json(w)}catch{t=null}return{title:b.title,jsonKey:a,text:p,json:t}}async function
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import{De,ct}from"./index-4kf3nr14.js";import{T,R,li,I,ne,B,e}from"./index-7wm4bqx5.js";import{M}from"./index-j99tkngg.js";import"./index-x4z055t8.js";import{we,Ut,K,vi,L,V}from"./index-qzwbctkv.js";import{i,d,s,A,l,o,g,n,c,F,v,Jr,Ge,G}from"./index-12gb48hg.js";import{U}from"./index-sq5j8bjn.js";import{Zr}from"./index-yfk0pb00.js";import{fi,pi,mi}from"./index-6b9vh0gq.js";import"./index-p1b10hs1.js";import"./index-p7fbnfwd.js";import{Ve,Pe,Me}from"./index-zn9snqbg.js";import{Ci}from"./index-90gn0b6x.js";import{D}from"./index-0vbsve3v.js";import{Nt}from"./index-6wfd7cv3.js";import{k}from"./index-e5jdx9c1.js";import{Ke}from"./index-cn4p1ks0.js";import{_,y,u}from"./index-v77bb0rm.js";import{f,Fe,m,S,q}from"./index-damc6cvc.js";function re(b){let{name:O,onInit:w,onShutdown:a,onNuke:p,telemetryEventName:t,skipPlatforms:h}=b;return{onServerStart:async(P,C)=>{if(h&&h.includes(process.platform)){process.stderr.write(`[${O}] skipping init on unsupported platform '${process.platform}'
|
|
3
|
+
`);return}if(w)await w(C);if(t)C.telemetry?.emit(t,{plugin:O})},onServerStop:async(P)=>{if(a)await a(P)},onNuke:async(P,C)=>{if(p)return p(P,C)}}}var ie=class{logger;source;constructor(b,O){this.logger=b,this.source=O}info(b,O){this.logger?.info?.(this.source,b,O)}warn(b,O){this.logger?.warn?.(this.source,b,O)}error(b,O){this.logger?.error?.(this.source,b,O)}debug(b,O){this.logger?.debug?.(this.source,b,O)}};import{existsSync as Je,rmSync as We,statSync as ze}from"fs";import{resolve as Ye}from"path";function ae(b=I()){let O=[],w=Ye(b),a=ne();if(!li(a,w))throw Error("Refusing to reset a path outside the agents directory");if(Je(w)&&ze(w).isDirectory())We(w,{recursive:!0,force:!0}),O.push(w);return{removed:O,agentDir:w}}var X="alias",ce=/^[a-zA-Z0-9_-]{1,64}$/,le=16384,ue=256,me=1024,Xe=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class H extends Error{code;constructor(b,O){super(O);this.code=b,this.name="AliasValidationError"}}class Q extends Error{constructor(b){super(`alias '${b}' already exists`);this.name="AliasConflictError"}}class W extends Error{constructor(b){super(`alias '${b}' not found`);this.name="AliasNotFoundError"}}function Qe(b){if(typeof b!=="string"||!ce.test(b))throw new H("invalid_name",`alias name must match ${ce} (got '${b}')`);if(Xe.has(b))throw new H("reserved_name",`alias name '${b}' is reserved`)}function ge(b){if(typeof b!=="string"||b.length===0)throw new H("invalid_command","alias command must be a non-empty string");if(b.length>le)throw new H("command_too_long",`alias command exceeds ${le} bytes`)}function pe(b){if(b===void 0)return;if(typeof b!=="string")throw new H("invalid_description","alias description must be a string");if(b.length>ue)throw new H("description_too_long",`alias description exceeds ${ue} chars`)}function fe(b){if(b===void 0||b===null||b==="")return;if(typeof b!=="string")throw new H("invalid_cwd","alias cwd must be a string");if(b.length>me)throw new H("cwd_too_long",`alias cwd exceeds ${me} chars`);if(b.includes("\x00"))throw new H("invalid_cwd","alias cwd must not contain NUL bytes")}function Ze(b){if(!b)return;try{return JSON.parse(b)}catch{return}}async function se(b){let O=await b.getAllPluginState(X),w=[];for(let a of O){let p=Ze(a.value);if(p)w.push(p)}return w.sort((a,p)=>a.name.localeCompare(p.name)),w}async function z(b,O){return(await se(b)).find((a)=>a.name===O)}function de(b){if(b===void 0||b===null)return null;let O=b.trim();return O===""?null:O}async function he(b,O){if(Qe(O.name),ge(O.command),pe(O.description),fe(O.cwd),await z(b,O.name))throw new Q(O.name);let a=new Date().toISOString(),p={id:crypto.randomUUID(),name:O.name,command:O.command,description:O.description,cwd:de(O.cwd),profile:R(),createdAt:a,updatedAt:a};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ye(b,O,w){let a=await z(b,O);if(!a)throw new W(O);if(w.command!==void 0)ge(w.command);if(w.description!==void 0)pe(w.description);if(w.cwd!==void 0)fe(w.cwd);let p={...a,command:w.command??a.command,description:w.description!==void 0?w.description:a.description,cwd:w.cwd!==void 0?de(w.cwd):a.cwd,updatedAt:new Date().toISOString()};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ve(b,O){let w=await z(b,O);if(!w)throw new W(O);await b.deletePluginState(X,w.id)}function Z(){let b=B()??e();return{dir:b.dataDir,scope:b.name}}function be(b){let{serviceRegistry:O,db:w}=b;return new E().get("/api-key",({request:a,set:p})=>{if(Ve(a))return p.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let t=L(Object.fromEntries(a.headers.entries()));if(!V(t))return p.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/reset-key",async({body:a,set:p})=>{let t=a.apiKey;if(!t||typeof t!=="string")return p.status=400,{error:"Missing required field: apiKey"};try{return await vi(t),await e().keyVault.bindApiKey(t),e().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(h){return p.status=400,{error:"reset-key failed",message:h instanceof Error?h.message:String(h)}}},{body:r.Object({apiKey:r.String()})}).get("/audit",({query:a})=>{let p=a,t=p.limit?Math.min(5000,Math.max(1,Number.parseInt(p.limit,10)||100)):100,h=e().audit.listEvents({since:p.since,limit:t,event:p.event});return{events:h,count:h.length}},{query:r.Object({since:r.Optional(r.String()),limit:r.Optional(r.String()),event:r.Optional(r.String())})}).get("/setup/check",()=>{let a=De();return{ready:a.filter((t)=>t.required).every((t)=>t.installed),dependencies:a}}).post("/setup/install",async({request:a,server:p,set:t})=>{let h=await Me(a,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",p);if(h)return t.status=403,{error:"Forbidden",message:h};return await ct()}).get("/url",async()=>{let a=O.getProvider("tunnel"),p=a&&a.getActiveTunnelUrl?await a.getActiveTunnelUrl():null,t=`http://localhost:${process.env.PORT||3005}`;return{url:p||t,tunnelUrl:p,localUrl:t,source:p?"tunnel":"local"}}).get("/lifecycle/state",()=>({state:O.getService("agent","lifecycle")?.getState()??"running"})).post("/lifecycle/stop",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.start(),{state:"running"}}).post("/lifecycle/kill",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>p.kill(),100),{state:"killing"}}).post("/log-level",async({body:a,request:p,server:t,set:h})=>{let P=await Me(p,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=String(a.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(C))return h.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return e().logger.setLevel(C),e().logger.info("agent",`Log level set to ${C} via API`),{ok:!0,level:C}},{body:r.Object({level:r.String()})}).post("/reset",async({body:a,request:p,server:t,set:h})=>{if(!a.confirm)return h.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let P=await Me(p,"VIBECONTROLS_ALLOW_REMOTE_RESET",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=O.getService("agent","lifecycle");try{if(C)await C.prepareForReset()}catch(Y){e().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(Y)})}try{T.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:x,agentDir:N}=ae();e().logger.info("agent","Reset wiped local agent state",{agentDir:N,removed:x});let j=new Uint8Array(32);crypto.getRandomValues(j);let J=`vcak_${Buffer.from(j).toString("base64url")}`;return M({"static-api-key":J},Z()),e().setBootState("awaiting-config"),h.status=200,{success:!0,state:"awaiting-config",...Pe(p,t)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:J}:{},agentDir:N,removed:x}},{body:r.Object({confirm:r.Boolean()})}).post("/sessions/:sessionId/share",async({params:a,body:p,server:t,request:h,set:P})=>{if(!Pe(h,t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return P.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!we(a.sessionId))return P.status=400,{error:"BadRequest",message:"invalid sessionId"};let C=et(p?.expiresIn)??1800000,x=crypto.randomUUID(),N=new Uint8Array(32);crypto.getRandomValues(N);let j=`vcak_${Buffer.from(N).toString("base64url")}`,J=new Date(Date.now()+C).toISOString(),oe=[...(await import("./agent-config-xwvsmn6b.js")).readAgentConfig({dir:Z().dir}).apiKeys??[],{id:x,name:`session-share:${a.sessionId}:${p?.label??"viewer"}`,key:j,scopes:["read"],expiresAt:J,createdAt:new Date().toISOString()}];(await import("./agent-config-xwvsmn6b.js")).writeAgentConfig({apiKeys:oe},Z());let Y=O.getProvider("tunnel"),Te=(Y&&Y.getActiveTunnelUrl?await Y.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,_e=Ut({pathPrefixes:[`/terminal/${a.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(C/1000))),je=`${Te.replace(/\/$/,"")}/terminal/${encodeURIComponent(a.sessionId)}/#vt=${encodeURIComponent(_e.token)}`;return e().logger.info("session-share","Minted share credential",{sessionId:a.sessionId,keyId:x,expiresAt:J}),{ok:!0,keyId:x,apiKey:j,joinUrl:je,sessionId:a.sessionId,expiresAt:J}},{params:r.Object({sessionId:r.String()}),body:r.Optional(r.Object({permissions:r.Optional(r.Array(r.String())),expiresIn:r.Optional(r.String()),label:r.Optional(r.String())}))}).get("/aliases",async()=>({aliases:await se(w)})).get("/aliases/:name",async({params:a,set:p})=>{let t=await z(w,a.name);if(!t)return p.status=404,{error:"Alias not found"};return t},{params:r.Object({name:r.String()})}).post("/aliases",async({body:a,set:p})=>{try{let t=await he(w,a);return p.status=201,t}catch(t){if(t instanceof Q)return p.status=409,{error:"Alias already exists",message:t.message};if(t instanceof H)return p.status=400,{error:t.code,message:t.message};throw t}},{body:r.Object({name:r.String(),command:r.String(),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).put("/aliases/:name",async({params:a,body:p,set:t})=>{try{return await ye(w,a.name,p)}catch(h){if(h instanceof W)return t.status=404,{error:"Alias not found"};if(h instanceof H)return t.status=400,{error:h.code,message:h.message};throw h}},{params:r.Object({name:r.String()}),body:r.Object({command:r.Optional(r.String()),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).delete("/aliases/:name",async({params:a,set:p})=>{try{return await ve(w,a.name),p.status=204,null}catch(t){if(t instanceof W)return p.status=404,{error:"Alias not found"};throw t}},{params:r.Object({name:r.String()})}).post("/aliases/:name/execute",async({params:a,body:p,set:t})=>{let h=await z(w,a.name);if(!h)return t.status=404,{error:"Alias not found"};let P=p?.args??[],C=await Ci(h,P);e().audit.emit("agent","alias.executed",{exit_code:C.exit_code});let x=Ke("alias.executed",{exit_code:C.exit_code});if(!x.ok)e().logger.debug("alias",`telemetry validate failed: ${x.reason}`);if(C.timed_out)t.status=408;return{exit_code:C.exit_code,stdout:C.stdout,stderr:C.stderr,duration_ms:C.duration_ms,truncated:C.truncated,cwd:C.cwd}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({args:r.Optional(r.Array(r.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:a,server:p,request:t,set:h})=>{if(!Pe(t,p)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return h.status=403,{error:"Forbidden"};let P=await import("./agent-config-xwvsmn6b.js"),C=Z(),x=P.readAgentConfig({dir:C.dir}),N=(x.apiKeys??[]).length,j=(x.apiKeys??[]).filter((J)=>J.id!==a.keyId);if(j.length===N)return h.status=404,{error:"No such share key"};return P.writeAgentConfig({apiKeys:j},C),{ok:!0,revoked:a.keyId}},{params:r.Object({keyId:r.String()})})}function et(b){if(!b)return null;let O=/^(\d+)([smhdw]?)$/.exec(b.trim());if(!O)return null;let w=Number(O[1]),a=O[2]||"m";return a==="s"?w*1000:a==="m"?w*60000:a==="h"?w*3600000:a==="d"?w*86400000:w*7*86400000}var tt="http://localhost:3005";function Se(b){b.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",tt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O};await y({mode:_(w),fetchData:async()=>{if(w.name){let t=await new D().checkHealth(w.name);return{mode:"named",agentUrl:f(w),name:w.name,healthy:t.healthy,details:t.details??{}}}let a=f(w);try{let p=await S(a,"/health");return{mode:"url",agentUrl:a,healthy:!0,details:p}}catch(p){return{mode:"url",agentUrl:a,healthy:!1,details:{status:"unhealthy",...p instanceof Error?{error:A(p)}:{}}}}},plain:(a)=>{if(g("Agent Health"),c(),a.mode==="named"){if(!a.healthy){s(`Agent instance ${i.bold(a.name??"")} is not responding.`);return}let p=a.details;if(n("Instance",a.name??""),n("Status",G(p.status??"healthy")),p.uptime!==void 0)n("Uptime",`${p.uptime}s`);if(p.checks){c(),o(`${d.info} Health checks:`);for(let[t,h]of Object.entries(p.checks)){let P=h.status==="healthy"?d.success:d.error;n(` ${P} ${t}`,G(h.status))}}}else{if(n("URL",a.agentUrl),n("Status",G(a.details.status??"unhealthy")),a.details.version)n("Version",a.details.version);if(a.details.uptime!==void 0)n("Uptime",`${a.details.uptime}s`);if(a.details.timestamp)n("Timestamp",a.details.timestamp);if(a.details.checks){c(),o(`${d.info} Health checks:`);for(let[p,t]of Object.entries(a.details.checks)){let h=t.status==="healthy"?d.success:d.error;n(` ${h} ${p}`,G(t.status))}}}if(c(),a.healthy)l(`${d.success} Agent is healthy.`)},interactive:async(a)=>{let p=[];if(a.mode==="named")p.push(`Instance: ${a.name??""}`);else p.push(`URL: ${a.agentUrl}`);if(p.push(`Status: ${G(a.details.status??(a.healthy?"healthy":"unhealthy"))}`),a.details.version)p.push(`Version: ${a.details.version}`);if(a.details.uptime!==void 0)p.push(`Uptime: ${a.details.uptime}s`);if(a.details.timestamp)p.push(`Time: ${a.details.timestamp}`);if(a.details.checks){p.push(""),p.push("Checks:");for(let[t,h]of Object.entries(a.details.checks))p.push(` ${t}: ${h.status}`)}await U({title:"Agent Health",body:p.join(`
|
|
4
|
+
`),footer:"press q to exit"})},json:(a)=>({mode:a.mode,agentUrl:a.agentUrl,name:a.name??null,healthy:a.healthy,details:a.details})})}catch(w){s(`Health check failed: ${A(w)}`)}})}import{platform as nt,arch as rt,release as it,hostname as st,cpus as ot,totalmem as at}from"os";var lt="http://localhost:3005";function Ae(b){b.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",lt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:async()=>{let t={hostname:st(),platform:nt(),arch:rt(),release:it(),cpus:ot().length,totalMemory:at(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let h=await S(a,`/api/profiles/${p}/agent/version`);return{local:t,agentUrl:a,remote:h}}catch(h){return{local:t,agentUrl:a,remote:null,remoteError:h instanceof Error?A(h):String(h)}}},plain:(t)=>{if(g("VibeControls Agent Info"),c(),o(`${d.info} Local System`),n("Hostname",t.local.hostname),n("Platform",`${t.local.platform} ${t.local.arch}`),n("OS Release",t.local.release),n("CPUs",String(t.local.cpus)),n("Total Memory",Ge(t.local.totalMemory)),n("Node.js",t.local.nodeVersion),t.local.bunVersion)n("Bun",t.local.bunVersion);if(c(),o(`${d.info} Remote Agent`),n("URL",t.agentUrl),t.remote){if(n("Version",i.bold(t.remote.version)),t.remote.build)n("Build",t.remote.build);if(t.remote.commit)n("Commit",t.remote.commit);if(t.remote.nodeVersion)n("Node.js (remote)",t.remote.nodeVersion);if(t.remote.bunVersion)n("Bun (remote)",t.remote.bunVersion)}else n("Status",i.dim("not reachable"));c()},interactive:async(t)=>{let h=[];if(h.push("Local System"),h.push(` Hostname: ${t.local.hostname}`),h.push(` Platform: ${t.local.platform} ${t.local.arch}`),h.push(` OS Release: ${t.local.release}`),h.push(` CPUs: ${t.local.cpus}`),h.push(` Total Memory: ${Ge(t.local.totalMemory)}`),h.push(` Node.js: ${t.local.nodeVersion}`),t.local.bunVersion)h.push(` Bun: ${t.local.bunVersion}`);if(h.push(""),h.push("Remote Agent"),h.push(` URL: ${t.agentUrl}`),t.remote){if(h.push(` Version: ${t.remote.version}`),t.remote.build)h.push(` Build: ${t.remote.build}`);if(t.remote.commit)h.push(` Commit: ${t.remote.commit}`);if(t.remote.nodeVersion)h.push(` Node.js: ${t.remote.nodeVersion} (remote)`);if(t.remote.bunVersion)h.push(` Bun: ${t.remote.bunVersion} (remote)`)}else h.push(" Status: not reachable");await U({title:"VibeControls Agent Info",body:h.join(`
|
|
5
|
+
`),footer:"press q to exit"})},json:(t)=>({local:t.local,agentUrl:t.agentUrl,remote:t.remote,remoteError:t.remoteError??null})})}catch(w){s(`Failed to get info: ${A(w)}`)}})}var ut="http://localhost:3005";function $e(b){b.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",ut).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:()=>S(a,`/api/profiles/${p}/agent/system`),plain:(t)=>{if(g("Agent System Information"),c(),o(`${d.info} Agent`),n("Version",i.bold(t.agentVersion)),t.bunVersion)n("Bun",t.bunVersion);if(t.environment)n("Environment",t.environment);n("Uptime",Jr(t.uptime)),c(),o(`${d.info} Platform`),n("OS",`${t.platform} ${t.arch}`),n("Hostname",t.hostname),n("Release",t.release),c(),o(`${d.info} Resources`),n("CPUs",String(t.cpus)),n("Total Memory",Ge(t.totalMemory)),n("Free Memory",Ge(t.freeMemory)),c(),o(`${d.info} Paths`),n("Home",t.homeDir),n("CWD",t.cwd),c()},interactive:async(t)=>{let h=["Agent",` Version: ${t.agentVersion}`,...t.bunVersion?[` Bun: ${t.bunVersion}`]:[],...t.environment?[` Environment: ${t.environment}`]:[],` Uptime: ${Jr(t.uptime)}`,"","Platform",` OS: ${t.platform} ${t.arch}`,` Hostname: ${t.hostname}`,` Release: ${t.release}`,"","Resources",` CPUs: ${t.cpus}`,` Total Mem: ${Ge(t.totalMemory)}`,` Free Mem: ${Ge(t.freeMemory)}`,"","Paths",` Home: ${t.homeDir}`,` CWD: ${t.cwd}`];await U({title:"Agent System Information",body:h.join(`
|
|
6
|
+
`),footer:"press q to exit"})}})}catch(w){s(`Failed to get system info: ${A(w)}`)}})}var mt="http://localhost:3005";async function Re(b){try{let O=await fetch(`${b}/health/ready`);if(O.status===200||O.status===503)return await O.json();return{healthy:!1,status:O.status}}catch{return{healthy:!1,error:"unreachable"}}}async function ke(b,O){try{let w=await Fe(b);if(!w)return null;let a=await fetch(`${b}/api/profiles/${O}/agent/api-key`,{headers:{"x-agent-api-key":w}});if(!a.ok)return w;return(await a.json()).apiKey??w}catch{return null}}async function gt(b,O){try{return await S(b,`/api/profiles/${O}/plugins`)}catch{return null}}function ee(b){let O=b??{};if(O.error==="unreachable")return i.red("unreachable");if(typeof O.status==="number"&&O.status>=400)return i.red(`http ${O.status}`);let w=typeof O.status==="string"?O.status:"",a=typeof O.bootState==="string"?O.bootState:"";if(w==="ok"&&a==="ready")return i.green("ready");if(a==="awaiting-config")return i.yellow("awaiting-config");if(a==="initializing")return i.yellow("initializing");if(a==="degraded"||w==="degraded")return i.red(`degraded${a?` (${a})`:""}`);if(O.healthy===!1)return i.red("unhealthy");return i.green("healthy")}function pt(b){let w=(b??{}).lastFinalizeError;if(!w||typeof w!=="object")return null;let a=w;if(typeof a.message!=="string"||typeof a.at!=="string")return null;return{message:a.message,at:a.at,attempt:typeof a.attempt==="number"?a.attempt:void 0}}function Ie(b){let O=b??{},w=typeof O.bootState==="string"?O.bootState:"";if(w!=="awaiting-config"&&w!=="degraded")return null;let a=[],p=pt(b);if(p)if(a.push(`${i.gray("\xB7")} Last error: ${i.red(p.message)}`),p.attempt!==void 0)a.push(`${i.gray("\xB7")} Background retry: attempt ${p.attempt}`);else a.push(`${i.gray("\xB7")} Last seen: ${p.at}`);if(w==="awaiting-config")a.push(`${i.gray("\xB7")} Force retry now: ${i.bold("vibe retry-config")}`);return a.push(`${i.gray("\xB7")} Full trace: ${i.bold("vibe logs --since 10m")}`),a.join(`
|
|
7
|
+
`)}async function ft(b,O){let w={agentUrl:O},a=b.jsonKey??b.title.toLowerCase(),p;try{p=await b.render(w)}catch(h){p=i.red(`error (${h.message})`)}let t=null;if(b.json)try{t=await b.json(w)}catch{t=null}return{title:b.title,jsonKey:a,text:p,json:t}}async function Oe(b){let w=Nt().getStatusSections();return Promise.all(w.map((a)=>ft(a,b)))}function Ue(b){b.command("status").description("Show comprehensive status of VibeControls agent instance(s)").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",mt).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=new D;await y({mode:_(w),fetchData:async()=>{if(w.name){let P=await a.getStatus(w.name);if(!P)return{kind:"instance",agentUrl:f(w),instance:null,contributed:[]};let C=P.status==="running"&&P.port?`http://localhost:${P.port}`:f(w);if(P.status!=="running")return{kind:"instance",agentUrl:C,instance:P,contributed:[]};let x=encodeURIComponent(m({profile:P.name})),[N,j,J,te]=await Promise.all([Re(C),ke(C,x),gt(C,x),Oe(C)]);return{kind:"instance",agentUrl:C,instance:P,health:N,apiKey:j,plugins:J,contributed:te}}let p=await a.listInstances(),t=p.filter((P)=>P.status==="running"),h=await Promise.all(t.map(async(P)=>{let C=`http://localhost:${P.port}`,x=encodeURIComponent(m({profile:P.name})),[N,j,J]=await Promise.all([Re(C),ke(C,x),Oe(C)]);return{name:P.name,agentUrl:C,health:N,apiKey:j,contributed:J}}));return{kind:"overview",instances:p,perRunning:h}},plain:(p)=>{if(p.kind==="instance"){if(!p.instance){s(`Agent instance ${i.bold(w.name??"")} not found.`);return}let h=p.instance;if(g(`Agent Status: ${h.name}`),n("Name",h.name),n("Status",G(h.status)),n("PID",h.pid?String(h.pid):i.dim("n/a")),n("Port",h.port?String(h.port):i.dim("n/a")),n("Host",h.config?.host||i.dim("n/a")),n("Database",h.config?.dbPath||i.dim("n/a")),h.startTime)n("Started",v(h.startTime));if(h.status==="running"){c(),n("Health",ee(p.health));let P=Ie(p.health);if(P)c(),console.log(P),c();let C=p.health?.uptime;if(C)n("Uptime",String(C));if(n("API Key",p.apiKey??i.dim("(unavailable)")),p.plugins){let x=p.plugins.plugins??[],N=x.filter((j)=>j.isCore).length;n("Plugins",`${x.length} total (${N} core, ${x.length-N} external)`)}else n("Plugins",i.dim("(unable to fetch)"));for(let x of p.contributed){if(x.text===null)continue;n(x.title,x.text)}}c();return}if(g("Agent Instances"),c(),!p.instances||p.instances.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let t=p.instances.map((h)=>({Name:h.name,Status:G(h.status),PID:h.pid||"-",Port:h.port||"-",Started:h.startTime?v(h.startTime):"-"}));F(t),c();for(let h of p.perRunning){c(),g(`Quick Status: ${h.name}`),n("Health",ee(h.health));let P=Ie(h.health);if(P)c(),console.log(P),c();n("API Key",h.apiKey??i.dim("(unavailable)"));for(let C of h.contributed){if(C.text===null)continue;n(C.title,C.text)}}c(),o(`${d.info} ${p.instances.length} instance(s) found. Use ${i.bold("vibe status -n <name>")} for full details.`)},interactive:async(p)=>{let t=[];if(p.kind==="instance"){if(!p.instance)t.push(`Agent instance "${w.name??""}" not found.`);else{let h=p.instance;if(t.push(`Name: ${h.name}`),t.push(`Status: ${G(h.status)}`),t.push(`PID: ${h.pid??"n/a"}`),t.push(`Port: ${h.port??"n/a"}`),t.push(`Host: ${h.config?.host??"n/a"}`),t.push(`Database: ${h.config?.dbPath??"n/a"}`),h.startTime)t.push(`Started: ${v(h.startTime)}`);if(h.status==="running"){if(t.push(""),t.push(`Health: ${ee(p.health)}`),t.push(`API Key: ${p.apiKey??"(unavailable)"}`),p.plugins){let P=p.plugins.plugins??[],C=P.filter((x)=>x.isCore).length;t.push(`Plugins: ${P.length} (${C} core, ${P.length-C} external)`)}for(let P of p.contributed){if(P.text===null)continue;t.push(`${P.title.padEnd(9)} ${P.text}`)}}}await U({title:`vibe status${w.name?` \u2014 ${w.name}`:""}`,body:t.join(`
|
|
8
8
|
`),footer:"press q to exit"});return}if(!p.instances||p.instances.length===0)t.push("No agent instances found."),t.push("Run `vibe start` to start an agent.");else for(let h of p.instances){t.push(`${i.bold(h.name)} ${G(h.status)}`),t.push(` PID: ${h.pid??"-"}`),t.push(` Port: ${h.port??"-"}`),t.push(` Started: ${h.startTime?v(h.startTime):"-"}`);let P=p.perRunning.find((C)=>C.name===h.name);if(P){t.push(` Health: ${ee(P.health)}`);for(let C of P.contributed){if(C.text===null)continue;t.push(` ${C.title.padEnd(9)} ${C.text}`)}}t.push("")}await U({title:`vibe status \u2014 ${p.instances.length} instance(s)`,body:t.join(`
|
|
9
|
-
`),footer:"press q to exit"})},json:(p)=>{let t=(h)=>Object.fromEntries(h.map((P)=>[P.jsonKey,P.json]));if(p.kind==="instance"){if(!p.instance)return{instance:null};let h={instance:{name:p.instance.name,status:p.instance.status,pid:p.instance.pid,port:p.instance.port,host:p.instance.config?.host,dbPath:p.instance.config?.dbPath,startTime:p.instance.startTime}};if(p.instance.status==="running")h.health=p.health??null,h.plugins=p.plugins??null,Object.assign(h,t(p.contributed));return h}return{instances:p.instances.map((h)=>({name:h.name,status:h.status,pid:h.pid,port:h.port,startTime:h.startTime})),perRunning:p.perRunning.map((h)=>({name:h.name,health:h.health??null,...t(h.contributed)}))}}})}catch(w){let a=w instanceof Error?A(w):String(w);s(`Failed to get status: ${a}`)}})}var dt="http://localhost:3005";function
|
|
10
|
-
`)})},json:(t)=>
|
|
11
|
-
`)})},json:(h)=>
|
|
9
|
+
`),footer:"press q to exit"})},json:(p)=>{let t=(h)=>Object.fromEntries(h.map((P)=>[P.jsonKey,P.json]));if(p.kind==="instance"){if(!p.instance)return{instance:null};let h={instance:{name:p.instance.name,status:p.instance.status,pid:p.instance.pid,port:p.instance.port,host:p.instance.config?.host,dbPath:p.instance.config?.dbPath,startTime:p.instance.startTime}};if(p.instance.status==="running")h.health=p.health??null,h.plugins=p.plugins??null,Object.assign(h,t(p.contributed));return h}return{instances:p.instances.map((h)=>({name:h.name,status:h.status,pid:h.pid,port:h.port,startTime:h.startTime})),perRunning:p.perRunning.map((h)=>({name:h.name,health:h.health??null,...t(h.contributed)}))}}})}catch(w){let a=w instanceof Error?A(w):String(w);s(`Failed to get status: ${a}`)}})}var dt="http://localhost:3005";function Ee(b){b.command("url").description("Show the active URL for a running VibeControls agent").option("--agent-url <url>","Agent URL",dt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(O)=>{try{let w={...b.opts(),...O},a=f(O),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:()=>S(a,`/api/profiles/${p}/agent/url`),plain:(t)=>{if(g("Agent URL"),c(),n("Active URL",i.bold(t.url)),n("Local URL",t.localUrl),t.tunnelUrl)n("Tunnel URL",i.cyan(t.tunnelUrl));if(n("Mode",t.isTunnel?`${d.running} Tunnel active`:`${d.info} Local only`),c(),t.isTunnel)o(`${d.info} Agent is accessible via tunnel at ${i.bold(t.tunnelUrl)}`);else o(`${d.info} Agent is running locally at ${i.bold(t.localUrl)}`)},interactive:async(t)=>{let h=[` Active URL: ${t.url}`,` Local URL: ${t.localUrl}`,` Tunnel URL: ${t.tunnelUrl??"-"}`,` Mode: ${t.isTunnel?"Tunnel active":"Local only"}`];await U({title:"Agent URL",body:h.join(`
|
|
10
|
+
`)})},json:(t)=>k(t)})}catch(w){s(`Failed to get URL: ${w.message}`)}})}var Ce="http://localhost:3005";function xe(b){let O=b.command("gateway-auth").description("Manage gateway authentication for VibeControls agent");O.command("configure").description("Configure gateway authentication credentials").requiredOption("--global-url <url>","Global gateway URL").requiredOption("--workspace-url <url>","Workspace gateway URL").requiredOption("--client-id <id>","OAuth client ID").requiredOption("--client-secret <secret>","OAuth client secret").option("--workspace-id <id>","Workspace ID for auto-report").option("--agent-record-id <id>","Existing backend agent record ID").option("--agent-url <url>","Agent URL",Ce).option("--json","Emit JSON result").action(async(w)=>{try{let a={...b.opts(),...w},p=f(w),t=encodeURIComponent(m(a)),h=await q(p,`/api/profiles/${t}/agent/gateway-auth`,{globalGatewayUrl:w.globalUrl,workspaceGatewayUrl:w.workspaceUrl,clientId:w.clientId,clientSecret:w.clientSecret,workspaceId:w.workspaceId,agentRecordId:w.agentRecordId});if(u(a,{ok:!!h.success,message:h.message??null,globalGatewayUrl:w.globalUrl,workspaceGatewayUrl:w.workspaceUrl,clientId:w.clientId,workspaceId:w.workspaceId??null,agentRecordId:w.agentRecordId??null}))return;if(g("Configure Gateway Authentication"),c(),o(`${d.info} Sending gateway auth configuration...`),c(),h.success){if(l(`${d.success} Gateway authentication configured successfully.`),c(),n("Global URL",w.globalUrl),n("Workspace URL",w.workspaceUrl),n("Client ID",w.clientId),n("Client Secret",i.dim("********")),w.workspaceId)n("Workspace ID",w.workspaceId);if(w.agentRecordId)n("Agent Record ID",w.agentRecordId)}else s(h.message||"Failed to configure gateway authentication.");c()}catch(a){s(`Failed to configure gateway auth: ${a instanceof Error?A(a):String(a)}`)}}),O.command("status").description("Check gateway authentication status").option("--agent-url <url>","Agent URL",Ce).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(w)=>{try{let a={...b.opts(),...w},p=f(w),t=encodeURIComponent(m(a));await y({mode:_(a),fetchData:()=>S(p,`/api/profiles/${t}/agent/gateway-auth`),plain:(h)=>{if(g("Gateway Authentication Status"),c(),n("Configured",h.configured?`${d.success} ${i.green("Yes")}`:`${d.error} ${i.red("No")}`),h.configured){if(n("Global URL",h.config?.globalGatewayUrl||i.dim("n/a")),n("Workspace URL",h.config?.workspaceGatewayUrl||i.dim("n/a")),n("Client ID",h.config?.clientId||i.dim("n/a")),h.config?.workspaceId)n("Workspace ID",h.config.workspaceId)}else c(),o(`${d.info} Run ${i.bold("vibe gateway-auth configure")} to set up gateway authentication.`);c()},interactive:async(h)=>{let P=h.configured?[" Configured: yes",` Global URL: ${h.config?.globalGatewayUrl??"n/a"}`,` Workspace URL: ${h.config?.workspaceGatewayUrl??"n/a"}`,` Client ID: ${h.config?.clientId??"n/a"}`,` Workspace ID: ${h.config?.workspaceId??"-"}`]:[" Configured: no",""," Run `vibe gateway-auth configure` to set up."];await U({title:"Gateway Authentication Status",body:P.join(`
|
|
11
|
+
`)})},json:(h)=>k(h)})}catch(a){s(`Failed to get gateway auth status: ${a instanceof Error?A(a):String(a)}`)}})}function Le(b,O){Se(b),Ae(b),Zr(b),$e(b),Ue(b),Ee(b),xe(b)}var Ne="agent";function Or(b){let O=null,w=re({name:Ne,onShutdown:()=>{pi(),fi()}});return{name:Ne,version:"2.3.0",description:"Core agent identity, system info, setup, gateway authentication, and auto-report",capabilities:{storage:"rw",secrets:"rw",gateway:!0,broadcast:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"agent",apiPrefix:"/api/agent",publicPaths:["/identity","/tunnel"],createRoutes:(a)=>(O=a.db,be(a)),onCliSetup:async(a,p)=>{Le(a,p)},onServerReady:async(a,p)=>{if(O){let t=a,h=(typeof t.decorator?.apiKey==="string"?t.decorator.apiKey:void 0)??(typeof t.store?.apiKey==="string"?t.store.apiKey:void 0)??"unknown",P=new ie(p.logger,"agent-plugin");mi(O,p.serviceRegistry,h).catch((C)=>{P.warn(`Auto-report background task failed: ${C}`)})}},onServerStop:w.onServerStop}}export{Or as createPlugin};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
`,{mode:384}),ut(n,this.path),!k(this.markerPath()))this.writeMarker()}markerPath(){return f(W(this.path),
|
|
4
|
-
`,{mode:384})}catch{}}}var
|
|
5
|
-
`,{mode:384}),ut(r,n)}async function
|
|
6
|
-
`,{mode:384})}catch{return{ok:!1,warning:"could not write install marker"}}let r=[{check:["sh","-c","command -v apt-get"],install:["sudo","-n","apt-get","install","-y","libsecret-1-0"]},{check:["sh","-c","command -v dnf"],install:["sudo","-n","dnf","install","-y","libsecret"]},{check:["sh","-c","command -v pacman"],install:["sudo","-n","pacman","-S","--noconfirm","libsecret"]}];for(let i of r){if(Q(i.check[0],i.check.slice(1),{stdio:["ignore","pipe","pipe"]}).status!==0)continue;let o=Q(i.install[0],i.install.slice(1),{stdio:["ignore","pipe","pipe"]});if(o.status===0)return{ok:!0};return{ok:!1,warning:`auto-install via '${i.install.join(" ")}' failed (exit ${o.status??"unknown"})`}}return{ok:!1,warning:"no supported package manager found"}}var D=null,F=null,ct=null;async function lt(t){try{return await t.get({service:v,name:"__probe__"}),!0}catch{return!1}}async function Xt(){if(ct)return ct;let t
|
|
7
|
-
`,{mode:384}),x(i,r)}function
|
|
8
|
-
`,{mode:384}),x(a,i),s}function
|
|
9
|
-
`,{mode:384}),x(g,r),s}async function
|
|
10
|
-
`,{mode:384}),x(c,r),s})}async function X(t){let n=w({dir:t?.dir,strict:t?.strict}),r=t?.scope??T();for(let i of E){if(n[i])continue;try{let s=await J(m(r,i));if(s)n[i]=s}catch(s){if(t?.strict)throw s}}return n}function ae(){return
|
|
11
|
-
export{J,
|
|
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)}
|
|
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
|
+
`,{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
|
+
`,{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()}
|
|
6
|
+
`,{mode:384})}catch{return{ok:!1,warning:"could not write install marker"}}let r=[{check:["sh","-c","command -v apt-get"],install:["sudo","-n","apt-get","install","-y","libsecret-1-0"]},{check:["sh","-c","command -v dnf"],install:["sudo","-n","dnf","install","-y","libsecret"]},{check:["sh","-c","command -v pacman"],install:["sudo","-n","pacman","-S","--noconfirm","libsecret"]}];for(let i of r){if(Q(i.check[0],i.check.slice(1),{stdio:["ignore","pipe","pipe"]}).status!==0)continue;let o=Q(i.install[0],i.install.slice(1),{stdio:["ignore","pipe","pipe"]});if(o.status===0)return{ok:!0};return{ok:!1,warning:`auto-install via '${i.install.join(" ")}' failed (exit ${o.status??"unknown"})`}}return{ok:!1,warning:"no supported package manager found"}}var D=null,F=null,ct=null;async function lt(t){try{return await t.get({service:v,name:"__probe__"}),!0}catch{return!1}}async function Xt(){if(ct)return ct;let t=$t();if(t&&await lt(t))return new j(t);if(dt()==="linux"&&t){let n=zt();if(n.ok&&await lt(t))return new j(t);if(n.warning)console.warn(`[secrets] libsecret unavailable (${n.warning}); using JSON fallback`);else console.warn("[secrets] Bun.secrets unavailable; using JSON fallback. Install libsecret-1-0 (apt) / libsecret (dnf/pacman) for OS keychain support.")}else if(!t)console.warn("[secrets] Bun.secrets API not present in this runtime; using JSON fallback.");return new kt}async function U(){if(D)return D;if(!F)F=Xt().then((t)=>(D=t,t));return F}async function J(t){let r=await(await U()).get(t);if(pt("read",t))e().audit.emit("agent","secret.read",{name:t,hit:r!==null});return r}async function de(t,n){if(await(await U()).set(t,n),pt("written",t))e().audit.emit("agent","secret.written",{name:t,valueLen:n.length})}async function Wr(){let t=await U(),n=(await t.list()).map((r)=>r.name);return{count:n.length,backend:n.length===0?"none":t.kind,names:n}}async function $i(){let t=await U(),r=(await t.list()).map((i)=>i.name);for(let i of r)try{await t.delete(i)}catch{}if(t.kind==="bun-secrets")G(Y()),G(f(C(),wt));else if(t.kind==="json-fallback"){let i=C();G(f(i,yt)),G(f(i,mt))}return{count:r.length,backend:r.length===0?"none":t.kind,names:r}}function G(t){try{if(k(t))Gt(t)}catch{}}function ne(t){return`agent-config:${t}`}var E=["clientId","clientSecret","gatewayClientId","gatewayClientSecret","static-api-key"];function bt(t){return E.includes(t)}function m(t,n){return`${t}:${n}`}function T(){try{return R()}catch{return"default"}}var y=1,re=[],N={globalGatewayUrl:"https://graphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://graphqlworkspaces.burdenoff.com/workspaces/graphql"},ie={globalGatewayUrl:"https://alphagraphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://alphagraphqlworkspaces.burdenoff.com/workspaces/graphql"},se={globalGatewayUrl:"http://localhost:4000/global/graphql",workspaceGatewayUrl:"http://localhost:4003/workspaces/graphql"},Ht={default:{...N}},Er={local:{...se},alpha:{...ie},prod:{...N}},A="default",St=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function _e(t){if(!St.test(t))throw Error("Profile name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return t}function Et(){return L(C(),"profiles")}function H(){return L(C(),"active")}function $e(t){return L(Et(),`${_e(t)}.json`)}function ye(){let t=H();if(!d(t))return A;try{let n=h(t,"utf8").trim();if(!n)return A;return _e(n)}catch{return A}}function Vt(t){let n=_e(t),r=H();O(B(r),{recursive:!0});let i=`${r}.${process.pid}.tmp`;S(i,`${n}
|
|
7
|
+
`,{mode:384}),x(i,r)}function Xr(){let t=Et();if(!d(t))return[];return Qt(t,{withFileTypes:!0}).filter((n)=>n.isFile()&&n.name.endsWith(".json")).map((n)=>n.name.slice(0,-5)).filter((n)=>St.test(n)).sort()}function It(t){let n=$e(t);if(!d(n))return{};try{return V(h(n,"utf8"))}catch{return{}}}function Pt(t,n){let r=JSON.parse(t);if(!r||typeof r!=="object"||Array.isArray(r))throw Error(`${n} is not a JSON object`);return r}function zr(t){let n=$e(t);if(!d(n))return{};return Pt(h(n,"utf8"),`Profile ${n}`)}function nt(t,n){let r=_e(t),i=$e(r);O(B(i),{recursive:!0});let s={schemaVersion:y,...n},o={...s};for(let g of E){let c=o[g];if(typeof c==="string"&&c.length>0)de(m(r,g),c).catch(()=>{});delete o[g]}let a=`${i}.${process.pid}.tmp`;return S(a,`${JSON.stringify(o,null,2)}
|
|
8
|
+
`,{mode:384}),x(a,i),s}function ei(t){let n=$e(t);if(!d(n))return!1;return te(n,{force:!0}),!0}function _r(t,n={}){let r=Ht[t];return{schemaVersion:y,globalGatewayUrl:r.globalGatewayUrl,workspaceGatewayUrl:r.workspaceGatewayUrl,...n}}function yr(){let t={created:[],activeWritten:null};for(let n of Object.keys(Ht))if(!d($e(n)))nt(n,_r(n)),t.created.push(n);if(!d(H()))Vt(A),t.activeWritten=A;return t}function oe(){return{...N}}function st(t){let n=t?.dir??I();return L(n,"config.json")}function Sr(){return{...N}}function ti(t={}){let n=oe();return{schemaVersion:y,globalGatewayUrl:n.globalGatewayUrl,workspaceGatewayUrl:n.workspaceGatewayUrl,...t}}function V(t){try{let n=JSON.parse(t);if(n&&typeof n==="object")return n}catch{}return{}}function w(t){let n=st(t);if(!d(n))return{};let r;try{let s=h(n,"utf8");r=t?.strict?Pt(s,`Agent config ${n}`):V(s)}catch(s){if(t?.strict)throw s;return{}}if((r.schemaVersion??0)>=y)return r;for(let s of re){if(s.from<(r.schemaVersion??0))continue;r=s.apply(r),r.schemaVersion=s.to}if(r.schemaVersion!==y)r.schemaVersion=y;if(!t?.strict)try{S(n,JSON.stringify(r,null,2),{mode:384})}catch{}return r}function ri(t){let n=w(t);if(n.agentInstanceId)return n.agentInstanceId;let r=ee();return M({agentInstanceId:r},t),r}function M(t,n){let r=st(n);O(B(r),{recursive:!0});let i=d(r)?V(h(r,"utf8")):{},s={...i},o={...i};for(let c of E)delete o[c];let a=n?.scope??T();for(let[c,l]of Object.entries(t)){if(l===void 0||l==="")continue;if(s[c]=l,bt(c)&&typeof l==="string"){de(m(a,c),l).catch(()=>{});continue}o[c]=l}let g=`${r}.${process.pid}.tmp`;return S(g,`${JSON.stringify(o,null,2)}
|
|
9
|
+
`,{mode:384}),x(g,r),s}async function Yt(t,n){let r=st(n);return he(ne(r),async()=>{O(B(r),{recursive:!0});let i=d(r)?V(h(r,"utf8")):{},s={...i},o={...i};for(let l of E)delete o[l];let a=n?.scope??T(),g=[];for(let[l,p]of Object.entries(t)){if(p===void 0||p==="")continue;if(s[l]=p,bt(l)&&typeof p==="string"){g.push(de(m(a,l),p));continue}o[l]=p}await Promise.all(g);let c=`${r}.${process.pid}.tmp`;return S(c,`${JSON.stringify(o,null,2)}
|
|
10
|
+
`,{mode:384}),x(c,r),s})}async function X(t){let n=w({dir:t?.dir,strict:t?.strict}),r=t?.scope??T();for(let i of E){if(n[i])continue;try{let s=await J(m(r,i));if(s)n[i]=s}catch(s){if(t?.strict)throw s}}return n}function ae(){return It(ye())}function u(t){if(!t)return null;try{return new URL(t).origin}catch{return null}}function Zt(t,n=new Date().toISOString()){let r={pairedAt:n},i=u(t.globalGatewayUrl);if(i)r.globalGatewayOrigin=i;let s=u(t.workspaceGatewayUrl);if(s)r.workspaceGatewayOrigin=s;if(t.workspaceId)r.workspaceId=t.workspaceId;if(t.agentRecordId)r.agentRecordId=t.agentRecordId;return r}function ce(t){if(!Boolean(t.clientId||t.pairedIdentity||t.workspaceId||t.agentRecordId))return null;let r=t.pairedIdentity,i={workspaceId:r?.workspaceId??t.workspaceId,globalGatewayUrl:u(r?.globalGatewayOrigin??t.globalGatewayUrl)??void 0,workspaceGatewayUrl:u(r?.workspaceGatewayOrigin??t.workspaceGatewayUrl)??void 0};if(Boolean(i.workspaceId||i.globalGatewayUrl||i.workspaceGatewayUrl))return i;return null}function ii(t,n){let r=ce(t);if(!r)return null;let i=Z(r,n);if(!i.length)return null;let s=b(r),o=t.pairedIdentity?.pairedAt;return`${t.clientId?`This agent is already paired with ${s}.`:`This agent holds no credential right now, but it is still bound to ${s}${o?` (paired ${o})`:""} \u2014 a cleared `+"secrets store is not an unpaired agent."} Refusing a credential push from ${b(n)} (${i.join("; ")}): it would overwrite the only credential slot and strand the existing pairing on 401. Re-send with "force": true to repair deliberately, or run the other environment under its own profile (VIBECONTROLS_PROFILE).`}function ni(t,n,r){let i=Z({globalGatewayUrl:t.globalGatewayUrl,workspaceGatewayUrl:t.workspaceGatewayUrl},{...n,workspaceId:void 0});if(!i.length)return null;let s=u(t.globalGatewayUrl)??u(t.workspaceGatewayUrl)??"its configured gateway";return`Profile "${r}" is configured for ${s}, but this credential push is for ${b(n)} (${i.join("; ")}). Accepting it would repoint the profile `+"without saying so \u2014 the agent would run against one environment while "+`"${r}" still describes another. Run that environment under its own profile (VIBECONTROLS_PROFILE=<name>, or \`vibe profile create <name>\`), or re-send with "force": true to repoint "${r}" deliberately.`}function b(t){return`${u(t.globalGatewayUrl)??"unknown gateway"} (workspace ${t.workspaceId??"unknown"})`}function Z(t,n){let r=[],i=u(t.globalGatewayUrl),s=u(n.globalGatewayUrl);if(i&&s&&i!==s)r.push(`global gateway ${i} -> ${s}`);let o=u(t.workspaceGatewayUrl),a=u(n.workspaceGatewayUrl);if(o&&a&&o!==a)r.push(`workspace gateway ${o} -> ${a}`);if(t.workspaceId&&n.workspaceId&&t.workspaceId!==n.workspaceId)r.push(`workspace ${t.workspaceId} -> ${n.workspaceId}`);return r}function si(t,n){if(!t.clientId)return null;let r=Z(t,n);if(!r.length)return null;return`Credentials were issued for ${b(t)} but this agent is configured for ${b(n)} (${r.join("; ")}). `+"They cannot authenticate there \u2014 re-pair the agent from the environment "+"it should belong to, or clear the conflicting environment override (VIBE_GLOBAL_GATEWAY_URL / VIBE_WORKSPACE_GATEWAY_URL / VIBE_WORKSPACE_ID)."}var z=null;function oi(){return{...z??{}}}function Ct(){try{yr()}catch{}let t=ae(),n=w(),r={...t,...n};if(z===null)z={globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL};let i=(o,a)=>{if(!process.env[o]&&a)process.env[o]=a};i("VIBE_WORKSPACE_ID",r.workspaceId),i("VIBE_ORGANIZATION_ID",r.organizationId);let s=Sr();return i("VIBE_GLOBAL_GATEWAY_URL",r.globalGatewayUrl??s.globalGatewayUrl),i("VIBE_WORKSPACE_GATEWAY_URL",r.workspaceGatewayUrl??s.workspaceGatewayUrl),i("VIBE_STORAGE_ADAPTER",r.storageAdapter),i("VIBECONTROLS_PLUGIN_INSTALL_SCOPE",r.pluginInstallScope),r}async function ai(){let t=(r,i)=>{if(!process.env[r]&&i)process.env[r]=i},n=T();try{let r=await J(m(n,"clientId"));t("VIBE_CLIENT_ID",r??void 0)}catch{}try{let r=await J(m(n,"clientSecret"));t("VIBE_CLIENT_SECRET",r??void 0)}catch{}}
|
|
11
|
+
export{J,de,Wr,$i,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};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Y,
|
|
2
|
+
import{Y,Ce,Ue}from"./index-p1b10hs1.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-0vbsve3v.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(`
|
|
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 yi(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 tr(){return new Set(Y.filter((t)=>t.defaultSelected||t.mandatory).map((t)=>t.key))}function Si(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 ot(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 he(){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 we(t,r,n){return f.join(n??he(),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 be(t){let r=t.platform??fe(),n=O(t.name,t.binaryName),o=we(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 ke(i,o,n,t.name),t.log?.info?.(`[install] installed ${t.name} \u2192 ${o}`),o}async function ke(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 Pe(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 Pe(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",ve={"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"}},Se=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function L(t,r){let n=r?.log??{},o;try{o=await be({name:"cloudflared",downloads:ve,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(Se);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 Te,unlinkSync as Ee}from"fs";import{dirname as Ae,join as F}from"path";import{readdirSync as Ce}from"fs";function A(t){return F(t??I(),"tunnel.state.json")}function j(t,r){let n=A(r);try{xe(Ae(n),{recursive:!0}),Te(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{Ee(r)}catch{}}function ae(t){return b().isProcessAlive(t)}function Ii(t){let r=[];if(t?.allProfiles){let o;try{o=ne()}catch{return r}let i;try{i=Ce(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 rr(t){return t.replace(/[^A-Za-z0-9_]/g,"_")}function v(){return(B()??e()).tunnel}async function Rr(t,r){let n=v();_e(t),Ie();let o=process.env.AGENT_TUNNEL_URL;if(o){let s=It(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)Ht("."+c.slice(-2).join("."))}catch{}try{Z.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let s=rr(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 Ji(){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 ir(){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 at(){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 Ue,mkdirSync as Oe,readFileSync as Be,renameSync as Me,writeFileSync as Fe}from"fs";import{dirname as je,join as ze}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 ze(t??I(),"agent-network.json")}function y(t){let r=z(t);if(!Ue(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 C(t,r){let n=z(r);Oe(je(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;Fe(o,JSON.stringify(t,null,2),{mode:384}),Me(o,n)}function Ci(t){return y(t).peers}function Ve(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 At(t,r){return y(r).peers.filter((n)=>H(n,t))}function Fr(t,r,n){return y(n).peers.find((o)=>o.agentRecordId===t&&H(o,r))??null}function Ye(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 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},C(o,n),o.peers[i]}function Rt(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 Ze(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 nr(){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 Xe(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 Qe(t){let r=Xe(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 et(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 Re(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 nr()}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 Je(t={}){let r=t.onLog??(()=>{}),n=t.restart!==!1,o=t.name||"default",i;try{i=await nr()}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=Qe(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 et(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 tt(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 We(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=tt(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 rt=/^[A-Za-z0-9._+-]+$/,nt=/^(?:@[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}$/,pt=/[`$;&|<>'"\\]/,ft=/['"`$\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 ct(t){if(!t||t.length>128||t.startsWith("-")||!rt.test(t))throw Error(`Invalid agent version: ${t}`);return t}function ut(t){if(!t||t.length>2048||G(t)||ft.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 lt(t){let r=t.trim();if(!r||r.includes("..")||!nt.test(r))throw Error(`Invalid plugin package name: ${t}`);return r}function gt(t){let r=t.trim();if(!r||r.length>16||!it.test(r))throw Error(`Invalid --expires-in value: ${t}`);return r}function Or(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 dt(t){let r=t.trim();if(!r||r.length>128||r.startsWith("-")||G(r)||pt.test(r))throw Error(`Invalid --label value: ${t}`);return r}function Ft(t,r){let n=ut(t),o=ct(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 Ot(t){return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; vibe plugin install "$1"',"_",lt(t)]}function Bt(t){let r=dt(t.label),n=Or(t.scope),o=t.expiresIn?gt(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 me(t,r,n={}){let o=Ve(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{
|
|
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};
|