viben 1.3.3 → 1.3.4
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/index.cjs +3 -3
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -800,7 +800,7 @@ ${u}
|
|
|
800
800
|
${l}`);let h=i.session,_=i.resume;i.newSession?(h=(await rt.createSession(a)).id,n.verbose&&console.log(Y__default.default.gray(`Created new session: ${h}`))):_&&(h=_,n.verbose&&console.log(Y__default.default.gray(`Resuming session: ${h}`)));let y=i.model||c.model,v=i.sdk!==!1,b=await Z5(o,v);if(n.verbose){let A=jk.isSdkAvailable(o);console.log(Y__default.default.gray(`Agent: ${a} (${o})`)),console.log(Y__default.default.gray(`Using ${b.proxyType} proxy`)),A&&b.proxyType==="spawn"&&console.log(Y__default.default.gray("SDK mode available but not used (--no-sdk or SDK not installed)")),y&&console.log(Y__default.default.gray(`Model: ${y}`));}let w=Date.now(),S=await b.execute({prompt:d,cwd:i.cwd||process.cwd(),inputFormat:i.inputFormat,outputFormat:i.outputFormat,verbose:n.verbose,sessionId:h,resume:_,model:y,dangerouslySkipPermissions:i.dangerouslySkipPermissions,systemPrompt:c.systemPrompt,appendPrompt:c.appendPrompt,mcpServers:c.mcpServers,skills:c.skills}),E=Date.now()-w;if(S.exitCode===0&&i.memory!==!1)try{await El.appendToDailyLog(a,{title:"Chat session",items:[`Prompt: ${l.slice(0,100)}${l.length>100?"...":""}`,`Duration: ${E}ms`,h?`Session: ${h}`:"No session"]});}catch{n.verbose&&console.error(Y__default.default.yellow("Warning: Failed to update daily log"));}if(n.json){let A={success:S.exitCode===0,agent_id:a,session_id:h,memory_loaded:i.memory!==!1&&u.length>0,duration_ms:E,error:S.error};console.log(JSON.stringify(A,null,2));}S.error&&console.error(Y__default.default.red(`Error: ${S.error}`)),process.exit(S.exitCode);}catch(a){Z(n,a);}});let r=t.command("session").description("Manage agent sessions");r.command("list").description("List sessions for an agent").requiredOption("-n, --name <agent-id>","Agent ID").action(async i=>{let n=i.name,a=js(e);try{if(!await rt.getAgent(n))throw ne.notFound("Agent",n);let o=await rt.listSessions(n);B(a,J({sessions:o}),()=>{if(o.length===0){console.log(Y__default.default.yellow(`No sessions found for agent: ${n}`));return}gt(a,["ID","Name","Created","Last Accessed"],o.map(l=>[l.id.slice(0,8)+"...",l.name||"-",l.created_at.split("T")[0],l.last_accessed_at.split("T")[0]]));});}catch(c){Z(a,c);}}),r.command("create").description("Create a new session").requiredOption("-n, --name <agent-id>","Agent ID").option("--session-name <name>","Session name").action(async i=>{let n=i.name,a=js(e);try{if(!await rt.getAgent(n))throw ne.notFound("Agent",n);let o=await rt.createSession(n,i.sessionName);B(a,J({session:o}),()=>{Ue(a,`Created session: ${o.id}`),a.verbose&&(console.log(),et(a,{ID:o.id,Agent:o.agent_id,Name:o.name||"-"}));});}catch(c){Z(a,c);}}),r.command("remove").description("Remove a session").requiredOption("-n, --name <agent-id>","Agent ID").requiredOption("-s, --session <session-id>","Session ID").action(async i=>{let n=i.name,a=i.session,c=js(e);try{await rt.removeSession(n,a),B(c,J({removed:a}),()=>{Ue(c,`Removed session: ${a}`);});}catch(o){Z(c,o);}});let s=t.command("memory").description("Manage agent memory");s.command("show").description("Show agent memory").requiredOption("-n, --name <agent-id>","Agent ID").option("-d, --days <days>","Show daily logs for N days",parseInt,7).action(async i=>{let n=i.name,a=js(e);try{if(!await rt.getAgent(n))throw ne.notFound("Agent",n);let o=await El.getMemory(n),l=await El.getMemoryStats(n),u=await El.getRecentLogs(n,i.days),d={memory:o,stats:l,recentLogs:u.map(h=>({date:h.date,entriesCount:h.entries.length}))};B(a,J(d),()=>{if(console.log(Y__default.default.bold(`Memory for agent: ${n}`)),console.log(),et(a,{"Main Memory Size":xoe(l.mainMemorySize),"Daily Logs Count":String(l.dailyLogsCount),"Total Size":xoe(l.totalSize)}),o.content){console.log(),console.log(Y__default.default.bold("Main Memory (MEMORY.md):")),console.log(Y__default.default.gray("\u2500".repeat(40)));let h=o.content.slice(0,500);console.log(h),o.content.length>500&&console.log(Y__default.default.gray(`... (${o.content.length} bytes total)`));}else console.log(),console.log(Y__default.default.gray("No main memory content"));if(u.length>0){console.log(),console.log(Y__default.default.bold(`Recent Daily Logs (last ${i.days} days):`));for(let h of u)console.log(` ${Y__default.default.cyan(h.date)}: ${h.entries.length} entries`);}});}catch(c){Z(a,c);}}),s.command("append").description("Append content to agent memory").requiredOption("-n, --name <agent-id>","Agent ID").argument("<content>","Content to append").action(async(i,n)=>{let a=n.name,c=js(e);try{if(!await rt.getAgent(a))throw ne.notFound("Agent",a);await El.appendMemory(a,i),B(c,J({appended:!0}),()=>{Ue(c,`Appended to memory for agent: ${a}`);});}catch(o){Z(c,o);}}),s.command("clear").description("Clear agent memory").requiredOption("-n, --name <agent-id>","Agent ID").option("-f, --force","Skip confirmation").action(async i=>{let n=i.name,a=js(e);try{if(!await rt.getAgent(n))throw ne.notFound("Agent",n);!i.force&&!a.json&&!a.quiet&&(console.log(Y__default.default.yellow(`Warning: This will clear all memory for agent "${n}".`)),console.log(Y__default.default.gray("Use --force to skip this warning"))),await El.clearMemory(n),B(a,J({cleared:!0}),()=>{Ue(a,`Cleared memory for agent: ${n}`);});}catch(c){Z(a,c);}});}function nct(e,t){return t.concat([e])}function oct(e){if(e==="true")return true;if(e==="false")return false;let t=Number(e);return isNaN(t)?e:t}function cct(e){let t=e.toLowerCase();if(t==="true"||t==="1"||t==="yes")return true;if(t==="false"||t==="0"||t==="no")return false;throw new Error(`Invalid boolean value: ${e}. Use true/false, yes/no, or 1/0.`)}function xoe(e){if(e===0)return "0 B";let t=1024,r=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return `${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${r[s]}`}var uct=$({"src/cli/commands/agent.ts"(){Ou(),wr(),th(),Tk(),zk();}}),Kbe={};yt(Kbe,{registerProviderCommand:()=>lct});function nu(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Ioe(e,t){return [...t??[],e]}function q4(e){if(e!==void 0){if(hM.includes(e))return e;throw new Error(`Invalid provider category: ${e}. Valid categories: ${hM.join(", ")}`)}}function Poe(e){if(e!==void 0){for(let t of e)if(!mk.includes(t))throw new Error(`Invalid provider surface: ${t}. Valid surfaces: ${mk.join(", ")}`);return e}}function lct(e){let t=e.command("provider").description("Manage AI providers");t.command("list").description("List all configured providers").option("--category <category>","Filter by provider category (llm, media)").option("--surface <surface>","Filter by supported surface").action(async function(r){let s=nu(this);try{let i=q4(r.category),n=r.surface;if(n!==void 0&&!mk.includes(n))throw new Error(`Invalid provider surface: ${n}. Valid surfaces: ${mk.join(", ")}`);let a=await mt.listProviders();i&&(a=a.filter(o=>o.category===i)),n&&(a=a.filter(o=>o.surfaces.includes(n)));let c=await mt.getDefault();B(s,J({providers:a,default:c}),()=>{if(a.length===0){console.log(Y__default.default.gray("No providers configured")),console.log(Y__default.default.gray("Use 'viben provider create <id>' to add a provider"));return}gt(s,["ID","Category","Type","Surfaces","Base URL","Default","Enabled"],a.map(o=>[o.id,o.category,o.type,o.surfaces.join(",")||"-",o.base_url||Y__default.default.gray("(default)"),o.isDefault?Y__default.default.green("Yes"):"",o.enabled?"Yes":Y__default.default.red("No")]));});}catch(i){Z(s,i);}}),t.command("create").description("Create a new provider").option("-n, --name <name>","Provider name (auto-generated if not provided)").option("-t, --type <type>",`Provider type (${Bm.join(", ")})`).option("--category <category>","Provider category (llm, media)").option("--surface <surface>","Supported surface",Ioe).option("-u, --base-url <url>","Custom base URL").option("-k, --api-key <key>","API key").option("-c, --config <file>","Config file path").option("--auth <method>","Authentication method").option("--timeout <seconds>","Request timeout in seconds",parseInt).option("--max-retries <count>","Maximum retry attempts",parseInt).option("-d, --default","Set as default provider").action(async function(r){let s=nu(this);try{let i=r.type||"openai";if(!Bm.includes(i))throw new Error(`Invalid provider type: ${i}. Valid types: ${Bm.join(", ")}`);let n=q4(r.category),a=Poe(r.surface),c=r.name||`${i}-${Date.now()}`,o=r.apiKey;!o&&d0[i]&&(o=process.env[d0[i]]);let l=await mt.createProvider({type:i,category:n,name:c,apiKey:o,base_url:r.baseUrl||Z2[i],timeout:r.timeout,max_retries:r.maxRetries,surfaces:a,setAsDefault:r.default});B(s,J({provider:l}),()=>{Ue(s,`Created provider "${l.id}"`),l.isDefault&&console.log(Y__default.default.gray("Set as default provider")),!o&&d0[i]&&console.log(Y__default.default.yellow(`Note: No API key provided. Set ${d0[i]} or update with 'viben provider update ${l.id} --api-key <key>'`));});}catch(i){Z(s,i);}}),t.command("remove").alias("rm").description("Remove a provider").requiredOption("-n, --name <name>","Provider name to remove").action(async function(r){let s=nu(this);try{await mt.removeProvider(r.name),B(s,J({removed:r.name}),()=>{Ue(s,`Removed provider "${r.name}"`);});}catch(i){Z(s,i);}}),t.command("set-default").description("Set the default provider").requiredOption("-n, --name <name>","Provider name to set as default").action(async function(r){let s=nu(this);try{await mt.setDefault(r.name),B(s,J({default:r.name}),()=>{Ue(s,`Set "${r.name}" as default provider`);});}catch(i){Z(s,i);}}),t.command("status").description("Show provider status").option("-n, --name <name>","Provider name (show all if not provided)").action(async function(r){let s=nu(this);try{if(r.name){let i=await mt.checkStatus(r.name);B(s,J({status:i}),()=>{console.log(Y__default.default.bold(`Provider: ${r.name}`)),et(s,{Connected:i.connected?Y__default.default.green("Yes"):Y__default.default.red("No"),Latency:i.latency?`${i.latency}ms`:"-",Error:i.error||"-","Checked At":i.checked_at});});}else {let i=await mt.checkAllStatus(),n=Object.values(i);B(s,J({statuses:i}),()=>{if(n.length===0){console.log(Y__default.default.gray("No providers configured"));return}gt(s,["Provider","Connected","Latency","Error"],n.map(a=>[a.id,a.connected?Y__default.default.green("Yes"):Y__default.default.red("No"),a.latency?`${a.latency}ms`:"-",a.error||"-"]));});}}catch(i){Z(s,i);}}),t.command("show").description("Show provider details").requiredOption("-n, --name <name>","Provider name to show").action(async function(r){let s=nu(this);try{let i=await mt.getProvider(r.name);if(!i)throw new Error(`Provider "${r.name}" not found`);B(s,J({provider:i}),()=>{console.log(Y__default.default.bold(`Provider: ${i.id}`)),et(s,{Type:i.type,Category:i.category,Name:i.name,Surfaces:i.surfaces.join(", ")||"-","Base URL":i.base_url||"(default)","API Key":i.apiKey?"********":Y__default.default.gray("(not set)"),"API Version":i.apiVersion||"-",Deployment:i.deployment||"-",Timeout:i.timeout?`${i.timeout}s`:"-","Max Retries":i.max_retries??"-",Default:i.isDefault?"Yes":"No",Enabled:i.enabled?"Yes":"No",Created:i.created_at,Updated:i.updated_at});});}catch(i){Z(s,i);}}),t.command("update").description("Update a provider").requiredOption("-n, --name <name>","Provider name to update").option("-t, --type <type>","Provider type").option("--category <category>","Provider category (llm, media)").option("--surface <surface>","Supported surface",Ioe).option("-u, --base-url <url>","Custom base URL").option("-k, --api-key <key>","API key").option("--display-name <displayName>","Display name").option("--timeout <seconds>","Request timeout in seconds",parseInt).option("--max-retries <count>","Maximum retry attempts",parseInt).action(async function(r){let s=nu(this);try{if(r.type&&!Bm.includes(r.type))throw new Error(`Invalid provider type: ${r.type}. Valid types: ${Bm.join(", ")}`);let i=q4(r.category),n=Poe(r.surface),a=await mt.updateProvider(r.name,{type:r.type,category:i,name:r.displayName,apiKey:r.apiKey,base_url:r.baseUrl,timeout:r.timeout,max_retries:r.maxRetries,surfaces:n});B(s,J({provider:a}),()=>{Ue(s,`Updated provider "${r.name}"`);});}catch(i){Z(s,i);}}),t.command("enable").description("Enable a provider").requiredOption("-n, --name <name>","Provider name to enable").action(async function(r){let s=nu(this);try{await mt.setEnabled(r.name,!0),B(s,J({enabled:r.name}),()=>{Ue(s,`Enabled provider "${r.name}"`);});}catch(i){Z(s,i);}}),t.command("disable").description("Disable a provider").requiredOption("-n, --name <name>","Provider name to disable").action(async function(r){let s=nu(this);try{await mt.setEnabled(r.name,!1),B(s,J({disabled:r.name}),()=>{Ue(s,`Disabled provider "${r.name}"`);});}catch(i){Z(s,i);}}),t.command("types").description("List supported provider types").action(function(){let r=nu(this),s=Bm.map(i=>({type:i,defaultUrl:Z2[i]||"(custom)",envVar:d0[i]||"-"}));B(r,J({types:s}),()=>{gt(r,["Type","Default Base URL","API Key Env Var"],s.map(i=>[i.type,i.defaultUrl,i.envVar]));});});}var Bm,hM,mk,dct=$({"src/cli/commands/provider.ts"(){wr(),Zp(),Bm=["openai","openai-responses","anthropic","azure","ollama","openrouter","google","volcengine","grok","nanobanana","imagerouter","fal","leonardo","minimax","elevenlabs","fishaudio","senseaudio","aihubmix","suno","udio"],hM=["llm","media"],mk=["chat","image","video","music","speech","sfx"];}}),Jbe={};yt(Jbe,{registerModelCommand:()=>hct});function pct(e,t){return [...t??[],e]}function Aoe(e){if(e!==void 0){if(mM.includes(e))return e;throw new Error(`Invalid model category: ${e}. Valid categories: ${mM.join(", ")}`)}}function L4(e){if(e!==void 0){if(fM.includes(e))return e;throw new Error(`Invalid model surface: ${e}. Valid surfaces: ${fM.join(", ")}`)}}function Rn(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Coe(e){return e===void 0?"-":`$${e.toFixed(2)}/1M`}function M4(e){return e===void 0?"-":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toString()}function hct(e){let t=e.command("model").description("Manage AI models");t.command("list").description("List all registered models").option("-p, --provider <provider>","Filter by provider").option("--category <category>","Filter by model category (llm, media)").option("--surface <surface>","Filter by model surface").action(async function(i){let n=Rn(this);try{let a=Aoe(i.category),c=L4(i.surface),o=await Ge.listModelsFiltered({provider:i.provider,category:a,surface:c}),l=await Ge.getDefault();B(n,J({models:o,default:l}),()=>{if(o.length===0){console.log(Y__default.default.gray("No models found"));return}gt(n,["ID","Name","Provider","Category","Surface","Caps","Context","Default"],o.map(u=>[u.id,u.name,u.provider,u.category??"llm",u.surface??"chat",u.capabilities?.join(",")??"-",M4(u.contextLength),l===u.id?Y__default.default.green("Yes"):""]));});}catch(a){Z(n,a);}}),t.command("show").description("Show model details").requiredOption("-n, --name <model>","Model ID or alias").action(async function(i){let n=i.name,a=Rn(this);try{let c=await Ge.resolveAlias(n),o=Ge.getModelInfo(c),l=await Ge.getModelConfig(n),u=await Ge.getDefault();B(a,J({model:o,resolved:c!==n?c:void 0,config:l,isDefault:u===c}),()=>{if(!o){console.log(Y__default.default.yellow(`Model "${n}" not found`)),c!==n&&console.log(Y__default.default.gray(`Resolved alias: ${c}`));return}console.log(Y__default.default.bold(`Model: ${o.id}`)),c!==n&&console.log(Y__default.default.gray(`(resolved from alias: ${n})`)),et(a,{Name:o.name,Provider:o.provider,"Context Length":M4(o.contextLength),"Max Output":M4(o.maxOutputTokens),"Input Price":Coe(o.inputPrice),"Output Price":Coe(o.outputPrice),"Is Default":u===c?"Yes":"No"}),l&&(console.log(),console.log(Y__default.default.bold("Custom Configuration:")),et(a,{Temperature:l.temperature??"-","Max Tokens":l.maxTokens??"-","Top P":l.topP??"-","Frequency Penalty":l.frequencyPenalty??"-","Presence Penalty":l.presencePenalty??"-"}));});}catch(c){Z(a,c);}}),t.command("status").description("Show model availability status").action(async function(){let i=Rn(this);try{let n=await Ge.listModels(),a=await Ge.getAliases(),c=await Ge.getDefault(),o=[...new Set(n.map(l=>l.provider))];B(i,J({providers:o,modelCount:n.length,aliasCount:Object.keys(a).length,default:c}),()=>{console.log(Y__default.default.bold("Model Status")),console.log(),et(i,{"Known Models":n.length.toString(),Providers:o.join(", "),"Configured Aliases":Object.keys(a).length.toString(),"Default Model":c||Y__default.default.gray("(not set)")}),console.log(),console.log(Y__default.default.bold("Models by Provider:"));for(let l of o){let u=n.filter(d=>d.provider===l).length;console.log(` ${l}: ${u} models`);}});}catch(n){Z(i,n);}}),t.command("set-default").description("Set the default model").requiredOption("-n, --name <model>","Model ID or alias").option("--surface <surface>","Set default for a specific surface").action(async function(i){let n=i.name,a=Rn(this);try{let c=await Ge.resolveAlias(n),o=L4(i.surface);o?await Ge.setDefaultForSurface(o,c):await Ge.setDefault(c),B(a,J({default:c,surface:o}),()=>{Ue(a,o?`Set "${c}" as default ${o} model`:`Set "${c}" as default model`),c!==n&&console.log(Y__default.default.gray(`(resolved from alias: ${n})`));});}catch(c){Z(a,c);}}),t.command("create").description("Create a custom model").requiredOption("-n, --name <model>","Model ID").requiredOption("--provider <provider>","Provider ID or type").option("--display-name <displayName>","Display name").option("--category <category>","Model category (llm, media)").option("--surface <surface>","Model surface").option("--capability <capability>","Capability tag",pct).option("--description <description>","Description").option("--context-window <tokens>","Context window",parseInt).option("--max-output-tokens <tokens>","Max output tokens",parseInt).option("-d, --default","Set as default model").action(async function(i){let n=Rn(this);try{let a=Aoe(i.category),c=L4(i.surface),o=await mt.getProvider(i.provider);if(!o)throw new Error(`Provider not found: ${i.provider}`);let l=await Ge.createModel({id:i.name,name:i.displayName??i.name,provider:o.type,provider_id:o.id,category:a,surface:c,capabilities:i.capability,description:i.description,contextWindow:i.contextWindow,maxOutputTokens:i.maxOutputTokens,setAsDefault:i.default});B(n,J({model:l}),()=>{Ue(n,`Created model "${l.id}"`);});}catch(a){Z(n,a);}});let r=t.command("alias").description("Manage model aliases");r.command("list").description("List all model aliases").action(async function(){let i=Rn(this);try{let n=await Ge.getAliases(),a=Object.entries(n);B(i,J({aliases:n}),()=>{if(a.length===0){console.log(Y__default.default.gray("No aliases configured"));return}console.log(Y__default.default.bold("Model Aliases:")),gt(i,["Alias","Model","Built-in"],a.map(([c,o])=>[c,o,dc[c]?"Yes":""]));});}catch(n){Z(i,n);}}),r.command("create").description("Create or update a model alias").requiredOption("-n, --name <name>","Alias name").requiredOption("-m, --model <model>","Target model ID").action(async function(i){let n=i.name,a=i.model,c=Rn(this);try{await Ge.createAlias(n,a),B(c,J({alias:n,model:a}),()=>{Ue(c,`Set alias "${n}" -> "${a}"`);});}catch(o){Z(c,o);}}),r.command("remove").alias("rm").description("Remove a model alias").requiredOption("-n, --name <name>","Alias name to remove").action(async function(i){let n=i.name,a=Rn(this);try{await Ge.removeAlias(n),B(a,J({removed:n}),()=>{Ue(a,`Removed alias "${n}"`);});}catch(c){Z(a,c);}}),r.command("resolve").description("Resolve an alias to its model ID").requiredOption("-n, --name <name>","Alias name to resolve").action(async function(i){let n=i.name,a=Rn(this);try{let c=await Ge.resolveAlias(n);B(a,J({alias:n,model:c}),()=>{console.log(c===n?Y__default.default.gray(`"${n}" is not an alias, using as model ID`):`${n} -> ${c}`);});}catch(c){Z(a,c);}});let s=t.command("config").description("Manage model-specific configuration");s.command("show").description("Show model-specific configuration").requiredOption("-n, --name <model>","Model ID").action(async function(i){let n=i.name,a=Rn(this);try{let c=await Ge.getModelConfig(n);B(a,J({model:n,config:c}),()=>{if(!c){console.log(Y__default.default.gray(`No custom configuration for "${n}"`));return}console.log(Y__default.default.bold(`Configuration for ${n}:`)),et(a,{Temperature:c.temperature??"-","Max Tokens":c.maxTokens??"-","Top P":c.topP??"-","Frequency Penalty":c.frequencyPenalty??"-","Presence Penalty":c.presencePenalty??"-"});});}catch(c){Z(a,c);}}),s.command("set").description("Set model-specific configuration").requiredOption("-n, --name <model>","Model ID").option("-t, --temperature <value>","Temperature (0-2)",parseFloat).option("--max-tokens <value>","Max tokens",parseInt).option("--top-p <value>","Top P (0-1)",parseFloat).option("--frequency-penalty <value>","Frequency penalty (-2 to 2)",parseFloat).option("--presence-penalty <value>","Presence penalty (-2 to 2)",parseFloat).action(async function(i){let n=i.name,a=Rn(this);try{let c=await Ge.getModelConfig(n),o={temperature:i.temperature??c?.temperature,maxTokens:i.maxTokens??c?.maxTokens,topP:i.topP??c?.topP,frequencyPenalty:i.frequencyPenalty??c?.frequencyPenalty,presencePenalty:i.presencePenalty??c?.presencePenalty};await Ge.setModelConfig(n,o),B(a,J({model:n,config:o}),()=>{Ue(a,`Updated configuration for "${n}"`);});}catch(c){Z(a,c);}}),s.command("remove").alias("rm").description("Remove model-specific configuration").requiredOption("-n, --name <model>","Model ID").action(async function(i){let n=i.name,a=Rn(this);try{await Ge.removeModelConfig(n),B(a,J({removed:n}),()=>{Ue(a,`Removed configuration for "${n}"`);});}catch(c){Z(a,c);}}),t.command("providers").description("List available model providers").action(async function(){let i=Rn(this);try{let n=await Ge.listModels(),c=[...new Set(n.map(o=>o.provider))].map(o=>({provider:o,modelCount:n.filter(l=>l.provider===o).length}));B(i,J({providers:c}),()=>{console.log(Y__default.default.bold("Available Providers:")),gt(i,["Provider","Models"],c.map(o=>[o.provider,o.modelCount.toString()]));});}catch(n){Z(i,n);}});}var mM,fM,mct=$({"src/cli/commands/model.ts"(){wr(),xk(),Zp(),mM=["llm","media"],fM=["chat","image","video","music","speech","sfx"];}}),Ybe={};yt(Ybe,{registerChannelCommand:()=>fct});function sc(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function fct(e){let t=e.command("channel").description("Manage notification channels");t.command("types").description("List supported channel types").action(async()=>{let r=sc(e);try{let s=j5;B(r,J({types:s}),()=>{console.log(Y__default.default.bold("Supported Channel Types:")),console.log(),gt(r,["Type","Name","Description","Difficulty"],s.map(i=>[i.id,i.name,i.description,i.setupDifficulty]));});}catch(s){Z(r,s);}}),t.command("list").description("List all configured channels").action(async()=>{let r=sc(e);try{let s=await er.listChannels(),i=await er.getDefaultChannel();B(r,J({channels:s,default:i?.id,count:s.length}),()=>{if(s.length===0){console.log(Y__default.default.gray("No channels configured.")),console.log(),console.log("Create a channel with:"),console.log(Y__default.default.cyan(" viben channel create my-telegram --type telegram --token <BOT_TOKEN>"));return}console.log(Y__default.default.bold("Channels:")),console.log(),gt(r,["ID","Name","Type","Status","Default"],s.map(n=>[n.id,n.name,n.type,n.enabled?Y__default.default.green("enabled"):Y__default.default.gray("disabled"),n.is_default?Y__default.default.yellow("*"):""])),i&&(console.log(),console.log(Y__default.default.yellow("* = default channel")));});}catch(s){Z(r,s);}}),t.command("create <id>").description("Create a new channel").requiredOption("--type <type>","Channel type: telegram, discord, feishu, whatsapp, slack, webhook").option("-n, --name <name>","Channel display name (defaults to ID)").option("--token <token>","Bot token (for Telegram, Discord, Slack)").option("--chat-id <id>","Default chat ID").option("--app-id <id>","App ID (for Feishu)").option("--app-secret <secret>","App Secret (for Feishu)").option("--url <url>","Webhook URL (for Webhook)").option("--bridge-url <url>","Bridge URL (for WhatsApp)").option("--proxy <url>","Proxy URL (for Telegram)").option("--disabled","Create channel as disabled").option("--set-default","Set as default channel").action(async(r,s)=>{let i=sc(e);try{let n=["telegram","discord","feishu","whatsapp","slack","webhook"],a=s.type.toLowerCase();if(!n.includes(a))throw new Error(`Invalid channel type: ${s.type}. Valid types: ${n.join(", ")}`);let c={id:r,name:s.name||r,type:a,enabled:!s.disabled,set_as_default:s.setDefault,token:s.token,proxy:s.proxy,app_id:s.appId,app_secret:s.appSecret,bridge_url:s.bridgeUrl,url:s.url,channel_id:s.chatId},o=await er.createChannel(c);B(i,J({channel:o}),()=>{Ue(i,`Channel "${o.id}" created successfully`),console.log(),et(i,{ID:o.id,Name:o.name,Type:o.type,Status:o.enabled?"enabled":"disabled",Default:o.is_default?"yes":"no"});});}catch(n){Z(i,n);}}),t.command("remove").description("Remove a channel").requiredOption("-n, --name <id>","Channel ID to remove").option("-f, --force","Skip confirmation").action(async r=>{let s=sc(e),i=r.name;try{if(!await er.getChannel(i))throw new Error(`Channel "${i}" not found`);await er.removeChannel(i),B(s,J({removed:i}),()=>{Ue(s,`Channel "${i}" removed successfully`);});}catch(n){Z(s,n);}}),t.command("enable").description("Enable a channel").requiredOption("-n, --name <id>","Channel ID to enable").action(async r=>{let s=sc(e),i=r.name;try{let n=await er.enableChannel(i);B(s,J({channel:n}),()=>{Ue(s,`Channel "${i}" enabled`);});}catch(n){Z(s,n);}}),t.command("disable").description("Disable a channel").requiredOption("-n, --name <id>","Channel ID to disable").action(async r=>{let s=sc(e),i=r.name;try{let n=await er.disableChannel(i);B(s,J({channel:n}),()=>{Ue(s,`Channel "${i}" disabled`);});}catch(n){Z(s,n);}}),t.command("set-default").description("Set the default channel").requiredOption("-n, --name <id>","Channel ID to set as default").action(async r=>{let s=sc(e),i=r.name;try{let n=await er.setDefaultChannel(i);B(s,J({channel:n}),()=>{Ue(s,`Channel "${i}" set as default`);});}catch(n){Z(s,n);}}),t.command("status").description("Show channel status (tests connectivity)").option("-n, --name <id>","Channel ID to check status for").action(async r=>{let s=sc(e),i=r.name;try{if(i){let n=await er.getChannelStatus(i);B(s,J({status:n}),()=>{console.log(Y__default.default.bold(`Channel: ${n.id}`)),console.log(),et(s,{Name:n.name,Type:n.type,Enabled:n.enabled?"yes":"no",Default:n.is_default?"yes":"no",Status:Ooe(n.status),Details:n.details||"-",Error:n.error||"-",Latency:n.latency_ms?`${n.latency_ms}ms`:"-"});});}else {let n=await er.getAllChannelStatuses();B(s,J({statuses:n,count:n.length}),()=>{if(n.length===0){console.log(Y__default.default.gray("No channels configured."));return}console.log(Y__default.default.bold("Channel Status:")),console.log(),gt(s,["ID","Type","Enabled","Status","Latency"],n.map(a=>[a.is_default?`${a.id}${Y__default.default.yellow("*")}`:a.id,a.type,a.enabled?Y__default.default.green("yes"):Y__default.default.gray("no"),Ooe(a.status),a.latency_ms?`${a.latency_ms}ms`:"-"]));});}}catch(n){Z(s,n);}}),t.command("config").description("Show or edit channel configuration").requiredOption("-n, --name <id>","Channel ID").argument("[action]","Action: set").argument("[key]","Configuration key").argument("[value]","Configuration value").action(async(r,s,i,n)=>{let a=sc(e),c=n.name;try{let o=await er.getChannel(c);if(!o)throw new Error(`Channel "${c}" not found`);if(r==="set"&&s){let l=await er.updateChannelConfig(c,s,i);B(a,J({channel:l}),()=>{Ue(a,`Channel "${c}" config updated: ${s}=${i}`);});}else B(a,J({channel:o}),()=>{if(console.log(Y__default.default.bold(`Channel: ${o.id}`)),console.log(),et(a,{ID:o.id,Name:o.name,Type:o.type,Enabled:o.enabled?"yes":"no",Default:o.is_default?"yes":"no","Created At":new Date(o.created_at).toLocaleString(),"Updated At":o.updated_at?new Date(o.updated_at).toLocaleString():"-","Notification Mode":o.notification_mode,"Allow From":o.allow_from.length>0?o.allow_from.join(", "):"(all)"}),Object.keys(o.config).length>0){console.log(),console.log(Y__default.default.bold("Type-specific Config:")),console.log();let l={};for(let[u,d]of Object.entries(o.config))u==="token"||u==="app_secret"?l[u]=d?gct(String(d)):"-":l[u]=d!=null?String(d):"-";et(a,l);}console.log(),console.log("To update a config value:"),console.log(Y__default.default.cyan(` viben channel config ${c} set <key> <value>`));});}catch(o){Z(a,o);}}),t.command("login <type>").description("Interactive login for a channel type").option("-n, --name <id>","Channel ID to login (for existing channel)").action(async(r,s)=>{let i=sc(e);try{let n=["telegram","discord","feishu","whatsapp","slack","webhook"],a=r.toLowerCase();if(!n.includes(a))throw new Error(`Invalid channel type: ${r}. Valid types: ${n.join(", ")}`);if(s.name){let c=await er.getChannel(s.name);if(!c)throw new Error(`Channel "${s.name}" not found`);if(c.type==="whatsapp"){console.log(Y__default.default.yellow("WhatsApp login requires bridge interaction.")),console.log("Please ensure your WhatsApp bridge is running and scan the QR code.");return}console.log(Y__default.default.gray(`Login flow for ${c.type} is not yet implemented.`)),console.log("Please configure credentials manually:"),console.log(Y__default.default.cyan(` viben channel config ${c.id} set token <YOUR_TOKEN>`));return}B(i,J({type:a,guide:!0}),()=>{switch(console.log(Y__default.default.bold(`Login Guide for ${a}:`)),console.log(),a){case "telegram":console.log("1. Open Telegram and search for @BotFather"),console.log("2. Send /newbot and follow the instructions"),console.log("3. Copy the bot token"),console.log("4. Create the channel:"),console.log(Y__default.default.cyan(" viben channel create my-telegram --type telegram --token <BOT_TOKEN>"));break;case "discord":console.log("1. Go to https://discord.com/developers/applications"),console.log("2. Create a new application"),console.log("3. Go to Bot section and create a bot"),console.log("4. Copy the bot token"),console.log("5. Create the channel:"),console.log(Y__default.default.cyan(" viben channel create my-discord --type discord --token <BOT_TOKEN>"));break;case "feishu":console.log("1. Go to https://open.feishu.cn/"),console.log("2. Create a new application"),console.log("3. Get App ID and App Secret"),console.log("4. Create the channel:"),console.log(Y__default.default.cyan(" viben channel create my-feishu --type feishu --app-id <ID> --app-secret <SECRET>"));break;case "slack":console.log("1. Go to https://api.slack.com/apps"),console.log("2. Create a new app"),console.log("3. Install to your workspace"),console.log("4. Copy the Bot User OAuth Token"),console.log("5. Create the channel:"),console.log(Y__default.default.cyan(" viben channel create my-slack --type slack --token <BOT_TOKEN>"));break;case "whatsapp":console.log("WhatsApp requires a bridge server."),console.log("1. Set up a WhatsApp bridge (e.g., whatsapp-web.js)"),console.log("2. Create the channel:"),console.log(Y__default.default.cyan(" viben channel create my-whatsapp --type whatsapp --bridge-url <BRIDGE_URL>")),console.log("3. Login via bridge QR code");break;case "webhook":console.log("Webhook channels send messages to a URL."),console.log("1. Set up your webhook endpoint"),console.log("2. Create the channel:"),console.log(Y__default.default.cyan(" viben channel create my-webhook --type webhook --url <WEBHOOK_URL>"));break}});}catch(n){Z(i,n);}}),t.command("test <id>").description("Send a test message through the channel").argument("[chat-id]","Target chat/channel ID to send test message").action(async(r,s)=>{let i=sc(e);try{let n=await er.getChannel(r);if(!n)throw new Error(`Channel "${r}" not found`);let a=er.buildChannelConfig(r,{type:n.type,name:n.name,enabled:n.enabled,created_at:n.created_at,allow_from:n.allow_from,...n.config});console.log(Y__default.default.gray("Testing channel connectivity..."));let c=await Xye(a);if(!c.success)throw new Error(`Channel test failed: ${c.error}`);if(console.log(Y__default.default.green("Connectivity test passed.")),s){console.log(Y__default.default.gray("Sending test message..."));let o=await Zye(a,s);if(!o.success)throw new Error(`Failed to send test message: ${o.error}`);B(i,J({test:"passed",message:"sent"}),()=>{Ue(i,"Test message sent successfully!"),o.messageId&&console.log(Y__default.default.gray(`Message ID: ${o.messageId}`));});}else B(i,J({test:"passed"}),()=>{Ue(i,"Channel connectivity test passed!"),c.details&&console.log(Y__default.default.gray(c.details)),console.log(),console.log("To send a test message:"),console.log(Y__default.default.cyan(` viben channel test ${r} <CHAT_ID>`));});}catch(n){Z(i,n);}});}function Ooe(e){switch(e){case "connected":return Y__default.default.green("connected");case "disconnected":return Y__default.default.gray("disconnected");case "error":return Y__default.default.red("error");case "disabled":return Y__default.default.gray("disabled");default:return e}}function gct(e){return e.length<=8?"****":e.substring(0,4)+"****"+e.substring(e.length-4)}var yct=$({"src/cli/commands/channel.ts"(){wr(),y_();}}),Qbe={};yt(Qbe,{registerServiceCommand:()=>kct});function Foe(e){switch(e){case "running":return Y__default.default.green("running");case "stopped":return Y__default.default.gray("stopped");case "failed":return Y__default.default.red("failed");default:return Y__default.default.yellow("unknown")}}function Ow(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}async function _ct(e,t){if(t){let i=await Ga.getServiceStatus(t);B(e,J(i),()=>{if(console.log(Y__default.default.bold(`Service: ${i.name}`)),console.log(),console.log(` ${Y__default.default.cyan("Type:")} ${i.type}`),console.log(` ${Y__default.default.cyan("Status:")} ${Foe(i.status)}`),i.pid&&console.log(` ${Y__default.default.cyan("PID:")} ${i.pid}`),i.uptime&&console.log(` ${Y__default.default.cyan("Uptime:")} ${i.uptime}`),i.command){let n=i.args?.length?`${i.command} ${i.args.join(" ")}`:i.command;console.log(` ${Y__default.default.cyan("Command:")} ${n}`);}i.error&&console.log(` ${Y__default.default.cyan("Error:")} ${Y__default.default.red(i.error)}`);});return}let r=await Ga.listServices(),s=J({services:r.map(i=>({name:i.name,type:i.type,status:i.status,pid:i.pid,uptime:i.uptime})),count:r.length});B(e,s,()=>{if(console.log(Y__default.default.bold("Services:")),console.log(),r.length===0){console.log(Y__default.default.gray(" No services tracked."));return}let i=["Name","Type","Status","PID","Uptime"],n=r.map(a=>[a.name,a.type,Foe(a.status),a.pid?.toString()||Y__default.default.gray("-"),a.uptime||Y__default.default.gray("-")]);gt(e,i,n);});}async function vct(e,t,r,s){let i=await Ga.getServiceStatus(t);if(i.status==="running"){B(e,J({name:t,status:"running",message:"Service is already running",pid:i.pid,uptime:i.uptime}),()=>{console.log(Y__default.default.yellow(`Service ${t} is already running`)),console.log(` PID: ${i.pid}`),console.log(` Uptime: ${i.uptime}`);});return}let n=await Ga.startService(t,r,s);n.status==="running"?B(e,J({name:t,status:"running",pid:n.pid,command:n.command,args:n.args}),()=>{if(console.log(Y__default.default.green(`Started service ${t}`)),console.log(` PID: ${n.pid}`),n.command){let a=n.args?.length?`${n.command} ${n.args.join(" ")}`:n.command;console.log(` Command: ${a}`);}}):B(e,J({name:t,status:n.status,error:n.error}),()=>{console.error(Y__default.default.red(`Failed to start service ${t}`)),n.error&&console.error(` Error: ${n.error}`);});}async function bct(e,t){let r=await Ga.getServiceStatus(t);if(r.status!=="running"){B(e,J({name:t,status:"stopped",message:"Service is not running"}),()=>{console.log(Y__default.default.yellow(`Service ${t} is not running`));});return}await Ga.stopService(t);B(e,J({name:t,status:"stopped",previousPid:r.pid}),()=>{console.log(Y__default.default.green(`Stopped service ${t}`)),console.log(` Previous PID: ${r.pid}`);});}async function wct(e,t,r,s){let i=await Ga.restartService(t,r,s);B(e,J({name:t,status:i.status,pid:i.pid}),()=>{i.status==="running"?(console.log(Y__default.default.green(`Restarted service ${t}`)),console.log(` PID: ${i.pid}`)):(console.log(Y__default.default.yellow(`Service ${t} status: ${i.status}`)),i.error&&console.log(` Error: ${i.error}`));});}async function Sct(e,t,r){let{follow:s,lines:i=100,clear:n}=r;if(n){await Ga.clearLogs(t),B(e,J({name:t,cleared:true}),()=>{console.log(Y__default.default.green(`Cleared logs for service ${t}`));});return}let a=Ga.getLogPath(t);if(s){if(e.json){let u=await Ga.getServiceLogs(t,i);console.log(JSON.stringify({success:true,data:{name:t,logPath:a,lines:u,count:u.length,note:"Follow mode not supported in JSON output"}},null,2));return}console.log(Y__default.default.bold(`Logs for ${t}:`)),console.log(Y__default.default.gray(`Path: ${a}`)),console.log(Y__default.default.gray("Press Ctrl+C to stop following")),console.log();let o=await Ga.getServiceLogs(t,i);for(let u of o)console.log(u);let l=Ga.watchLogs({name:t,onLine:u=>{console.log(u);}});process.on("SIGINT",()=>{l(),console.log(),console.log(Y__default.default.gray("Stopped following logs")),process.exit(0);}),await new Promise(()=>{});return}let c=await Ga.getServiceLogs(t,i);B(e,J({name:t,logPath:a,lines:c,count:c.length}),()=>{if(console.log(Y__default.default.bold(`Logs for ${t}:`)),console.log(Y__default.default.gray(`Path: ${a}`)),console.log(),c.length===0){console.log(Y__default.default.gray("No logs available."));return}for(let o of c)console.log(o);});}function kct(e){let t=e.command("service").description("Manage background services");t.command("status").argument("[name]","Service name").description("Show service status (all or specific)").action(async r=>{let s=Ow(e);try{await _ct(s,r);}catch(i){Z(s,i);}}),t.command("start").argument("<name>","Service name").option("-c, --command <command>","Command to run").argument("[args...]","Arguments to pass to the command").description("Start a service").action(async(r,s,i)=>{let n=Ow(e);try{await vct(n,r,i.command,s.length>0?s:void 0);}catch(a){Z(n,a);}}),t.command("stop").argument("<name>","Service name").description("Stop a service").action(async r=>{let s=Ow(e);try{await bct(s,r);}catch(i){Z(s,i);}}),t.command("restart").argument("<name>","Service name").option("-c, --command <command>","Command to run").argument("[args...]","Arguments to pass to the command").description("Restart a service").action(async(r,s,i)=>{let n=Ow(e);try{await wct(n,r,i.command,s.length>0?s:void 0);}catch(a){Z(n,a);}}),t.command("logs").argument("<name>","Service name").option("-f, --follow","Follow log output").option("-n, --lines <number>","Number of lines to show","100").option("--clear","Clear service logs").description("Show/follow service logs").action(async(r,s)=>{let i=Ow(e);try{await Sct(i,r,{follow:s.follow,lines:s.lines?parseInt(s.lines,10):100,clear:s.clear});}catch(n){Z(i,n);}});}var Ect=$({"src/cli/commands/service.ts"(){wr(),KA();}}),Xbe,Doe=$({"src/gateway/queue/types.ts"(){Xbe={max_concurrency:3,default_max_retries:3,persist_debounce_ms:500,shutdown_timeout_ms:3e4};}});function M0(){return qe.join(nn.homedir(),".viben","queue")}function $oe(){return qe.join(M0(),"state.yaml")}function gM(){return qe.join(M0(),"tasks")}function Roe(){return qe.join(M0(),"corrupted")}function PI(e){return qe.join(gM(),`task-${e}.yaml`)}function Act(e){return P2||(P2=new Zbe(e)),P2}var Tm,Zbe,P2,Cct=$({"src/gateway/queue/persistence.ts"(){Pr(),Ye(),Tm=je.child({module:"queue-persistence"}),Zbe=class{constructor(e=500){this.stateDebounceTimer=null,this.pendingState=null,this.taskDebounceTimers=new Map,this.pendingTasks=new Map,this.debounceMs=e;}async ensureDirectories(){await _t(M0()),await _t(gM());}async loadState(){let e=$oe();return It(e)}async saveState(e,t=false){if(t){await this.writeState(e);return}this.pendingState=e,this.stateDebounceTimer&&clearTimeout(this.stateDebounceTimer),this.stateDebounceTimer=setTimeout(async()=>{this.pendingState&&(await this.writeState(this.pendingState),this.pendingState=null);},this.debounceMs);}async writeState(e){await this.ensureDirectories();let t=$oe();e.last_updated=Date.now(),await xr(t,e);}async loadTask(e){let t=PI(e),r=await It(t);if(r)return {id:r.id,type:r.type,payload:r.payload,status:r.status,retry_count:r.retry_count,max_retries:r.max_retries,created_at:r.created_at,started_at:r.started_at,completed_at:r.completed_at,error:r.error}}async saveTask(e,t=false){let r={id:e.id,type:e.type,status:e.status,retry_count:e.retry_count,max_retries:e.max_retries,created_at:e.created_at,started_at:e.started_at,completed_at:e.completed_at,error:e.error,payload:e.payload};if(t){let n=this.taskDebounceTimers.get(e.id);n&&(clearTimeout(n),this.taskDebounceTimers.delete(e.id)),this.pendingTasks.delete(e.id),await this.writeTask(e.id,r);return}this.pendingTasks.set(e.id,r);let s=this.taskDebounceTimers.get(e.id);s&&clearTimeout(s);let i=setTimeout(async()=>{let n=this.pendingTasks.get(e.id);if(n)try{await this.writeTask(e.id,n);}catch(a){throw Tm.error({err:a,taskId:e.id},"Failed to write task"),a}finally{this.pendingTasks.delete(e.id),this.taskDebounceTimers.delete(e.id);}},this.debounceMs);this.taskDebounceTimers.set(e.id,i);}async writeTask(e,t){await this.ensureDirectories();let r=PI(e);await xr(r,t);}async deleteTask(e){let t=PI(e);if(Ne.existsSync(t))try{await Xs.unlink(t);}catch(r){Tm.warn({err:r,taskId:e},"Failed to delete task");}}async moveToCorrupted(e){let t=PI(e);if(!Ne.existsSync(t))return;await _t(Roe());let r=qe.join(Roe(),`task-${e}-${Date.now()}.yaml`);try{await Xs.rename(t,r),Tm.warn({taskId:e,corruptedPath:r},"Moved corrupted task");}catch(s){Tm.error({err:s,taskId:e},"Failed to move corrupted task");}}async loadAllTasks(){let e=new Map,t=gM();if(!Ne.existsSync(t))return e;try{let r=await Xs.readdir(t);for(let s of r){if(!s.startsWith("task-")||!s.endsWith(".yaml"))continue;let i=s.replace(/^task-/,"").replace(/\.yaml$/,"");try{let n=await this.loadTask(i);n&&e.set(i,n);}catch(n){Tm.error({err:n,taskId:i},"Failed to load task"),await this.moveToCorrupted(i);}}}catch(r){Tm.error({err:r},"Failed to read tasks directory");}return e}async flush(){this.stateDebounceTimer&&(clearTimeout(this.stateDebounceTimer),this.stateDebounceTimer=null),this.pendingState&&(await this.writeState(this.pendingState),this.pendingState=null);for(let[e,t]of this.taskDebounceTimers)clearTimeout(t);this.taskDebounceTimers.clear();for(let[e,t]of this.pendingTasks)await this.writeTask(e,t);this.pendingTasks.clear();}async saveConfig(e){await this.ensureDirectories();let t=qe.join(M0(),"config.yaml");await xr(t,e);}async loadConfig(){let e=qe.join(M0(),"config.yaml");return It(e)}},P2=null;}});function Fct(e,t){if(t!==void 0)return t!==0;if(e){if(e.includes("rate limit")||e.includes("429")||e.includes("ETIMEDOUT")||e.includes("ECONNREFUSED")||e.includes("ENOTFOUND")||e.includes("network")||e.includes("timeout")||e.includes("exited with code"))return true;if(e.includes("API key")||e.includes("authentication")||e.includes("401")||e.includes("not found")||e.includes("ENOENT"))return false}return true}var z4,ewe,Dct=$({"src/gateway/queue/worker.ts"(){ah(),Ye(),z4=je.child({module:"queue-worker"}),ewe=class extends Tst.EventEmitter{constructor(){super(...arguments),this.abortControllers=new Map,this.activeExecutions=new Map;}async execute(e){let t=Date.now(),r=new AbortController;this.abortControllers.set(e.id,r);let s=this.runTask(e,t,r.signal);this.activeExecutions.set(e.id,s);try{return await s}finally{this.abortControllers.delete(e.id),this.activeExecutions.delete(e.id);}}async runTask(e,t,r){let s=new Au,i=e.payload;try{let n=s.executeStreaming({prompt:i.input,cwd:i.cwd||process.cwd(),sessionId:i.session_id,resume:i.resume_session,dangerouslySkipPermissions:!0}),a=!1,c;for await(let l of n){if(r.aborted)return {success:!1,error:"Task cancelled",duration:Date.now()-t};this.emit("progress",e.id,l),l.type==="error"&&(a=!0,c=l.message),l.type==="result"&&l.subtype==="error"&&(a=!0);}let o=Date.now()-t;return a?{success:!1,error:c||"Task execution failed",duration:o}:{success:!0,duration:o}}catch(n){let a=n instanceof Error?n.message:String(n),c=Date.now()-t,o=a;if(a.includes("exited with code")){let l=a.match(/exited with code (\d+)/),u=l?parseInt(l[1],10):1;return {success:false,error:`Agent process exited with code ${u}`,duration:c,exit_code:u}}return {success:false,error:o,duration:c}}}cancel(e){let t=this.abortControllers.get(e);return t?(t.abort(),z4.info({taskId:e},"Cancelled task"),true):false}isExecuting(e){return this.activeExecutions.has(e)}getActiveCount(){return this.activeExecutions.size}async waitForAll(e){if(this.activeExecutions.size===0)return true;let t=Array.from(this.activeExecutions.values()),r=new Promise(i=>setTimeout(()=>i("timeout"),e));return await Promise.race([Promise.allSettled(t).then(()=>"done"),r])==="done"}cancelAll(){for(let[e,t]of this.abortControllers)t.abort(),z4.info({taskId:e},"Force cancelled task");this.abortControllers.clear();}};}});function Nct(){return `task_${nk.randomUUID()}`}var Ma,twe,qct=$({"src/gateway/queue/index.ts"(){Doe(),Cct(),Dct(),Ye(),Doe(),w_e(),Ma=je.child({module:"task-queue"}),twe=class extends Tst.EventEmitter{constructor(e,t){super(),this.queue=[],this.running=new Map,this.tasks=new Map,this.accepting=true,this.started=false,this.events=e,this.config={...Xbe,...t},this.persistence=Act(this.config.persist_debounce_ms),this.worker=new ewe,this.worker.on("progress",(r,s)=>{this.emit("task:progress",{id:r,progress:s}),this.events.broadcast({type:"queue_task_progress",data:{task_id:r,progress:s}});});}async start(){this.started||(Ma.info("Starting queue manager..."),await this.restore(),this.started=true,this.accepting=true,this.tryDequeue(),Ma.info("Queue manager started"));}async enqueue(e){if(!this.accepting)throw new Error("Queue is not accepting new tasks");let t=Nct(),r=Date.now(),s={agent_id:e.agent_id,session_id:e.session_id,input:e.input,cwd:e.cwd,agent_config_path:e.agent_config_path,resume_session:e.resume_session,attachments:e.attachments},i={id:t,type:"agent-run",payload:s,status:"pending",retry_count:0,max_retries:e.max_retries??this.config.default_max_retries,created_at:r};return this.queue.push(i),this.tasks.set(t,i),await this.persistTask(i,true),await this.persistState(true),this.emit("task:queued",{task:i}),this.events.broadcast({type:"queue_task_queued",data:{task:this.taskToSummary(i)}}),this.emitQueueChanged(),Ma.info({taskId:t,position:this.queue.length},"Task enqueued"),this.tryDequeue(),{task_id:t,position:this.queue.length,status:"pending"}}async cancel(e){let t=this.tasks.get(e);if(!t)return false;if(t.status==="pending"){let r=this.queue.findIndex(s=>s.id===e);r!==-1&&this.queue.splice(r,1),t.status="failed",t.error="Cancelled by user",t.completed_at=Date.now();}else if(t.status==="running")this.worker.cancel(e),this.running.delete(e),t.status="failed",t.error="Cancelled by user",t.completed_at=Date.now();else return false;return await this.persistTask(t),await this.persistState(),this.emit("task:cancelled",{task:t}),this.events.broadcast({type:"queue_task_cancelled",data:{task:this.taskToSummary(t)}}),this.emitQueueChanged(),Ma.info({taskId:e},"Task cancelled"),true}getTask(e){return this.tasks.get(e)}getTasks(e){let t=Array.from(this.tasks.values());return e?t.filter(r=>r.status===e):t}getStatus(){let e=this.queue.map((r,s)=>({...this.taskToSummary(r),position:s+1})),t=Array.from(this.running.values()).map(r=>this.taskToSummary(r));return {pending_count:this.queue.length,running_count:this.running.size,max_concurrency:this.config.max_concurrency,tasks:[...e,...t]}}async updateConfig(e){return this.config={...this.config,...e},await this.persistence.saveConfig(this.config),e.max_concurrency&&this.tryDequeue(),this.config}getConfig(){return {...this.config}}async shutdown(){if(Ma.info("Shutting down..."),this.accepting=false,!await this.worker.waitForAll(this.config.shutdown_timeout_ms)){Ma.warn("Shutdown timeout, force cancelling remaining tasks"),this.worker.cancelAll();for(let[t,r]of this.running)r.status="failed",r.error="Shutdown timeout",r.completed_at=Date.now(),await this.persistTask(r);}await this.persistState(true),await this.persistence.flush(),this.started=false,Ma.info("Shutdown complete");}tryDequeue(){for(;this.running.size<this.config.max_concurrency&&this.queue.length>0;){let e=this.queue.shift();if(!e)break;this.executeTask(e);}}async executeTask(e){e.status="running",e.started_at=Date.now(),this.running.set(e.id,e),await this.persistTask(e),await this.persistState(),this.emit("task:started",{task:e}),this.events.broadcast({type:"queue_task_started",data:{task:this.taskToSummary(e)}}),this.emitQueueChanged(),Ma.info({taskId:e.id,runningCount:this.running.size},"Task started");try{let t=await this.worker.execute(e);await this.onTaskComplete(e,t);}catch(t){let r=t instanceof Error?t.message:String(t);await this.onTaskComplete(e,{success:false,error:r});}}async onTaskComplete(e,t){this.running.delete(e.id),t.success?(e.status="completed",e.completed_at=Date.now(),await this.persistTask(e),await this.persistState(),this.emit("task:completed",{task:e}),this.events.broadcast({type:"queue_task_completed",data:{task:this.taskToSummary(e),duration:t.duration}}),Ma.info({taskId:e.id,durationMs:t.duration},"Task completed")):e.retry_count<e.max_retries&&Fct(t.error,t.exit_code)?(e.status="retrying",e.retry_count++,e.error=t.error,Ma.warn({taskId:e.id,retryCount:e.retry_count,maxRetries:e.max_retries,err:t.error},"Task failed, retrying"),e.status="pending",e.started_at=void 0,this.queue.unshift(e),await this.persistTask(e),await this.persistState(),this.emitQueueChanged()):(e.status="failed",e.error=t.error,e.completed_at=Date.now(),await this.persistTask(e),await this.persistState(),this.emit("task:failed",{task:e}),this.events.broadcast({type:"queue_task_failed",data:{task:this.taskToSummary(e),error:t.error,duration:t.duration}}),Ma.error({taskId:e.id,err:t.error},"Task failed permanently")),this.emitQueueChanged(),this.tryDequeue();}async restore(){try{let e=await this.persistence.loadConfig();e&&(this.config={...this.config,...e});let t=await this.persistence.loadState();if(!t){Ma.info("No persisted state found, starting fresh");return}let r=await this.persistence.loadAllTasks();for(let n of t.task_ids.pending){let a=r.get(n);a&&(this.queue.push(a),this.tasks.set(n,a));}let s=0,i=0;for(let n of t.task_ids.running){let a=r.get(n);a&&(a.retry_count++,a.retry_count>a.max_retries?(a.status="failed",a.error=`Max retries exceeded (${a.max_retries}) after gateway restart`,a.completed_at=Date.now(),this.tasks.set(n,a),i++,Ma.warn({taskId:n,retryCount:a.retry_count,maxRetries:a.max_retries},"Task marked as failed - exceeded retry limit"),await this.persistTask(a)):(a.status="pending",a.started_at=void 0,this.queue.unshift(a),this.tasks.set(n,a),s++,Ma.info({taskId:n,retryCount:a.retry_count,maxRetries:a.max_retries},"Task re-queued for retry"),await this.persistTask(a)));}for(let[n,a]of r)this.tasks.has(n)||this.tasks.set(n,a);Ma.info({pendingCount:this.queue.length,runningRecovered:s,runningFailed:i},"Restored queue state"),this.emit("queue:restored",{pending_count:this.queue.length,running_recovered:s,running_failed:i}),this.events.broadcast({type:"queue_restored",data:{pending_count:this.queue.length,running_recovered:s,running_failed:i}});}catch(e){Ma.error({err:e},"Failed to restore state");}}async persistState(e=false){let t={version:1,max_concurrency:this.config.max_concurrency,last_updated:Date.now(),task_ids:{pending:this.queue.map(r=>r.id),running:Array.from(this.running.keys())}};try{await this.persistence.saveState(t,e);}catch(r){Ma.error({err:r},"Failed to persist state"),this.events.broadcast({type:"error",data:{message:"Failed to persist queue state",code:"PERSIST_ERROR"}});}}async persistTask(e,t=false){try{await this.persistence.saveTask(e,t);}catch(r){Ma.error({err:r,taskId:e.id},"Failed to persist task");}}taskToSummary(e){return {id:e.id,status:e.status,agent_id:e.payload.agent_id,created_at:e.created_at}}emitQueueChanged(){let e=this.getStatus();this.emit("queue:changed",{status:e}),this.events.broadcast({type:"queue_status_changed",data:e});}async deleteTask(e){let t=this.tasks.get(e);return !t||t.status==="pending"||t.status==="running"?false:(this.tasks.delete(e),await this.persistence.deleteTask(e),true)}async clearHistory(){let e=0;for(let[t,r]of this.tasks)(r.status==="completed"||r.status==="failed")&&(this.tasks.delete(t),await this.persistence.deleteTask(t),e++);return e}async retry(e,t=false){let r=this.tasks.get(e);return !r||r.status!=="failed"?null:(t&&(r.retry_count=0),r.status="pending",r.started_at=void 0,r.completed_at=void 0,r.error=void 0,this.queue.push(r),await this.persistTask(r,true),await this.persistState(true),this.emit("task:queued",{task:r}),this.events.broadcast({type:"queue_task_queued",data:{task:this.taskToSummary(r)}}),this.emitQueueChanged(),Ma.info({taskId:e,position:this.queue.length},"Task re-queued for retry"),this.tryDequeue(),r)}isTaskExecuting(e){return this.worker.isExecuting(e)}};}}),pp,Noe,yM,Ei,dC=$({"src/gateway/sse/task-sse-manager.ts"(){Ye(),pp=je.child({module:"task-sse-manager"}),Noe={maxListeners:1e3,heartbeatIntervalMs:3e4,staleTimeoutMs:12e4,maxFailedSends:3,cleanupIntervalMs:6e4},yM=class{constructor(e){this.heartbeatIntervalId=null,this.cleanupIntervalId=null,this.config={...Noe,...e},this.emitter=new Tst.EventEmitter,this.emitter.setMaxListeners(this.config.maxListeners),this.subscribers=new Map,this.taskSubscribers=new Map,this.workspaceSubscribers=new Map;}subscribe(e,t,r){let s=`sub_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now(),n={id:s,taskId:e,workspace_path:r,subscriptionType:"task",listener:t,connectedAt:i,lastActivity:i,failedSends:0};this.subscribers.set(s,n),this.taskSubscribers.has(e)||this.taskSubscribers.set(e,new Set);let a=this.taskSubscribers.get(e);a&&a.add(s);let c=`task:${e}`;return this.emitter.on(c,t),this.sendToSubscriber(s,{type:"CONNECTED",task_id:e,workspace_path:r,timestamp:i}),()=>{this.unsubscribeById(s);}}unsubscribeById(e){let t=this.subscribers.get(e);if(t){if(t.subscriptionType==="workspace"&&t.workspace_path){let r=`workspace:${t.workspace_path}`;this.emitter.off(r,t.listener),this.workspaceSubscribers.get(t.workspace_path)?.delete(e),this.workspaceSubscribers.get(t.workspace_path)?.size===0&&this.workspaceSubscribers.delete(t.workspace_path);}else if(t.subscriptionType==="batch"&&t.taskIds)for(let r of t.taskIds){let s=`task:${r}`;this.emitter.off(s,t.listener),this.taskSubscribers.get(r)?.delete(e),this.taskSubscribers.get(r)?.size===0&&this.taskSubscribers.delete(r);}else if(t.subscriptionType==="global")this.emitter.off("task:*",t.listener),this.taskSubscribers.get("*")?.delete(e),this.taskSubscribers.get("*")?.size===0&&this.taskSubscribers.delete("*");else {let r=t.taskId==="*"?"task:*":`task:${t.taskId}`;this.emitter.off(r,t.listener),this.taskSubscribers.get(t.taskId)?.delete(e),this.taskSubscribers.get(t.taskId)?.size===0&&this.taskSubscribers.delete(t.taskId);}this.subscribers.delete(e);}}subscribeAll(e){let t=`sub_all_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now(),s={id:t,taskId:"*",subscriptionType:"global",listener:e,connectedAt:r,lastActivity:r,failedSends:0};this.subscribers.set(t,s),this.taskSubscribers.has("*")||this.taskSubscribers.set("*",new Set);let i=this.taskSubscribers.get("*");return i&&i.add(t),this.emitter.on("task:*",e),()=>{this.unsubscribeById(t);}}subscribeWorkspace(e,t){let r=`sub_ws_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,s=Date.now(),i={id:r,taskId:"",workspace_path:e,subscriptionType:"workspace",listener:t,connectedAt:s,lastActivity:s,failedSends:0};this.subscribers.set(r,i),this.workspaceSubscribers.has(e)||this.workspaceSubscribers.set(e,new Set);let n=this.workspaceSubscribers.get(e);n&&n.add(r);let a=`workspace:${e}`;return this.emitter.on(a,t),this.sendToSubscriber(r,{type:"CONNECTED",task_id:"",workspace_path:e,timestamp:s}),()=>{this.unsubscribeById(r);}}subscribeTasks(e,t,r){let s=`sub_batch_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now(),n={id:s,taskId:e[0]||"",taskIds:e,workspace_path:r,subscriptionType:"batch",listener:t,connectedAt:i,lastActivity:i,failedSends:0};this.subscribers.set(s,n);for(let a of e){this.taskSubscribers.has(a)||this.taskSubscribers.set(a,new Set);let c=this.taskSubscribers.get(a);c&&c.add(s);let o=`task:${a}`;this.emitter.on(o,t);}return this.sendToSubscriber(s,{type:"CONNECTED",task_id:e.join(","),workspace_path:r,timestamp:i}),()=>{this.unsubscribeById(s);}}broadcast(e,t,r){let s={...t,type:t.type,task_id:e,workspace_path:r,timestamp:t.timestamp??Date.now()};this.emitter.emit(`task:${e}`,s),r&&this.emitter.emit(`workspace:${r}`,s),this.emitter.emit("task:*",s);}broadcastAll(e){this.emitter.emit(`task:${e.task_id}`,e),e.workspace_path&&this.emitter.emit(`workspace:${e.workspace_path}`,e),this.emitter.emit("task:*",e);}sendHeartbeat(){let e=Date.now(),t=0;for(let[r,s]of this.subscribers){let i={type:"HEARTBEAT",task_id:s.taskId,timestamp:e};this.sendToSubscriberWithTracking(r,i)||t++;}return t}sendToSubscriberWithTracking(e,t){let r=this.subscribers.get(e);if(!r)return false;try{return r.listener(t)===!1?(r.failedSends++,!1):(r.failedSends=0,r.lastActivity=Date.now(),!0)}catch(s){return r.failedSends++,pp.error({err:s,subscriberId:e},"Error sending to subscriber"),false}}cleanupStaleSubscribers(){let e=Date.now(),t=e-this.config.staleTimeoutMs,r=[];for(let[s,i]of this.subscribers){let n=i.lastActivity<t,a=i.failedSends>=this.config.maxFailedSends;(n||a)&&(r.push(s),pp.debug({subscriberId:s,isStale:n,isDead:a,lastActivityMs:e-i.lastActivity,failedSends:i.failedSends},"Cleaning up subscriber"));}for(let s of r)this.unsubscribeById(s);return r.length>0&&pp.info({count:r.length},"Cleaned up stale subscribers"),r.length}startHeartbeat(e){let t=e??this.config.heartbeatIntervalMs;return this.heartbeatIntervalId=setInterval(()=>{this.sendHeartbeat();},t),this.cleanupIntervalId=setInterval(()=>{this.cleanupStaleSubscribers();},this.config.cleanupIntervalMs),pp.info({heartbeatMs:t,cleanupIntervalMs:this.config.cleanupIntervalMs},"Started heartbeat and cleanup intervals"),()=>this.stopHeartbeat()}stopHeartbeat(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null),this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),pp.info("Stopped heartbeat and cleanup intervals");}getSubscriberCount(e){return this.taskSubscribers.get(e)?.size??0}getTotalSubscriberCount(){return this.subscribers.size}getActiveTaskIds(){return Array.from(this.taskSubscribers.keys()).filter(e=>e!=="*")}getStats(){let t=Date.now()-this.config.staleTimeoutMs,r=0,s=0;for(let i of this.subscribers.values())i.lastActivity<t&&r++,i.failedSends>0&&s++;return {totalSubscribers:this.subscribers.size,taskCount:this.taskSubscribers.size,staleCount:r,failingCount:s}}sendToSubscriber(e,t){let r=this.subscribers.get(e);if(r)try{r.listener(t),r.lastActivity=Date.now();}catch(s){r.failedSends++,pp.error({err:s,subscriberId:e},"Error sending to subscriber");}}markActive(e){let t=this.subscribers.get(e);t&&(t.lastActivity=Date.now(),t.failedSends=0);}close(){this.stopHeartbeat(),this.emitter.removeAllListeners(),this.subscribers.clear(),this.taskSubscribers.clear(),this.workspaceSubscribers.clear(),pp.info("Closed and cleaned up all resources");}getWorkspaceSubscriberCount(e){return this.workspaceSubscribers.get(e)?.size??0}getActiveWorkspaces(){return Array.from(this.workspaceSubscribers.keys())}},Ei=new yM;}}),hp,rwe,Uct=$({"src/queue/core/promoter.ts"(){hn(),Ye(),hp=je.child({module:"command-queue-promoter"}),rwe=class extends Tst.EventEmitter{constructor(){super(),this.intervalId=null,this.running=false;}start(){if(this.running)return;this.running=true;let e=Ml();hp.debug({intervalMs:e.promoter_interval_ms},"Promoter started"),this.tick(),this.intervalId=setInterval(()=>{this.tick();},e.promoter_interval_ms);}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.running=false,hp.debug("Promoter stopped");}tick(){try{let e=Ml(),t=Yn(),r=e.max_concurrency-t.length;if(r<=0){hp.trace({runningCount:t.length,maxConcurrency:e.max_concurrency},"No slots available");return}let s=_c();if(s.length===0)return;hp.debug({pendingCount:s.length,availableSlots:r},"Promoting pending items");let i=s.slice(0,r),n=s.slice(r);for(let a of i)try{let c=this.spawnProcess(a);hp.debug({itemId:a.id,pid:c.pid},"Process spawned"),this.emit("item:promoted",c);}catch(c){let o=c instanceof Error?c:new Error(String(c));hp.error({itemId:a.id,err:o},"Failed to spawn process"),this.emit("item:spawn-error",a,o),n.unshift(a);}wf(n);}catch(e){let t=e instanceof Error?e:new Error(String(e));hp.error({err:t},"Promoter tick failed"),this.emit("error",t);}}spawnProcess(e){let t=Cit(e.id),r=Ne.openSync(t,"a"),s=Ne.openSync(t,"a"),i=`[${new Date().toISOString()}] Starting command: ${e.command}
|
|
801
801
|
`;Ne.writeSync(r,i);let n=child_process.spawn(e.command,{cwd:e.cwd,shell:true,detached:true,stdio:["ignore",r,s],env:{...process.env,VIBEN_QUEUE_ITEM_ID:e.id}});n.unref(),Ne.closeSync(r),Ne.closeSync(s);let a={...e,pid:n.pid,started_at:Date.now(),log_file:t};return J_e(a),a}promoteOne(){let e=_c();if(e.length===0)return null;let t=Ml();if(Yn().length>=t.max_concurrency)return null;let s=e[0],i=e.slice(1);try{let n=this.spawnProcess(s);return wf(i),this.emit("item:promoted",n),n}catch(n){let a=n instanceof Error?n:new Error(String(n));return this.emit("item:spawn-error",s,a),null}}};}});function Hct(e){try{return process.kill(e,0),!0}catch{return false}}function Wct(e){return Hct(e.pid)?{running:true}:{running:false,exitCode:0}}var xm,awe,Vct=$({"src/queue/core/monitor.ts"(){hn(),Ye(),xm=je.child({module:"command-queue-monitor"}),awe=class extends Tst.EventEmitter{constructor(){super(),this.intervalId=null,this.running=false;}start(){if(this.running)return;this.running=true;let e=Ml();xm.debug({intervalMs:e.monitor_interval_ms},"Monitor started"),this.tick(),this.intervalId=setInterval(()=>{this.tick();},e.monitor_interval_ms);}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.running=false,xm.debug("Monitor stopped");}tick(){try{let e=Yn();e.length>0&&xm.trace({runningCount:e.length},"Checking running processes");for(let t of e){let r=Wct(t);r.running||(xm.debug({itemId:t.id,pid:t.pid,exitCode:r.exitCode},"Process exited"),this.handleCompletion(t,r.exitCode??0));}}catch(e){let t=e instanceof Error?e:new Error(String(e));xm.error({err:t},"Monitor tick failed"),this.emit("error",t);}}handleCompletion(e,t){let r=Date.now(),s=r-e.started_at;try{let n=`
|
|
802
802
|
[${new Date().toISOString()}] Process exited with code ${t} (duration: ${s}ms)
|
|
803
|
-
`;Ne.appendFileSync(e.log_file,n);}catch{}let i={...e,completed_at:r,exit_code:t};Pit(e.id),iz(i),t===0?this.emit("item:completed",i):(this.shouldRetry(e)&&this.retryItem(e),this.emit("item:failed",i));}shouldRetry(e){let t=Ml(),r=e.metadata?.retry_count||0,s=e.metadata?.max_retries||t.default_max_retries;return r<s}retryItem(e){let t=(e.metadata?.retry_count||0)+1,r=e.metadata?.max_retries||3;xm.info({itemId:e.id,retryCount:t,maxRetries:r},"Queuing item for retry");let s={id:e.id,command:e.command,cwd:e.cwd,created_at:Date.now(),metadata:{...e.metadata,retry_count:t,original_started_at:e.started_at}},i=_c();i.push(s),wf(i),this.emit("item:retried",s,e.id);}checkNow(){this.tick();}forceComplete(e,t=0){let s=Yn().find(i=>i.id===e);return s?(this.handleCompletion(s,t),true):false}};}}),Za,swe,Jct=$({"src/queue/core/command-queue.ts"(){Uct(),Vct(),hn(),Ye(),Ibe(),cz(),Tbe(),Pbe(),Ube(),$be(),Rbe(),zbe(),xbe(),Za=je.child({module:"command-queue"}),swe=class extends Tst.EventEmitter{constructor(){super(),this.started=false,ad(),this.promoter=new rwe,this.monitor=new awe,this.promoter.on("item:promoted",e=>{Za.info({itemId:e.id,pid:e.pid,command:e.command},"Item started"),this.emit("item:started",e),this.emit("queue:changed");}),this.promoter.on("item:spawn-error",(e,t)=>{Za.error({itemId:e.id,err:t},"Item spawn failed"),this.emit("error",t);}),this.promoter.on("error",e=>{Za.error({err:e},"Promoter error"),this.emit("error",e);}),this.monitor.on("item:completed",e=>{let t=e.completed_at-e.started_at;Za.info({itemId:e.id,exitCode:e.exit_code,durationMs:t},"Item completed"),this.emit("item:completed",e),this.emit("queue:changed");}),this.monitor.on("item:failed",e=>{let t=e.completed_at-e.started_at;Za.warn({itemId:e.id,exitCode:e.exit_code,durationMs:t},"Item failed"),this.emit("item:failed",e),this.emit("queue:changed");}),this.monitor.on("item:retried",e=>{let t=e.metadata?.retry_count??0;Za.info({itemId:e.id,retryCount:t},"Item queued for retry"),this.emit("item:retried",e),this.emit("queue:changed");}),this.monitor.on("error",e=>{Za.error({err:e},"Monitor error"),this.emit("error",e);});}async start(){if(this.started)return;Za.info("Starting command queue..."),this.started=true;let{recovered:e}=await this.recoverFromRestart();e>0&&Za.info({recovered:e},"Recovered dead processes from previous run"),this.promoter.start(),this.monitor.start(),Za.info("Command queue started");}async stop(){this.started&&(Za.info("Stopping command queue..."),this.promoter.stop(),this.monitor.stop(),this.started=false,Za.info("Command queue stopped (running processes will continue)"));}async recoverFromRestart(){let e=Yn(),t=0;for(let r of e)this.isProcessAlive(r.pid)||(this.monitor.forceComplete(r.id,1),t++);return t>0&&this.emit("queue:changed"),{recovered:t}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return false}}enqueue(e){let t=oz(e);if(t.success){Za.info({itemId:t.id,command:e.command,cwd:e.cwd},"Item enqueued");let r=i_({id:t.id});r.success&&r.item&&this.emit("item:enqueued",r.item),this.emit("queue:changed");}else Za.warn({command:e.command,error:t.error},"Failed to enqueue item");return t}cancel(e,t=false){let r=Ebe({id:e,force:t});return r.success?(Za.info({itemId:e,force:t},"Item cancelled"),this.emit("item:cancelled",e),this.emit("queue:changed")):Za.warn({itemId:e,error:r.error},"Failed to cancel item"),r}retry(e){let t=wz(e);return t.success?(Za.info({itemId:e.id},"Item retry initiated"),this.emit("queue:changed")):Za.warn({itemId:e.id,error:t.error},"Failed to retry item"),t}getStatus(){return lC()}list(e){return Bf(e)}inspect(e){return i_({id:e})}getLogs(e){return Sz(e)}getConfig(){return kz()}updateConfig(e){let t=AP(e);return t.success&&(e.promoter_interval_ms||e.monitor_interval_ms)&&this.started&&(this.promoter.stop(),this.monitor.stop(),this.promoter.start(),this.monitor.start()),t}clean(e){let t=jbe(e);return t.success&&t.cleaned>0&&this.emit("queue:changed"),t}isRunning(){return this.started}};}}),iwe,Yct=$({"src/devices/device-registry.ts"(){iwe=class{constructor(e,t){this.events=e,this.devices=new Map,this.peerDevices=new Map,this.gatewayId=t??nk.randomUUID();}getGatewayId(){return this.gatewayId}registerClient(e){let t={id:nk.randomUUID(),type:"client",name:e.name,gateway_id:this.gatewayId,platform:e.platform,status:"online",capabilities:e.capabilities??[],connected_at:new Date().toISOString(),last_seen:new Date().toISOString()};return this.devices.set(t.id,t),this.events.broadcast({type:"device_connected",data:{device:t}}),t}registerClientWithId(e,t){let r=this.devices.get(e);if(r)return r.status="online",r.last_seen=new Date().toISOString(),r.name=t.name,r.platform=t.platform,r.capabilities=t.capabilities??r.capabilities,this.events.broadcast({type:"device_connected",data:{device:r}}),r;let s={id:e,type:"client",name:t.name,gateway_id:this.gatewayId,platform:t.platform,status:"online",capabilities:t.capabilities??[],connected_at:new Date().toISOString(),last_seen:new Date().toISOString()};return this.devices.set(s.id,s),this.events.broadcast({type:"device_connected",data:{device:s}}),s}unregisterClient(e){this.devices.get(e)&&(this.devices.delete(e),this.events.broadcast({type:"device_disconnected",data:{device_id:e}}));}registerPeer(e,t){let r={id:e,type:"gateway",name:t.name,gateway_id:e,platform:"desktop",status:"online",address:t.address,capabilities:t.capabilities??[],connected_at:new Date().toISOString(),last_seen:new Date().toISOString()};return this.devices.set(r.id,r),this.peerDevices.set(e,new Set),this.events.broadcast({type:"device_connected",data:{device:r}}),r}unregisterPeer(e){this.devices.delete(e);let t=this.peerDevices.get(e);if(t){for(let r of t)this.devices.delete(r);this.peerDevices.delete(e);}this.events.broadcast({type:"device_disconnected",data:{device_id:e}});}syncPeerDevices(e,t){let r=this.peerDevices.get(e);if(r)for(let i of r)this.devices.delete(i);let s=new Set;for(let i of t)this.devices.set(i.id,i),s.add(i.id);this.peerDevices.set(e,s);}updateLastSeen(e){let t=this.devices.get(e);t&&(t.last_seen=new Date().toISOString());}getAllDevices(){return Array.from(this.devices.values())}getDevice(e){return this.devices.get(e)}getDevicesByGateway(e){return this.getAllDevices().filter(t=>t.gateway_id===e)}getOnlineGateways(){return this.getAllDevices().filter(e=>e.type==="gateway"&&e.status==="online")}getLocalClients(){return this.getAllDevices().filter(e=>e.type==="client"&&e.gateway_id===this.gatewayId)}};}}),_M,Zct=$({"src/mesh/peer-connection.ts"(){_M=class extends Tst.EventEmitter{constructor(e,t=6e4){super(),this.localInfo=e,this.maxReconnectDelay=t,this.ws=null,this.heartbeatTimer=null,this.peerInfo=null,this.reconnectAttempts=0,this.reconnectTimer=null,this.manualClose=false;}connectTo(e){this.manualClose=false;let t=e.replace(/^http/,"ws")+"/api/mesh/ws";this.ws=new aI__default.default(t),this.ws.on("open",()=>{this.send({type:"Hello",data:this.localInfo}),this.startHeartbeat();}),this.ws.on("message",r=>{try{let s=JSON.parse(r.toString());if(s.type==="Pong")return;s.type==="Welcome"&&(this.peerInfo={gateway_id:s.data.gateway_id,name:s.data.name,version:s.data.version,capabilities:s.data.capabilities,address:s.data.address},this.reconnectAttempts=0,this.emit("ready",this.peerInfo)),this.emit("message",s);}catch{}}),this.ws.on("close",(r,s)=>{this.stopHeartbeat(),this.emit("close",r,s.toString()),this.manualClose||this.scheduleReconnect(e);}),this.ws.on("error",r=>{this.emit("error",r);});}accept(e,t,r){this.manualClose=false,this.ws=e,this.peerInfo=t;let s={...this.localInfo,peers:r??[]};this.send({type:"Welcome",data:s}),this.startHeartbeat(),e.on("message",i=>{try{let n=JSON.parse(i.toString());if(n.type==="Pong")return;this.emit("message",n);}catch{}}),e.on("close",(i,n)=>{this.stopHeartbeat(),this.emit("close",i,n.toString());}),e.on("error",i=>this.emit("error",i)),this.emit("ready",t);}send(e){return !this.ws||this.ws.readyState!==1?false:(this.ws.send(JSON.stringify(e)),true)}getPeerInfo(){return this.peerInfo}close(){this.manualClose=true,this.stopHeartbeat(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close(1e3);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.send({type:"Ping"});},3e4);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}scheduleReconnect(e){let t=Math.min(1e3*2**this.reconnectAttempts,this.maxReconnectDelay);this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>this.connectTo(e),t);}};}}),nwe,eut=$({"src/mesh/mesh-service.ts"(){Zct(),nwe=class{constructor(e,t,r,s){this.events=e,this.registry=t,this.peerStore=r,this.localInfo=s,this.peers=new Map,this.pendingMessages=new Map,this.localActionHandler=null;}getLocalInfo(){return this.localInfo}getPeers(){let e=[];for(let t of this.peers.values()){let r=t.getPeerInfo();r&&e.push(r);}return e}connectToPeer(e){let t=new _M(this.localInfo);t.on("error",()=>{}),t.on("ready",r=>{this.peers.set(r.gateway_id,t),this.registry.registerPeer(r.gateway_id,{gateway_id:r.gateway_id,name:r.name,address:r.address,capabilities:r.capabilities}),this.peerStore.upsert({gateway_id:r.gateway_id,name:r.name,lan:r.address,last_seen:new Date().toISOString()}).catch(()=>{}),this.broadcastToPeers({type:"PeerJoined",data:r},r.gateway_id);}),t.on("message",r=>this.handleMessage(r)),t.on("close",()=>{let r=t.getPeerInfo();r&&(this.peers.delete(r.gateway_id),this.registry.unregisterPeer(r.gateway_id),this.broadcastToPeers({type:"PeerLeft",data:{gateway_id:r.gateway_id}}));}),t.connectTo(e);}acceptPeer(e,t){if(this.peers.has(t.gateway_id)){e.close(4001,"already_connected");return}let r=new _M(this.localInfo);r.on("error",()=>{}),r.on("message",i=>this.handleMessage(i)),r.on("close",()=>{this.peers.delete(t.gateway_id),this.registry.unregisterPeer(t.gateway_id),this.broadcastToPeers({type:"PeerLeft",data:{gateway_id:t.gateway_id}});});let s=this.getPeers();r.accept(e,t,s),this.peers.set(t.gateway_id,r),this.registry.registerPeer(t.gateway_id,{gateway_id:t.gateway_id,name:t.name,address:t.address,capabilities:t.capabilities}),this.peerStore.upsert({gateway_id:t.gateway_id,name:t.name,lan:t.address,last_seen:new Date().toISOString()}).catch(()=>{}),this.broadcastToPeers({type:"PeerJoined",data:t},t.gateway_id);}sendDeviceMessage(e){if(e.to_gateway==="*")return this.broadcastToPeers({type:"DeviceMessage",data:e}),true;let t=this.peers.get(e.to_gateway);return t?t.send({type:"DeviceMessage",data:e}):false}handleIncomingDeviceMessage(e){if(e.reply_to){this.resolveMessage(e.reply_to,e.payload);return}this.localActionHandler&&this.localActionHandler(e);}onLocalAction(e){this.localActionHandler=e;}trackPendingMessage(e,t=3e4){return new Promise((r,s)=>{let i=setTimeout(()=>{this.pendingMessages.delete(e),s(new Error("timeout"));},t);this.pendingMessages.set(e,{resolve:r,reject:s,timer:i});})}resolveMessage(e,t){let r=this.pendingMessages.get(e);r&&(clearTimeout(r.timer),this.pendingMessages.delete(e),r.resolve(t));}async reconnectKnownPeers(){let e=await this.peerStore.load();for(let t of e){if(t.gateway_id===this.localInfo.gateway_id)continue;let r=t.lan??t.tunnel;r&&this.connectToPeer(r);}}shutdown(){for(let e of this.peers.values())e.close();this.peers.clear();for(let e of this.pendingMessages.values())clearTimeout(e.timer),e.reject(new Error("shutdown"));this.pendingMessages.clear();}handleMessage(e){switch(e.type){case "DeviceMessage":{let t=e.data;t.to_gateway===this.localInfo.gateway_id||t.to_gateway==="*"?this.handleIncomingDeviceMessage(t):this.peers.get(t.to_gateway)?.send(e);break}case "PeerJoined":this.events.broadcast({type:"mesh_peer_joined",data:{gateway_id:e.data.gateway_id,name:e.data.name,address:e.data.address??""}});break;case "PeerLeft":this.events.broadcast({type:"mesh_peer_left",data:{gateway_id:e.data.gateway_id}});break;case "DeviceEvent":{let t=e.data;t.type==="device_connected"&&t.device?this.events.broadcast({type:"device_connected",data:{device:t.device}}):t.type==="device_disconnected"&&t.device_id?this.events.broadcast({type:"device_disconnected",data:{device_id:t.device_id}}):t.type==="device_updated"&&t.device&&this.events.broadcast({type:"device_updated",data:{device:t.device}});break}}}broadcastToPeers(e,t){for(let[r,s]of this.peers)r!==t&&s.send(e);}};}}),joe,owe,aut=$({"src/mesh/peer-store.ts"(){Pr(),joe=qe.join(nn.homedir(),".viben","mesh","peers.yaml"),owe=class{constructor(e=joe){this.path=e;}async load(){return (await It(this.path))?.peers??[]}async save(e){await xr(this.path,{peers:e});}async upsert(e){let t=await this.load(),r=t.findIndex(s=>s.gateway_id===e.gateway_id);r>=0?t[r]=e:t.push(e),await this.save(t);}async remove(e){let t=await this.load();await this.save(t.filter(r=>r.gateway_id!==e));}};}});async function zoe(){if(vM)return oS;vM=true;try{oS=(await import('bonjour-service')).Bonjour;}catch{oS=null;}return oS}var U4,oS,vM,cwe,sut=$({"src/discovery/mdns.ts"(){U4="viben-gateway",oS=null,vM=false,cwe=class{constructor(){this.instance=null,this.browser=null,this.published=false,this.onDiscoverCallback=null;}async start(e){let t=await zoe();t&&(this.instance=new t,this.instance.publish({name:e.name,type:U4,port:e.port,txt:{gateway_id:e.gateway_id,name:e.name,version:e.version}}),this.published=true,this.browser=this.instance.find({type:U4},r=>{let s=r.txt||{};if(s.gateway_id===e.gateway_id)return;let i={gateway_id:s.gateway_id||"",name:s.name||r.name,version:s.version||"unknown",host:r.host,port:r.port,addresses:r.addresses||[]};this.onDiscoverCallback?.(i);}));}onDiscover(e){this.onDiscoverCallback=e;}stop(){this.browser&&(this.browser.stop(),this.browser=null),this.instance&&(this.instance.unpublishAll(),this.instance.destroy(),this.instance=null),this.published=false;}async isAvailable(){return await zoe()!==null}};}});async function iut(){if(cS)return cS;if(bM)throw new Error("qrcode package not available");bM=true;try{return cS=await import('qrcode'),cS}catch{throw new Error("qrcode package not available. Install it with: pnpm add qrcode")}}async function nut(e){let t=await iut(),r=JSON.stringify(e);return t.toDataURL(r,{width:256,margin:2})}var cS,bM,out=$({"src/discovery/qr.ts"(){cS=null,bM=false;}}),uwe,cut=$({"src/discovery/discovery-service.ts"(){sut(),out(),uwe=class{constructor(e,t){this.events=e,this.mdns=new cwe,this.onPeerDiscoveredCallback=null,this.config=t;}async start(){let e={gateway_id:this.config.gateway_id,name:this.config.name,version:this.config.version,host:"0.0.0.0",port:this.config.port,addresses:[]};this.mdns.onDiscover(t=>{let r=`http://${t.addresses[0]||t.host}:${t.port}`;this.onPeerDiscoveredCallback?.(r);}),await this.mdns.start(e);}onPeerDiscovered(e){this.onPeerDiscoveredCallback=e;}stop(){this.mdns.stop();}getQrPayload(){return {type:"viben-gateway",gateway_id:this.config.gateway_id,name:this.config.name,lan:this.config.lan_address?`http://${this.config.lan_address}:${this.config.port}`:void 0,tunnel:this.config.tunnel_url}}async getQrDataUrl(){return nut(this.getQrPayload())}async isMdnsAvailable(){return this.mdns.isAvailable()}};}}),lwe={};yt(lwe,{generateKeyPair:()=>uut,sign:()=>lut,verify:()=>dut});function wM(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function SM(e){let t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.substr(r*2,2),16);return t}function uut(){let e=wB.randomSecretKey(),t=gB(e);return {publicKey:wM(t),privateKey:wM(e)}}async function lut(e,t){let r=SM(t),s=new TextEncoder().encode(e),i=await _B(s,r);return wM(i)}async function dut(e,t,r){try{let s=SM(r),i=SM(t),n=new TextEncoder().encode(e);return await bB(i,n,s)}catch{return false}}var put=$({"src/utils/crypto.ts"(){}});function hut(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return (t>>>0).toString(36)}function mut(e,t){let r=e+t.namespace+t.name+t.description+JSON.stringify(t.inputSchema??null)+JSON.stringify(t.outputSchema??null);return hut(r)}var _i,Uoe,Boe,Goe,Tz,dwe=$({"src/gateway/client-store.ts"(){Ye(),_i=je.child({module:"client-store"}),Uoe=3e4,Boe=1e3,Goe=1024*1024,Tz=class{constructor(e={}){this.clients=new Map,this.nameIndex=new Map,this._globalTheme="light",this.config={gracePeriodMs:e.gracePeriodMs??Uoe,maxActionsPerClient:e.maxActionsPerClient??Boe,maxPayloadSize:e.maxPayloadSize??Goe};}get globalTheme(){return this._globalTheme}setGlobalTheme(e){this._globalTheme=e;}getClient(e){return this.clients.get(e)}async verifySignature(e,t,r,s){let i=Date.now();if(Math.abs(i-s)>300*1e3)return _i.warn({clientId:e,timestamp:s,now:i},"Signature timestamp expired"),false;try{let{verify:n}=await Promise.resolve().then(()=>(put(),lwe)),a=`${e}:${s}`;return await n(a,r,t)}catch(n){return _i.error({clientId:e,error:n},"Signature verification failed"),false}}async registerClient(e,t){let r=this.clients.get(e);if(r){if(r.publicKey!==t.publicKey)throw new Error("Public key mismatch for existing client");if(!await this.verifySignature(e,t.publicKey,t.signature,t.timestamp))throw new Error("Invalid signature for clientId");r.disconnectTimer&&(clearTimeout(r.disconnectTimer),r.disconnectTimer=void 0,_i.info({clientId:e},"Grace period cancelled (new socket connected)"));}else {if(!await this.verifySignature(e,t.publicKey,t.signature,t.timestamp))throw new Error("Invalid signature for clientId");r={clientId:e,publicKey:t.publicKey,sockets:new Map,actionStore:new Map,metadata:{theme:t.theme??"light",workspacePath:t.workspacePath??""}},this.clients.set(e,r),_i.info({clientId:e},"Client registered");}return r.sockets.has(t.socketId)||(r.sockets.set(t.socketId,{socketId:t.socketId,source:t.source,pageUid:t.pageUid,connectedAt:Date.now()}),_i.info({clientId:e,socketId:t.socketId,source:t.source},"Socket added to client")),t.theme&&(r.metadata.theme=t.theme),t.workspacePath&&(r.metadata.workspacePath=t.workspacePath),r}removeSocket(e,t){let r=this.clients.get(e);if(!r)return {actionsRemoved:[],clientRemoved:false};r.sockets.delete(t),_i.info({clientId:e,socketId:t},"Socket removed from client");let s=[];for(let[i,n]of r.actionStore)n.socketId===t&&s.push(i);if(r.sockets.size>0){for(let i of s){let n=r.actionStore.get(i);n&&this.removeFromNameIndex(e,n),r.actionStore.delete(i),_i.info({clientId:e,action:i},"Action removed (socket disconnected)");}return {actionsRemoved:s,clientRemoved:false}}return _i.info({clientId:e,gracePeriodMs:this.config.gracePeriodMs},"All sockets disconnected, starting grace period"),r.disconnectTimer=setTimeout(()=>{let i=this.clients.get(e);if(i&&i.sockets.size===0){for(let n of i.actionStore.values())this.removeFromNameIndex(e,n);this.clients.delete(e),_i.info({clientId:e,actionsRemoved:Array.from(i.actionStore.keys())},"Client removed after grace period");}},this.config.gracePeriodMs),{actionsRemoved:[],clientRemoved:false}}registerAction(e,t,r){let s=this.clients.get(e);if(!s)return {updated:false,fullName:"",error:`Client not found: ${e}`};if(s.actionStore.size>=this.config.maxActionsPerClient)return _i.warn({clientId:e,count:s.actionStore.size},"Max actions limit reached"),{updated:false,fullName:"",error:"Max actions limit reached"};let i=`${r.namespace}.${r.name}`,n=mut(e,r),a=s.actionStore.get(i);if(a&&a.hash===n)return a.socketId!==t&&(a.socketId=t,_i.info({clientId:e,action:i,oldSocketId:a.socketId,newSocketId:t},"Action socketId updated (reconnect)")),{updated:false,fullName:i};let c={namespace:r.namespace,name:r.name,description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema,socketId:t,registeredAt:Date.now(),hash:n,timeout:r.timeout},o=s.actionStore.get(i);return o&&this.removeFromNameIndex(e,o),s.actionStore.set(i,c),this.addToNameIndex(e,c),_i.info({clientId:e,action:i,socketId:t,timeout:r.timeout},"Action registered"),{updated:true,fullName:i}}unregisterAction(e,t,r){let s=this.clients.get(e);if(!s)return [];let i=[];for(let[n,a]of s.actionStore){let c=!t||a.namespace===t,o=!r||a.socketId===r;c&&o&&(s.actionStore.delete(n),this.removeFromNameIndex(e,a),i.push(n));}return i.length>0&&_i.info({clientId:e,removed:i},"Actions unregistered"),i}findAction(e,t,r){let s=this.clients.get(e);if(s)return s.actionStore.get(`${t}.${r}`)}getAllActions(){let e=[];for(let[t,r]of this.clients)for(let s of r.actionStore.values())e.push({...s,clientId:t});return e}removeStaleActions(e,t,r,s){let i=this.clients.get(e);if(!i)return [];let n=[];for(let[a,c]of i.actionStore)c.namespace===t&&c.socketId===r&&!s.has(c.name)&&(this.removeFromNameIndex(e,c),i.actionStore.delete(a),n.push(a));return n}findActionByName(e){return this.nameIndex.get(e)?.[0]}findActionByFullName(e){for(let[t,r]of this.clients){let s=r.actionStore.get(e);if(s)return {...s,clientId:t}}}resolveAction(e){let t=this.findActionByFullName(e);if(t)return t;let r=this.findActionByName(e);if(r)return r;let s=e.indexOf(".");if(s>0){let i=e.slice(0,s),n=e.slice(s+1),a=this.clients.get(i);if(a){let c=a.actionStore.get(n);if(c)return {...c,clientId:i}}}}addToNameIndex(e,t){let r=this.nameIndex.get(t.name),s={...t,clientId:e};r?r.push(s):this.nameIndex.set(t.name,[s]);}removeFromNameIndex(e,t){let r=this.nameIndex.get(t.name);if(!r)return;let s=r.findIndex(i=>i.clientId===e&&i.namespace===t.namespace);s!==-1&&(r.splice(s,1),r.length===0&&this.nameIndex.delete(t.name));}getSocketInfo(e,t){return this.clients.get(e)?.sockets.get(t)}getAllClients(){return Array.from(this.clients.keys())}getConfig(){return {...this.config}}shutdown(){for(let e of this.clients.values())e.disconnectTimer&&clearTimeout(e.disconnectTimer);this.clients.clear(),this.nameIndex.clear(),_i.info("ClientStore shut down");}};}});function pwe(e={}){let{host:t="127.0.0.1",port:r=18790,runtime:s=true}=e,i=new yP,n=new XS,a=new F8(i),c=new D8(i,n),o=new _P,l=new $8(i),u=new Zfe({events:i,channels:er,container:c,responseTimeout:12e4}),d=new Qye({channelManager:er,messageBus:l,auto_start:true,pollingTimeout:30}),h=new twe(i),_=new yM({heartbeatIntervalMs:3e4,staleTimeoutMs:12e4,maxFailedSends:3,cleanupIntervalMs:6e4});s&&_.startHeartbeat();let y=new C_e(rr,_,{stuckThresholdMs:300*1e3,autoRecover:true}),v=new swe,b=new iwe(i),w=b.getGatewayId(),S=new owe,E={gateway_id:w,name:`viben-${w.slice(0,8)}`,version:"1.0.0",capabilities:["navigate","notify","ping"],address:`http://${t}:${r}`},A=new nwe(i,b,S,E),D=new Tz,q=new uwe(i,{gateway_id:w,name:E.name,version:"1.0.0",port:r}),O=new bP;return s&&q.onPeerDiscovered(R=>{A.connectToPeer(R);}),{events:i,sessionStore:n,cron:a,container:c,history:o,messageBus:l,channelRouter:u,channelRuntime:d,taskQueue:h,taskRecovery:y,taskSSEManager:_,commandQueue:v,deviceRegistry:b,mesh:A,discovery:q,clientStore:D,firebase:O}}var Hoe=$({"src/gateway/state.ts"(){qA(),eh(),g0e(),y0e(),v0e(),b0e(),y_(),qct(),O_e(),zf(),dC(),Jct(),Yct(),eut(),aut(),cut(),dwe(),f_e();}});function hwe(e){let t=qe.join(nn.homedir(),".viben");Iz={host:e.host||"127.0.0.1",port:e.port||18790,cors:e.cors??true,started_at:new Date().toISOString(),pid:process.pid,node_version:process.version,platform:process.platform,arch:process.arch,config_dir:t,state_dir:t,command:`viben gateway serve --host ${e.host||"127.0.0.1"} --port ${e.port||18790}`};}function yut(e){e.get("/health",{schema:{description:"Health check endpoint",tags:["health"],response:{200:{type:"object",properties:{status:{type:"string",enum:["ok"]},service:{type:"string"},version:{type:"string"},timestamp:{type:"string",format:"date-time"},uptime:{type:"string"},uptime_seconds:{type:"number"},startup:{type:"object",properties:{host:{type:"string"},port:{type:"number"},cors:{type:"boolean"},started_at:{type:"string",format:"date-time"},pid:{type:"number"},node_version:{type:"string"},platform:{type:"string"},arch:{type:"string"},config_dir:{type:"string"},state_dir:{type:"string"},command:{type:"string"}}}}}}}},async()=>{let t=Date.now()-mwe,r=Math.floor(t/1e3),s=Math.floor(r/3600),i=Math.floor(r%3600/60),n=r%60,a=s>0?`${s}h ${i}m ${n}s`:i>0?`${i}m ${n}s`:`${n}s`;return {status:"ok",service:"viben-gateway",version:xz,timestamp:new Date().toISOString(),uptime:a,uptime_seconds:r,startup:Iz||void 0}});}var xz,Iz,mwe,CP=$({"src/gateway/routes/health.ts"(){xz="1.3.3",Iz=null,mwe=Date.now();}});function Pz(e){return e.replace(/\//g,"-")}function Az(){return qe__namespace.join(nn__namespace.homedir(),".claude","projects")}async function _ut(e){let t=Az(),r=Pz(e),s=qe__namespace.join(t,r);if(!Ne__namespace.existsSync(s))return [];let a=(await Ne__namespace.promises.readdir(s,{withFileTypes:true})).filter(o=>o.isFile()&&o.name.endsWith(".jsonl")).map(async o=>{let l=o.name.replace(".jsonl",""),u=qe__namespace.join(s,o.name);try{let[d,h]=await Promise.all([Ne__namespace.promises.stat(u),gwe(u)]);return {id:l,executor_type:"CLAUDE_CODE",workspace_path:e,created_at:d.birthtime.toISOString(),updated_at:d.mtime.toISOString(),name:h,message_count:Math.floor(d.size/1024)}}catch{return null}}),c=(await Promise.all(a)).filter(o=>o!==null);return c.sort((o,l)=>new Date(l.updated_at).getTime()-new Date(o.updated_at).getTime()),c}async function gwe(e){try{let t=Ne__namespace.createReadStream(e),r=kj__namespace.createInterface({input:t,crlfDelay:1/0});for await(let s of r)if(s.trim()!=="")try{let i=JSON.parse(s);if(i.type==="user"&&i.message?.content){let n=typeof i.message.content=="string"?i.message.content:JSON.stringify(i.message.content),a=n.substring(0,100);return n.length>100?`${a}...`:a}}catch{}}catch{}}async function ywe(e,t){if(!Ne__namespace.existsSync(e))throw new Error(`Session file not found: ${e}`);let r=[],s=new Map,n=(await Ne__namespace.promises.readFile(e,"utf-8")).split(`
|
|
803
|
+
`;Ne.appendFileSync(e.log_file,n);}catch{}let i={...e,completed_at:r,exit_code:t};Pit(e.id),iz(i),t===0?this.emit("item:completed",i):(this.shouldRetry(e)&&this.retryItem(e),this.emit("item:failed",i));}shouldRetry(e){let t=Ml(),r=e.metadata?.retry_count||0,s=e.metadata?.max_retries||t.default_max_retries;return r<s}retryItem(e){let t=(e.metadata?.retry_count||0)+1,r=e.metadata?.max_retries||3;xm.info({itemId:e.id,retryCount:t,maxRetries:r},"Queuing item for retry");let s={id:e.id,command:e.command,cwd:e.cwd,created_at:Date.now(),metadata:{...e.metadata,retry_count:t,original_started_at:e.started_at}},i=_c();i.push(s),wf(i),this.emit("item:retried",s,e.id);}checkNow(){this.tick();}forceComplete(e,t=0){let s=Yn().find(i=>i.id===e);return s?(this.handleCompletion(s,t),true):false}};}}),Za,swe,Jct=$({"src/queue/core/command-queue.ts"(){Uct(),Vct(),hn(),Ye(),Ibe(),cz(),Tbe(),Pbe(),Ube(),$be(),Rbe(),zbe(),xbe(),Za=je.child({module:"command-queue"}),swe=class extends Tst.EventEmitter{constructor(){super(),this.started=false,ad(),this.promoter=new rwe,this.monitor=new awe,this.promoter.on("item:promoted",e=>{Za.info({itemId:e.id,pid:e.pid,command:e.command},"Item started"),this.emit("item:started",e),this.emit("queue:changed");}),this.promoter.on("item:spawn-error",(e,t)=>{Za.error({itemId:e.id,err:t},"Item spawn failed"),this.emit("error",t);}),this.promoter.on("error",e=>{Za.error({err:e},"Promoter error"),this.emit("error",e);}),this.monitor.on("item:completed",e=>{let t=e.completed_at-e.started_at;Za.info({itemId:e.id,exitCode:e.exit_code,durationMs:t},"Item completed"),this.emit("item:completed",e),this.emit("queue:changed");}),this.monitor.on("item:failed",e=>{let t=e.completed_at-e.started_at;Za.warn({itemId:e.id,exitCode:e.exit_code,durationMs:t},"Item failed"),this.emit("item:failed",e),this.emit("queue:changed");}),this.monitor.on("item:retried",e=>{let t=e.metadata?.retry_count??0;Za.info({itemId:e.id,retryCount:t},"Item queued for retry"),this.emit("item:retried",e),this.emit("queue:changed");}),this.monitor.on("error",e=>{Za.error({err:e},"Monitor error"),this.emit("error",e);});}async start(){if(this.started)return;Za.info("Starting command queue..."),this.started=true;let{recovered:e}=await this.recoverFromRestart();e>0&&Za.info({recovered:e},"Recovered dead processes from previous run"),this.promoter.start(),this.monitor.start(),Za.info("Command queue started");}async stop(){this.started&&(Za.info("Stopping command queue..."),this.promoter.stop(),this.monitor.stop(),this.started=false,Za.info("Command queue stopped (running processes will continue)"));}async recoverFromRestart(){let e=Yn(),t=0;for(let r of e)this.isProcessAlive(r.pid)||(this.monitor.forceComplete(r.id,1),t++);return t>0&&this.emit("queue:changed"),{recovered:t}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return false}}enqueue(e){let t=oz(e);if(t.success){Za.info({itemId:t.id,command:e.command,cwd:e.cwd},"Item enqueued");let r=i_({id:t.id});r.success&&r.item&&this.emit("item:enqueued",r.item),this.emit("queue:changed");}else Za.warn({command:e.command,error:t.error},"Failed to enqueue item");return t}cancel(e,t=false){let r=Ebe({id:e,force:t});return r.success?(Za.info({itemId:e,force:t},"Item cancelled"),this.emit("item:cancelled",e),this.emit("queue:changed")):Za.warn({itemId:e,error:r.error},"Failed to cancel item"),r}retry(e){let t=wz(e);return t.success?(Za.info({itemId:e.id},"Item retry initiated"),this.emit("queue:changed")):Za.warn({itemId:e.id,error:t.error},"Failed to retry item"),t}getStatus(){return lC()}list(e){return Bf(e)}inspect(e){return i_({id:e})}getLogs(e){return Sz(e)}getConfig(){return kz()}updateConfig(e){let t=AP(e);return t.success&&(e.promoter_interval_ms||e.monitor_interval_ms)&&this.started&&(this.promoter.stop(),this.monitor.stop(),this.promoter.start(),this.monitor.start()),t}clean(e){let t=jbe(e);return t.success&&t.cleaned>0&&this.emit("queue:changed"),t}isRunning(){return this.started}};}}),iwe,Yct=$({"src/devices/device-registry.ts"(){iwe=class{constructor(e,t){this.events=e,this.devices=new Map,this.peerDevices=new Map,this.gatewayId=t??nk.randomUUID();}getGatewayId(){return this.gatewayId}registerClient(e){let t={id:nk.randomUUID(),type:"client",name:e.name,gateway_id:this.gatewayId,platform:e.platform,status:"online",capabilities:e.capabilities??[],connected_at:new Date().toISOString(),last_seen:new Date().toISOString()};return this.devices.set(t.id,t),this.events.broadcast({type:"device_connected",data:{device:t}}),t}registerClientWithId(e,t){let r=this.devices.get(e);if(r)return r.status="online",r.last_seen=new Date().toISOString(),r.name=t.name,r.platform=t.platform,r.capabilities=t.capabilities??r.capabilities,this.events.broadcast({type:"device_connected",data:{device:r}}),r;let s={id:e,type:"client",name:t.name,gateway_id:this.gatewayId,platform:t.platform,status:"online",capabilities:t.capabilities??[],connected_at:new Date().toISOString(),last_seen:new Date().toISOString()};return this.devices.set(s.id,s),this.events.broadcast({type:"device_connected",data:{device:s}}),s}unregisterClient(e){this.devices.get(e)&&(this.devices.delete(e),this.events.broadcast({type:"device_disconnected",data:{device_id:e}}));}registerPeer(e,t){let r={id:e,type:"gateway",name:t.name,gateway_id:e,platform:"desktop",status:"online",address:t.address,capabilities:t.capabilities??[],connected_at:new Date().toISOString(),last_seen:new Date().toISOString()};return this.devices.set(r.id,r),this.peerDevices.set(e,new Set),this.events.broadcast({type:"device_connected",data:{device:r}}),r}unregisterPeer(e){this.devices.delete(e);let t=this.peerDevices.get(e);if(t){for(let r of t)this.devices.delete(r);this.peerDevices.delete(e);}this.events.broadcast({type:"device_disconnected",data:{device_id:e}});}syncPeerDevices(e,t){let r=this.peerDevices.get(e);if(r)for(let i of r)this.devices.delete(i);let s=new Set;for(let i of t)this.devices.set(i.id,i),s.add(i.id);this.peerDevices.set(e,s);}updateLastSeen(e){let t=this.devices.get(e);t&&(t.last_seen=new Date().toISOString());}getAllDevices(){return Array.from(this.devices.values())}getDevice(e){return this.devices.get(e)}getDevicesByGateway(e){return this.getAllDevices().filter(t=>t.gateway_id===e)}getOnlineGateways(){return this.getAllDevices().filter(e=>e.type==="gateway"&&e.status==="online")}getLocalClients(){return this.getAllDevices().filter(e=>e.type==="client"&&e.gateway_id===this.gatewayId)}};}}),_M,Zct=$({"src/mesh/peer-connection.ts"(){_M=class extends Tst.EventEmitter{constructor(e,t=6e4){super(),this.localInfo=e,this.maxReconnectDelay=t,this.ws=null,this.heartbeatTimer=null,this.peerInfo=null,this.reconnectAttempts=0,this.reconnectTimer=null,this.manualClose=false;}connectTo(e){this.manualClose=false;let t=e.replace(/^http/,"ws")+"/api/mesh/ws";this.ws=new aI__default.default(t),this.ws.on("open",()=>{this.send({type:"Hello",data:this.localInfo}),this.startHeartbeat();}),this.ws.on("message",r=>{try{let s=JSON.parse(r.toString());if(s.type==="Pong")return;s.type==="Welcome"&&(this.peerInfo={gateway_id:s.data.gateway_id,name:s.data.name,version:s.data.version,capabilities:s.data.capabilities,address:s.data.address},this.reconnectAttempts=0,this.emit("ready",this.peerInfo)),this.emit("message",s);}catch{}}),this.ws.on("close",(r,s)=>{this.stopHeartbeat(),this.emit("close",r,s.toString()),this.manualClose||this.scheduleReconnect(e);}),this.ws.on("error",r=>{this.emit("error",r);});}accept(e,t,r){this.manualClose=false,this.ws=e,this.peerInfo=t;let s={...this.localInfo,peers:r??[]};this.send({type:"Welcome",data:s}),this.startHeartbeat(),e.on("message",i=>{try{let n=JSON.parse(i.toString());if(n.type==="Pong")return;this.emit("message",n);}catch{}}),e.on("close",(i,n)=>{this.stopHeartbeat(),this.emit("close",i,n.toString());}),e.on("error",i=>this.emit("error",i)),this.emit("ready",t);}send(e){return !this.ws||this.ws.readyState!==1?false:(this.ws.send(JSON.stringify(e)),true)}getPeerInfo(){return this.peerInfo}close(){this.manualClose=true,this.stopHeartbeat(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close(1e3);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.send({type:"Ping"});},3e4);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}scheduleReconnect(e){let t=Math.min(1e3*2**this.reconnectAttempts,this.maxReconnectDelay);this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>this.connectTo(e),t);}};}}),nwe,eut=$({"src/mesh/mesh-service.ts"(){Zct(),nwe=class{constructor(e,t,r,s){this.events=e,this.registry=t,this.peerStore=r,this.localInfo=s,this.peers=new Map,this.pendingMessages=new Map,this.localActionHandler=null;}getLocalInfo(){return this.localInfo}getPeers(){let e=[];for(let t of this.peers.values()){let r=t.getPeerInfo();r&&e.push(r);}return e}connectToPeer(e){let t=new _M(this.localInfo);t.on("error",()=>{}),t.on("ready",r=>{this.peers.set(r.gateway_id,t),this.registry.registerPeer(r.gateway_id,{gateway_id:r.gateway_id,name:r.name,address:r.address,capabilities:r.capabilities}),this.peerStore.upsert({gateway_id:r.gateway_id,name:r.name,lan:r.address,last_seen:new Date().toISOString()}).catch(()=>{}),this.broadcastToPeers({type:"PeerJoined",data:r},r.gateway_id);}),t.on("message",r=>this.handleMessage(r)),t.on("close",()=>{let r=t.getPeerInfo();r&&(this.peers.delete(r.gateway_id),this.registry.unregisterPeer(r.gateway_id),this.broadcastToPeers({type:"PeerLeft",data:{gateway_id:r.gateway_id}}));}),t.connectTo(e);}acceptPeer(e,t){if(this.peers.has(t.gateway_id)){e.close(4001,"already_connected");return}let r=new _M(this.localInfo);r.on("error",()=>{}),r.on("message",i=>this.handleMessage(i)),r.on("close",()=>{this.peers.delete(t.gateway_id),this.registry.unregisterPeer(t.gateway_id),this.broadcastToPeers({type:"PeerLeft",data:{gateway_id:t.gateway_id}});});let s=this.getPeers();r.accept(e,t,s),this.peers.set(t.gateway_id,r),this.registry.registerPeer(t.gateway_id,{gateway_id:t.gateway_id,name:t.name,address:t.address,capabilities:t.capabilities}),this.peerStore.upsert({gateway_id:t.gateway_id,name:t.name,lan:t.address,last_seen:new Date().toISOString()}).catch(()=>{}),this.broadcastToPeers({type:"PeerJoined",data:t},t.gateway_id);}sendDeviceMessage(e){if(e.to_gateway==="*")return this.broadcastToPeers({type:"DeviceMessage",data:e}),true;let t=this.peers.get(e.to_gateway);return t?t.send({type:"DeviceMessage",data:e}):false}handleIncomingDeviceMessage(e){if(e.reply_to){this.resolveMessage(e.reply_to,e.payload);return}this.localActionHandler&&this.localActionHandler(e);}onLocalAction(e){this.localActionHandler=e;}trackPendingMessage(e,t=3e4){return new Promise((r,s)=>{let i=setTimeout(()=>{this.pendingMessages.delete(e),s(new Error("timeout"));},t);this.pendingMessages.set(e,{resolve:r,reject:s,timer:i});})}resolveMessage(e,t){let r=this.pendingMessages.get(e);r&&(clearTimeout(r.timer),this.pendingMessages.delete(e),r.resolve(t));}async reconnectKnownPeers(){let e=await this.peerStore.load();for(let t of e){if(t.gateway_id===this.localInfo.gateway_id)continue;let r=t.lan??t.tunnel;r&&this.connectToPeer(r);}}shutdown(){for(let e of this.peers.values())e.close();this.peers.clear();for(let e of this.pendingMessages.values())clearTimeout(e.timer),e.reject(new Error("shutdown"));this.pendingMessages.clear();}handleMessage(e){switch(e.type){case "DeviceMessage":{let t=e.data;t.to_gateway===this.localInfo.gateway_id||t.to_gateway==="*"?this.handleIncomingDeviceMessage(t):this.peers.get(t.to_gateway)?.send(e);break}case "PeerJoined":this.events.broadcast({type:"mesh_peer_joined",data:{gateway_id:e.data.gateway_id,name:e.data.name,address:e.data.address??""}});break;case "PeerLeft":this.events.broadcast({type:"mesh_peer_left",data:{gateway_id:e.data.gateway_id}});break;case "DeviceEvent":{let t=e.data;t.type==="device_connected"&&t.device?this.events.broadcast({type:"device_connected",data:{device:t.device}}):t.type==="device_disconnected"&&t.device_id?this.events.broadcast({type:"device_disconnected",data:{device_id:t.device_id}}):t.type==="device_updated"&&t.device&&this.events.broadcast({type:"device_updated",data:{device:t.device}});break}}}broadcastToPeers(e,t){for(let[r,s]of this.peers)r!==t&&s.send(e);}};}}),joe,owe,aut=$({"src/mesh/peer-store.ts"(){Pr(),joe=qe.join(nn.homedir(),".viben","mesh","peers.yaml"),owe=class{constructor(e=joe){this.path=e;}async load(){return (await It(this.path))?.peers??[]}async save(e){await xr(this.path,{peers:e});}async upsert(e){let t=await this.load(),r=t.findIndex(s=>s.gateway_id===e.gateway_id);r>=0?t[r]=e:t.push(e),await this.save(t);}async remove(e){let t=await this.load();await this.save(t.filter(r=>r.gateway_id!==e));}};}});async function zoe(){if(vM)return oS;vM=true;try{oS=(await import('bonjour-service')).Bonjour;}catch{oS=null;}return oS}var U4,oS,vM,cwe,sut=$({"src/discovery/mdns.ts"(){U4="viben-gateway",oS=null,vM=false,cwe=class{constructor(){this.instance=null,this.browser=null,this.published=false,this.onDiscoverCallback=null;}async start(e){let t=await zoe();t&&(this.instance=new t,this.instance.publish({name:e.name,type:U4,port:e.port,txt:{gateway_id:e.gateway_id,name:e.name,version:e.version}}),this.published=true,this.browser=this.instance.find({type:U4},r=>{let s=r.txt||{};if(s.gateway_id===e.gateway_id)return;let i={gateway_id:s.gateway_id||"",name:s.name||r.name,version:s.version||"unknown",host:r.host,port:r.port,addresses:r.addresses||[]};this.onDiscoverCallback?.(i);}));}onDiscover(e){this.onDiscoverCallback=e;}stop(){this.browser&&(this.browser.stop(),this.browser=null),this.instance&&(this.instance.unpublishAll(),this.instance.destroy(),this.instance=null),this.published=false;}async isAvailable(){return await zoe()!==null}};}});async function iut(){if(cS)return cS;if(bM)throw new Error("qrcode package not available");bM=true;try{return cS=await import('qrcode'),cS}catch{throw new Error("qrcode package not available. Install it with: pnpm add qrcode")}}async function nut(e){let t=await iut(),r=JSON.stringify(e);return t.toDataURL(r,{width:256,margin:2})}var cS,bM,out=$({"src/discovery/qr.ts"(){cS=null,bM=false;}}),uwe,cut=$({"src/discovery/discovery-service.ts"(){sut(),out(),uwe=class{constructor(e,t){this.events=e,this.mdns=new cwe,this.onPeerDiscoveredCallback=null,this.config=t;}async start(){let e={gateway_id:this.config.gateway_id,name:this.config.name,version:this.config.version,host:"0.0.0.0",port:this.config.port,addresses:[]};this.mdns.onDiscover(t=>{let r=`http://${t.addresses[0]||t.host}:${t.port}`;this.onPeerDiscoveredCallback?.(r);}),await this.mdns.start(e);}onPeerDiscovered(e){this.onPeerDiscoveredCallback=e;}stop(){this.mdns.stop();}getQrPayload(){return {type:"viben-gateway",gateway_id:this.config.gateway_id,name:this.config.name,lan:this.config.lan_address?`http://${this.config.lan_address}:${this.config.port}`:void 0,tunnel:this.config.tunnel_url}}async getQrDataUrl(){return nut(this.getQrPayload())}async isMdnsAvailable(){return this.mdns.isAvailable()}};}}),lwe={};yt(lwe,{generateKeyPair:()=>uut,sign:()=>lut,verify:()=>dut});function wM(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function SM(e){let t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.substr(r*2,2),16);return t}function uut(){let e=wB.randomSecretKey(),t=gB(e);return {publicKey:wM(t),privateKey:wM(e)}}async function lut(e,t){let r=SM(t),s=new TextEncoder().encode(e),i=await _B(s,r);return wM(i)}async function dut(e,t,r){try{let s=SM(r),i=SM(t),n=new TextEncoder().encode(e);return await bB(i,n,s)}catch{return false}}var put=$({"src/utils/crypto.ts"(){}});function hut(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return (t>>>0).toString(36)}function mut(e,t){let r=e+t.namespace+t.name+t.description+JSON.stringify(t.inputSchema??null)+JSON.stringify(t.outputSchema??null);return hut(r)}var _i,Uoe,Boe,Goe,Tz,dwe=$({"src/gateway/client-store.ts"(){Ye(),_i=je.child({module:"client-store"}),Uoe=3e4,Boe=1e3,Goe=1024*1024,Tz=class{constructor(e={}){this.clients=new Map,this.nameIndex=new Map,this._globalTheme="light",this.config={gracePeriodMs:e.gracePeriodMs??Uoe,maxActionsPerClient:e.maxActionsPerClient??Boe,maxPayloadSize:e.maxPayloadSize??Goe};}get globalTheme(){return this._globalTheme}setGlobalTheme(e){this._globalTheme=e;}getClient(e){return this.clients.get(e)}async verifySignature(e,t,r,s){let i=Date.now();if(Math.abs(i-s)>300*1e3)return _i.warn({clientId:e,timestamp:s,now:i},"Signature timestamp expired"),false;try{let{verify:n}=await Promise.resolve().then(()=>(put(),lwe)),a=`${e}:${s}`;return await n(a,r,t)}catch(n){return _i.error({clientId:e,error:n},"Signature verification failed"),false}}async registerClient(e,t){let r=this.clients.get(e);if(r){if(r.publicKey!==t.publicKey)throw new Error("Public key mismatch for existing client");if(!await this.verifySignature(e,t.publicKey,t.signature,t.timestamp))throw new Error("Invalid signature for clientId");r.disconnectTimer&&(clearTimeout(r.disconnectTimer),r.disconnectTimer=void 0,_i.info({clientId:e},"Grace period cancelled (new socket connected)"));}else {if(!await this.verifySignature(e,t.publicKey,t.signature,t.timestamp))throw new Error("Invalid signature for clientId");r={clientId:e,publicKey:t.publicKey,sockets:new Map,actionStore:new Map,metadata:{theme:t.theme??"light",workspacePath:t.workspacePath??""}},this.clients.set(e,r),_i.info({clientId:e},"Client registered");}return r.sockets.has(t.socketId)||(r.sockets.set(t.socketId,{socketId:t.socketId,source:t.source,pageUid:t.pageUid,connectedAt:Date.now()}),_i.info({clientId:e,socketId:t.socketId,source:t.source},"Socket added to client")),t.theme&&(r.metadata.theme=t.theme),t.workspacePath&&(r.metadata.workspacePath=t.workspacePath),r}removeSocket(e,t){let r=this.clients.get(e);if(!r)return {actionsRemoved:[],clientRemoved:false};r.sockets.delete(t),_i.info({clientId:e,socketId:t},"Socket removed from client");let s=[];for(let[i,n]of r.actionStore)n.socketId===t&&s.push(i);if(r.sockets.size>0){for(let i of s){let n=r.actionStore.get(i);n&&this.removeFromNameIndex(e,n),r.actionStore.delete(i),_i.info({clientId:e,action:i},"Action removed (socket disconnected)");}return {actionsRemoved:s,clientRemoved:false}}return _i.info({clientId:e,gracePeriodMs:this.config.gracePeriodMs},"All sockets disconnected, starting grace period"),r.disconnectTimer=setTimeout(()=>{let i=this.clients.get(e);if(i&&i.sockets.size===0){for(let n of i.actionStore.values())this.removeFromNameIndex(e,n);this.clients.delete(e),_i.info({clientId:e,actionsRemoved:Array.from(i.actionStore.keys())},"Client removed after grace period");}},this.config.gracePeriodMs),{actionsRemoved:[],clientRemoved:false}}registerAction(e,t,r){let s=this.clients.get(e);if(!s)return {updated:false,fullName:"",error:`Client not found: ${e}`};if(s.actionStore.size>=this.config.maxActionsPerClient)return _i.warn({clientId:e,count:s.actionStore.size},"Max actions limit reached"),{updated:false,fullName:"",error:"Max actions limit reached"};let i=`${r.namespace}.${r.name}`,n=mut(e,r),a=s.actionStore.get(i);if(a&&a.hash===n)return a.socketId!==t&&(a.socketId=t,_i.info({clientId:e,action:i,oldSocketId:a.socketId,newSocketId:t},"Action socketId updated (reconnect)")),{updated:false,fullName:i};let c={namespace:r.namespace,name:r.name,description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema,socketId:t,registeredAt:Date.now(),hash:n,timeout:r.timeout},o=s.actionStore.get(i);return o&&this.removeFromNameIndex(e,o),s.actionStore.set(i,c),this.addToNameIndex(e,c),_i.info({clientId:e,action:i,socketId:t,timeout:r.timeout},"Action registered"),{updated:true,fullName:i}}unregisterAction(e,t,r){let s=this.clients.get(e);if(!s)return [];let i=[];for(let[n,a]of s.actionStore){let c=!t||a.namespace===t,o=!r||a.socketId===r;c&&o&&(s.actionStore.delete(n),this.removeFromNameIndex(e,a),i.push(n));}return i.length>0&&_i.info({clientId:e,removed:i},"Actions unregistered"),i}findAction(e,t,r){let s=this.clients.get(e);if(s)return s.actionStore.get(`${t}.${r}`)}getAllActions(){let e=[];for(let[t,r]of this.clients)for(let s of r.actionStore.values())e.push({...s,clientId:t});return e}removeStaleActions(e,t,r,s){let i=this.clients.get(e);if(!i)return [];let n=[];for(let[a,c]of i.actionStore)c.namespace===t&&c.socketId===r&&!s.has(c.name)&&(this.removeFromNameIndex(e,c),i.actionStore.delete(a),n.push(a));return n}findActionByName(e){return this.nameIndex.get(e)?.[0]}findActionByFullName(e){for(let[t,r]of this.clients){let s=r.actionStore.get(e);if(s)return {...s,clientId:t}}}resolveAction(e){let t=this.findActionByFullName(e);if(t)return t;let r=this.findActionByName(e);if(r)return r;let s=e.indexOf(".");if(s>0){let i=e.slice(0,s),n=e.slice(s+1),a=this.clients.get(i);if(a){let c=a.actionStore.get(n);if(c)return {...c,clientId:i}}}}addToNameIndex(e,t){let r=this.nameIndex.get(t.name),s={...t,clientId:e};r?r.push(s):this.nameIndex.set(t.name,[s]);}removeFromNameIndex(e,t){let r=this.nameIndex.get(t.name);if(!r)return;let s=r.findIndex(i=>i.clientId===e&&i.namespace===t.namespace);s!==-1&&(r.splice(s,1),r.length===0&&this.nameIndex.delete(t.name));}getSocketInfo(e,t){return this.clients.get(e)?.sockets.get(t)}getAllClients(){return Array.from(this.clients.keys())}getConfig(){return {...this.config}}shutdown(){for(let e of this.clients.values())e.disconnectTimer&&clearTimeout(e.disconnectTimer);this.clients.clear(),this.nameIndex.clear(),_i.info("ClientStore shut down");}};}});function pwe(e={}){let{host:t="127.0.0.1",port:r=18790,runtime:s=true}=e,i=new yP,n=new XS,a=new F8(i),c=new D8(i,n),o=new _P,l=new $8(i),u=new Zfe({events:i,channels:er,container:c,responseTimeout:12e4}),d=new Qye({channelManager:er,messageBus:l,auto_start:true,pollingTimeout:30}),h=new twe(i),_=new yM({heartbeatIntervalMs:3e4,staleTimeoutMs:12e4,maxFailedSends:3,cleanupIntervalMs:6e4});s&&_.startHeartbeat();let y=new C_e(rr,_,{stuckThresholdMs:300*1e3,autoRecover:true}),v=new swe,b=new iwe(i),w=b.getGatewayId(),S=new owe,E={gateway_id:w,name:`viben-${w.slice(0,8)}`,version:"1.0.0",capabilities:["navigate","notify","ping"],address:`http://${t}:${r}`},A=new nwe(i,b,S,E),D=new Tz,q=new uwe(i,{gateway_id:w,name:E.name,version:"1.0.0",port:r}),O=new bP;return s&&q.onPeerDiscovered(R=>{A.connectToPeer(R);}),{events:i,sessionStore:n,cron:a,container:c,history:o,messageBus:l,channelRouter:u,channelRuntime:d,taskQueue:h,taskRecovery:y,taskSSEManager:_,commandQueue:v,deviceRegistry:b,mesh:A,discovery:q,clientStore:D,firebase:O}}var Hoe=$({"src/gateway/state.ts"(){qA(),eh(),g0e(),y0e(),v0e(),b0e(),y_(),qct(),O_e(),zf(),dC(),Jct(),Yct(),eut(),aut(),cut(),dwe(),f_e();}});function hwe(e){let t=qe.join(nn.homedir(),".viben");Iz={host:e.host||"127.0.0.1",port:e.port||18790,cors:e.cors??true,started_at:new Date().toISOString(),pid:process.pid,node_version:process.version,platform:process.platform,arch:process.arch,config_dir:t,state_dir:t,command:`viben gateway serve --host ${e.host||"127.0.0.1"} --port ${e.port||18790}`};}function yut(e){e.get("/health",{schema:{description:"Health check endpoint",tags:["health"],response:{200:{type:"object",properties:{status:{type:"string",enum:["ok"]},service:{type:"string"},version:{type:"string"},timestamp:{type:"string",format:"date-time"},uptime:{type:"string"},uptime_seconds:{type:"number"},startup:{type:"object",properties:{host:{type:"string"},port:{type:"number"},cors:{type:"boolean"},started_at:{type:"string",format:"date-time"},pid:{type:"number"},node_version:{type:"string"},platform:{type:"string"},arch:{type:"string"},config_dir:{type:"string"},state_dir:{type:"string"},command:{type:"string"}}}}}}}},async()=>{let t=Date.now()-mwe,r=Math.floor(t/1e3),s=Math.floor(r/3600),i=Math.floor(r%3600/60),n=r%60,a=s>0?`${s}h ${i}m ${n}s`:i>0?`${i}m ${n}s`:`${n}s`;return {status:"ok",service:"viben-gateway",version:xz,timestamp:new Date().toISOString(),uptime:a,uptime_seconds:r,startup:Iz||void 0}});}var xz,Iz,mwe,CP=$({"src/gateway/routes/health.ts"(){xz="1.3.4",Iz=null,mwe=Date.now();}});function Pz(e){return e.replace(/\//g,"-")}function Az(){return qe__namespace.join(nn__namespace.homedir(),".claude","projects")}async function _ut(e){let t=Az(),r=Pz(e),s=qe__namespace.join(t,r);if(!Ne__namespace.existsSync(s))return [];let a=(await Ne__namespace.promises.readdir(s,{withFileTypes:true})).filter(o=>o.isFile()&&o.name.endsWith(".jsonl")).map(async o=>{let l=o.name.replace(".jsonl",""),u=qe__namespace.join(s,o.name);try{let[d,h]=await Promise.all([Ne__namespace.promises.stat(u),gwe(u)]);return {id:l,executor_type:"CLAUDE_CODE",workspace_path:e,created_at:d.birthtime.toISOString(),updated_at:d.mtime.toISOString(),name:h,message_count:Math.floor(d.size/1024)}}catch{return null}}),c=(await Promise.all(a)).filter(o=>o!==null);return c.sort((o,l)=>new Date(l.updated_at).getTime()-new Date(o.updated_at).getTime()),c}async function gwe(e){try{let t=Ne__namespace.createReadStream(e),r=kj__namespace.createInterface({input:t,crlfDelay:1/0});for await(let s of r)if(s.trim()!=="")try{let i=JSON.parse(s);if(i.type==="user"&&i.message?.content){let n=typeof i.message.content=="string"?i.message.content:JSON.stringify(i.message.content),a=n.substring(0,100);return n.length>100?`${a}...`:a}}catch{}}catch{}}async function ywe(e,t){if(!Ne__namespace.existsSync(e))throw new Error(`Session file not found: ${e}`);let r=[],s=new Map,n=(await Ne__namespace.promises.readFile(e,"utf-8")).split(`
|
|
804
804
|
`).filter(a=>a.trim()!=="");for(let a of n)try{let c=JSON.parse(a);if(c.type==="progress"){let o=c.data;o?.type==="agent_progress"&&o.agentId&&c.parentToolUseID&&s.set(c.parentToolUseID,o.agentId);}}catch{}for(let a of n)try{let c=JSON.parse(a),o=vut(c);for(let l of o)if(l.type==="tool_use"&&l.tool_name==="Task"&&l.tool_use_id){let u=s.get(l.tool_use_id);u&&(l.subagent_id=u);}if(r.push(...o),t&&r.length>=t)break}catch{}return r}function vut(e){let t=e.uuid||crypto.randomUUID(),r=e.timestamp||new Date().toISOString();switch(e.type){case "user":{let i=e.message;if(!i)return [];if(typeof i.content=="string")return [{id:t,timestamp:r,type:"user",content:i.content}];if(Array.isArray(i.content)){let n=[];return i.content.forEach((a,c)=>{a.type==="text"&&a.text?n.push({id:`${t}-${c}`,timestamp:r,type:"user",content:a.text}):a.type==="tool_result"&&n.push({id:`${t}-${c}`,timestamp:r,type:"tool_result",content:a.content,tool_use_id:a.tool_use_id,is_error:a.is_error});}),n}return []}case "assistant":{let i=e.message;return !i?.content||!Array.isArray(i.content)?[]:i.content.map((n,a)=>{switch(n.type){case "thinking":return {id:`${t}-${a}`,timestamp:r,type:"thinking",content:n.thinking||n.content};case "text":return n.text?{id:`${t}-${a}`,timestamp:r,type:"text",content:n.text}:null;case "tool_use":return {id:`${t}-${a}`,timestamp:r,type:"tool_use",tool_use_id:n.id,tool_name:n.name,tool_input:n.input};default:return null}}).filter(n=>n!==null)}case "result":{let i=e.result,n=e.subtype;return [{id:t,timestamp:r,type:"text",content:i||(n?`[${n}]`:void 0)}]}default:return []}}function _we(){return process.platform==="darwin"?qe__namespace.join(nn__namespace.homedir(),"Library","Application Support","codex","sessions"):process.platform==="win32"?qe__namespace.join(process.env.APPDATA||"","codex","sessions"):qe__namespace.join(nn__namespace.homedir(),".config","codex","sessions")}async function but(e){let t=_we();if(!Ne__namespace.existsSync(t))return [];let r=[];try{let s=await Ne__namespace.promises.readdir(t,{withFileTypes:!0});for(let i of s)if(i.isFile()&&i.name.endsWith(".jsonl")){let n=i.name.replace(".jsonl",""),a=qe__namespace.join(t,i.name),c=await Ne__namespace.promises.stat(a),o=await gwe(a);r.push({id:n,executor_type:"codex",workspace_path:e,created_at:c.birthtime.toISOString(),updated_at:c.mtime.toISOString(),name:o,message_count:Math.floor(c.size/1024)});}r.sort((i,n)=>new Date(n.updated_at).getTime()-new Date(i.updated_at).getTime());}catch{}return r}async function wut(e,t){if(!Ne__namespace.existsSync(e))return [];let r=[];try{let i=(await Ne__namespace.promises.readFile(e,"utf-8")).split(`
|
|
805
805
|
`).filter(n=>n.trim()!=="");for(let n of i)try{let a=JSON.parse(n),c=Sut(a);if(r.push(...c),t&&r.length>=t)break}catch{}}catch{}return r}function Sut(e){let t=e.uuid||e.id||crypto.randomUUID(),r=e.timestamp||new Date().toISOString();switch(e.type){case "user":{let i=e.content,n=e.message,a=i||n?.content;return a?[{id:t,timestamp:r,type:"user",content:a}]:[]}case "assistant":{let i=e.content,n=e.message,a=i||n?.content;return a?[{id:t,timestamp:r,type:"text",content:a}]:[]}default:return []}}function kut(e,t){let r=nn__namespace.homedir();switch(e){case "CLAUDE_CODE":{let s=qe__namespace.join(r,".claude"),i=t?qe__namespace.join(t,".claude"):void 0;return {globalConfigPath:Ne__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&Ne__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "CODEX":{let s;process.platform==="darwin"?s=qe__namespace.join(r,"Library","Application Support","codex"):process.platform==="win32"?s=qe__namespace.join(process.env.APPDATA||"","codex"):s=qe__namespace.join(r,".config","codex");let i=t?qe__namespace.join(t,".codex"):void 0;return {globalConfigPath:Ne__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&Ne__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "CURSOR_AGENT":{let s;process.platform==="darwin"?s=qe__namespace.join(r,"Library","Application Support","Cursor","User"):process.platform==="win32"?s=qe__namespace.join(process.env.APPDATA||"","Cursor","User"):s=qe__namespace.join(r,".config","Cursor","User");let i=t?qe__namespace.join(t,".cursor"):void 0;return {globalConfigPath:Ne__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&Ne__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "GEMINI":{let s=qe__namespace.join(r,".gemini"),i=t?qe__namespace.join(t,".gemini"):void 0;return {globalConfigPath:Ne__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&Ne__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "AMP":{let s;process.platform==="darwin"?s=qe__namespace.join(r,"Library","Application Support","amp"):process.platform==="win32"?s=qe__namespace.join(process.env.APPDATA||"","amp"):s=qe__namespace.join(r,".config","amp");let i=t?qe__namespace.join(t,".amp"):void 0;return {globalConfigPath:Ne__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&Ne__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "OPENCLAW":{let s=qe__namespace.join(r,".openclaw"),i=qe__namespace.join(s,"openclaw.json"),n=t?qe__namespace.join(t,".openclaw"):void 0;return {globalConfigPath:Ne__namespace.existsSync(i)?i:Ne__namespace.existsSync(s)?s:void 0,workspaceConfigPath:n&&Ne__namespace.existsSync(n)?n:void 0,globalConfigDir:s,workspaceConfigDir:n}}default:{let s=qe__namespace.join(r,".viben"),i=t?qe__namespace.join(t,".viben"):void 0;return {globalConfigPath:Ne__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&Ne__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}}}function Eut(e,t){let r=vwe[e]||{name:e,description:`${e} executor`},s=kut(e,t),i=!!(s.globalConfigPath||s.workspaceConfigPath),n=!!s.workspaceConfigPath,a;if(i)if(e==="CLAUDE_CODE"&&s.globalConfigPath){let l=qe__namespace.join(s.globalConfigPath,".credentials.json");if(Ne__namespace.existsSync(l))try{a={type:"LOGIN_DETECTED",last_auth_timestamp:Ne__namespace.statSync(l).mtimeMs};}catch{a={type:"INSTALLATION_FOUND"};}else a={type:"INSTALLATION_FOUND"};}else a={type:"INSTALLATION_FOUND"};else a={type:"NOT_FOUND"};let c=[],o=false;switch(e){case "CLAUDE_CODE":c.push("chat","code-edit","file-ops","terminal"),o=true;break;case "CURSOR_AGENT":c.push("chat","code-edit"),o=true;break;case "CODEX":c.push("chat","code-edit"),o=true;break;case "GEMINI":c.push("chat","code-edit");break;case "AMP":c.push("chat","code-edit");break;case "OPENCLAW":c.push("chat","code-edit","file-ops","terminal");break;default:c.push("chat");}return {type:e,name:r.name,description:r.description,docs_url:r.docsUrl,availability:a,config_path:s.workspaceConfigPath||s.globalConfigPath,workspace_config_path:s.workspaceConfigPath,global_config_path:s.globalConfigPath,supports_mcp:o,capabilities:c,has_workspace_config:n,workspace_path:t||nn__namespace.homedir()}}function Tut(e){return ["CLAUDE_CODE","CODEX","CURSOR_AGENT","GEMINI","AMP","OPENCLAW"].map(r=>Eut(r,e))}function xut(e){e.get("/api/executors",{schema:{description:"List available executors",tags:["executors"],querystring:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path for context"},include_global:{type:"string",description:"Include global config (default: true)"}}},response:{200:{type:"object",properties:{executors:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"Executor type (e.g., CLAUDE_CODE)"},name:{type:"string"},description:{type:"string"},docs_url:{type:"string"},availability:{type:"object",properties:{type:{type:"string",enum:["LOGIN_DETECTED","INSTALLATION_FOUND","NOT_FOUND"]},last_auth_timestamp:{type:"number"}}},supports_mcp:{type:"boolean"},capabilities:{type:"array",items:{type:"string"}},has_workspace_config:{type:"boolean"},workspace_path:{type:"string"}}}},workspace_path:{type:"string"},include_global:{type:"boolean"},total:{type:"number"}}}}}},async y=>{let v=y.query.workspace_path,b=y.query.include_global!=="false",w=Tut(v);return {executors:w,workspace_path:v||nn__namespace.homedir(),include_global:b,total:w.length}}),e.get("/api/executors/:type/discover-sessions",async(y,v)=>{let{type:b}=y.params,{workspace_path:w}=y.query;if(!w)return v.code(400),{error:"workspace_path query parameter is required"};let S=[];switch(b){case "CLAUDE_CODE":S=await _ut(w);break;case "CODEX":S=await but(w);break;default:return v.code(404),{error:`Unknown executor type: ${b}. Use uppercase format like CLAUDE_CODE`}}return {sessions:S,total:S.length}}),e.get("/api/executors/:type/sessions/:sessionId/messages",async(y,v)=>{let{type:b,sessionId:w}=y.params,{workspace_path:S,limit:E}=y.query;if(!S)return v.code(400),{error:"workspace_path query parameter is required"};let A=[];switch(b){case "CLAUDE_CODE":{let q=Az(),O=Pz(S),R=qe__namespace.join(q,O,`${w}.jsonl`);A=await ywe(R,E);break}case "CODEX":{let q=_we(),O=qe__namespace.join(q,`${w}.jsonl`);Ne__namespace.existsSync(O)&&(A=await wut(O,E));break}default:return v.code(404),{error:`Unknown executor type: ${b}. Use uppercase format like CLAUDE_CODE`}}return {messages:A,total:A.length}});function t(y,v){let b=y||nn__namespace.homedir();switch(v){case "CLAUDE_CODE":let w=qe__namespace.join(b,".mcp.json");return Ne__namespace.existsSync(w)?w:qe__namespace.join(nn__namespace.homedir(),".claude.json");case "CURSOR_AGENT":return qe__namespace.join(b,".cursor","mcp.json");default:return qe__namespace.join(b,".viben","mcp.json")}}function r(y,v){if(!Ne__namespace.existsSync(y))return [];try{let b=Ne__namespace.readFileSync(y,"utf-8"),w=JSON.parse(b);if(v==="CLAUDE_CODE"){let S=w.mcpServers||{};return Object.entries(S).map(([E,A])=>({name:E,...A}))}return w.servers&&Array.isArray(w.servers)?w.servers:w.mcpServers?Object.entries(w.mcpServers).map(([S,E])=>({name:S,...E})):[]}catch{return []}}e.get("/api/executors/:type/mcp-servers",async y=>{let{type:v}=y.params,{workspace_path:b}=y.query,w=v,S=t(b,w);if(!S)return {servers:[],total:0};let E=r(S,w);return {servers:E,total:E.length}});function s(y,v){let b=y||nn__namespace.homedir();switch(v){case "CLAUDE_CODE":return {jsonPath:qe__namespace.join(b,".claude","skills.json"),folderPath:qe__namespace.join(b,".claude","skills")};case "CURSOR_AGENT":return {jsonPath:qe__namespace.join(b,".cursor","skills.json"),folderPath:qe__namespace.join(b,".cursor","skills")};default:return {jsonPath:qe__namespace.join(b,".viben","skills.json"),folderPath:qe__namespace.join(b,".viben","skills")}}}function i(y){try{let v=Ne__namespace.readFileSync(y,"utf-8"),b=qe__namespace.basename(qe__namespace.dirname(y)),w=v.match(/^---\n([\s\S]*?)\n---/),S=b,E;if(w){let A=w[1],D=A.match(/^name:\s*(.+)$/m);D&&(S=D[1].trim());let q=A.match(/^description:\s*(.+)$/m);q&&(E=q[1].trim());}return {id:b,name:S,version:"1.0.0",source:"local",path:qe__namespace.dirname(y),description:E}}catch{return null}}function n(y){let v=[];if(!Ne__namespace.existsSync(y))return v;try{let b=Ne__namespace.readdirSync(y);for(let w of b){let S=qe__namespace.join(y,w);if(Ne__namespace.statSync(S).isDirectory()){let A=qe__namespace.join(S,"skill.md");if(Ne__namespace.existsSync(A)){let D=i(A);D&&v.push(D);}}}}catch{}return v}e.get("/api/executors/:type/skills",async y=>{let{type:v}=y.params,{workspace_path:b,include_global:w}=y.query,S=v,E=w!=="false",A=[];if(b){let{jsonPath:D,folderPath:q}=s(b,S);if(D&&Ne__namespace.existsSync(D))try{let O=Ne__namespace.readFileSync(D,"utf-8"),R=JSON.parse(O);Array.isArray(R.skills)&&A.push(...R.skills);}catch{}if(q){let O=n(q);for(let R of O)A.find(C=>C.id===R.id)||A.push(R);}}if(E){let D=nn__namespace.homedir();if(!(!b||b===D)){let{jsonPath:O,folderPath:R}=s(void 0,S);if(O&&Ne__namespace.existsSync(O))try{let C=Ne__namespace.readFileSync(O,"utf-8"),N=JSON.parse(C);if(Array.isArray(N.skills))for(let L of N.skills)A.find(F=>F.id===L.id)||A.push(L);}catch{}if(R){let C=n(R);for(let N of C)A.find(L=>L.id===N.id)||A.push(N);}}}if(!b){let{jsonPath:D,folderPath:q}=s(void 0,S);if(D&&Ne__namespace.existsSync(D))try{let O=Ne__namespace.readFileSync(D,"utf-8"),R=JSON.parse(O);if(Array.isArray(R.skills))for(let C of R.skills)A.find(N=>N.id===C.id)||A.push(C);}catch{}if(q){let O=n(q);for(let R of O)A.find(C=>C.id===R.id)||A.push(R);}}return {skills:A,total:A.length}});function a(y,v){let b=y||nn__namespace.homedir();switch(v){case "CLAUDE_CODE":return qe__namespace.join(b,".claude","agents");case "CURSOR_AGENT":return qe__namespace.join(b,".cursor","agents");default:return qe__namespace.join(b,".viben","agents")}}function c(y,v){let b=qe__namespace.basename(y,".md"),w=b,S="",E=[],A="",D=v,q=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(q){let O=q[1];D=q[2].trim();let R=O.match(/^name:\s*(.+)$/m);R&&(w=R[1].trim());let C=O.match(/^description:\s*(.+)$/m);C&&(S=C[1].trim());let N=O.match(/^tools:\s*(.+)$/m);N&&(E=N[1].split(",").map(F=>F.trim()).filter(Boolean));let L=O.match(/^model:\s*(.+)$/m);L&&(A=L[1].trim());}return {id:b,name:w,description:S,tools:E,model:A,path:y,content:D}}function o(y){let v=[];if(!Ne__namespace.existsSync(y))return v;try{let b=Ne__namespace.readdirSync(y);for(let w of b){let S=qe__namespace.join(y,w);if(Ne__namespace.statSync(S).isFile()&&w.endsWith(".md"))try{let A=Ne__namespace.readFileSync(S,"utf-8");v.push(c(S,A));}catch{}}}catch{}return v}e.get("/api/executors/:type/subagents",async y=>{let{type:v}=y.params,{workspace_path:b}=y.query,S=a(b,v);return S?{configs:o(S)}:{configs:[]}}),e.get("/api/executors/:type/subagents/:config_id",async(y,v)=>{let{type:b,config_id:w}=y.params,{workspace_path:S}=y.query,A=a(S,b);if(!A)return v.code(404),{error:"Subagents path not found"};let D=qe__namespace.join(A,`${w}.md`);if(!Ne__namespace.existsSync(D))return v.code(404),{error:"Subagent file not found"};try{let q=Ne__namespace.readFileSync(D,"utf-8");return {config:c(D,q)}}catch(q){return v.code(500),{error:q instanceof Error?q.message:"Failed to read subagent"}}});function l(y,v){let b=y||nn__namespace.homedir();switch(v){case "CLAUDE_CODE":return qe__namespace.join(b,".claude","commands");case "CURSOR_AGENT":return qe__namespace.join(b,".cursor","commands");default:return qe__namespace.join(b,".viben","commands")}}function u(y){let v=[];if(!Ne__namespace.existsSync(y))return v;try{let b=Ne__namespace.readdirSync(y);for(let w of b){let S=qe__namespace.join(y,w),E=Ne__namespace.statSync(S);if(E.isDirectory())try{let A=Ne__namespace.readdirSync(S);for(let D of A)if(D.endsWith(".md")){let q=qe__namespace.join(S,D),O=D.replace(/\.md$/,"");try{let R=Ne__namespace.readFileSync(q,"utf-8");v.push({id:`${w}/${O}`,namespace:w,name:O,path:q,content:R});}catch{}}}catch{}else if(E.isFile()&&w.endsWith(".md")){let A=w.replace(/\.md$/,"");try{let D=Ne__namespace.readFileSync(S,"utf-8");v.push({id:A,namespace:"",name:A,path:S,content:D});}catch{}}}}catch{}return v}e.get("/api/executors/:type/commands",async y=>{let{type:v}=y.params,{workspace_path:b}=y.query,S=l(b,v);return S?{commands:u(S)}:{commands:[]}}),e.get("/api/executors/:type/commands/:command_id",async(y,v)=>{let{type:b,command_id:w}=y.params,{workspace_path:S}=y.query,A=l(S,b);if(!A)return v.code(404),{error:"Commands path not found"};let D=w.split("/"),q,O="",R=w;if(D.length===2?(O=D[0],R=D[1],q=qe__namespace.join(A,O,`${R}.md`)):q=qe__namespace.join(A,`${w}.md`),!Ne__namespace.existsSync(q))return v.code(404),{error:"Command file not found"};try{let C=Ne__namespace.readFileSync(q,"utf-8");return {command:{id:w,namespace:O,name:R,path:q,content:C}}}catch(C){return v.code(500),{error:C instanceof Error?C.message:"Failed to read command"}}});function d(y,v){let b=y||nn__namespace.homedir();switch(v){case "CLAUDE_CODE":return qe__namespace.join(b,".claude","prompts");case "CURSOR_AGENT":return qe__namespace.join(b,".cursor","prompts");default:return qe__namespace.join(b,".viben","prompts")}}function h(y,v){let b=qe__namespace.basename(y,".md"),w=b,S="",E=v,A=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(A){let D=A[1];E=A[2].trim();let q=D.match(/^name:\s*(.+)$/m);q&&(w=q[1].trim());let O=D.match(/^description:\s*(.+)$/m);O&&(S=O[1].trim());}return {id:b,name:w,description:S,path:y,content:E}}function _(y){let v=[];if(!Ne__namespace.existsSync(y))return v;try{let b=Ne__namespace.readdirSync(y);for(let w of b){let S=qe__namespace.join(y,w);if(Ne__namespace.statSync(S).isFile()&&w.endsWith(".md"))try{let A=Ne__namespace.readFileSync(S,"utf-8");v.push(h(S,A));}catch{}}}catch{}return v}e.get("/api/executors/:type/prompts",async y=>{let{type:v}=y.params,{workspace_path:b}=y.query,S=d(b,v);return S?{prompts:_(S)}:{prompts:[]}}),e.get("/api/executors/:type/prompts/:prompt_id",async(y,v)=>{let{type:b,prompt_id:w}=y.params,{workspace_path:S}=y.query,A=d(S,b);if(!A)return v.code(404),{error:"Prompts path not found"};let D=qe__namespace.join(A,`${w}.md`);if(!Ne__namespace.existsSync(D))return v.code(404),{error:"Prompt file not found"};try{let q=Ne__namespace.readFileSync(D,"utf-8");return {prompt:h(D,q)}}catch(q){return v.code(500),{error:q instanceof Error?q.message:"Failed to read prompt"}}}),e.post("/api/executors/openclaw/test-connection",{schema:{description:"Test connection to an OpenClaw gateway with device auth handshake",tags:["executors"],body:{type:"object",required:["host","port"],properties:{host:{type:"string"},port:{type:"number"},token:{type:"string"},password:{type:"string"}}},response:{200:{type:"object",properties:{status:{type:"string",enum:["connected","pairing_required","failed"]},message:{type:"string"},device_id:{type:"string"}}}}}},async y=>{let{host:v,port:b,token:w,password:S}=y.body;try{let{loadGatewayConfig:E}=await Promise.resolve().then(()=>(Z0(),SL)),{loadOrCreateDeviceIdentity:A,publicKeyToBase64Url:D}=await Promise.resolve().then(()=>(ffe(),nfe)),q=E({host:v,port:b,token:w,password:S}),O=A(),R=D(O.publicKeyPem),C=(await import('ws')).default,N=`ws://${q.host}:${q.port}`;return await new Promise(L=>{let F=setTimeout(()=>{M.close(),L({status:"failed",message:`Connection timeout (5s) to ${v}:${b}`});},5e3),M=new C(N);M.on("open",()=>{let ue={type:"req",id:"test-"+Date.now(),method:"connect",params:{protocolVersion:3,clientId:"viben-desktop-test",clientMode:"operator",role:"operator",scopes:["operator.admin"],device:{id:O.deviceId,publicKey:R}}};M.send(JSON.stringify(ue));}),M.on("message",ue=>{try{let ge=JSON.parse(ue.toString());ge.type==="res"?(clearTimeout(F),M.close(1e3),ge.ok?L({status:"connected",device_id:O.deviceId}):ge.error?.code==="PAIRING_REQUIRED"?L({status:"pairing_required",device_id:O.deviceId,message:ge.error.message}):L({status:"failed",message:ge.error?.message||"Auth rejected"})):ge.type==="event"&&ge.event;}catch{}}),M.on("error",ue=>{clearTimeout(F),L({status:"failed",message:`Connection error: ${ue.message}`});}),M.on("close",(ue,ge)=>{clearTimeout(F),ue!==1e3&&L({status:"failed",message:`Connection closed: ${ge||`code ${ue}`}`});});})}catch(E){return {status:"failed",message:E instanceof Error?E.message:"Test failed"}}}),e.get("/api/executors/openclaw/runtime-config",{schema:{description:"Get the effective OpenClaw gateway config from the server side",tags:["executors"],response:{200:{type:"object",properties:{host:{type:"string"},port:{type:"number"},has_auth:{type:"boolean"},cli_path:{type:"string"},config_source:{type:"string"}}}}}},async()=>{try{let{loadGatewayConfig:y}=await Promise.resolve().then(()=>(Z0(),SL)),v=y();return {host:v.host,port:v.port,has_auth:v.auth?.mode!=="none"&&!!v.auth?.mode,cli_path:v.cliPath||void 0,config_source:"~/.openclaw/openclaw.json"}}catch{return {host:"127.0.0.1",port:18789,has_auth:false,config_source:"defaults"}}});}var vwe,kM=$({"src/gateway/routes/executors.ts"(){vwe={CLAUDE_CODE:{name:"Claude Code",description:"Anthropic's coding assistant powered by Claude",docsUrl:"https://claude.ai"},CODEX:{name:"Codex",description:"OpenAI's code-specialized model",docsUrl:"https://openai.com"},CURSOR_AGENT:{name:"Cursor Agent",description:"Cursor's AI coding assistant",docsUrl:"https://cursor.so"},GEMINI:{name:"Gemini",description:"Google's AI coding assistant",docsUrl:"https://gemini.google.com"},AMP:{name:"Amp",description:"AI-powered code assistant"},OPENCODE:{name:"Opencode",description:"Open source coding assistant"},QWEN_CODE:{name:"Qwen Code",description:"Alibaba's Qwen coding model",docsUrl:"https://qwen.aliyun.com"},COPILOT:{name:"GitHub Copilot",description:"GitHub's AI pair programmer",docsUrl:"https://github.com/features/copilot"},DROID:{name:"Droid",description:"Droid AI coding assistant"},OPENCLAW:{name:"OpenClaw",description:"Personal AI assistant gateway with multi-agent routing",docsUrl:"https://openclaw.dev"},CURSOR:{name:"Cursor",description:"AI-first code editor",docsUrl:"https://cursor.so"},IFLOW:{name:"iFlow CLI",description:"iFlow coding assistant"},KILO:{name:"Kilo CLI",description:"Kilo coding assistant"},KIRO:{name:"Kiro Code",description:"Kiro coding assistant"},ANTIGRAVITY:{name:"Antigravity",description:"Antigravity AI workflows"},WINDSURF:{name:"Windsurf",description:"Codeium IDE",docsUrl:"https://codeium.com"},AIDER:{name:"Aider",description:"AI pair programming",docsUrl:"https://aider.chat"},CONTINUE:{name:"Continue",description:"IDE plugin for AI coding",docsUrl:"https://continue.dev"}};}});async function Xy(e,t){if(t){let s=qe.join(t,".viben","agents"),i=await rt.getAgentFromDir(s,e);if(i?.path)return i.path}let r=await rt.getAgent(e);if(r?.path)return r.path}function Aut(e){try{return child_process.execFileSync("which",[e],{stdio:"ignore"}),!0}catch{return false}}function B4(e){return {id:e.id,agent_id:e.agentId,agent_dir:e.agentDir,agent_config:e.agent_config,task_id:e.taskId,prompt:e.prompt,status:e.status,workspace_path:e.workspace_path,created_at:e.created_at,updated_at:e.updated_at,metadata:e.metadata}}function Voe(e){return {timestamp:e.timestamp,role:e.role,content:e.content,tool_calls:e.toolCalls,tool_result:e.toolResult}}function Cut(e){return {id:e.id,timestamp:e.timestamp,type:e.type,content:e.content,tool_use_id:e.toolUseId,tool_name:e.toolName,tool_input:e.toolInput,tool_output:e.toolOutput,is_error:e.isError,attachments:e.attachments,sdk_session_id:e.sdkSessionId}}function Out(e,t){e.get("/api/agent",{schema:{description:"List all agents",tags:["agents"],querystring:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path to include workspace agents"},include_global:{type:"string",description:"Include global agents (default: true)"}}},response:{200:{type:"object",properties:{agents:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},agent_type:{type:"string"},source:{type:"string",enum:["global","workspace"]},agent_dir:{type:"string"},workspace_path:{type:"string"},config_path:{type:"string"},description:{type:"string"},model:{type:"string"},provider_id:{type:"string"},executor_type:{type:"string"}}}},total:{type:"number"}}}}}},async r=>{let{workspace_path:s,include_global:i}=r.query,n=i!=="false",a=nn.homedir(),c=(u,d,h)=>{if(!u)return null;let _=d||(u.path&&u.path.startsWith(a)&&u.path.includes("/.viben/agents/")?"global":"workspace");return {id:u.id,name:u.name,agent_type:"viben",source:_,agent_dir:u.path,workspace_path:_==="workspace"?h:void 0,config_path:u.path?`${u.path}/AGENTS.md`:void 0,description:u.description,model:u.model,provider_id:u.provider_id,system_prompt:u.systemPrompt,append_prompt:u.appendPrompt,temperature:u.temperature,max_tokens:u.maxTokens,executor_type:u.executorType,executor_config:u.executorConfig,mcp_servers:u.mcpServers,skills:u.skills,permission_mode:u.permissionMode,created_at:u.created_at,updated_at:u.updated_at}},o=new Map;if(n){let u=await rt.listAgents();for(let d of u){let h=c(d,"global");h&&o.set(d.id,h);}}if(s){let u=qe.join(s,".viben","agents"),d=await rt.listAgentsFromDir(u);for(let h of d){let _=c(h,"workspace",s);_&&o.set(h.id,_);}}let l=Array.from(o.values()).filter(Boolean);return {agents:l,total:l.length}}),e.post("/api/agent",async(r,s)=>{let i=r.body;try{let n=await rt.createAgent({id:i.id,name:i.name,description:i.description,model:i.model,provider_id:i.provider_id,system_prompt:i.system_prompt,append_prompt:i.append_prompt,temperature:i.temperature,max_tokens:i.max_tokens,from_template:i.from_template,base_path:i.base_path,executor_type:i.executor_type,executor_config:i.executor_config,mcp_servers:i.mcp_servers,skills:i.skills,permission_mode:i.permission_mode});s.code(201);let a=nn.homedir(),c=n.path&&n.path.startsWith(a)&&n.path.includes("/.viben/agents/"),o=c?"global":"workspace",l=!c&&n.path?n.path.replace(/\/.viben\/agents\/[^/]+$/,""):void 0;return {id:n.id,name:n.name,agent_type:"viben",source:o,agent_dir:n.path,workspace_path:l,config_path:n.path?`${n.path}/AGENTS.md`:void 0,description:n.description,model:n.model,provider_id:n.provider_id,system_prompt:n.systemPrompt,append_prompt:n.appendPrompt,temperature:n.temperature,max_tokens:n.maxTokens,executor_type:n.executorType,executor_config:n.executorConfig,mcp_servers:n.mcpServers,skills:n.skills,permission_mode:n.permissionMode,created_at:n.created_at,updated_at:n.updated_at}}catch(n){return s.code(400),{error:n instanceof Error?n.message:"Failed to create agent"}}}),e.get("/api/agent/default",async()=>({default_agent_id:await rt.getDefault()||null})),e.put("/api/agent/default",async(r,s)=>{let{agent_id:i}=r.body;try{return await rt.setDefault(i),{success:!0,default_agent_id:i}}catch(n){return s.code(400),{error:n instanceof Error?n.message:"Failed to set default agent"}}}),e.get("/api/agent/templates",async r=>{let{workspace_path:s}=r.query,i=await rt.listTemplates(s);return {templates:i.map(n=>({id:n.id,name:n.name,description:n.description||n.templateDescription,is_template:n.isTemplate,template_description:n.templateDescription,model:n.model,provider_id:n.provider_id,executor_type:n.executorType,created_at:n.created_at,updated_at:n.updated_at})),total:i.length}}),e.post("/api/agent/templates",async(r,s)=>{let{agent_id:i,is_template:n,template_description:a,workspace_path:c}=r.body;try{let o=await rt.setAsTemplate(i,n,a,c);return s.code(200),{id:o.id,name:o.name,description:o.description,is_template:o.isTemplate,template_description:o.templateDescription,created_at:o.created_at,updated_at:o.updated_at}}catch(o){return s.code(400),{error:o instanceof Error?o.message:"Failed to update template status"}}}),e.get("/api/agent/templates/:id",async(r,s)=>{let{id:i}=r.params,{workspace_path:n}=r.query,a=await rt.getTemplate(i,n);return a?{id:a.id,name:a.name,description:a.description,is_template:a.isTemplate,template_description:a.templateDescription,model:a.model,provider_id:a.provider_id,executor_type:a.executorType,system_prompt:a.systemPrompt,created_at:a.created_at,updated_at:a.updated_at}:(s.code(404),{error:`Template not found: ${i}`})}),e.post("/api/agent/templates/:id/instantiate",async(r,s)=>{let{id:i}=r.params,{agent_id:n,name:a,base_path:c,template_workspace_path:o}=r.body;try{let l=await rt.createFromTemplate(i,n,{name:a,base_path:c},o);s.code(201);let u=nn.homedir(),d=l.path&&l.path.startsWith(u)&&l.path.includes("/.viben/agents/"),h=d?"global":"workspace",_=!d&&l.path?l.path.replace(/\/.viben\/agents\/[^/]+$/,""):void 0;return {id:l.id,name:l.name,agent_type:"viben",source:h,agent_dir:l.path,workspace_path:_,config_path:l.path?`${l.path}/AGENTS.md`:void 0,description:l.description,model:l.model,provider_id:l.provider_id,system_prompt:l.systemPrompt,append_prompt:l.appendPrompt,temperature:l.temperature,max_tokens:l.maxTokens,executor_type:l.executorType,executor_config:l.executorConfig,mcp_servers:l.mcpServers,skills:l.skills,permission_mode:l.permissionMode,created_at:l.created_at,updated_at:l.updated_at}}catch(l){return s.code(400),{error:l instanceof Error?l.message:"Failed to instantiate template"}}}),e.post("/api/agent/:id/promote",async(r,s)=>{let{id:i}=r.params,{new_id:n,workspace_path:a}=r.body;if(!a)return s.code(400),{error:"workspace_path is required"};try{let c=await rt.promoteToGlobal(a,i,n);return s.code(201),{id:c.id,name:c.name,agent_type:"viben",source:"global",agent_dir:c.path,workspace_path:void 0,config_path:c.path?`${c.path}/AGENTS.md`:void 0,description:c.description,model:c.model,provider_id:c.provider_id,system_prompt:c.systemPrompt,append_prompt:c.appendPrompt,temperature:c.temperature,max_tokens:c.maxTokens,executor_type:c.executorType,executor_config:c.executorConfig,mcp_servers:c.mcpServers,skills:c.skills,permission_mode:c.permissionMode,is_template:c.isTemplate,template_description:c.templateDescription,created_at:c.created_at,updated_at:c.updated_at}}catch(c){return s.code(400),{error:c instanceof Error?c.message:"Failed to promote template"}}}),e.get("/api/agent/:id/sessions",async(r,s)=>{let{id:i}=r.params,{workspace_path:n}=r.query;try{let a=[],c=new Set;if(n){let l=qe.join(n,".viben","agents"),u=await rt.getAgentFromDir(l,i);if(u?.path){let d=await t.sessionStore.listSessions(i,u.path);for(let h of d)c.has(h.id)||(c.add(h.id),a.push(h));}}let o=await rt.getAgent(i);if(o?.path){let l=await t.sessionStore.listSessions(i,o.path);for(let u of l)c.has(u.id)||(c.add(u.id),a.push(u));}return a.sort((l,u)=>new Date(u.created_at).getTime()-new Date(l.created_at).getTime()),{sessions:a.map(B4),total:a.length}}catch(a){return s.code(500),{error:a instanceof Error?a.message:"Failed to list sessions"}}}),e.post("/api/agent/:id/sessions",async(r,s)=>{let{id:i}=r.params,n=r.body,a=n.session_id||nk.randomUUID();try{let c=n.agent_dir||await Xy(i,n.workspace_path),o=mpe(a,i,c,n.agent_config,n.workspace_path);return o.prompt=n.prompt,o.taskId=n.task_id,await t.sessionStore.createSession(o),s.code(201),B4(o)}catch(c){return s.code(500),{error:c instanceof Error?c.message:"Failed to create session"}}}),e.get("/api/agent/:id/sessions/:session_id",async(r,s)=>{let{id:i,session_id:n}=r.params,{workspace_path:a}=r.query;try{let c=await Xy(i,a),o=await t.sessionStore.getSession(i,n,c);return B4(o)}catch(c){return s.code(404),{error:c instanceof Error?c.message:"Session not found"}}}),e.delete("/api/agent/:id/sessions/:session_id",async(r,s)=>{let{id:i,session_id:n}=r.params,{workspace_path:a}=r.query;try{let c=await Xy(i,a);return await t.sessionStore.deleteSession(i,n,c),{deleted:n,agent_id:i}}catch(c){return s.code(500),{error:c instanceof Error?c.message:"Failed to delete session"}}}),e.get("/api/agent/:id/sessions/:session_id/messages",async(r,s)=>{let{id:i,session_id:n}=r.params,{workspace_path:a}=r.query;try{let c=await Xy(i,a),o=await t.sessionStore.readMessages(i,n,c);return {messages:o.map(Voe),total:o.length}}catch(c){return s.code(500),{error:c instanceof Error?c.message:"Failed to read messages"}}}),e.post("/api/agent/:id/sessions/:session_id/messages",async(r,s)=>{let{id:i,session_id:n}=r.params,{workspace_path:a}=r.query,c=r.body;try{let o=await Xy(i,a),l={timestamp:new Date().toISOString(),role:c.role,content:c.content,toolCalls:c.tool_calls,toolResult:c.tool_result};return await t.sessionStore.appendMessage(i,n,l,o),s.code(201),Voe(l)}catch(o){return s.code(500),{error:o instanceof Error?o.message:"Failed to append message"}}}),e.get("/api/agent/:id/sessions/:session_id/ui-messages",async(r,s)=>{let{id:i,session_id:n}=r.params,{workspace_path:a}=r.query;try{let c=await Xy(i,a),o=await t.sessionStore.readUIMessages(i,n,c);if(o.length>0)return {messages:o.map(Cut),total:o.length};if(a)try{let l=Az(),u=Pz(a),d=qe.join(l,u,`${n}.jsonl`);if(Ne.existsSync(d)){let h=await ywe(d);if(h.length>0)return {messages:h,total:h.length}}}catch{}return {messages:[],total:0}}catch(c){return s.code(500),{error:c instanceof Error?c.message:"Failed to read UI messages"}}}),e.get("/api/agent/:id/availability",async(r,s)=>{let{id:i}=r.params,n=nn.homedir(),a=["CLAUDE_CODE","CODEX","AMP","GEMINI","OPENCODE","CURSOR_AGENT","QWEN_CODE","COPILOT","DROID","OPENCLAW","WINDSURF","GOOSE","ROOCODE","AIDE","AUGMENT","CLINE","CONTINUE","TRAE","MELTY","ZENCODER","MARSCODE","VOID","AIDER","PLANDEX","MENTAT","GPT_ENGINEER","AGENT_CODE","SWEEP","MICRO_AGENT","AUTODEBUG","DEVON","SWEBENCH","GPTPILOT","DEVIN","MAGIC","PYTHAGORA","FINE","AI2WARE","SOURCEGRAPH_CODY"],c=i.toUpperCase().replace(/-/g,"_");if(a.includes(c)){let l={type:"NOT_FOUND"};switch(c){case "CLAUDE_CODE":{let u=qe.join(n,".claude"),d=qe.join(u,"config.json");if(Ne.existsSync(d))try{let h=Ne.statSync(d);l={type:"LOGIN_DETECTED",last_auth_timestamp:Math.floor(h.mtimeMs)};}catch{l={type:"INSTALLATION_FOUND"};}else Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "CODEX":{let u=qe.join(n,".codex");Aut("codex")?l={type:"INSTALLATION_FOUND"}:Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "CURSOR_AGENT":{let u=[qe.join(n,".cursor"),qe.join(n,"Library/Application Support/Cursor")];for(let d of u)if(Ne.existsSync(d)){l={type:"INSTALLATION_FOUND"};break}break}case "AMP":{let u=qe.join(n,".amp");Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "GEMINI":{let u=qe.join(n,".gemini");Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "OPENCLAW":{let u=qe.join(n,".openclaw"),d=qe.join(u,"openclaw.json");if(Ne.existsSync(d))try{let h=Ne.statSync(d);l={type:"LOGIN_DETECTED",last_auth_timestamp:Math.floor(h.mtimeMs)};}catch{l={type:"INSTALLATION_FOUND"};}else Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "WINDSURF":{let u=qe.join(n,".windsurf");Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "GOOSE":{let u=qe.join(n,".goose");Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "AIDER":{let u=qe.join(n,".aider");Ne.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}}return l}let o=await rt.getAgent(i);return o?{type:"VIBEN_AGENT",available:true,agent_id:o.id,name:o.name}:(s.code(404),{error:`Agent or executor not found: ${i}`})}),e.get("/api/agent/:id",async(r,s)=>{let{id:i}=r.params,{workspace_path:n}=r.query,a=nn.homedir(),c=null,o="global";if(n){let u=qe.join(n,".viben","agents");c=await rt.getAgentFromDir(u,i),c&&(o="workspace");}if(c||(c=await rt.getAgent(i),c&&(o=c.path&&c.path.startsWith(a)&&c.path.includes("/.viben/agents/")?"global":"workspace")),!c)return s.code(404),{error:`Agent not found: ${i}`};let l=o==="workspace"&&c.path?c.path.replace(/\/.viben\/agents\/[^/]+$/,""):void 0;return {id:c.id,name:c.name,agent_type:"viben",source:o,agent_dir:c.path,workspace_path:l,config_path:c.path?`${c.path}/AGENTS.md`:void 0,description:c.description,model:c.model,provider_id:c.provider_id,system_prompt:c.systemPrompt,append_prompt:c.appendPrompt,temperature:c.temperature,max_tokens:c.maxTokens,executor_type:c.executorType,executor_config:c.executorConfig,mcp_servers:c.mcpServers,skills:c.skills,permission_mode:c.permissionMode,created_at:c.created_at,updated_at:c.updated_at}}),e.patch("/api/agent/:id",async(r,s)=>{let{id:i}=r.params,{workspace_path:n}=r.query,a=r.body,c={name:a.name,description:a.description,model:a.model,provider_id:a.provider_id,systemPrompt:a.system_prompt,appendPrompt:a.append_prompt,temperature:a.temperature,maxTokens:a.max_tokens,executorType:a.executor_type,executorConfig:a.executor_config,mcpServers:a.mcp_servers,skills:a.skills,permissionMode:a.permission_mode,isTemplate:a.is_template,templateDescription:a.template_description};try{let o=await rt.updateAgent(i,c,n),l=nn.homedir(),u=o.path&&o.path.startsWith(l)&&o.path.includes("/.viben/agents/"),d=u?"global":"workspace",h=!u&&o.path?o.path.replace(/\/.viben\/agents\/[^/]+$/,""):void 0;return {id:o.id,name:o.name,agent_type:"viben",source:d,agent_dir:o.path,workspace_path:h,config_path:o.path?`${o.path}/AGENTS.md`:void 0,description:o.description,model:o.model,provider_id:o.provider_id,system_prompt:o.systemPrompt,append_prompt:o.appendPrompt,temperature:o.temperature,max_tokens:o.maxTokens,executor_type:o.executorType,executor_config:o.executorConfig,mcp_servers:o.mcpServers,skills:o.skills,permission_mode:o.permissionMode,is_template:o.isTemplate,template_description:o.templateDescription,created_at:o.created_at,updated_at:o.updated_at}}catch(o){return s.code(400),{error:o instanceof Error?o.message:"Failed to update agent"}}}),e.delete("/api/agent/:id",async(r,s)=>{let{id:i}=r.params,{workspace_path:n}=r.query;try{return await rt.removeAgent(i,n),{success:!0,deleted:i}}catch(a){return s.code(400),{error:a instanceof Error?a.message:"Failed to delete agent"}}});}var Koe=$({"src/gateway/routes/agents.ts"(){th(),eh(),kM();}});function Joe(e){return {id:e.id,title:e.title||e.prompt?.slice(0,50)||"Untitled",description:e.description||e.prompt,status:e.status,agentId:e.agent,created_at:e.created_at,updated_at:e.updated_at||e.created_at}}function Dut(e){return e.subtask_details&&e.subtask_details.length>0?e.subtask_details:e.subtasks&&e.subtasks.length>0?e.subtasks.map((t,r)=>({id:`subtask_${r}`,name:t,status:"pending"})):null}function Gm(e){return {id:e.id,name:e.name,title:e.title||e.prompt?.slice(0,100)||"Untitled",description:e.description||e.prompt||null,status:e.status,review_reason:e.review_reason??null,current_phase:e.current_phase??0,next_action:e.next_action??null,priority:e.priority||rA,workspace_path:e.workspace_path??null,creator:e.creator??null,assignee:e.assignee??null,branch:e.branch??null,base_branch:e.base_branch??null,worktree_path:e.worktree_path??null,commit:e.commit??null,pr_url:e.pr_url??null,agent_id:e.agent??null,session_id:e.session_id??null,task_index:e.task_index??0,prompt:e.prompt??null,cost:e.cost??null,duration:e.duration??null,favorite:e.favorite??false,executor:e.executor||"Agent",subtasks_detail:Dut(e),execution_progress:e.execution_progress??null,created_at:e.created_at,updated_at:e.updated_at??e.created_at,completed_at:e.completed_at??null,is_template:e.is_template??false}}function v0(e){let t=Np.get(e);if(!t)return null;let r=Date.now();return r-t.created_at>bwe?(Np.delete(e),null):(t.last_accessed=r,t)}function Hm(e,t,r){let s=Date.now();if(Np.size>=wwe){let i=null,n=1/0;for(let[a,c]of Np)c.last_accessed<n&&(n=c.last_accessed,i=a);i&&Np.delete(i);}Np.set(e,{workspace_path:t,task_dir:r,last_accessed:s,created_at:s});}function A2(e){Np.delete(e);}function $ut(e,t){e.get("/api/tasks",{schema:{description:"List all tasks for a workspace (workspace_path required)",tags:["tasks"],querystring:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},is_template:{type:"string",description:"Filter by template status (true/false)"}},required:["workspace_path"]},response:{200:{type:"object",properties:{tasks:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string",nullable:true},title:{type:"string"},description:{type:"string",nullable:true},status:{type:"string",enum:["backlog","queue","in_progress","paused","review","completed","failed","cancelled","archived"]},review_reason:{type:"string",nullable:true},current_phase:{type:"number",nullable:true},next_action:{type:"array",nullable:true,items:{type:"object",properties:{phase:{type:"number"},action:{type:"string"}}}},priority:{type:"string",enum:["urgent","high","medium","low","none"]},workspace_path:{type:"string",nullable:true},creator:{type:"string",nullable:true},assignee:{type:"string",nullable:true},branch:{type:"string",nullable:true},base_branch:{type:"string",nullable:true},worktree_path:{type:"string",nullable:true},commit:{type:"string",nullable:true},pr_url:{type:"string",nullable:true},agent_id:{type:"string",nullable:true},session_id:{type:"string",nullable:true},task_index:{type:"number"},prompt:{type:"string",nullable:true},cost:{type:"number",nullable:true},duration:{type:"number",nullable:true},favorite:{type:"boolean"},executor:{type:"string"},subtasks_detail:{type:"array",nullable:true,items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},status:{type:"string"}}}},execution_progress:{type:"object",nullable:true},created_at:{type:"string"},updated_at:{type:"string"},completed_at:{type:"string",nullable:true},is_template:{type:"boolean"}}}}}},400:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,is_template:a}=s.query;if(!n)return i.code(400),{error:"workspace_path is required"};let c=await $e.listTasks(n);if(a!==void 0){let o=a==="true";c=c.filter(l=>(l.is_template??false)===o);}for(let o of c){let l=await $e.findTaskById(n,o.id);l&&Hm(o.id,n,l);}return {tasks:c.map(Gm)}}),e.get("/api/tasks/:id",{schema:{description:"Get a specific task by ID",tags:["tasks"],params:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},querystring:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path"}}},response:{200:{type:"object",properties:{id:{type:"string"},name:{type:"string"},title:{type:"string"},description:{type:"string"},status:{type:"string"},workspace_path:{type:"string"},agent_id:{type:"string"},session_id:{type:"string"},task_index:{type:"number"},prompt:{type:"string"},cost:{type:"number"},duration:{type:"number"},favorite:{type:"boolean"},executor:{type:"string"},created_at:{type:"string"},updated_at:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let {id:n}=s.params,{workspace_path:a}=s.query,c=null,l=v0(n);if(l?(c=l.task_dir,l.workspace_path):a&&(c=await $e.findTaskById(a,n),c&&Hm(n,a,c)),!c)return i.code(404),{error:`Task not found: ${n}. Provide workspace_path parameter.`};let u=await $e.getTask(c);return u?Gm(u):(i.code(404),{error:`Task not found: ${n}`})}),e.post("/api/tasks",async(s,i)=>{let n=s.body,a=n.workspace_path;if(!a)return i.code(400),{error:"workspace_path is required to create a task"};let c=null;if(n.copy_from){let u=n.copy_from.includes("/")?n.copy_from:await $e.findTaskById(a,n.copy_from);if(u&&(c=await $e.getTask(u)),!c)return i.code(400),{error:`Source task not found: ${n.copy_from}`}}let o="backlog";n.status&&(o=$e.normalizeStatus(n.status));let l={title:n.title||c?.title||n.prompt?.slice(0,100)||"Untitled",description:n.description??c?.description,prompt:n.prompt??c?.prompt??n.description,status:o,priority:n.priority??c?.priority??rA,creator:n.creator??c?.creator,assignee:n.assignee??c?.assignee,agent:n.agent_id||c?.agent,session_id:n.session_id,task_index:n.task_index||0,branch:n.branch??c?.branch,base_branch:n.base_branch??c?.base_branch,executor:n.executor??c?.executor??"Agent",model:n.model_id??c?.model,workspace_path:a,is_template:n.is_template??false};try{let{taskDir:u,task:d}=await $e.createTask(a,l);return Hm(d.id,a,u),t.events.taskCreated(Joe(d)),i.code(201),Gm(d)}catch(u){return i.code(400),{error:u instanceof Error?u.message:"Failed to create task"}}});let r=async(s,i)=>{let{id:n}=s.params,a=s.body,{workspace_path:c}=s.query;try{let o=null,l=c,u=v0(n);if(u?(o=u.task_dir,l=u.workspace_path):c&&(o=await $e.findTaskById(c,n),o&&Hm(n,c,o)),!o)return i.code(404),{error:`Task not found: ${n}. Provide workspace_path parameter.`};let d=await $e.getTask(o);if(!d)return i.code(404),{error:`Task not found: ${n}`};let h={};a.title!==void 0&&(h.title=a.title),a.description!==void 0&&(h.description=a.description),a.prompt!==void 0&&(h.prompt=a.prompt),a.status!==void 0&&(h.status=$e.normalizeStatus(a.status)),a.priority!==void 0&&(h.priority=a.priority),a.assignee!==void 0&&(h.assignee=a.assignee),a.cost!==void 0&&(h.cost=a.cost),a.duration!==void 0&&(h.duration=a.duration),a.favorite!==void 0&&(h.favorite=a.favorite),a.is_template!==void 0&&(h.is_template=a.is_template),a.session_id!==void 0&&(h.session_id=a.session_id),a.agent_id!==void 0&&(h.agent=a.agent_id),a.workspace_path!==void 0&&(h.workspace_path=a.workspace_path),a.executor!==void 0&&(h.executor=a.executor),a.branch!==void 0&&(h.branch=a.branch),a.base_branch!==void 0&&(h.base_branch=a.base_branch),a.commit!==void 0&&(h.commit=a.commit),a.pr_url!==void 0&&(h.pr_url=a.pr_url);let _=await $e.updateTask(o,h);return t.events.taskUpdated(Joe(_)),a.status&&d.status!==_.status&&t.events.taskStatusChanged(n,d.status,_.status),Gm(_)}catch(o){return i.code(400),{error:o instanceof Error?o.message:"Failed to update task"}}};e.patch("/api/tasks/:id",r),e.put("/api/tasks/:id",r),e.delete("/api/tasks/:id",async(s,i)=>{let{id:n}=s.params,{workspace_path:a}=s.query;try{let c=null,o=v0(n);return o?c=o.task_dir:a&&(c=await $e.findTaskById(a,n)),c?await $e.deleteTask(c)?(A2(n),t.events.taskDeleted(n),{deleted:n}):(i.code(404),{error:`Task not found: ${n}`}):(i.code(404),{error:`Task not found: ${n}. Provide workspace_path parameter.`})}catch(c){return i.code(400),{error:c instanceof Error?c.message:"Failed to delete task"}}}),e.get("/api/agent/:agentId/tasks",async(s,i)=>{let{agentId:n}=s.params,{workspace_path:a}=s.query;return a?{tasks:(await $e.listTasks(a)).filter(l=>l.agent===n).map(Gm)}:(i.code(400),{error:"workspace_path is required"})}),e.get("/api/agent/:agentId/sessions/:sessionId/tasks",async(s,i)=>{let{sessionId:n}=s.params,{workspace_path:a}=s.query;if(!a)return i.code(400),{error:"workspace_path is required"};try{let o=(await $e.listTasks(a)).filter(l=>l.session_id===n);return o.sort((l,u)=>(l.task_index??0)-(u.task_index??0)),{tasks:o.map(Gm)}}catch(c){return i.code(500),{error:c instanceof Error?c.message:"Failed to list tasks"}}}),e.get("/api/agent/:agentId/sessions/:sessionId/tasks/:taskId/messages",async(s,i)=>{let{agentId:n,sessionId:a,taskId:c}=s.params;try{return {messages:await Ts.readUIMessagesByTask(n,a,c)}}catch(o){return i.code(500),{error:o instanceof Error?o.message:"Failed to get messages"}}}),e.get("/api/tasks/:id/specs",{schema:{description:"Get task specs data (PRD, subtasks, logs, files)",tags:["tasks"],params:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},querystring:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path"}}},response:{200:{type:"object",properties:{prd_content:{type:"string",nullable:true},prd_path:{type:"string",nullable:true},subtasks:{type:"array",items:{type:"object",properties:{id:{type:"string"},title:{type:"string"},description:{type:"string"},status:{type:"string",enum:["pending","in_progress","completed","failed"]},files:{type:"array",items:{type:"string"}},order:{type:"number"}}}},logs:{type:"object",nullable:true,properties:{phases:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},status:{type:"string",enum:["pending","running","complete","failed"]},entries:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},message:{type:"string"},timestamp:{type:"string"}}}}}}}}},task_dir:{type:"string",description:"Task directory path for file browsing"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{id:n}=s.params,{workspace_path:a}=s.query;Sp.info({taskId:n,workspacePath:a},"Getting specs for task");let c=null,l=v0(n);if(l?(Sp.debug({taskDir:l.task_dir},"Found in cache"),c=l.task_dir,l.workspace_path):a&&(Sp.debug("Searching for task by ID..."),c=await $e.findTaskById(a,n),Sp.debug({taskDir:c},"findTaskById result"),c&&Hm(n,a,c)),!c)return Sp.warn({taskId:n},"Task not found"),i.code(404),{error:`Task not found: ${n}. Provide workspace_path parameter.`};try{let u=await $e.getTaskSpecsData(c);return Sp.debug({taskDir:u.task_dir},"Specs data loaded"),{prd_content:u.prd_content,prd_path:u.prd_path,subtasks:u.subtasks,logs:u.logs,task_dir:u.task_dir}}catch(u){return Sp.error({err:u},"Error getting task specs"),i.code(500),{error:u instanceof Error?u.message:"Failed to get task specs"}}}),e.post("/api/tasks/batch/events",{schema:{description:"Apply an event to multiple tasks (batch operation)",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_dirs:{type:"array",items:{type:"string"},description:"Task directories or IDs to apply event to"},event_type:{type:"string",description:"Event type to apply"},payload:{type:"object",description:"Optional event payload"}},required:["workspace_path","task_dirs","event_type"]},response:{200:{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{task_dir:{type:"string"},success:{type:"boolean"},error:{type:"string"},new_state:{type:"string"}}}},summary:{type:"object",properties:{total:{type:"number"},succeeded:{type:"number"},failed:{type:"number"}}}}},400:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_dirs:a,event_type:c,payload:o}=s.body;if(!n)return i.code(400),{error:"workspace_path is required"};if(!nP(c))return i.code(400),{error:`Invalid event type: ${c}`};if(!a||a.length===0)return i.code(400),{error:"task_dirs must be a non-empty array"};let l=await Promise.all(a.map(async h=>{try{let _=h.includes("/")?h:await $e.findTaskById(n,h);if(!_)return {task_dir:h,success:!1,error:"Task not found"};let y=await $e.getTask(_);if(!y)return {task_dir:h,success:!1,error:"Task not found"};let v=(y.last_event?.sequence??0)+1,b={event_id:nk.randomUUID(),sequence:v,type:c,timestamp:new Date().toISOString(),payload:o},w=await rr.applyEvent(_,b);return w.success?{task_dir:h,success:!0,new_state:w.newState}:{task_dir:h,success:!1,error:w.error}}catch(_){return {task_dir:h,success:false,error:_ instanceof Error?_.message:"Unknown error"}}})),u=l.filter(h=>h.success).length,d=l.filter(h=>!h.success).length;return {results:l,summary:{total:l.length,succeeded:u,failed:d}}}),e.get("/api/tasks/:id/running",{schema:{description:"Check if a task's execution process is currently running",tags:["tasks"],params:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},querystring:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path"}}},response:{200:{type:"object",properties:{success:{type:"boolean"},data:{type:"object",properties:{task_id:{type:"string"},running:{type:"boolean"},status:{type:"string"}}}}},404:{type:"object",properties:{success:{type:"boolean"},error:{type:"string"}}}}}},async(s,i)=>{let {id:n}=s.params,{workspace_path:a}=s.query,c=null,l=v0(n);if(l?(c=l.task_dir,l.workspace_path):a&&(c=await $e.findTaskById(a,n),c&&Hm(n,a,c)),!c)return i.code(404),{success:false,error:`Task not found: ${n}`};let u=await $e.getTask(c);if(!u)return i.code(404),{success:false,error:`Task not found: ${n}`};if(!(u.status==="in_progress"))return {success:true,data:{task_id:n,running:false,status:u.status}};let h=false;return u.session_id&&t.taskQueue&&(h=t.taskQueue.getTasks("running").some(y=>y.payload.session_id===u.session_id)),{success:true,data:{task_id:n,running:h,status:u.status}}});}var Sp,bwe,wwe,Np,EM=$({"src/gateway/routes/tasks.ts"(){Wl(),Ye(),eh(),zf(),Ok(),Sp=je.child({module:"tasks"}),bwe=300*1e3,wwe=1e3,Np=new Map;}});function qut(e,t){e.post("/api/task/set-branch",{schema:{description:"Set Git branch for a task",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"},branch:{type:"string",description:"Branch name to set"}},required:["workspace_path","task_id","branch"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},branch:{type:"string"}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a,branch:c}=s.body;if(!n||!a||!c)return i.code(400),{error:"workspace_path, task_id, and branch are required"};let o=fve(n,a,c);return o.success?{success:true,task_id:o.task,branch:c}:(i.code(o.error?.includes("not found")?404:400),{error:o.error})}),e.post("/api/task/set-base",{schema:{description:"Set PR target branch for a task",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"},base_branch:{type:"string",description:"Base branch name (PR target)"}},required:["workspace_path","task_id","base_branch"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},base_branch:{type:"string"}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a,base_branch:c}=s.body;if(!n||!a||!c)return i.code(400),{error:"workspace_path, task_id, and base_branch are required"};let o=gve(n,a,c);return o.success?{success:true,task_id:o.task,base_branch:c}:(i.code(o.error?.includes("not found")?404:400),{error:o.error})}),e.post("/api/task/set-agent",{schema:{description:"Set associated agent configuration for a task",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"},agent_id:{type:"string",description:"Agent ID to associate"}},required:["workspace_path","task_id","agent_id"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},agent_id:{type:"string"}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a,agent_id:c}=s.body;if(!n||!a||!c)return i.code(400),{error:"workspace_path, task_id, and agent_id are required"};let o=yve(n,a,c);return o.success?{success:true,task_id:o.task,agent_id:c}:(i.code(o.error?.includes("not found")?404:400),{error:o.error})}),e.post("/api/task/init-context",{schema:{description:"Initialize empty context files (implement.jsonl, check.jsonl, fix.jsonl) for a task. Use add-context to add specific files.",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"}},required:["workspace_path","task_id"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},files_created:{type:"array",items:{type:"string"}}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a}=s.body;if(!n||!a)return i.code(400),{error:"workspace_path and task_id are required"};let c=dz(n,a);return c.success?{success:true,task_id:a,files_created:["implement.jsonl","check.jsonl","fix.jsonl"]}:(i.code(404),{error:c.error||`Task not found: ${a}`})}),e.post("/api/task/add-context",{schema:{description:"Add context files to a task",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"},files:{type:"array",items:{type:"object",properties:{path:{type:"string"},reason:{type:"string"}},required:["path"]},description:"Files to add with optional reasons"},context_type:{type:"string",enum:["implement","check","fix"],description:"Context file to add to (default: implement)"}},required:["workspace_path","task_id","files"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},added:{type:"number"},skipped:{type:"number"},total:{type:"number"}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a,files:c,context_type:o="implement"}=s.body;if(!n||!a||!c||c.length===0)return i.code(400),{error:"workspace_path, task_id, and files are required"};let l=0,u=0;for(let d of c){let h=sve(n,a,[d.path],{reason:d.reason||"Added via API",contextType:o});if(!h.success)return i.code(404),{error:h.error||`Task not found: ${a}`};l+=h.added,u+=h.skipped;}return {success:true,task_id:a,added:l,skipped:u,total:c.length}}),e.post("/api/task/remove-context",{schema:{description:"Remove context files from a task",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"},files:{type:"array",items:{type:"string"},description:"File paths to remove"}},required:["workspace_path","task_id","files"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},removed:{type:"number"}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a,files:c}=s.body;if(!n||!a||!c||c.length===0)return i.code(400),{error:"workspace_path, task_id, and files are required"};let o=ive(n,a,c);return o.success?{success:true,task_id:a,removed:o.removed.length}:(i.code(404),{error:o.error||`Task not found: ${a}`})}),e.post("/api/task/list-context",{schema:{description:"List all context entries for a task",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"}},required:["workspace_path","task_id"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},context:{type:"object",properties:{implement:{type:"array",items:{type:"object",properties:{file:{type:"string"},reason:{type:"string"},type:{type:"string"}}}},check:{type:"array",items:{type:"object",properties:{file:{type:"string"},reason:{type:"string"},type:{type:"string"}}}},debug:{type:"array",items:{type:"object",properties:{file:{type:"string"},reason:{type:"string"},type:{type:"string"}}}}}}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a}=s.body;if(!n||!a)return i.code(400),{error:"workspace_path and task_id are required"};let c=nve(n,a);if(!c.success)return i.code(404),{error:c.error||`Task not found: ${a}`};let o={implement:[],check:[],debug:[]};for(let[l,u]of Object.entries(c.context)){let d=l.replace(".jsonl",""),h=d==="fix"?"debug":d;h in o&&(o[h]=u);}return {success:true,task_id:a,context:o}}),e.post("/api/task/validate-context",{schema:{description:"Validate that all context file references exist",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_id:{type:"string",description:"Task ID or directory"}},required:["workspace_path","task_id"]},response:{200:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string"},valid_count:{type:"number"},missing_count:{type:"number"},missing_files:{type:"array",items:{type:"string"}},all_valid:{type:"boolean"}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_id:a}=s.body;if(!n||!a)return i.code(400),{error:"workspace_path and task_id are required"};let c=ove(n,a);return c.error?(i.code(404),{error:c.error}):{success:true,task_id:a,valid_count:c.valid.length,missing_count:c.missing.length,missing_files:c.missing,all_valid:c.missing.length===0}}),e.post("/api/task/execute",{schema:{description:"Trigger task execution via queue system",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_dir:{type:"string",description:"Task directory path or ID (required)"},agent_id:{type:"string",description:"Agent ID to use"},input:{type:"string",description:"User prompt"},cwd:{type:"string",description:"Working directory"},agent_config_path:{type:"string",description:"Path to agent config"},resume_session:{type:"string",description:"Resume from existing session"},max_retries:{type:"number",description:"Maximum retry attempts"},attachments:{type:"array",items:{type:"object",properties:{type:{type:"string"},data:{type:"string"},name:{type:"string"}}}}},required:["workspace_path","task_dir"]},response:{201:{type:"object",properties:{success:{type:"boolean"},task_id:{type:"string",description:"Queue task ID"},position:{type:"number"},status:{type:"string"}}},400:{type:"object",properties:{error:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_dir:a,agent_id:c,input:o,cwd:l,agent_config_path:u,resume_session:d,max_retries:h,attachments:_}=s.body;if(!n)return i.code(400),{error:"workspace_path is required"};let y=a.includes("/")?a:await $e.findTaskById(n,a);if(!y)return i.code(404),{error:`Task not found: ${a}`};let v=await $e.getTask(y);if(!v)return i.code(404),{error:`Task not found: ${a}`};let b=c||v.agent,w=o||v.prompt||v.description||v.title,S=l||n;if(!b)return i.code(400),{error:"agent_id is required (not found in task or request)"};if(!w)return i.code(400),{error:"input is required (not found in task or request)"};try{let E=await t.taskQueue.enqueue({agent_id:b,session_id:v.session_id,input:w,cwd:S,agent_config_path:u,resume_session:d,max_retries:h,attachments:_});return await $e.updateTask(y,{status:"queue",session_id:v.session_id||E.task_id}),i.code(201),{success:!0,task_id:E.task_id,position:E.position,status:E.status}}catch(E){return i.code(400),{error:E instanceof Error?E.message:"Failed to enqueue task"}}}),e.post("/api/task/stop",{schema:{description:"Stop task execution",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_dir:{type:"string",description:"Task directory path or ID (required)"}},required:["workspace_path","task_dir"]},response:{200:{type:"object",properties:{success:{type:"boolean"},cancelled:{type:"boolean"},task_id:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_dir:a}=s.body,c=a.includes("/")?a:await $e.findTaskById(n,a);if(!c)return i.code(404),{error:`Task not found: ${a}`};let o=await $e.getTask(c);if(!o)return i.code(404),{error:`Task not found: ${a}`};let l=false,u=null;if(o.session_id&&t.taskQueue){let d=t.taskQueue.getTasks("running"),h=t.taskQueue.getTasks("pending"),y=[...d,...h].find(v=>v.payload.session_id===o.session_id);y&&(u=y.id,l=await t.taskQueue.cancel(y.id));}return (l||o.status==="in_progress"||o.status==="queue")&&await $e.updateTask(c,{status:"review",review_reason:"stopped"}),{success:true,cancelled:l,task_id:u}}),e.post("/api/task/running",{schema:{description:"Check if task execution is running",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_dir:{type:"string",description:"Task directory path or ID (required)"}},required:["workspace_path","task_dir"]},response:{200:{type:"object",properties:{success:{type:"boolean"},data:{type:"object",properties:{task_id:{type:"string"},running:{type:"boolean"},status:{type:"string"},queue_task_id:{type:"string"},queue_status:{type:"string"}}}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_dir:a}=s.body,c=a.includes("/")?a:await $e.findTaskById(n,a);if(!c)return i.code(404),{error:`Task not found: ${a}`};let o=await $e.getTask(c);if(!o)return i.code(404),{error:`Task not found: ${a}`};let l=null,u=null,d=false;if(o.session_id&&t.taskQueue){let y=t.taskQueue.getTasks().find(v=>v.payload.session_id===o.session_id);y&&(l=y.id,u=y.status,d=y.status==="running");}let h=o.status==="in_progress"||o.status==="queue";return {success:true,data:{task_id:o.id,running:d||h,status:o.status,queue_task_id:l,queue_status:u}}}),e.post("/api/task/queue-status",{schema:{description:"Get queue status",tags:["tasks"],response:{200:{type:"object",properties:{pending_count:{type:"number"},running_count:{type:"number"},max_concurrency:{type:"number"},tasks:{type:"array",items:{type:"object",properties:{id:{type:"string"},status:{type:"string"},agent_id:{type:"string"},created_at:{type:"number"},position:{type:"number"}}}}}}}}},async()=>t.taskQueue.getStatus()),e.post("/api/task/queue-config",{schema:{description:"Get or update queue configuration",tags:["tasks"],body:{type:"object",properties:{max_concurrency:{type:"number"},default_max_retries:{type:"number"}}},response:{200:{type:"object",properties:{max_concurrency:{type:"number"},default_max_retries:{type:"number"},persist_debounce_ms:{type:"number"},shutdown_timeout_ms:{type:"number"}}}}}},async s=>{let i=s.body;return i&&Object.keys(i).length>0?await t.taskQueue.updateConfig(i):t.taskQueue.getConfig()}),e.post("/api/task/batch-enqueue",{schema:{description:"Batch enqueue multiple tasks for execution",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_dirs:{type:"array",items:{type:"string"},description:"Task directories or IDs to enqueue"},agent_id:{type:"string",description:"Agent ID to use for all tasks"}},required:["workspace_path","task_dirs"]},response:{200:{type:"object",properties:{success:{type:"boolean"},queued:{type:"number"},failed:{type:"number"},results:{type:"array",items:{type:"object",properties:{task_dir:{type:"string"},success:{type:"boolean"},error:{type:"string"},queue_task_id:{type:"string"}}}}}}}}},async s=>{let{workspace_path:i,task_dirs:n,agent_id:a}=s.body;if(!n||n.length===0)return {success:false,queued:0,failed:0,results:[]};let c=[],o=0,l=0;for(let u of n)try{let d=u.includes("/")?u:await $e.findTaskById(i,u);if(!d){c.push({task_dir:u,success:!1,error:"Task not found"}),l++;continue}let h=await $e.getTask(d);if(!h){c.push({task_dir:u,success:!1,error:"Task not found"}),l++;continue}let _=a||h.agent;if(!_){c.push({task_dir:u,success:!1,error:"No agent_id specified"}),l++;continue}let y=h.prompt||h.description||h.title;if(!y){c.push({task_dir:u,success:!1,error:"No input/prompt found"}),l++;continue}let v=await t.taskQueue.enqueue({agent_id:_,session_id:h.session_id,input:y,cwd:i});await $e.updateTask(d,{status:"queue"}),c.push({task_dir:u,success:!0,queue_task_id:v.task_id}),o++;}catch(d){c.push({task_dir:u,success:false,error:d instanceof Error?d.message:"Unknown error"}),l++;}return {success:l===0,queued:o,failed:l,results:c}}),e.post("/api/task/clear-history",{schema:{description:"Clear completed and failed tasks from queue history",tags:["tasks"],response:{200:{type:"object",properties:{success:{type:"boolean"},cleared:{type:"number"}}}}}},async()=>({success:true,cleared:await t.taskQueue.clearHistory()})),e.post("/api/task/events",{schema:{description:"Get event history for a task",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_dir:{type:"string",description:"Task directory path or ID (required)"},since:{type:"number",description:"Get events after this sequence number"}},required:["workspace_path","task_dir"]},response:{200:{type:"object",properties:{task_id:{type:"string"},events:{type:"array",items:{type:"object"}},count:{type:"number"},next_sequence:{type:"number"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_dir:a,since:c}=s.body,o=a.includes("/")?a:await $e.findTaskById(n,a);if(!o)return i.code(404),{error:`Task not found: ${a}`};let l=await $e.getTask(o);if(!l)return i.code(404),{error:`Task not found: ${a}`};let u=await rr.getEventHistory(o,c),d=await rr.getNextSequence(o);return {task_id:l.id,events:u,count:u.length,next_sequence:d}}),e.post("/api/task/specs",{schema:{description:"Get task specs (PRD, subtasks, logs)",tags:["tasks"],body:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_dir:{type:"string",description:"Task directory path or ID (required)"}},required:["workspace_path","task_dir"]},response:{200:{type:"object",properties:{prd_content:{type:"string",nullable:true},prd_path:{type:"string",nullable:true},subtasks:{type:"array",items:{type:"object"}},logs:{type:"object",nullable:true},task_dir:{type:"string"}}},404:{type:"object",properties:{error:{type:"string"}}}}}},async(s,i)=>{let{workspace_path:n,task_dir:a}=s.body,c=a.includes("/")?a:await $e.findTaskById(n,a);if(!c)return i.code(404),{error:`Task not found: ${a}`};try{let o=await $e.getTaskSpecsData(c);return {prd_content:o.prd_content,prd_path:o.prd_path,subtasks:o.subtasks,logs:o.logs,task_dir:o.task_dir}}catch(o){return i.code(500),{error:o instanceof Error?o.message:"Failed to get task specs"}}}),e.get("/api/task/events-stream",{schema:{description:"SSE stream for task events",tags:["tasks"],querystring:{type:"object",properties:{workspace_path:{type:"string",description:"Workspace path (required)"},task_ids:{type:"string",description:"Comma-separated task IDs for filtering"},last_sequence:{type:"string",description:"Last received sequence for replay"}},required:["workspace_path"]}}},async(s,i)=>{let{workspace_path:n,task_ids:a,last_sequence:c}=s.query;if(!n)return i.status(400).send({error:"workspace_path required"});let o=a?a.split(",").map(h=>h.trim()).filter(Boolean):[],l=o.length>0,u=c?parseInt(c,10):void 0;if(i.raw.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","X-Accel-Buffering":"no"}),u!==void 0&&!isNaN(u))try{if(l)for(let h of o){let _=await $e.findTaskById(n,h);if(_){let y=await rr.getEventHistory(_,u);for(let v of y){let b={type:"STATE_CHANGED",task_id:h,workspace_path:n,timestamp:new Date(v.timestamp).getTime(),event:v,replay:!0};i.raw.write(`event: STATE_CHANGED
|
|
806
806
|
data: ${JSON.stringify(b)}
|
|
@@ -1114,7 +1114,7 @@ ${Y__default.default.bold("Available dates")}:
|
|
|
1114
1114
|
`),gt(s,["Date","Traces"],a.map(c=>[c.date,String(c.count)])),console.log(`
|
|
1115
1115
|
Telemetry directory: ${Y__default.default.cyan(i)}`);});}}catch(n){Z(s,n);}}),t.command("view <traceId> [date]").description("View a trace as tree. Date defaults to today").action(async function(r,s){let i=XI(this),n=uf(),a=s||new Date().toISOString().split("T")[0];try{let c=qe__namespace.join(n,"traces",a,`${r}.jsonl`),o=v9e(c),l=fde(o);l||(console.log(Y__default.default.red("No spans found in trace")),process.exit(1)),B(i,J({tree:l,stats:qq(l)}),()=>{console.log(b9e(l)),console.log("");let u=qq(l);console.log(Y__default.default.bold("\u7EDF\u8BA1\u4FE1\u606F:")),console.log(` \u603B spans: ${u.totalSpans}`),console.log(` \u6210\u529F: ${Y__default.default.green(u.successSpans)}`),console.log(` \u9519\u8BEF: ${Y__default.default.red(u.errorSpans)}`),console.log(` \u6700\u5927\u6DF1\u5EA6: ${u.maxDepth}`),console.log(""),console.log(Y__default.default.bold("\u64CD\u4F5C\u8017\u65F6:"));for(let[d,h]of u.operations){let _=(h.totalDuration/h.count).toFixed(2);console.log(` ${d}: ${h.count}\u6B21, \u5E73\u5747 ${Y__default.default.yellow(_+"ms")}`);}});}catch(c){Z(i,c);}}),t.command("stats").description("Show telemetry statistics").action(async function(){let r=XI(this),s=uf();try{let i=Ap(s),n=0,a=0;for(let o of i){let l=await wu(s,o);n+=l.length,a+=l.reduce((u,d)=>u+d.size,0);}let c={directory:s,dates:i.length,totalTraces:n,totalSizeBytes:a,totalSizeMB:(a/1024/1024).toFixed(2)};B(r,J(c),()=>{console.log(`
|
|
1116
1116
|
${Y__default.default.bold("Telemetry \u7EDF\u8BA1")}:
|
|
1117
|
-
`),console.log(` \u76EE\u5F55: ${Y__default.default.cyan(c.directory)}`),console.log(` \u65E5\u671F\u6570: ${c.dates}`),console.log(` \u603B traces: ${c.totalTraces}`),console.log(` \u603B\u5927\u5C0F: ${c.totalSizeMB} MB`);});}catch(i){Z(r,i);}}),t.command("clean [days]").description("Clean old telemetry files. Default: 7 days retention").action(async function(r){let s=XI(this),i=uf(),n=parseInt(r||"7",10);(isNaN(n)||n<1)&&(console.log(Y__default.default.red("Invalid retention days. Must be a positive number.")),process.exit(1));try{let a=Ap(i),c=0;for(let d of a)c+=(await wu(i,d)).length;Ade(i,n);let o=Ap(i),l=0;for(let d of o)l+=(await wu(i,d)).length;let u={retentionDays:n,datesRemoved:a.length-o.length,tracesRemoved:c-l};B(s,J(u),()=>{console.log(Y__default.default.green(`\u2713 Cleaned telemetry files older than ${n} days`)),console.log(` Dates removed: ${u.datesRemoved}`),console.log(` Traces removed: ${u.tracesRemoved}`);});}catch(a){Z(s,a);}});}var e_t=$({"src/cli/commands/telemetry.ts"(){Ye(),wr();}}),_Te={};yt(_Te,{registerUpdateCommand:()=>d_t});function i_t(e,t){let r=l=>l.replace(/^v/,"").split(".").map(u=>parseInt(u,10)||0),[s,i,n]=r(e),[a,c,o]=r(t);return s!==a?s>a?1:-1:i!==c?i>c?1:-1:n!==o?n>o?1:-1:0}async function n_t(){try{let e=await $t(`https://api.github.com/repos/${jP}/releases`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":`viben/${fc}`}});if(!e.ok)return null;let r=(await e.json()).find(i=>i.tag_name.startsWith("v")&&!i.prerelease);if(!r)return null;let s=r.tag_name.replace(/^v/,"");return {version:s,tag:r.tag_name,date:r.published_at,hasUpdate:i_t(s,fc)>0,currentVersion:fc}}catch{return null}}async function o_t(){try{let{stdout:t}=await Ym("npm config get prefix"),{stdout:r}=await Ym("which viben").catch(()=>({stdout:""}));if(r.includes(t.trim()))return "npm"}catch{}let e=["pnpm","yarn","bun","npm"];for(let t of e)try{if(await Ym(`which ${t}`),t==="pnpm"){let{stdout:r}=await Ym("pnpm list -g viben").catch(()=>({stdout:""}));if(r.includes("viben"))return "pnpm"}else if(t==="yarn"){let{stdout:r}=await Ym("yarn global list").catch(()=>({stdout:""}));if(r.includes("viben"))return "yarn"}else if(t==="bun"){let{stdout:r}=await Ym("bun pm ls -g").catch(()=>({stdout:""}));if(r.includes("viben"))return "bun"}}catch{}return "npm"}function mj(e){switch(e){case "pnpm":return ["pnpm","add","-g",wS];case "yarn":return ["yarn","global","add",wS];case "bun":return ["bun","add","-g",wS];default:return ["npm","install","-g","--force",wS]}}async function c_t(e,t){let[r,...s]=mj(t);return new Promise(i=>{e.quiet||(console.log(Y__default.default.cyan(`Running: ${r} ${s.join(" ")}`)),console.log());let n=child_process.spawn(r,s,{stdio:e.quiet?"ignore":"inherit"});n.on("close",a=>{i(a===0);}),n.on("error",()=>{i(false);});})}async function u_t(e,t){e.quiet||(console.log(Y__default.default.cyan("Checking for updates...")),console.log(Y__default.default.gray(` Current version: v${fc}`)),console.log());let r=await n_t();if(r||(B(e,ot("FETCH_FAILED","Failed to fetch release information from GitHub"),()=>{console.log(Y__default.default.red("Error: Failed to check for updates.")),console.log(Y__default.default.gray(" Please check your internet connection and try again."));}),process.exit(1)),!r.hasUpdate){B(e,J({status:"up_to_date",currentVersion:fc,latestVersion:r.version}),()=>{console.log(Y__default.default.green(`\u2713 You're already on the latest version (v${fc})`));});return}if(t){B(e,J({status:"update_available",currentVersion:fc,latestVersion:r.version,releaseDate:r.date}),()=>{console.log(Y__default.default.yellow(`\u2B06 Update available: v${fc} \u2192 v${r.version}`)),console.log(),console.log("To update, run:"),console.log(Y__default.default.cyan(" viben update")),console.log(),console.log(Y__default.default.gray(`Release date: ${new Date(r.date).toLocaleDateString()}`)),console.log(Y__default.default.gray(`Changelog: https://github.com/${jP}/releases/tag/${r.tag}`));});return}e.quiet||(console.log(Y__default.default.yellow(`\u2B06 Updating: v${fc} \u2192 v${r.version}`)),console.log());let s=await o_t();s||(B(e,ot("NO_PACKAGE_MANAGER","Could not detect package manager. Please update manually."),()=>{console.log(Y__default.default.red("Error: Could not detect how viben was installed.")),console.log(),console.log("Please update manually using one of:"),console.log(Y__default.default.cyan(" npm install -g viben")),console.log(Y__default.default.cyan(" pnpm add -g viben")),console.log(Y__default.default.cyan(" yarn global add viben")),console.log(Y__default.default.cyan(" bun add -g viben"));}),process.exit(1)),e.quiet||(console.log(Y__default.default.gray(` Detected package manager: ${s}`)),console.log()),await c_t(e,s)?B(e,J({status:"updated",previousVersion:fc,newVersion:r.version,packageManager:s}),()=>{console.log(),console.log(Y__default.default.green(`\u2713 Successfully updated to v${r.version}`)),console.log(),console.log("What's new:"),console.log(Y__default.default.gray(` https://github.com/${jP}/releases/tag/${r.tag}`));}):(B(e,ot("UPDATE_FAILED","Failed to update viben"),()=>{console.log(),console.log(Y__default.default.red("Error: Update failed.")),console.log(),console.log("Please try updating manually:"),console.log(Y__default.default.cyan(` ${mj(s).join(" ")}`)),console.log(),console.log(Y__default.default.gray("If you encounter permission issues, try running with sudo:")),console.log(Y__default.default.gray(` sudo ${mj(s).join(" ")}`));}),process.exit(1));}async function l_t(e,t,r){let s=qe.resolve(t),i=[],n={force:r.force,skipExisting:r.skipExisting};e.quiet||(console.log(Y__default.default.cyan("Updating Viben workspace...")),console.log(Y__default.default.gray(` Target: ${s}`)),console.log()),r.ideaTypes&&(e.quiet||console.log(Y__default.default.gray(" Updating idea-types templates...")),await gYe(s,n,i)),r.rewardTypes&&(e.quiet||console.log(Y__default.default.gray(" Updating reward-types templates...")),await yYe(s,n,i)),B(e,J({path:s,files:i,count:i.length}),()=>{if(console.log(Y__default.default.green("\u2713 Workspace updated successfully!")),console.log(),i.length>0){console.log(`Updated ${Y__default.default.bold(i.length)} files:`);for(let a of i)console.log(Y__default.default.gray(` ${a}`));}else console.log(Y__default.default.gray("No files were updated (all files already exist)."));});}function d_t(e){e.command("update").description("Update Viben CLI or workspace components").argument("[target-dir]","Target directory for workspace updates (default: current directory)",".").option("-c, --check","Check for updates without installing").option("--idea-types","Update idea-types templates in docs/idea-types/").option("--reward-types","Update reward-types templates in docs/reward-types/").option("-f, --force","Force overwrite existing files").option("-s, --skip-existing","Skip existing files without error").action(async(t,r)=>{let s={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{r.ideaTypes||r.rewardTypes?await l_t(s,t,r):await u_t(s,r.check??!1);}catch(i){Z(s,i);}});}var Ym,fc,jP,wS,p_t=$({"src/cli/commands/update.ts"(){wr(),Bme(),As(),Ym=Uae.promisify(child_process.exec),fc="1.3.3",jP="LinXueyuanStdio/viben",wS="viben";}}),vTe={};yt(vTe,{registerQueueCommand:()=>E_t});function bTe(e){switch(e){case "pending":return Y__default.default.yellow("pending");case "running":return Y__default.default.blue("running");case "completed":return Y__default.default.green("completed");case "failed":return Y__default.default.red("failed");case "cancelled":return Y__default.default.gray("cancelled");default:return Y__default.default.gray(e)}}function W2(e){return new Date(e).toLocaleString()}function fj(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m ${Math.round(e%6e4/1e3)}s`:`${Math.round(e/36e5)}h ${Math.round(e%36e5/6e4)}m`}function du(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}function h_t(e){let t=e.opts();return new wTe(t.gateway||zP,t.timeout||UP)}async function m_t(e){let t=lC({include_items:true});if(!t.success){B(e,ot("QUEUE_ERROR",t.error||"Failed to get queue status"),()=>{console.error(Y__default.default.red(`Error: ${t.error}`));});return}B(e,J(t),()=>{if(console.log(Y__default.default.bold("Queue Status")),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Pending: ${t.pending} task(s)`),console.log(` Running: ${t.running} / ${t.max_concurrency} (max concurrency)`),console.log(` Completed: ${t.completed} task(s)`),t.items?.running&&t.items.running.length>0){console.log(),console.log("Running Tasks:");for(let r of t.items.running){let s=Date.now()-r.started_at;console.log(` ${r.id} pid:${r.pid} ${fj(s)}`);}}console.log(),console.log(`Storage: ${rd()}`);});}async function f_t(e,t){let r;t.status?r=[t.status]:t.all||(r=["pending","running"]);let s=Bf({status:r,limit:t.limit||50});if(!s.success){B(e,ot("QUEUE_ERROR",s.error||"Failed to list items"),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{if(s.items.length===0){console.log(Y__default.default.gray("No items found"));return}let i=["ID","STATUS","COMMAND","CWD","CREATED"],n=s.items.map(a=>{let c="pending";if("pid"in a)if("completed_at"in a){let u=a;c=u.exit_code===0?"completed":u.exit_code===-1?"cancelled":"failed";}else c="running";let o=a.command.length>40?a.command.slice(0,40)+"...":a.command,l=a.cwd.length>30?"..."+a.cwd.slice(-27):a.cwd;return [a.id,bTe(c),o,l,W2(a.created_at).split(" ")[1]]});gt(e,i,n),console.log(),console.log(`Showing ${s.items.length} of ${s.total} items`);});}async function g_t(e,t){let r=i_({id:t});if(!r.success){B(e,ot("NOT_FOUND",r.error||`Item not found: ${t}`),()=>{console.error(Y__default.default.red(r.error||`Item not found: ${t}`));});return}let s=r.item,i=r.status;B(e,J({item:s,status:i}),()=>{if(console.log(Y__default.default.bold(`Item: ${s.id}`)),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(`Status: ${bTe(i)}`),console.log(`Command: ${s.command}`),console.log(`CWD: ${s.cwd}`),console.log(`Created: ${W2(s.created_at)}`),"pid"in s){let n=s;if(console.log(),console.log("Execution:"),console.log(` PID: ${n.pid}`),console.log(` Started: ${W2(n.started_at)}`),console.log(` Log file: ${n.log_file}`),"completed_at"in s){let a=s;console.log(` Completed: ${W2(a.completed_at)}`),console.log(` Exit code: ${a.exit_code}`),console.log(` Duration: ${fj(a.completed_at-n.started_at)}`);}else {let a=Date.now()-n.started_at;console.log(` Elapsed: ${fj(a)}`);}}if(s.metadata&&Object.keys(s.metadata).length>0){console.log(),console.log("Metadata:");for(let[n,a]of Object.entries(s.metadata))console.log(` ${n}: ${JSON.stringify(a)}`);}});}async function y_t(e,t){let r=oz({command:t.command,cwd:t.cwd,metadata:t.metadata});if(!r.success){B(e,ot("ENQUEUE_ERROR",r.error||"Failed to enqueue command"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{console.log(Y__default.default.green("Command enqueued successfully")),console.log(` ID: ${r.id}`),console.log(` Position: ${r.position}`),console.log(` Command: ${t.command}`),console.log(` CWD: ${t.cwd}`),console.log(),console.log(`Use 'viben queue inspect ${r.id}' to view details`),console.log(`Use 'viben queue logs ${r.id}' to view output`);});}async function __t(e,t,r){let s=Ebe({id:t,force:r.force});if(!s.success){B(e,ot("CANCEL_ERROR",s.error||`Failed to cancel: ${t}`),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{console.log(Y__default.default.green("Item cancelled successfully")),console.log(` ID: ${s.cancelled}`);});}async function v_t(e,t,r){let s=wz({id:t,reset_count:r.resetCount});if(!s.success){B(e,ot("RETRY_ERROR",s.error||`Failed to retry: ${t}`),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{console.log(Y__default.default.green("Item queued for retry")),console.log(` New ID: ${s.id}`),console.log(` Position: ${s.position}`);});}async function b_t(e,t,r){let s=Sz({id:t,tail:r.tail!==void 0,lines:r.tail});if(!s.success){B(e,ot("LOGS_ERROR",s.error||`Failed to get logs: ${t}`),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}e.json?B(e,J(s),()=>{}):(s.content?console.log(s.content):console.log(Y__default.default.gray("No log content available")),s.truncated&&(console.log(),console.log(Y__default.default.yellow(`(Truncated - ${s.size} bytes total)`))));}async function w_t(e,t){if(t.reset){let r=AP({max_concurrency:3,promoter_interval_ms:5e3,monitor_interval_ms:3e4,log_retention_days:7,completed_retention_days:30,default_max_retries:3});if(!r.success){B(e,ot("CONFIG_ERROR",r.error||"Failed to reset config"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{console.log(Y__default.default.green("Queue configuration reset to defaults")),r.config&&et(e,r.config);});}else if(t.set&&t.set.length>0){let r={};for(let i of t.set){let[n,a]=i.split("=",2);if(!n||a===void 0){B(e,ot("VALIDATION_ERROR",`Invalid setting format: ${i}`),()=>{console.error(Y__default.default.red(`Invalid setting format: ${i}`)),console.error("Expected format: key=value");});return}let c=Number(a);r[n]=isNaN(c)?a:c;}let s=AP(r);if(!s.success){B(e,ot("CONFIG_ERROR",s.error||"Failed to update config"),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{console.log(Y__default.default.green("Queue configuration updated")),s.config&&et(e,s.config);});}else {let r=kz();if(!r.success){B(e,ot("CONFIG_ERROR",r.error||"Failed to get config"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{console.log(Y__default.default.bold("Queue Configuration")),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),r.config&&et(e,r.config),console.log(),console.log(`Config file: ${rd()}/config.json`);});}}async function S_t(e,t){let r=jbe({dry_run:t.dryRun});if(!r.success){B(e,ot("CLEAN_ERROR",r.error||"Failed to clean items"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{if(t.dryRun){if(console.log("Would clean:"),r.items)for(let s of r.items)console.log(` ${s}`);console.log(),console.log(`Total: ${r.cleaned} item(s)`);}else console.log(Y__default.default.green(`Cleaned ${r.cleaned} item(s)`)),console.log(` Removed from ${rd()}/`);});}async function k_t(e,t){e.json?console.log(JSON.stringify({type:"watch_started",timestamp:Date.now()})):(console.log("Watching queue (Ctrl+C to stop)"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let r=-1,s=-1,i=()=>{let a=lC();if(a.success){if(r>=0&&(a.pending!==r||a.running!==s)){let c={type:"queue:changed",timestamp:Date.now(),pending:a.pending,running:a.running};if(e.json)console.log(JSON.stringify(c));else {let o=new Date().toTimeString().split(" ")[0];console.log(`[${o}] queue:changed pending=${a.pending} running=${a.running}`);}}r=a.pending,s=a.running;}},n=setInterval(i,2e3);process.on("SIGINT",()=>{clearInterval(n),e.json||(console.log(),console.log("Watch stopped")),process.exit(0);}),i(),await new Promise(()=>{});}function E_t(e){let t=e.command("queue").description("Manage command queue").option("--gateway <url>","Gateway URL (for watch/stream)",zP).option("--timeout <ms>","Request timeout in milliseconds (default: 30000)",String(UP));t.command("status").description("Show queue status").action(async()=>{let r=du(e);try{await m_t(r);}catch(s){Z(r,s);}}),t.command("list").description("List queue items").option("-s, --status <status>","Filter by status (pending, running, completed, failed, cancelled)").option("-n, --limit <num>","Limit results (default: 50)",r=>parseInt(r,10)).option("--all","Show all items (including completed)").action(async r=>{let s=du(e);try{await f_t(s,r);}catch(i){Z(s,i);}}),t.command("inspect").argument("<id>","Item ID").description("Show item details").action(async r=>{let s=du(e);try{await g_t(s,r);}catch(i){Z(s,i);}}),t.command("enqueue").description("Enqueue a new command").requiredOption("-c, --command <command>","Command to execute").requiredOption("--cwd <path>","Working directory").option("-m, --metadata <json>","Metadata (JSON string)").action(async r=>{let s=du(e);try{let i;if(r.metadata)try{i=JSON.parse(r.metadata);}catch{B(s,ot("VALIDATION_ERROR","Invalid JSON in metadata"),()=>{console.error(Y__default.default.red("Invalid JSON in metadata"));});return}await y_t(s,{command:r.command,cwd:r.cwd,metadata:i});}catch(i){Z(s,i);}}),t.command("cancel").argument("<id>","Item ID").description("Cancel an item").option("-f, --force","Force kill running process (SIGKILL)").action(async(r,s)=>{let i=du(e);try{await __t(i,r,s);}catch(n){Z(i,n);}}),t.command("retry").argument("<id>","Item ID").description("Retry a failed item").option("--reset-count","Reset retry counter").action(async(r,s)=>{let i=du(e);try{await v_t(i,r,s);}catch(n){Z(i,n);}}),t.command("logs").argument("<id>","Item ID").description("View item logs").option("-n, --tail <num>","Show last N lines",r=>parseInt(r,10)).option("-f, --follow","Follow log output in real-time").action(async(r,s)=>{let i=du(e);try{await b_t(i,r,s);}catch(n){Z(i,n);}}),t.command("watch").description("Watch queue events").action(async()=>{let r=du(e),s=h_t(e);try{await k_t(r,s);}catch(i){Z(r,i);}}),t.command("config").description("Manage queue configuration").option("--set <key=value...>","Set configuration values").option("--reset","Reset to default values").action(async r=>{let s=du(e);try{await w_t(s,r);}catch(i){Z(s,i);}}),t.command("clean").description("Clean completed and failed items").option("--dry-run","Show what would be cleaned").option("-f, --force","Skip confirmation").action(async r=>{let s=du(e);try{await S_t(s,r);}catch(i){Z(s,i);}});}var zP,UP,wTe,T_t=$({"src/cli/commands/queue.ts"(){wr(),Ez(),hn(),zP="http://127.0.0.1:18790",UP=3e4,wTe=class{constructor(e=zP,t=UP){this.baseUrl=e,this.timeout=t;}async request(e,t,r,s){let i=`${this.baseUrl}${t}`,n=s?.timeout||this.timeout,a=new AbortController,c=setTimeout(()=>a.abort(),n);try{let o=await fetch(i,{method:e,headers:{"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0,signal:a.signal});if(clearTimeout(c),!o.ok){let l=await o.text().catch(()=>o.statusText);throw new Error(`HTTP ${o.status}: ${l}`)}return o.json()}catch(o){throw clearTimeout(c),o.name==="AbortError"?new Error(`Request timeout after ${n}ms`):o}}async testConnection(){try{return await this.request("GET","/health"),!0}catch{return false}}};}}),STe={};yt(STe,{registerSwarmCommand:()=>q_t});function u0(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function kTe(e,t){let r=e.agents.find(s=>s.id===t);return r||e.agents.find(s=>s.task_dir.includes(t))}function O_t(e,t){let r=qe.join(e,".viben","tasks");if(!Ne.existsSync(r))return null;let s=qe.basename(t);if(Ne.existsSync(qe.join(r,s)))return qe.join(".viben","tasks",s);try{let i=Ne.readdirSync(r);for(let n of i)if(n.includes(s)||s.includes(n))return qe.join(".viben","tasks",n)}catch{}return null}async function F_t(e,t){let r=Mk(t),s=wc(t);if(e.json){B(e,J({worktrees:r,agents:s.agents}));return}if(console.log(Y__default.default.blue("=== Git Worktrees ===")),console.log(),r.length===0)console.log(" (no worktrees)");else {console.log("PATH".padEnd(50)+"COMMIT".padEnd(10)+"BRANCH");for(let i of r)console.log(i.path.padEnd(50)+i.commit.substring(0,7).padEnd(10)+`[${i.branch||"(detached)"}]`);}if(console.log(),console.log(Y__default.default.blue("=== Registered Agents ===")),console.log(),s.agents.length===0)console.log(" (no agents registered)");else for(let i of s.agents){let n=Q0(i.pid)?Y__default.default.green("\u25CF"):Y__default.default.red("\u25CB");console.log(` ${n} ${i.id} (PID: ${i.pid})`),console.log(Y__default.default.dim(` Worktree: ${i.worktree_path}`)),console.log(Y__default.default.dim(` Started: ${i.started_at}`)),console.log();}}async function D_t(e,t,r,s){let i=O_t(t,r);if(!i){B(e,ot("TASK_NOT_FOUND",`Task not found: ${r}`),()=>{console.error(Y__default.default.red(`Error: Task not found: ${r}`)),console.log(Y__default.default.gray("Use 'viben task list' to see available tasks"));}),process.exit(1);return}if(s.resume){let c=wc(t),o=kTe(c,r);if(!o){B(e,ot("AGENT_NOT_FOUND",`No agent found for task: ${r}`),()=>{console.error(Y__default.default.red(`Error: No agent found for task: ${r}`)),console.log(Y__default.default.gray("The agent may not have been started yet"));}),process.exit(1);return}let l=s.session;if(!l){let y=qe.isAbsolute(o.task_dir)?o.task_dir:qe.join(t,o.task_dir);l=gA(y)||void 0;}if(!l){B(e,ot("NO_SESSION","No session ID found for resume"),()=>{console.error(Y__default.default.red("Error: No session ID found for resume")),console.log(Y__default.default.gray("No session_id in task.json and no --session provided"));}),process.exit(1);return}let u=o.platform||"claude",h=fs(u).buildResumeCommand(l);e.quiet||(console.log(Y__default.default.blue("=== Resuming Agent ===")),console.log(` Session: ${l}`),console.log(` Worktree: ${o.worktree_path}`),console.log(` Command: ${h.join(" ")}`),console.log()),child_process.spawn(h[0],h.slice(1),{cwd:o.worktree_path,stdio:"inherit"}).on("close",y=>{process.exit(y??0);});return}let n=s.executor&&ETe[s.executor.toUpperCase()]||"claude";e.quiet||(console.log(Y__default.default.blue("=== Multi-Agent Pipeline: Start ===")),console.log(`[INFO] Task: ${i}`),console.log(`[INFO] Platform: ${n}`));let a=await sJe(t,i,{platform:n,detach:s.detach??true,skipPermissions:true,verbose:e.verbose,jsonOutput:true});if(e.json)a.success?B(e,J(a)):B(e,ot("START_FAILED",a.error||"Unknown error"));else if(a.success){if(console.log(),console.log(Y__default.default.green("=== Agent Started ===")),console.log(),console.log(` ID: ${a.agentId}`),console.log(` PID: ${a.pid}`),console.log(` Session: ${a.session_id||"N/A"}`),console.log(` Worktree: ${a.worktreePath}`),console.log(` Log: ${a.log_file}`),console.log(),console.log(Y__default.default.yellow(`To monitor: tail -f ${a.log_file}`)),console.log(Y__default.default.yellow(`To stop: kill ${a.pid}`)),a.session_id){let o=fs(n).getResumeCommandStr(a.session_id,a.worktreePath);console.log(Y__default.default.yellow(`To resume: ${o}`));}}else console.error(Y__default.default.red(`Error: ${a.error}`)),process.exit(1);}async function $_t(e,t,r,s){let i=wc(t);if(s.all){let a=i.agents.filter(l=>Q0(l.pid));if(a.length===0){B(e,J({stopped:[]}),()=>{console.log(Y__default.default.yellow("No running agents found"));});return}let c=[],o=[];for(let l of a)try{process.kill(l.pid,s.force?"SIGKILL":"SIGTERM"),c.push(l.id),e.quiet||console.log(Y__default.default.green(`Stopped: ${l.id} (PID: ${l.pid})`));}catch{o.push(l.id),e.quiet||console.log(Y__default.default.red(`Failed to stop: ${l.id} (PID: ${l.pid})`));}B(e,J({stopped:c,failed:o}));return}if(!r){B(e,ot("MISSING_TASK","Task name required"),()=>{console.error(Y__default.default.red("Error: Task name is required")),console.log(Y__default.default.gray("Usage: viben swarm stop <task>")),console.log(Y__default.default.gray(" viben swarm stop --all"));}),process.exit(1);return}let n=kTe(i,r);if(!n){B(e,ot("AGENT_NOT_FOUND",`Agent not found: ${r}`),()=>{console.error(Y__default.default.red(`Error: Agent not found: ${r}`));}),process.exit(1);return}if(!Q0(n.pid)){B(e,J({agent:n,status:"already_stopped"}),()=>{console.log(Y__default.default.yellow(`Agent ${n.id} is not running (PID: ${n.pid})`));});return}try{process.kill(n.pid,s.force?"SIGKILL":"SIGTERM"),B(e,J({agent:n,status:"stopped"}),()=>{console.log(Y__default.default.green(`Stopped agent: ${n.id} (PID: ${n.pid})`));});}catch(a){B(e,ot("STOP_FAILED",`Failed to stop agent: ${a}`),()=>{console.error(Y__default.default.red(`Error: Failed to stop agent ${n.id}: ${a}`));}),process.exit(1);}}async function R_t(e,t,r,s){if(s.watch&&r){let u=iN(r,t);if(!u){console.error(Y__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=qe.join(u.worktree_path,"agent.log.jsonl");if(!Ne.existsSync(d)){console.error(Y__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(Y__default.default.blue(`Watching: ${d}`)),console.log(Y__default.default.dim("Press Ctrl+C to stop")),console.log(),gJe(d);return}if(s.log&&r){let u=iN(r,t);if(!u){console.error(Y__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=qe.join(u.worktree_path,"agent.log.jsonl");if(!Ne.existsSync(d)){console.error(Y__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(Y__default.default.blue(`=== Recent Log: ${r} ===`)),console.log(Y__default.default.dim(`Platform: ${u.platform}`)),console.log();let h=mJe(d,50,u.platform);for(let _ of h)console.log(_);return}if((s.detail||r)&&r){let u=iN(r,t);if(!u){console.error(Y__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}if(e.json){B(e,J(u));return}if(console.log(Y__default.default.blue(`=== Agent Detail: ${u.id} ===`)),console.log(),console.log(` ID: ${u.id}`),console.log(` PID: ${u.pid}`),console.log(` Session: ${u.session_id||"N/A"}`),console.log(` Worktree: ${u.worktree_path}`),console.log(` Task Dir: ${u.task_dir}`),console.log(` Started: ${u.started_at}`),console.log(),u.running)console.log(` Status: ${Y__default.default.green("Running")}`);else if(console.log(` Status: ${Y__default.default.red("Stopped")}`),u.session_id){let h=fs(u.platform).getResumeCommandStr(u.session_id,u.worktree_path);console.log(),console.log(Y__default.default.yellow(` Resume: ${h}`));}if(Ne.existsSync(u.worktree_path)){console.log(),console.log(Y__default.default.blue("=== Git Changes ===")),console.log();try{let d=child_process.execSync("git status --short",{cwd:u.worktree_path,encoding:"utf-8"});if(d.trim()){let h=d.trim().split(`
|
|
1117
|
+
`),console.log(` \u76EE\u5F55: ${Y__default.default.cyan(c.directory)}`),console.log(` \u65E5\u671F\u6570: ${c.dates}`),console.log(` \u603B traces: ${c.totalTraces}`),console.log(` \u603B\u5927\u5C0F: ${c.totalSizeMB} MB`);});}catch(i){Z(r,i);}}),t.command("clean [days]").description("Clean old telemetry files. Default: 7 days retention").action(async function(r){let s=XI(this),i=uf(),n=parseInt(r||"7",10);(isNaN(n)||n<1)&&(console.log(Y__default.default.red("Invalid retention days. Must be a positive number.")),process.exit(1));try{let a=Ap(i),c=0;for(let d of a)c+=(await wu(i,d)).length;Ade(i,n);let o=Ap(i),l=0;for(let d of o)l+=(await wu(i,d)).length;let u={retentionDays:n,datesRemoved:a.length-o.length,tracesRemoved:c-l};B(s,J(u),()=>{console.log(Y__default.default.green(`\u2713 Cleaned telemetry files older than ${n} days`)),console.log(` Dates removed: ${u.datesRemoved}`),console.log(` Traces removed: ${u.tracesRemoved}`);});}catch(a){Z(s,a);}});}var e_t=$({"src/cli/commands/telemetry.ts"(){Ye(),wr();}}),_Te={};yt(_Te,{registerUpdateCommand:()=>d_t});function i_t(e,t){let r=l=>l.replace(/^v/,"").split(".").map(u=>parseInt(u,10)||0),[s,i,n]=r(e),[a,c,o]=r(t);return s!==a?s>a?1:-1:i!==c?i>c?1:-1:n!==o?n>o?1:-1:0}async function n_t(){try{let e=await $t(`https://api.github.com/repos/${jP}/releases`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":`viben/${fc}`}});if(!e.ok)return null;let r=(await e.json()).find(i=>i.tag_name.startsWith("v")&&!i.prerelease);if(!r)return null;let s=r.tag_name.replace(/^v/,"");return {version:s,tag:r.tag_name,date:r.published_at,hasUpdate:i_t(s,fc)>0,currentVersion:fc}}catch{return null}}async function o_t(){try{let{stdout:t}=await Ym("npm config get prefix"),{stdout:r}=await Ym("which viben").catch(()=>({stdout:""}));if(r.includes(t.trim()))return "npm"}catch{}let e=["pnpm","yarn","bun","npm"];for(let t of e)try{if(await Ym(`which ${t}`),t==="pnpm"){let{stdout:r}=await Ym("pnpm list -g viben").catch(()=>({stdout:""}));if(r.includes("viben"))return "pnpm"}else if(t==="yarn"){let{stdout:r}=await Ym("yarn global list").catch(()=>({stdout:""}));if(r.includes("viben"))return "yarn"}else if(t==="bun"){let{stdout:r}=await Ym("bun pm ls -g").catch(()=>({stdout:""}));if(r.includes("viben"))return "bun"}}catch{}return "npm"}function mj(e){switch(e){case "pnpm":return ["pnpm","add","-g",wS];case "yarn":return ["yarn","global","add",wS];case "bun":return ["bun","add","-g",wS];default:return ["npm","install","-g","--force",wS]}}async function c_t(e,t){let[r,...s]=mj(t);return new Promise(i=>{e.quiet||(console.log(Y__default.default.cyan(`Running: ${r} ${s.join(" ")}`)),console.log());let n=child_process.spawn(r,s,{stdio:e.quiet?"ignore":"inherit"});n.on("close",a=>{i(a===0);}),n.on("error",()=>{i(false);});})}async function u_t(e,t){e.quiet||(console.log(Y__default.default.cyan("Checking for updates...")),console.log(Y__default.default.gray(` Current version: v${fc}`)),console.log());let r=await n_t();if(r||(B(e,ot("FETCH_FAILED","Failed to fetch release information from GitHub"),()=>{console.log(Y__default.default.red("Error: Failed to check for updates.")),console.log(Y__default.default.gray(" Please check your internet connection and try again."));}),process.exit(1)),!r.hasUpdate){B(e,J({status:"up_to_date",currentVersion:fc,latestVersion:r.version}),()=>{console.log(Y__default.default.green(`\u2713 You're already on the latest version (v${fc})`));});return}if(t){B(e,J({status:"update_available",currentVersion:fc,latestVersion:r.version,releaseDate:r.date}),()=>{console.log(Y__default.default.yellow(`\u2B06 Update available: v${fc} \u2192 v${r.version}`)),console.log(),console.log("To update, run:"),console.log(Y__default.default.cyan(" viben update")),console.log(),console.log(Y__default.default.gray(`Release date: ${new Date(r.date).toLocaleDateString()}`)),console.log(Y__default.default.gray(`Changelog: https://github.com/${jP}/releases/tag/${r.tag}`));});return}e.quiet||(console.log(Y__default.default.yellow(`\u2B06 Updating: v${fc} \u2192 v${r.version}`)),console.log());let s=await o_t();s||(B(e,ot("NO_PACKAGE_MANAGER","Could not detect package manager. Please update manually."),()=>{console.log(Y__default.default.red("Error: Could not detect how viben was installed.")),console.log(),console.log("Please update manually using one of:"),console.log(Y__default.default.cyan(" npm install -g viben")),console.log(Y__default.default.cyan(" pnpm add -g viben")),console.log(Y__default.default.cyan(" yarn global add viben")),console.log(Y__default.default.cyan(" bun add -g viben"));}),process.exit(1)),e.quiet||(console.log(Y__default.default.gray(` Detected package manager: ${s}`)),console.log()),await c_t(e,s)?B(e,J({status:"updated",previousVersion:fc,newVersion:r.version,packageManager:s}),()=>{console.log(),console.log(Y__default.default.green(`\u2713 Successfully updated to v${r.version}`)),console.log(),console.log("What's new:"),console.log(Y__default.default.gray(` https://github.com/${jP}/releases/tag/${r.tag}`));}):(B(e,ot("UPDATE_FAILED","Failed to update viben"),()=>{console.log(),console.log(Y__default.default.red("Error: Update failed.")),console.log(),console.log("Please try updating manually:"),console.log(Y__default.default.cyan(` ${mj(s).join(" ")}`)),console.log(),console.log(Y__default.default.gray("If you encounter permission issues, try running with sudo:")),console.log(Y__default.default.gray(` sudo ${mj(s).join(" ")}`));}),process.exit(1));}async function l_t(e,t,r){let s=qe.resolve(t),i=[],n={force:r.force,skipExisting:r.skipExisting};e.quiet||(console.log(Y__default.default.cyan("Updating Viben workspace...")),console.log(Y__default.default.gray(` Target: ${s}`)),console.log()),r.ideaTypes&&(e.quiet||console.log(Y__default.default.gray(" Updating idea-types templates...")),await gYe(s,n,i)),r.rewardTypes&&(e.quiet||console.log(Y__default.default.gray(" Updating reward-types templates...")),await yYe(s,n,i)),B(e,J({path:s,files:i,count:i.length}),()=>{if(console.log(Y__default.default.green("\u2713 Workspace updated successfully!")),console.log(),i.length>0){console.log(`Updated ${Y__default.default.bold(i.length)} files:`);for(let a of i)console.log(Y__default.default.gray(` ${a}`));}else console.log(Y__default.default.gray("No files were updated (all files already exist)."));});}function d_t(e){e.command("update").description("Update Viben CLI or workspace components").argument("[target-dir]","Target directory for workspace updates (default: current directory)",".").option("-c, --check","Check for updates without installing").option("--idea-types","Update idea-types templates in docs/idea-types/").option("--reward-types","Update reward-types templates in docs/reward-types/").option("-f, --force","Force overwrite existing files").option("-s, --skip-existing","Skip existing files without error").action(async(t,r)=>{let s={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{r.ideaTypes||r.rewardTypes?await l_t(s,t,r):await u_t(s,r.check??!1);}catch(i){Z(s,i);}});}var Ym,fc,jP,wS,p_t=$({"src/cli/commands/update.ts"(){wr(),Bme(),As(),Ym=Uae.promisify(child_process.exec),fc="1.3.4",jP="LinXueyuanStdio/viben",wS="viben";}}),vTe={};yt(vTe,{registerQueueCommand:()=>E_t});function bTe(e){switch(e){case "pending":return Y__default.default.yellow("pending");case "running":return Y__default.default.blue("running");case "completed":return Y__default.default.green("completed");case "failed":return Y__default.default.red("failed");case "cancelled":return Y__default.default.gray("cancelled");default:return Y__default.default.gray(e)}}function W2(e){return new Date(e).toLocaleString()}function fj(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m ${Math.round(e%6e4/1e3)}s`:`${Math.round(e/36e5)}h ${Math.round(e%36e5/6e4)}m`}function du(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}function h_t(e){let t=e.opts();return new wTe(t.gateway||zP,t.timeout||UP)}async function m_t(e){let t=lC({include_items:true});if(!t.success){B(e,ot("QUEUE_ERROR",t.error||"Failed to get queue status"),()=>{console.error(Y__default.default.red(`Error: ${t.error}`));});return}B(e,J(t),()=>{if(console.log(Y__default.default.bold("Queue Status")),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Pending: ${t.pending} task(s)`),console.log(` Running: ${t.running} / ${t.max_concurrency} (max concurrency)`),console.log(` Completed: ${t.completed} task(s)`),t.items?.running&&t.items.running.length>0){console.log(),console.log("Running Tasks:");for(let r of t.items.running){let s=Date.now()-r.started_at;console.log(` ${r.id} pid:${r.pid} ${fj(s)}`);}}console.log(),console.log(`Storage: ${rd()}`);});}async function f_t(e,t){let r;t.status?r=[t.status]:t.all||(r=["pending","running"]);let s=Bf({status:r,limit:t.limit||50});if(!s.success){B(e,ot("QUEUE_ERROR",s.error||"Failed to list items"),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{if(s.items.length===0){console.log(Y__default.default.gray("No items found"));return}let i=["ID","STATUS","COMMAND","CWD","CREATED"],n=s.items.map(a=>{let c="pending";if("pid"in a)if("completed_at"in a){let u=a;c=u.exit_code===0?"completed":u.exit_code===-1?"cancelled":"failed";}else c="running";let o=a.command.length>40?a.command.slice(0,40)+"...":a.command,l=a.cwd.length>30?"..."+a.cwd.slice(-27):a.cwd;return [a.id,bTe(c),o,l,W2(a.created_at).split(" ")[1]]});gt(e,i,n),console.log(),console.log(`Showing ${s.items.length} of ${s.total} items`);});}async function g_t(e,t){let r=i_({id:t});if(!r.success){B(e,ot("NOT_FOUND",r.error||`Item not found: ${t}`),()=>{console.error(Y__default.default.red(r.error||`Item not found: ${t}`));});return}let s=r.item,i=r.status;B(e,J({item:s,status:i}),()=>{if(console.log(Y__default.default.bold(`Item: ${s.id}`)),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(`Status: ${bTe(i)}`),console.log(`Command: ${s.command}`),console.log(`CWD: ${s.cwd}`),console.log(`Created: ${W2(s.created_at)}`),"pid"in s){let n=s;if(console.log(),console.log("Execution:"),console.log(` PID: ${n.pid}`),console.log(` Started: ${W2(n.started_at)}`),console.log(` Log file: ${n.log_file}`),"completed_at"in s){let a=s;console.log(` Completed: ${W2(a.completed_at)}`),console.log(` Exit code: ${a.exit_code}`),console.log(` Duration: ${fj(a.completed_at-n.started_at)}`);}else {let a=Date.now()-n.started_at;console.log(` Elapsed: ${fj(a)}`);}}if(s.metadata&&Object.keys(s.metadata).length>0){console.log(),console.log("Metadata:");for(let[n,a]of Object.entries(s.metadata))console.log(` ${n}: ${JSON.stringify(a)}`);}});}async function y_t(e,t){let r=oz({command:t.command,cwd:t.cwd,metadata:t.metadata});if(!r.success){B(e,ot("ENQUEUE_ERROR",r.error||"Failed to enqueue command"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{console.log(Y__default.default.green("Command enqueued successfully")),console.log(` ID: ${r.id}`),console.log(` Position: ${r.position}`),console.log(` Command: ${t.command}`),console.log(` CWD: ${t.cwd}`),console.log(),console.log(`Use 'viben queue inspect ${r.id}' to view details`),console.log(`Use 'viben queue logs ${r.id}' to view output`);});}async function __t(e,t,r){let s=Ebe({id:t,force:r.force});if(!s.success){B(e,ot("CANCEL_ERROR",s.error||`Failed to cancel: ${t}`),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{console.log(Y__default.default.green("Item cancelled successfully")),console.log(` ID: ${s.cancelled}`);});}async function v_t(e,t,r){let s=wz({id:t,reset_count:r.resetCount});if(!s.success){B(e,ot("RETRY_ERROR",s.error||`Failed to retry: ${t}`),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{console.log(Y__default.default.green("Item queued for retry")),console.log(` New ID: ${s.id}`),console.log(` Position: ${s.position}`);});}async function b_t(e,t,r){let s=Sz({id:t,tail:r.tail!==void 0,lines:r.tail});if(!s.success){B(e,ot("LOGS_ERROR",s.error||`Failed to get logs: ${t}`),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}e.json?B(e,J(s),()=>{}):(s.content?console.log(s.content):console.log(Y__default.default.gray("No log content available")),s.truncated&&(console.log(),console.log(Y__default.default.yellow(`(Truncated - ${s.size} bytes total)`))));}async function w_t(e,t){if(t.reset){let r=AP({max_concurrency:3,promoter_interval_ms:5e3,monitor_interval_ms:3e4,log_retention_days:7,completed_retention_days:30,default_max_retries:3});if(!r.success){B(e,ot("CONFIG_ERROR",r.error||"Failed to reset config"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{console.log(Y__default.default.green("Queue configuration reset to defaults")),r.config&&et(e,r.config);});}else if(t.set&&t.set.length>0){let r={};for(let i of t.set){let[n,a]=i.split("=",2);if(!n||a===void 0){B(e,ot("VALIDATION_ERROR",`Invalid setting format: ${i}`),()=>{console.error(Y__default.default.red(`Invalid setting format: ${i}`)),console.error("Expected format: key=value");});return}let c=Number(a);r[n]=isNaN(c)?a:c;}let s=AP(r);if(!s.success){B(e,ot("CONFIG_ERROR",s.error||"Failed to update config"),()=>{console.error(Y__default.default.red(`Error: ${s.error}`));});return}B(e,J(s),()=>{console.log(Y__default.default.green("Queue configuration updated")),s.config&&et(e,s.config);});}else {let r=kz();if(!r.success){B(e,ot("CONFIG_ERROR",r.error||"Failed to get config"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{console.log(Y__default.default.bold("Queue Configuration")),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),r.config&&et(e,r.config),console.log(),console.log(`Config file: ${rd()}/config.json`);});}}async function S_t(e,t){let r=jbe({dry_run:t.dryRun});if(!r.success){B(e,ot("CLEAN_ERROR",r.error||"Failed to clean items"),()=>{console.error(Y__default.default.red(`Error: ${r.error}`));});return}B(e,J(r),()=>{if(t.dryRun){if(console.log("Would clean:"),r.items)for(let s of r.items)console.log(` ${s}`);console.log(),console.log(`Total: ${r.cleaned} item(s)`);}else console.log(Y__default.default.green(`Cleaned ${r.cleaned} item(s)`)),console.log(` Removed from ${rd()}/`);});}async function k_t(e,t){e.json?console.log(JSON.stringify({type:"watch_started",timestamp:Date.now()})):(console.log("Watching queue (Ctrl+C to stop)"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let r=-1,s=-1,i=()=>{let a=lC();if(a.success){if(r>=0&&(a.pending!==r||a.running!==s)){let c={type:"queue:changed",timestamp:Date.now(),pending:a.pending,running:a.running};if(e.json)console.log(JSON.stringify(c));else {let o=new Date().toTimeString().split(" ")[0];console.log(`[${o}] queue:changed pending=${a.pending} running=${a.running}`);}}r=a.pending,s=a.running;}},n=setInterval(i,2e3);process.on("SIGINT",()=>{clearInterval(n),e.json||(console.log(),console.log("Watch stopped")),process.exit(0);}),i(),await new Promise(()=>{});}function E_t(e){let t=e.command("queue").description("Manage command queue").option("--gateway <url>","Gateway URL (for watch/stream)",zP).option("--timeout <ms>","Request timeout in milliseconds (default: 30000)",String(UP));t.command("status").description("Show queue status").action(async()=>{let r=du(e);try{await m_t(r);}catch(s){Z(r,s);}}),t.command("list").description("List queue items").option("-s, --status <status>","Filter by status (pending, running, completed, failed, cancelled)").option("-n, --limit <num>","Limit results (default: 50)",r=>parseInt(r,10)).option("--all","Show all items (including completed)").action(async r=>{let s=du(e);try{await f_t(s,r);}catch(i){Z(s,i);}}),t.command("inspect").argument("<id>","Item ID").description("Show item details").action(async r=>{let s=du(e);try{await g_t(s,r);}catch(i){Z(s,i);}}),t.command("enqueue").description("Enqueue a new command").requiredOption("-c, --command <command>","Command to execute").requiredOption("--cwd <path>","Working directory").option("-m, --metadata <json>","Metadata (JSON string)").action(async r=>{let s=du(e);try{let i;if(r.metadata)try{i=JSON.parse(r.metadata);}catch{B(s,ot("VALIDATION_ERROR","Invalid JSON in metadata"),()=>{console.error(Y__default.default.red("Invalid JSON in metadata"));});return}await y_t(s,{command:r.command,cwd:r.cwd,metadata:i});}catch(i){Z(s,i);}}),t.command("cancel").argument("<id>","Item ID").description("Cancel an item").option("-f, --force","Force kill running process (SIGKILL)").action(async(r,s)=>{let i=du(e);try{await __t(i,r,s);}catch(n){Z(i,n);}}),t.command("retry").argument("<id>","Item ID").description("Retry a failed item").option("--reset-count","Reset retry counter").action(async(r,s)=>{let i=du(e);try{await v_t(i,r,s);}catch(n){Z(i,n);}}),t.command("logs").argument("<id>","Item ID").description("View item logs").option("-n, --tail <num>","Show last N lines",r=>parseInt(r,10)).option("-f, --follow","Follow log output in real-time").action(async(r,s)=>{let i=du(e);try{await b_t(i,r,s);}catch(n){Z(i,n);}}),t.command("watch").description("Watch queue events").action(async()=>{let r=du(e),s=h_t(e);try{await k_t(r,s);}catch(i){Z(r,i);}}),t.command("config").description("Manage queue configuration").option("--set <key=value...>","Set configuration values").option("--reset","Reset to default values").action(async r=>{let s=du(e);try{await w_t(s,r);}catch(i){Z(s,i);}}),t.command("clean").description("Clean completed and failed items").option("--dry-run","Show what would be cleaned").option("-f, --force","Skip confirmation").action(async r=>{let s=du(e);try{await S_t(s,r);}catch(i){Z(s,i);}});}var zP,UP,wTe,T_t=$({"src/cli/commands/queue.ts"(){wr(),Ez(),hn(),zP="http://127.0.0.1:18790",UP=3e4,wTe=class{constructor(e=zP,t=UP){this.baseUrl=e,this.timeout=t;}async request(e,t,r,s){let i=`${this.baseUrl}${t}`,n=s?.timeout||this.timeout,a=new AbortController,c=setTimeout(()=>a.abort(),n);try{let o=await fetch(i,{method:e,headers:{"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0,signal:a.signal});if(clearTimeout(c),!o.ok){let l=await o.text().catch(()=>o.statusText);throw new Error(`HTTP ${o.status}: ${l}`)}return o.json()}catch(o){throw clearTimeout(c),o.name==="AbortError"?new Error(`Request timeout after ${n}ms`):o}}async testConnection(){try{return await this.request("GET","/health"),!0}catch{return false}}};}}),STe={};yt(STe,{registerSwarmCommand:()=>q_t});function u0(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function kTe(e,t){let r=e.agents.find(s=>s.id===t);return r||e.agents.find(s=>s.task_dir.includes(t))}function O_t(e,t){let r=qe.join(e,".viben","tasks");if(!Ne.existsSync(r))return null;let s=qe.basename(t);if(Ne.existsSync(qe.join(r,s)))return qe.join(".viben","tasks",s);try{let i=Ne.readdirSync(r);for(let n of i)if(n.includes(s)||s.includes(n))return qe.join(".viben","tasks",n)}catch{}return null}async function F_t(e,t){let r=Mk(t),s=wc(t);if(e.json){B(e,J({worktrees:r,agents:s.agents}));return}if(console.log(Y__default.default.blue("=== Git Worktrees ===")),console.log(),r.length===0)console.log(" (no worktrees)");else {console.log("PATH".padEnd(50)+"COMMIT".padEnd(10)+"BRANCH");for(let i of r)console.log(i.path.padEnd(50)+i.commit.substring(0,7).padEnd(10)+`[${i.branch||"(detached)"}]`);}if(console.log(),console.log(Y__default.default.blue("=== Registered Agents ===")),console.log(),s.agents.length===0)console.log(" (no agents registered)");else for(let i of s.agents){let n=Q0(i.pid)?Y__default.default.green("\u25CF"):Y__default.default.red("\u25CB");console.log(` ${n} ${i.id} (PID: ${i.pid})`),console.log(Y__default.default.dim(` Worktree: ${i.worktree_path}`)),console.log(Y__default.default.dim(` Started: ${i.started_at}`)),console.log();}}async function D_t(e,t,r,s){let i=O_t(t,r);if(!i){B(e,ot("TASK_NOT_FOUND",`Task not found: ${r}`),()=>{console.error(Y__default.default.red(`Error: Task not found: ${r}`)),console.log(Y__default.default.gray("Use 'viben task list' to see available tasks"));}),process.exit(1);return}if(s.resume){let c=wc(t),o=kTe(c,r);if(!o){B(e,ot("AGENT_NOT_FOUND",`No agent found for task: ${r}`),()=>{console.error(Y__default.default.red(`Error: No agent found for task: ${r}`)),console.log(Y__default.default.gray("The agent may not have been started yet"));}),process.exit(1);return}let l=s.session;if(!l){let y=qe.isAbsolute(o.task_dir)?o.task_dir:qe.join(t,o.task_dir);l=gA(y)||void 0;}if(!l){B(e,ot("NO_SESSION","No session ID found for resume"),()=>{console.error(Y__default.default.red("Error: No session ID found for resume")),console.log(Y__default.default.gray("No session_id in task.json and no --session provided"));}),process.exit(1);return}let u=o.platform||"claude",h=fs(u).buildResumeCommand(l);e.quiet||(console.log(Y__default.default.blue("=== Resuming Agent ===")),console.log(` Session: ${l}`),console.log(` Worktree: ${o.worktree_path}`),console.log(` Command: ${h.join(" ")}`),console.log()),child_process.spawn(h[0],h.slice(1),{cwd:o.worktree_path,stdio:"inherit"}).on("close",y=>{process.exit(y??0);});return}let n=s.executor&&ETe[s.executor.toUpperCase()]||"claude";e.quiet||(console.log(Y__default.default.blue("=== Multi-Agent Pipeline: Start ===")),console.log(`[INFO] Task: ${i}`),console.log(`[INFO] Platform: ${n}`));let a=await sJe(t,i,{platform:n,detach:s.detach??true,skipPermissions:true,verbose:e.verbose,jsonOutput:true});if(e.json)a.success?B(e,J(a)):B(e,ot("START_FAILED",a.error||"Unknown error"));else if(a.success){if(console.log(),console.log(Y__default.default.green("=== Agent Started ===")),console.log(),console.log(` ID: ${a.agentId}`),console.log(` PID: ${a.pid}`),console.log(` Session: ${a.session_id||"N/A"}`),console.log(` Worktree: ${a.worktreePath}`),console.log(` Log: ${a.log_file}`),console.log(),console.log(Y__default.default.yellow(`To monitor: tail -f ${a.log_file}`)),console.log(Y__default.default.yellow(`To stop: kill ${a.pid}`)),a.session_id){let o=fs(n).getResumeCommandStr(a.session_id,a.worktreePath);console.log(Y__default.default.yellow(`To resume: ${o}`));}}else console.error(Y__default.default.red(`Error: ${a.error}`)),process.exit(1);}async function $_t(e,t,r,s){let i=wc(t);if(s.all){let a=i.agents.filter(l=>Q0(l.pid));if(a.length===0){B(e,J({stopped:[]}),()=>{console.log(Y__default.default.yellow("No running agents found"));});return}let c=[],o=[];for(let l of a)try{process.kill(l.pid,s.force?"SIGKILL":"SIGTERM"),c.push(l.id),e.quiet||console.log(Y__default.default.green(`Stopped: ${l.id} (PID: ${l.pid})`));}catch{o.push(l.id),e.quiet||console.log(Y__default.default.red(`Failed to stop: ${l.id} (PID: ${l.pid})`));}B(e,J({stopped:c,failed:o}));return}if(!r){B(e,ot("MISSING_TASK","Task name required"),()=>{console.error(Y__default.default.red("Error: Task name is required")),console.log(Y__default.default.gray("Usage: viben swarm stop <task>")),console.log(Y__default.default.gray(" viben swarm stop --all"));}),process.exit(1);return}let n=kTe(i,r);if(!n){B(e,ot("AGENT_NOT_FOUND",`Agent not found: ${r}`),()=>{console.error(Y__default.default.red(`Error: Agent not found: ${r}`));}),process.exit(1);return}if(!Q0(n.pid)){B(e,J({agent:n,status:"already_stopped"}),()=>{console.log(Y__default.default.yellow(`Agent ${n.id} is not running (PID: ${n.pid})`));});return}try{process.kill(n.pid,s.force?"SIGKILL":"SIGTERM"),B(e,J({agent:n,status:"stopped"}),()=>{console.log(Y__default.default.green(`Stopped agent: ${n.id} (PID: ${n.pid})`));});}catch(a){B(e,ot("STOP_FAILED",`Failed to stop agent: ${a}`),()=>{console.error(Y__default.default.red(`Error: Failed to stop agent ${n.id}: ${a}`));}),process.exit(1);}}async function R_t(e,t,r,s){if(s.watch&&r){let u=iN(r,t);if(!u){console.error(Y__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=qe.join(u.worktree_path,"agent.log.jsonl");if(!Ne.existsSync(d)){console.error(Y__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(Y__default.default.blue(`Watching: ${d}`)),console.log(Y__default.default.dim("Press Ctrl+C to stop")),console.log(),gJe(d);return}if(s.log&&r){let u=iN(r,t);if(!u){console.error(Y__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=qe.join(u.worktree_path,"agent.log.jsonl");if(!Ne.existsSync(d)){console.error(Y__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(Y__default.default.blue(`=== Recent Log: ${r} ===`)),console.log(Y__default.default.dim(`Platform: ${u.platform}`)),console.log();let h=mJe(d,50,u.platform);for(let _ of h)console.log(_);return}if((s.detail||r)&&r){let u=iN(r,t);if(!u){console.error(Y__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}if(e.json){B(e,J(u));return}if(console.log(Y__default.default.blue(`=== Agent Detail: ${u.id} ===`)),console.log(),console.log(` ID: ${u.id}`),console.log(` PID: ${u.pid}`),console.log(` Session: ${u.session_id||"N/A"}`),console.log(` Worktree: ${u.worktree_path}`),console.log(` Task Dir: ${u.task_dir}`),console.log(` Started: ${u.started_at}`),console.log(),u.running)console.log(` Status: ${Y__default.default.green("Running")}`);else if(console.log(` Status: ${Y__default.default.red("Stopped")}`),u.session_id){let h=fs(u.platform).getResumeCommandStr(u.session_id,u.worktree_path);console.log(),console.log(Y__default.default.yellow(` Resume: ${h}`));}if(Ne.existsSync(u.worktree_path)){console.log(),console.log(Y__default.default.blue("=== Git Changes ===")),console.log();try{let d=child_process.execSync("git status --short",{cwd:u.worktree_path,encoding:"utf-8"});if(d.trim()){let h=d.trim().split(`
|
|
1118
1118
|
`);for(let _ of h.slice(0,10))console.log(` ${_}`);h.length>10&&console.log(` ... and ${h.length-10} more`);}else console.log(" (no changes)");}catch{console.log(" (could not get git status)");}}console.log();return}let i=fJe(t),n=i;if(s.running?n=i.filter(u=>u.running):s.stopped&&(n=i.filter(u=>!u.running)),e.json){B(e,J({agents:n}));return}let a=i.filter(u=>u.running).length,c=i.length;console.log(Y__default.default.blue("=== Swarm Status ===")),console.log(`Agents: ${Y__default.default.green(a.toString())} running / ${c} registered`),console.log();let o=n.filter(u=>u.running),l=n.filter(u=>!u.running);if(o.length>0){console.log(Y__default.default.cyan("Running:"));for(let u of o)console.log(` ${Y__default.default.green("\u25B6")} ${Y__default.default.cyan(u.id)} ${Y__default.default.green("[running]")}`),u.phase&&console.log(` Phase: ${u.phase}`),console.log(` Elapsed: ${u.elapsed}`),u.branch&&console.log(` Branch: ${Y__default.default.dim(u.branch)}`),console.log(` Modified: ${u.modifiedFiles} file(s)`),u.last_tool&&console.log(` Activity: ${Y__default.default.yellow(u.last_tool)}`),console.log(` PID: ${Y__default.default.dim(u.pid.toString())}`),console.log();}if(l.length>0){console.log(Y__default.default.red("Stopped:"));for(let u of l){if(console.log(` ${Y__default.default.red("\u25CB")} ${u.id} ${Y__default.default.red("[stopped]")}`),u.last_message&&console.log(` ${Y__default.default.dim(`"${u.last_message}"`)}`),u.session_id){let h=fs(u.platform).getResumeCommandStr(u.session_id,u.worktree_path);console.log(` ${Y__default.default.yellow(h)}`);}console.log();}}}async function N_t(e,t){let r=C5(t),s=wc(t);if(e.json){B(e,J({path:r,...s}));return}console.log(Y__default.default.blue("=== Agent Registry ===")),console.log(),console.log(`File: ${r}`),console.log(),console.log(JSON.stringify(s,null,2));}function q_t(e){let t=e.command("swarm").description("Manage multi-agent pipelines using git worktrees");t.command("list").description("List all git worktrees and registered agents").action(async()=>{let r=u0(e),s=Js();if(!s){Z(r,new Error("Not in a Viben workspace"));return}try{await F_t(r,s);}catch(i){Z(r,i);}}),t.command("start").description("[DEPRECATED] Start an agent in a worktree. Use 'viben task work-phase <task>' instead.").argument("<task>","Task name or directory").option("--executor <type>","Executor type (CLAUDE_CODE, CURSOR, etc.)").option("--detach","Run in background").option("--resume","Resume an existing session").option("--session <id>","Session ID for resume").action(async(r,s)=>{let i=u0(e),n=Js();if(console.log(Y__default.default.yellow("\u26A0\uFE0F DEPRECATED: 'viben swarm start' is deprecated.")),console.log(Y__default.default.yellow(" Please use 'viben task work-phase <task>' instead.")),console.log(Y__default.default.yellow(" This command will be removed in a future version.")),console.log(),!n){Z(i,new Error("Not in a Viben workspace"));return}try{await D_t(i,n,r,s);}catch(a){Z(i,a);}}),t.command("stop").description("Stop a running agent").argument("[task]","Task name (optional if --all)").option("--force","Force kill with SIGKILL").option("--all","Stop all running agents").action(async(r,s)=>{let i=u0(e),n=Js();if(!n){Z(i,new Error("Not in a Viben workspace"));return}try{await $_t(i,n,r,s);}catch(a){Z(i,a);}}),t.command("status").description("Show agent status").argument("[task]","Task name for specific agent status").option("--running","Show only running agents").option("--stopped","Show only stopped agents").option("--detail","Show detailed status").option("--watch","Watch agent log in real-time").option("--log","Show recent log entries").action(async(r,s)=>{let i=u0(e),n=Js();if(!n){Z(i,new Error("Not in a Viben workspace"));return}try{await R_t(i,n,r,s);}catch(a){Z(i,a);}}),t.command("registry").description("Show agent registry").action(async()=>{let r=u0(e),s=Js();if(!s){Z(r,new Error("Not in a Viben workspace"));return}try{await N_t(r,s);}catch(i){Z(r,i);}}),t.command("cleanup-registry").description("Remove dead agents from registry").action(async()=>{let r=u0(e),s=Js();if(!s){Z(r,new Error("Not in a Viben workspace"));return}try{let i=yme(s);B(r,J({removedCount:i.removedCount,removedIds:i.removedIds}),()=>{if(i.removedCount===0)console.log(Y__default.default.gray("No dead agents to clean up"));else {console.log(Y__default.default.green(`Removed ${i.removedCount} dead agent(s) from registry:`));for(let n of i.removedIds)console.log(Y__default.default.gray(` - ${n}`));}});}catch(i){Z(r,i);}});}var ETe,L_t=$({"src/cli/commands/swarm.ts"(){wr(),_A(),Vt(),ETe={CLAUDE_CODE:"claude",CURSOR:"cursor",GEMINI:"gemini",OPENCODE:"opencode",IFLOW:"iflow",CODEX:"codex",KILO:"kilo",KIRO:"kiro",ANTIGRAVITY:"antigravity"};}}),TTe={};yt(TTe,{registerTaskCommand:()=>G_t});async function U_t(e,t){let r=Mk(t),s=wc(t);if(e.json){B(e,J({worktrees:r,agents:s.agents}));return}if(console.log(Y__default.default.blue("=== Git Worktrees ===")),console.log(),r.length===0)console.log(" (no worktrees)");else {console.log("PATH".padEnd(50)+"COMMIT".padEnd(10)+"BRANCH");for(let i of r)console.log(i.path.padEnd(50)+i.commit.substring(0,7).padEnd(10)+`[${i.branch||"(detached)"}]`);}if(console.log(),console.log(Y__default.default.blue("=== Registered Agents ===")),console.log(),s.agents.length===0)console.log(" (no agents registered)");else for(let i of s.agents){let n=Q0(i.pid)?Y__default.default.green("\u25CF"):Y__default.default.red("\u25CB");console.log(` ${n} ${i.id} (PID: ${i.pid})`),console.log(Y__default.default.dim(` Worktree: ${i.worktree_path}`)),console.log(Y__default.default.dim(` Started: ${i.started_at}`)),console.log();}}async function B_t(e,t,r,s){if(s.list){await U_t(e,t);return}if(s.merged){e.quiet||(console.log(Y__default.default.blue("=== Cleaning Merged Worktrees ===")),console.log());let n=await kJe(t,{keepBranch:s.keepBranch,skipConfirm:s.yes});if(e.json){B(e,J({results:n}));return}if(n.length===0)console.log("No merged worktrees found");else for(let a of n)a.success?console.log(Y__default.default.green(`Cleaned: ${a.branch}`)):console.log(Y__default.default.red(`Failed: ${a.branch} - ${a.error}`));return}if(s.all){e.quiet||(console.log(Y__default.default.blue("=== Cleaning All Worktrees ===")),console.log(Y__default.default.red("WARNING: This will remove ALL worktrees!")),console.log());let n=await EJe(t,{keepBranch:s.keepBranch,skipConfirm:s.yes});if(e.json){B(e,J({results:n}));return}if(n.length===0)console.log("No worktrees to remove");else for(let a of n)a.success?console.log(Y__default.default.green(`Cleaned: ${a.branch}`)):console.log(Y__default.default.red(`Failed: ${a.branch} - ${a.error}`));return}if(!r){B(e,ot("MISSING_ARG","Branch name or --merged/--all required"),()=>{console.error(Y__default.default.red("Error: Branch name or --merged/--all required")),console.log(),console.log("Usage:"),console.log(Y__default.default.gray(" viben task cleanup <branch> Remove specific worktree")),console.log(Y__default.default.gray(" viben task cleanup --merged Remove merged worktrees")),console.log(Y__default.default.gray(" viben task cleanup --all Remove all worktrees")),console.log(Y__default.default.gray(" viben task cleanup --list List all worktrees"));}),process.exit(1);return}e.quiet||(console.log(Y__default.default.blue(`=== Cleaning Worktree: ${r} ===`)),console.log());let i=await yA(t,r,{keepBranch:s.keepBranch,skipConfirm:s.yes});if(e.json){i.success?B(e,J(i)):B(e,ot("CLEANUP_FAILED",i.error||"Unknown error"));return}i.success?(console.log(Y__default.default.green(`Cleanup complete for: ${r}`)),i.archived&&console.log(` Archived: ${i.archived}`),i.worktreeRemoved&&console.log(" Worktree removed"),i.branchDeleted&&console.log(" Branch deleted")):(console.error(Y__default.default.red(`Error: ${i.error}`)),process.exit(1));}function bt(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}function wt(e){let t=Js(e);if(!t)throw ne.operationFailed("Task command",'Not a Viben workspace (.viben not found). Run "viben init" first.');return t}function G_t(e){let t=e.command("task").description("Manage development tasks");t.command("list").description("List all tasks, or view task details if task is specified").argument("[task]","Task name or directory (if specified, shows task details)").option("-m, --mine","Show only tasks assigned to current developer").option("-s, --status <status>","Filter by status (backlog, queue, in_progress, review, completed)").option("--json","Output in JSON format").action(async(s,i)=>{let n=bt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=wt(a);if(s){let u=Ul(c,s);if(!u.success)throw ne.notFound("Task",s);let d=u.task,h=u.files;B(n,J({task:d,task_dir:u.task_dir,dir_name:u.dir_name,files:h,runtime:u.runtime}),()=>{if(console.log(Y__default.default.bold.cyan(`=== ${d.title} ===`)),console.log(),et(n,{Status:Um(d.status),Priority:O4(d.priority),Assignee:d.assignee||"-",Branch:d.branch||"-",Phase:`${d.current_phase||0}`,"PR URL":d.pr_url||Y__default.default.gray("(none)")}),h.prd.exists||h.implement_jsonl.exists){console.log();let y=[];h.prd.exists&&y.push("prd.md"),h.implement_jsonl.exists&&y.push("implement.jsonl"),h.check_jsonl.exists&&y.push("check.jsonl"),console.log(Y__default.default.gray(`Files: ${y.join(", ")}`));}d.description&&(console.log(),console.log(Y__default.default.gray(d.description))),console.log(),console.log(Y__default.default.dim(`Use 'viben task view ${u.dir_name}' for full details`));});return}let o=uve(c,{mine:i.mine,status:i.status});if(!o.success)throw ne.operationFailed("List tasks",o.error);let{tasks:l}=o;B(n,J({tasks:l}),()=>{if(i.mine){let u=cn(c);console.log(Y__default.default.blue(`My tasks (assignee: ${u}):`));}else console.log(Y__default.default.blue("All active tasks:"));if(console.log(),l.length===0)i.mine?console.log(" (no tasks assigned to you)"):console.log(" (no active tasks)");else for(let u of l)i.mine?console.log(` - ${u.dir}/ (${Um(u.status)})`):console.log(` - ${u.dir}/ (${Um(u.status)}) [${Y__default.default.cyan(u.assignee)}]`);console.log(),console.log(`Total: ${l.length} task(s)`);});}catch(c){Z(n,c);}}),t.command("create").description("Create a new task").argument("<title>","Task title (used as commit/PR title)").option("-s, --slug <name>","Task identifier (auto-generated from title if not provided)").option("-b, --branch <branch>","Custom branch name (default: feature/<slug>)").option("-a, --assignee <dev>","Assignee developer name").option("-p, --priority <priority>","Priority (urgent, high, medium, low, none)","medium").option("-d, --description <text>","Task description").option("--agent <agent-id>","Associated agent configuration").option("--executor <type>","Executor type (CLAUDE_CODE, CURSOR, etc.)").option("--model <model>","Model to use for execution").option("--start","Auto-enqueue task for execution (status: queue)").option("--worktree","Run agent in a git worktree (isolated branch)").option("--compute-reward","Enable compute-reward phase after create-pr").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=sC(c,s,i);if(!o.success)throw ne.operationFailed("Create task",o.error);let{dir_name:l,status:u,context_initialized:d}=o,h=`${Qt}/${un}/${l}`;if(i.start&&l){let _=await kP(c,l,{agent:i.agent,executor:i.executor,model:i.model,priority:i.priority,skipQueue:!1});if(!_.success){B(n,ot("ENQUEUE_FAILED",_.error||"Failed to enqueue task"),()=>{console.log(Y__default.default.yellow(`Created task: ${l}`)),console.log(Y__default.default.red(`Failed to enqueue: ${_.error}`)),console.log(Y__default.default.gray(`Run manually: viben task enqueue ${l}`));});return}let y=_.additionalData?.queue_id;B(n,J({task_dir:h,status:"queue",context_initialized:d,queueId:y}),()=>{console.log(Y__default.default.green(`Created and enqueued: ${l}`)),console.log(Y__default.default.gray("Status: backlog -> queue")),y&&console.log(Y__default.default.gray(`Queue ID: ${y}`)),i.worktree&&console.log(Y__default.default.gray("Worktree: enabled")),d&&console.log(Y__default.default.gray("Context: initialized (empty)"));});}else B(n,J({task_dir:h,context_initialized:d}),()=>{console.log(Y__default.default.green(`Created task: ${l}`)),console.log(),i.branch&&(console.log(Y__default.default.blue("Configured:")),console.log(` Branch: ${i.branch}`),console.log()),console.log(Y__default.default.blue("Next steps:")),console.log(" 1. Create prd.md with requirements"),console.log(" 2. Use research agent to add context (add-context)"),console.log(` 3. Run: viben task start ${l}`),console.log();});}catch(c){Z(n,c);}}),t.command("view").description("View task details").argument("<task>","Task name or directory").option("--json","Output in JSON format").action(async(s,i)=>{let n=bt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=wt(a),o=Ul(c,s);if(!o.success)throw ne.notFound("Task",s);let l=o.task,u=o.files,d=o.worktree;B(n,J({task:l,task_dir:o.task_dir,dir_name:o.dir_name,files:u,worktree:d,runtime:o.runtime,timing:o.timing}),()=>{if(console.log(Y__default.default.bold.cyan(`=== Task: ${l.title} ===`)),console.log(),console.log(Y__default.default.bold("Basic Info")),et(n,{ID:l.id||"-",Directory:o.dir_name||"-",Status:Um(l.status),Priority:O4(l.priority)}),console.log(),console.log(Y__default.default.bold("People")),et(n,{Creator:l.creator||"-",Assignee:l.assignee||"-"}),console.log(),console.log(Y__default.default.bold("Git")),et(n,{Branch:l.branch||"-","Base Branch":l.base_branch||"-","PR URL":l.pr_url||Y__default.default.gray("(none)")}),console.log(),console.log(Y__default.default.bold("Worktree")),d?.enabled||d?.path){let E=d.path?d.exists?d.isDirty?Y__default.default.yellow("active (dirty)"):Y__default.default.green("active (clean)"):Y__default.default.red("missing"):Y__default.default.gray("(not created)");et(n,{Mode:d.enabled?Y__default.default.green("enabled"):Y__default.default.gray("disabled"),Status:E}),d.path&&console.log(` Path: ${Y__default.default.gray(d.path)}`),d.branch&&console.log(` Branch: ${Y__default.default.cyan(d.branch)}`),d.isDirty&&d.uncommittedFiles&&console.log(` Changes: ${Y__default.default.yellow(`${d.uncommittedFiles} uncommitted file(s)`)}`);}else console.log(Y__default.default.gray(" (not using worktree)"));console.log(),console.log(Y__default.default.bold("Progress"));let h=["plan","implement","check","finish"],_=l.current_phase||0,y=h.map((E,A)=>A<_?Y__default.default.green(`${E} \u2713`):A===_?Y__default.default.yellow(`${E} \u25CF`):Y__default.default.gray(`${E} \u25CB`)).join(" \u2192 ");if(console.log(` ${y}`),l.next_action&&l.next_action.length>0){let E=l.next_action.map(A=>`${A.phase}:${A.action}`).join(" \u2192 ");console.log(` Next Actions: ${Y__default.default.gray(E)}`);}console.log(),console.log(Y__default.default.bold("Files"));let v=(E,A)=>{if(!E.exists)return Y__default.default.gray("(missing)");let D=E.size?`${(E.size/1024).toFixed(1)}KB`:"";return Y__default.default.green("\u2713")+" "+Y__default.default.gray(D)};console.log(` prd.md: ${v(u.prd,"prd.md")}`),console.log(` implement.jsonl: ${v(u.implement_jsonl,"implement.jsonl")}`),console.log(` check.jsonl: ${v(u.check_jsonl,"check.jsonl")}`),console.log(` fix.jsonl: ${v(u.fix_jsonl,"fix.jsonl")}`),console.log(),console.log(Y__default.default.bold("Logs"));let b=E=>{if(!E.exists)return Y__default.default.gray("-");let A=E.size?`${(E.size/1024).toFixed(1)}KB`:"",D=E.modifiedAt?new Date(E.modifiedAt).toLocaleString():"";return `${Y__default.default.green("\u2713")} ${Y__default.default.gray(A)} ${Y__default.default.dim(D)}`};u.start_log.exists&&console.log(` start.log.jsonl: ${b(u.start_log)}`),u.plan_log.exists&&console.log(` plan.log.jsonl: ${b(u.plan_log)}`),u.work_log.exists&&console.log(` work.log.jsonl: ${b(u.work_log)}`),u.implement_log.exists&&console.log(` implement.log.jsonl: ${b(u.implement_log)}`),u.review_log.exists&&console.log(` review.log.jsonl: ${b(u.review_log)}`),!u.start_log.exists&&!u.plan_log.exists&&!u.work_log.exists&&!u.implement_log.exists&&!u.review_log.exists&&console.log(Y__default.default.gray(" (no logs yet)")),console.log(),console.log(Y__default.default.bold("Timestamps"));let w={"Created At":l.created_at||"-"};l.queued_at&&(w["Queued At"]=l.queued_at),l.started_at&&(w["Started At"]=l.started_at),l.check_passed_at&&(w["Check Passed"]=l.check_passed_at),l.pr_created_at&&(w["PR Created"]=l.pr_created_at),l.completed_at&&(w["Completed At"]=l.completed_at),et(n,w);let S=o.timing;if(S){console.log(),console.log(Y__default.default.bold("Timing"));let E={};S.totalDurationStr&&(E.Total=S.totalDurationStr),S.executionDurationStr&&(E.Execution=S.executionDurationStr),S.queueDurationStr&&(E["Queue Wait"]=S.queueDurationStr),S.planDurationStr&&(E["Plan Phase"]=S.planDurationStr),S.implementDurationStr&&(E["Implement Phase"]=S.implementDurationStr),S.checkDurationStr&&(E["Check Phase"]=S.checkDurationStr),S.idleDurationStr&&l.status!=="completed"&&l.status!=="archived"&&(E.Idle=Y__default.default.yellow(S.idleDurationStr)),Object.keys(E).length>0?et(n,E):console.log(Y__default.default.gray(" (no timing data yet)"));}o.runtime?.session_id&&(console.log(),console.log(Y__default.default.bold("Session")),et(n,{"Session ID":o.runtime.session_id})),l.description&&(console.log(),console.log(Y__default.default.bold("Description")),console.log(Y__default.default.gray(l.description))),l.notes&&(console.log(),console.log(Y__default.default.bold("Notes")),console.log(Y__default.default.gray(l.notes))),console.log();});}catch(c){Z(n,c);}}),t.command("edit").description("Edit task (opens editor)").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),{result:c}=int(a,s,{onClose:o=>{o===0&&Ue(i,`Edited task: ${s}`);}});if(!c.success)throw ne.notFound("Task",s)}catch(a){Z(i,a);}}),t.command("delete").description("Delete a task").argument("<task>","Task name or directory").option("-f, --force","Skip confirmation").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a);if(!Ul(c,s).success)throw ne.notFound("Task",s);if(!i.force&&!n.quiet){console.log(Y__default.default.yellow(`Warning: This will permanently delete task "${s}".`)),console.log(Y__default.default.gray("Use --force to skip this warning"));return}let l=lve(c,s);if(!l.success)throw ne.operationFailed("Delete task",l.error);B(n,J({deleted:s}),()=>{Ue(n,`Deleted task: ${s}`);});}catch(c){Z(n,c);}}),t.command("update").description("Update task fields").argument("<task>","Task name or directory").option("--title <title>","Update task title").option("--description <desc>","Update task description").option("--agent <agent>","Update associated agent").option("--executor <executor>","Update executor type").option("--model <model>","Update model").option("--priority <priority>","Update priority (P0/P1/P2/P3 or urgent/high/medium/low/none)").option("--branch <branch>","Update git branch").option("--base-branch <branch>","Update PR target branch").option("--assignee <name>","Update assignee").option("--notes <notes>","Update notes").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o||!Ne.existsSync(o))throw ne.notFound("Task",s);let l=Mt(o);if(!l)throw ne.operationFailed("Update task",`Failed to read task.json for: ${s}`);let u={};if(i.title!==void 0&&(l.title=i.title,u.title=i.title),i.description!==void 0&&(l.description=i.description,u.description=i.description),i.agent!==void 0&&(l.agent=i.agent,u.agent=i.agent),i.executor!==void 0&&(l.executor=i.executor,u.executor=i.executor),i.model!==void 0&&(l.model=i.model,u.model=i.model),i.priority!==void 0){let d=i.priority.toLowerCase(),h={p0:"urgent",p1:"high",p2:"medium",p3:"low"};h[d]&&(d=h[d]),l.priority=d,u.priority=d;}if(i.branch!==void 0&&(l.branch=i.branch,u.branch=i.branch),i.baseBranch!==void 0&&(l.base_branch=i.baseBranch,u.base_branch=i.baseBranch),i.assignee!==void 0&&(l.assignee=i.assignee,u.assignee=i.assignee),i.notes!==void 0&&(l.notes=i.notes,u.notes=i.notes),Object.keys(u).length===0){B(n,ot("NO_FIELDS","No fields to update. Use --help to see available options."),()=>{console.log(Y__default.default.yellow("No fields to update.")),console.log(),console.log("Available options:"),console.log(" --title <title> Update task title"),console.log(" --description <desc> Update task description"),console.log(" --agent <agent> Update associated agent"),console.log(" --executor <executor> Update executor type"),console.log(" --model <model> Update model"),console.log(" --priority <priority> Update priority (P0/P1/P2/P3)"),console.log(" --branch <branch> Update git branch"),console.log(" --base-branch <branch> Update PR target branch"),console.log(" --assignee <name> Update assignee"),console.log(" --notes <notes> Update notes");});return}if(l.updated_at=new Date().toISOString(),!xs(o,l))throw ne.operationFailed("Update task","Failed to write task.json");B(n,J({task:s,updated_fields:u}),()=>{console.log(Y__default.default.green(`Updated task: ${s}`)),console.log(),console.log(Y__default.default.blue("Updated fields:"));for(let[d,h]of Object.entries(u))console.log(` ${d}: ${h}`);});}catch(c){Z(n,c);}}),t.command("start").description("Start task execution (serial mode by default, use --worktree for parallel)").argument("<task>","Task name or directory").option("--executor <type>","Executor type (CLAUDE_CODE, CURSOR, etc.)").option("--detach","Run in background").option("--worktree","Run in isolated git worktree (parallel mode)").option("--resume","Resume an existing session").option("--session <id>","Session ID for resume").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o||!Ne.existsSync(o)){B(n,ot("TASK_NOT_FOUND",`Task not found: ${s}`),()=>{console.error(Y__default.default.red(`Error: Task not found: ${s}`)),console.log(Y__default.default.gray("Use 'viben task list' to see available tasks"));}),process.exit(1);return}let l;try{l=qe.relative(c,o);}catch{l=o;}let u=Mt(o);if(i.resume){let _=i.session;if(!_&&u?.session_id&&(_=u.session_id),!_){B(n,ot("NO_SESSION","No session ID found for resume"),()=>{console.error(Y__default.default.red("Error: No session ID found for resume")),console.log(Y__default.default.gray("No sessionId in task.json and no --session provided"));}),process.exit(1);return}let y=u?.executor||"claude",b=fs(y).buildResumeCommand(_);n.quiet||(console.log(Y__default.default.blue("=== Resuming Agent ===")),console.log(` Session: ${_}`),console.log(` Task: ${l}`),console.log(` Command: ${b.join(" ")}`),console.log()),child_process.spawn(b[0],b.slice(1),{cwd:o,stdio:"inherit"}).on("close",S=>{process.exit(S??0);});return}let d=i.executor&&xTe[i.executor.toUpperCase()]||"claude";n.quiet||(console.log(Y__default.default.blue("=== Task Start ===")),console.log(`[INFO] Task: ${l}`),console.log(`[INFO] Platform: ${d}`));let h=await Ove(c,l,{platform:d,detach:i.detach??!0,skipPermissions:!0,verbose:n.verbose});if(n.json)h.success?B(n,J(h)):B(n,ot("START_FAILED",h.error||"Unknown error"));else if(h.success){if(console.log(),console.log(Y__default.default.green("=== Task Started ===")),console.log(),console.log(` ID: ${h.agent_id}`),console.log(` PID: ${h.pid}`),console.log(` Session: ${h.session_id||"N/A"}`),console.log(` Working: ${h.working_dir}`),console.log(` Log: ${h.log_file}`),console.log(),console.log(Y__default.default.yellow(`To monitor: tail -f ${h.log_file}`)),console.log(Y__default.default.yellow(`To stop: kill ${h.pid}`)),h.session_id){let y=fs(d).getResumeCommandStr(h.session_id,h.working_dir);console.log(Y__default.default.yellow(`To resume: ${y}`));}}else console.error(Y__default.default.red(`Error: ${h.error}`)),process.exit(1);}catch(c){Z(n,c);}}),t.command("finish").description("Finish a task (clears current task if it matches)").argument("<task>","Task name or directory to finish").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=dve(a,s);if(!c.success)throw ne.operationFailed("Finish task",c.error);B(i,J({finished:c.cleared}),()=>{console.log(Y__default.default.green(`Finished task: ${c.cleared}`));});}catch(a){Z(i,a);}}),t.command("archive").description("Archive completed task").argument("<task>","Task name").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=pve(a,s);if(!c.success)throw ne.operationFailed("Archive task",c.error);B(i,J({archived:c.archived,to:c.destination}),()=>{console.log(Y__default.default.green(`Archived: ${c.archived} -> ${c.destination}`));});}catch(a){Z(i,a);}}),t.command("list-archive").description("List archived tasks").argument("[month]","Filter by month (YYYY-MM)").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=hve(a,s),{archived:o}=c;B(i,J({archived:Object.fromEntries(o)}),()=>{if(console.log(Y__default.default.blue("Archived tasks:")),console.log(),o.size===0)console.log(s?` No archives for ${s}`:" (no archived tasks)");else for(let[l,u]of Array.from(o.entries()))if(s){console.log(`[${l}]`);for(let d of u)console.log(` - ${d}/`);}else console.log(`[${l}] - ${u.length} task(s)`);});}catch(a){Z(i,a);}}),t.command("enqueue").description("Move task from backlog to queue for execution").argument("<task>","Task name or directory").option("--agent <id>","Agent ID to execute this task").option("--executor <type>","Executor type (CLAUDE_CODE, CURSOR, OPENCODE, etc.)").option("--model <id>","Model ID for execution").option("--priority <p>","Priority (urgent/high/medium/low/none)").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=await kP(c,s,i);if(!o.success)throw ne.operationFailed("Enqueue task",o.error);B(n,J({task:o.task,status:o.status}),()=>{console.log(Y__default.default.green(`Enqueued: ${o.task}`)),console.log(Y__default.default.gray(`Status: ${o.fromStatus} -> ${o.status}`)),i.agent&&console.log(Y__default.default.gray(`Agent: ${i.agent}`)),i.executor&&console.log(Y__default.default.gray(`Executor: ${i.executor}`)),i.model&&console.log(Y__default.default.gray(`Model: ${i.model}`));});}catch(c){Z(n,c);}}),t.command("dequeue").description("Remove task from queue back to backlog").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=await Z_e(a,s);if(!c.success)throw ne.operationFailed("Dequeue task",c.error);B(i,J({task:c.task,status:c.status}),()=>{console.log(Y__default.default.green(`Dequeued: ${c.task}`)),console.log(Y__default.default.gray(`Status: ${c.fromStatus} -> ${c.status}`));});}catch(a){Z(i,a);}}),t.command("pause").description("Pause execution of a task").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=await eve(a,s);if(!c.success)throw ne.operationFailed("Pause task",c.error);B(i,J({task:c.task,status:c.status,fromState:c.fromStatus}),()=>{console.log(Y__default.default.green(`Paused: ${c.task}`)),console.log(Y__default.default.gray(`Status: ${c.fromStatus} -> paused`));});}catch(a){Z(i,a);}}),t.command("resume").description("Resume a paused task").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=await tve(a,s);if(!c.success)throw ne.operationFailed("Resume task",c.error);B(i,J({task:c.task,status:c.status}),()=>{console.log(Y__default.default.green(`Resumed: ${c.task}`)),console.log(Y__default.default.gray(`Status: paused -> ${c.status}`));});}catch(a){Z(i,a);}}),t.command("set-branch").description("Set Git branch for task").argument("<task>","Task name or directory").requiredOption("-b, --branch <name>","Branch name").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=fve(c,s,i.branch);if(!o.success)throw ne.operationFailed("Set branch",o.error);B(n,J({task:s,branch:i.branch}),()=>{console.log(Y__default.default.green(`Branch set to: ${i.branch}`)),console.log(),console.log(Y__default.default.blue("Now you can start the multi-agent pipeline:")),console.log(` viben task plan --name ${s} ...`);});}catch(c){Z(n,c);}}),t.command("set-base").description("Set PR target branch").argument("<task>","Task name or directory").requiredOption("-b, --branch <name>","Base branch name").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=gve(c,s,i.branch);if(!o.success)throw ne.operationFailed("Set base branch",o.error);B(n,J({task:s,base_branch:i.branch}),()=>{console.log(Y__default.default.green(`Base branch set to: ${i.branch}`)),console.log(` PR will target: ${i.branch}`);});}catch(c){Z(n,c);}}),t.command("set-agent").description("Set associated agent configuration").argument("<task>","Task name or directory").requiredOption("-a, --agent <id>","Agent ID").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=yve(c,s,i.agent);if(!o.success)throw ne.operationFailed("Set agent",o.error);B(n,J({task:s,agent:i.agent}),()=>{Ue(n,`Set agent "${i.agent}" for task "${s}"`);});}catch(c){Z(n,c);}}),t.command("init-context").description("Initialize empty context files for task (to be populated by research)").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=dz(a,s);if(!c.success)throw ne.operationFailed("Initialize context",c.error);B(i,J({task_dir:c.taskDir,files:c.files}),()=>{console.log(Y__default.default.green(`Initialized context files for: ${s}`)),console.log(),console.log("Created:"),console.log(" - implement.jsonl (empty)"),console.log(" - check.jsonl (empty)"),console.log(" - fix.jsonl (empty)"),console.log(),console.log(Y__default.default.blue("Next steps:")),console.log(" 1. Use research agent or add-context to populate specs"),console.log(" 2. Run: viben task start <task>");});}catch(a){Z(i,a);}}),t.command("add-context").description("Add context files to task").argument("<task>","Task name or directory").argument("<files...>","Files to add").option("-r, --reason <text>","Reason for adding").option("--recursive","Recursively add directory contents").action(async(s,i,n)=>{let a=bt(e),c=process.cwd();try{let o=wt(c),l=sve(o,s,i,n);if(!l.success)throw ne.operationFailed("Add context",l.error);B(a,J({added:l.added,skipped:l.skipped,total:l.total}),()=>{l.skipped>0&&console.log(Y__default.default.yellow(`Skipped ${l.skipped} existing file(s)`)),console.log(Y__default.default.blue(`Added ${l.added}/${l.total} file(s) to implement.jsonl`));});}catch(o){Z(a,o);}}),t.command("remove-context").description("Remove context files from task").argument("<task>","Task name or directory").argument("<files...>","Files to remove").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=ive(c,s,i);if(!o.success)throw ne.operationFailed("Remove context",o.error);B(n,J({removed:o.removed}),()=>{Ue(n,`Removed ${o.removed.length} context file(s) from task "${s}"`);});}catch(c){Z(n,c);}}),t.command("list-context").description("List context entries for task").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=nve(a,s);if(!c.success)throw ne.operationFailed("List context",c.error);B(i,J(c.context),()=>{console.log(Y__default.default.blue(`Context entries for task: ${s}`)),console.log();for(let[o,l]of Object.entries(c.context)){if(console.log(Y__default.default.cyan(`[${o}]`)),l.length===0)console.log(" (empty)");else for(let u of l){let d=u.type?Y__default.default.gray(` [${u.type}]`):"";console.log(` - ${u.file}${d}`),u.reason&&console.log(Y__default.default.gray(` Reason: ${u.reason}`));}console.log();}});}catch(a){Z(i,a);}}),t.command("validate-context").description("Validate context files (check referenced files exist)").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=ove(a,s);if(c.error)throw ne.operationFailed("Validate context",c.error);B(i,J({valid:c.valid.length,missing:c.missing}),()=>{if(console.log(Y__default.default.blue(`Validating context files for task: ${s}`)),console.log(),c.success)console.log(Y__default.default.green(`All ${c.valid.length} referenced files exist.`));else {console.log(Y__default.default.yellow(`Found ${c.missing.length} missing file(s):`));for(let o of c.missing)console.log(Y__default.default.red(` - ${o}`));console.log(),console.log(Y__default.default.gray(`Valid: ${c.valid.length}, Missing: ${c.missing.length}`));}});}catch(a){Z(i,a);}}),t.command("status").description("Show task status").argument("[task]","Specific task to show (shows all if not specified)").option("-a, --assignee <dev>","Filter by assignee").option("-s, --status <status>","Filter by status (backlog, queue, in_progress, review, completed)").option("--running","Show only tasks with running agents").option("--json","Output in JSON format").option("--list","List all worktrees and agents").option("--detail","Show detailed status (for specific task)").option("--watch","Watch agent log in real-time (for specific task)").option("--log","Show recent log entries (for specific task)").option("--registry","Show agent registry").action(async(s,i)=>{let n=bt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=wt(a);if(i.registry){wit(c,n);return}if(i.list){_it(c,n);return}if(s){i.detail?_oe(s,c,n):i.watch?vit(s,c,n):i.log?bit(s,c,n):_oe(s,c,n);return}yit(c,{filter_assignee:i.assignee,filter_status:i.status,only_running:i.running},n);}catch(c){Z(n,c);}}),t.command("create-pr").description("Create PR from task").argument("<task>","Task name or directory").option("--dry-run","Show what would be done without making changes").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=i.dryRun||!1;console.log(Y__default.default.blue("=== Create PR ===")),o&&console.log(Y__default.default.yellow("[DRY-RUN MODE] No actual changes will be made")),console.log();let l=wve(c,s,{dry_run:o});if(!l.success)throw console.log(Y__default.default.red(`Error: ${l.error}`)),l.help&&(console.log(),console.log(Y__default.default.cyan("How to fix:")),console.log(l.help)),ne.operationFailed("Create PR",l.error||"Unknown error");if(console.log(`Task: ${l.task_name}`),console.log(`Base branch: ${l.base_branch}`),console.log(`Current branch: ${l.current_branch}`),console.log(),o&&l.dry_run_info){if(l.had_staged_changes){console.log(`[DRY-RUN] Would commit with message: ${l.commit_message}`),console.log("[DRY-RUN] Staged files:");for(let u of l.dry_run_info.staged_files)console.log(` - ${u}`);}else l.unpushed_commits&&console.log(`Found ${l.unpushed_commits} unpushed commit(s)`);l.local_only?console.log("[DRY-RUN] No remote detected, would skip push and PR creation"):(console.log(`[DRY-RUN] Would push to: origin/${l.current_branch}`),console.log("[DRY-RUN] Would create PR:"),console.log(` Title: ${l.dry_run_info.pr_title}`),console.log(` Base: ${l.dry_run_info.pr_base}`),console.log(` Head: ${l.dry_run_info.pr_head}`),console.log(` pr_url: ${l.pr_url}`)),console.log("[DRY-RUN] Would update task.json:"),console.log(" status: review");}else if(l.local_only){let u={NO_REMOTE:"No remote configured",NOT_GITHUB:"Remote is not GitHub",GH_NOT_INSTALLED:"GitHub CLI not installed",GH_AUTH_REQUIRED:"GitHub CLI not authenticated"},d=l.error_code?u[l.error_code]||"Unknown reason":"No remote";console.log(Y__default.default.yellow(`=== Local-Only Mode (${d}) ===`)),console.log(),l.had_staged_changes?console.log(Y__default.default.green(`Committed: ${l.commit_message}`)):l.unpushed_commits&&console.log(`Found ${l.unpushed_commits} unpushed commit(s)`),l.error_code&&["NOT_GITHUB","GH_NOT_INSTALLED","GH_AUTH_REQUIRED"].includes(l.error_code)&&console.log(Y__default.default.green(`Pushed to origin/${l.current_branch}`)),console.log(Y__default.default.green("Task status updated to 'review'")),l.help&&(console.log(),console.log(Y__default.default.cyan("Next steps:")),console.log(l.help));}else l.had_staged_changes?console.log(Y__default.default.green(`Committed: ${l.commit_message}`)):l.unpushed_commits&&console.log(`Found ${l.unpushed_commits} unpushed commit(s)`),console.log(Y__default.default.green(`Pushed to origin/${l.current_branch}`)),console.log(Y__default.default.green("Task status updated to 'review'"));console.log(),l.local_only?console.log(Y__default.default.green("=== Ready for Review (Local) ===")):(console.log(Y__default.default.green("=== PR Created Successfully ===")),console.log(`PR URL: ${l.pr_url}`));}catch(c){Z(n,c);}}),t.command("review").description("View task details for review").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=vve(a,s);if(!c.success)throw ne.notFound("Task",s);let{task:o,dirName:l,prInfo:u}=c;B(i,J({task:l,...o,prInfo:u}),()=>{console.log(Y__default.default.bold(`=== Task Review: ${l} ===`)),console.log(),console.log(`Title: ${o.title}`),console.log(`Status: ${Um(o.status)}`),console.log(`Priority: ${O4(o.priority)}`),console.log(),o.pr_url&&(console.log(`PR URL: ${Y__default.default.cyan(o.pr_url)}`),console.log(`Branch: ${o.branch||"-"}`),console.log(),u?.changedFiles&&(console.log(`Files Changed: ${u.changedFiles}`),console.log(`+${u.additions||0} -${u.deletions||0}`),console.log())),o.status==="review"?(console.log(Y__default.default.blue("Next steps:")),console.log(` viben task approve ${l} # Approve and complete`),console.log(` viben task reject ${l} # Reject and return to backlog`)):o.status==="failed"&&(console.log(Y__default.default.blue("Next steps:")),console.log(` viben task retry ${l} # Retry failed task`));});}catch(a){Z(i,a);}}),t.command("approve").description("Approve task and mark as completed (auto-merges PR if exists)").argument("<task>","Task name or directory").option("--skip-merge","Skip PR merge (just update status)").option("--cleanup-if-merged","Clean up worktree and branch after PR is merged").option("--pull-if-merged","Git pull to sync merged code to local after PR is merged").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o)throw ne.notFound("Task",s);let l=Mt(o);if(!l)throw ne.operationFailed("Read task","Cannot read task.json");n.quiet||(console.log(Y__default.default.blue("=== Task Approve ===")),console.log(`Task: ${s}`),l.pr_url&&console.log(`PR: ${l.pr_url}`),l.worktree_path&&console.log(`Worktree: ${l.worktree_path}`),console.log());let u=await uz(c,s,{skipMerge:i.skipMerge,cleanupIfMerged:i.cleanupIfMerged,pullIfMerged:i.pullIfMerged});if(!u.success)throw ne.operationFailed("Approve task",u.error);let d=u.additionalData?.merge_commit,h=u.additionalData?.worktreeCleanup,_=u.additionalData?.pullResult;B(n,J({task:u.task,status:u.status,merge_commit:d,merged_at:u.additionalData?.merged_at,worktree_cleanup:h,pull_result:_}),()=>{console.log(Y__default.default.green(`Approved: ${u.task}`)),console.log(Y__default.default.gray(`Status: ${u.fromStatus} -> completed`)),d&&console.log(Y__default.default.gray(`Merge commit: ${d}`)),_?.success&&console.log(Y__default.default.gray("Git pull: synced")),h&&(h.worktreeRemoved&&console.log(Y__default.default.gray("Worktree: removed")),h.branchDeleted&&console.log(Y__default.default.gray("Local branch: deleted"))),console.log(),console.log(Y__default.default.blue("Next steps:")),l.worktree_path&&!i.cleanupIfMerged&&console.log(` viben task cleanup ${u.task} # Clean up worktree`),console.log(` viben task archive ${u.task} # Archive completed task`);});}catch(c){Z(n,c);}}),t.command("reject").description("Reject task and return to backlog").argument("<task>","Task name or directory").option("--reason <text>","Reason for rejection").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=await rve(c,s,i.reason);if(!o.success)throw ne.operationFailed("Reject task",o.error);B(n,J({task:o.task,status:o.status,reason:i.reason}),()=>{console.log(Y__default.default.yellow(`Rejected: ${o.task}`)),console.log(Y__default.default.gray(`Status: ${o.fromStatus} -> backlog`)),i.reason&&console.log(Y__default.default.gray(`Reason: ${i.reason}`));});}catch(c){Z(n,c);}}),t.command("retry").description("Retry a failed task").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=await ave(a,s);if(!c.success)throw ne.operationFailed("Retry task",c.error);B(i,J({task:c.task,status:c.status}),()=>{console.log(Y__default.default.green(`Retrying: ${c.task}`)),console.log(Y__default.default.gray(`Status: ${c.fromStatus} -> queue`));});}catch(a){Z(i,a);}});let r=async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=await lz(c,s,i);if(!o.success)throw ne.operationFailed("Cancel task",o.error);B(n,J({task:o.task,status:o.status,reason:i.reason}),()=>{console.log(Y__default.default.red(`Cancelled: ${o.task}`)),console.log(Y__default.default.gray(`Status: ${o.fromStatus} -> cancelled`)),i.reason&&console.log(Y__default.default.gray(`Reason: ${i.reason}`));});}catch(c){Z(n,c);}};t.command("cancel").description("Cancel a task (enters cancelled state)").argument("<task>","Task name or directory").option("--reason <text>","Cancellation reason").option("-f, --force","Force cancel a running (in_progress) task").action(r),t.command("stop").description("Stop a task (alias for cancel)").argument("<task>","Task name or directory").option("--reason <text>","Cancellation reason").option("-f, --force","Force stop a running (in_progress) task").action(r),t.command("context").description("Get session context for AI agents").argument("<task>","Task name or directory").option("-j, --json","Output in JSON format").action(async(s,i)=>{let n=bt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o||!Ne.existsSync(o))throw ne.notFound("Task",s);if(n.json){let l=U_e(c,o);B(n,J(l),()=>{});}else {let l=B_e(c,o);B(n,J({context:l}),()=>{console.log(l);});}}catch(c){Z(n,c);}}),t.command("add-session").description("Add a new session to journal file and update index.md").requiredOption("--title <title>","Session title").option("--commit <hashes>","Comma-separated commit hashes","-").option("--summary <summary>","Brief summary","(Add summary)").option("--content <content>","Detailed content","(Add details)").action(async s=>{let i=bt(e),n=process.cwd(),a=2e3;try{let c=wt(n),o=cn(c);if(!o)throw ne.operationFailed("Add session","Developer not initialized. Run 'viben init' first.");let l=qe.join(c,Qt,Kn,o);if(!Ne.existsSync(l))throw ne.operationFailed("Add session",`Workspace directory not found: ${l}`);let u=qe.join(l,"index.md"),d=Y0(),h=R_e(l),y=N_e(u)+1,v=q_e({session_num:y,title:s.title,commit:s.commit,summary:s.summary,extra_content:s.content,date:d}),b=v.split(`
|
|
1119
1119
|
`).length;console.log(Y__default.default.blue("========================================")),console.log(Y__default.default.blue("ADD SESSION")),console.log(Y__default.default.blue("========================================")),console.log(),console.log(`Session: ${y}`),console.log(`Title: ${s.title}`),console.log(`Commit: ${s.commit}`),console.log(),console.log(`Current journal file: journal-${h.number}.md`),console.log(`Current lines: ${h.lines}`),console.log(`New content lines: ${b}`),console.log(`Total after append: ${h.lines+b}`),console.log();let w=h.file,S=h.number;h.lines+b>a&&(S=h.number+1,console.log(Y__default.default.yellow(`[!] Exceeds ${a} lines, creating journal-${S}.md`)),w=SP(l,S,o,d,h.number),console.log(`Created: ${w}`)),w||(S=1,w=SP(l,S,o,d,0),console.log(`Created initial: ${w}`));let E=Ne.readFileSync(w,"utf-8");Ne.writeFileSync(w,E+v,"utf-8"),console.log(Y__default.default.green(`[OK] Appended session to ${qe.basename(w)}`)),console.log(),console.log("Updating index.md...");let A=`journal-${S}.md`,D=L_e({index_path:u,dev_dir:l,session_num:y,title:s.title,commit:s.commit,active_file:A,date:d});console.log(D?Y__default.default.green("[OK] Updated index.md successfully!"):Y__default.default.yellow("[!] Could not update index.md (markers not found or file missing)")),console.log(),console.log(Y__default.default.green("========================================")),console.log(Y__default.default.green(`[OK] Session ${y} added successfully!`)),console.log(Y__default.default.green("========================================")),console.log(),console.log("Files updated:"),console.log(` - ${qe.basename(w)}`),console.log(" - index.md"),B(i,J({session:y,journalFile:A,title:s.title}),()=>{});}catch(c){Z(i,c);}}),t.command("plan-phase").description("Run plan phase for an existing task (spawns plan agent)").argument("<task>","Task name or directory").option("-p, --platform <platform>","Platform (claude, cursor, iflow, opencode)","claude").option("-v, --verbose","Enable verbose output").option("--detach","Run in background (default: foreground)").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(Y__default.default.blue("=== Plan Phase ===")),console.log(Y__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(Y__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log(Y__default.default.cyan("[INFO]"),`Mode: ${i.detach?"background":"foreground"}`),console.log();let l=await Pve(c,o,{platform:i.platform,verbose:i.verbose,detach:i.detach??!1});if(l.success)console.log(Y__default.default.green("=== Plan Agent Started ===")),console.log(),console.log(` ID: ${l.agentId}`),console.log(` PID: ${l.pid}`),console.log(` Log: ${l.logFile}`),console.log(),console.log(Y__default.default.yellow("To monitor:")),console.log(` tail -f ${l.logFile}`),console.log(),B(n,J(l));else throw ne.operationFailed("Plan Phase",l.error||"Unknown error")}catch(c){Z(n,c);}}),t.command("implement-phase").description("Run implement phase for a task (spawns implement agent)").argument("<task>","Task name or directory").option("-p, --platform <platform>","Platform (claude, cursor, iflow, opencode)","claude").option("-v, --verbose","Enable verbose output").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(Y__default.default.blue("=== Implement Phase ===")),console.log(Y__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(Y__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log();let l=await Ave(c,o,{platform:i.platform,verbose:i.verbose});if(l.success)console.log(Y__default.default.green("=== Implement Agent Started ===")),console.log(),console.log(` ID: ${l.agentId}`),console.log(` PID: ${l.pid}`),console.log(` Log: ${l.logFile}`),console.log(),console.log(Y__default.default.yellow("To monitor:")),console.log(` tail -f ${l.logFile}`),console.log(),B(n,J(l));else throw ne.operationFailed("Implement Phase",l.error||"Unknown error")}catch(c){Z(n,c);}}),t.command("check-phase").description("Run check phase for a task (spawns check agent)").argument("<task>","Task name or directory").option("-p, --platform <platform>","Platform (claude, cursor, iflow, opencode)","claude").option("-v, --verbose","Enable verbose output").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(Y__default.default.blue("=== Check Phase ===")),console.log(Y__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(Y__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log();let l=await Cve(c,o,{platform:i.platform,verbose:i.verbose});if(l.success)console.log(Y__default.default.green("=== Check Agent Started ===")),console.log(),console.log(` ID: ${l.agentId}`),console.log(` PID: ${l.pid}`),console.log(` Log: ${l.logFile}`),console.log(),console.log(Y__default.default.yellow("To monitor:")),console.log(` tail -f ${l.logFile}`),console.log(),B(n,J(l));else throw ne.operationFailed("Check Phase",l.error||"Unknown error")}catch(c){Z(n,c);}}),t.command("compute-reward").description("Manually trigger PR quality evaluation using reward types").argument("<task>","Task name or directory").option("-p, --platform <platform>","Platform (claude, cursor, iflow, opencode)","claude").option("-v, --verbose","Enable verbose output").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(Y__default.default.blue("=== Compute Reward Phase ===")),console.log(Y__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(Y__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log();let l=tE(c,o,{platform:i.platform,verbose:i.verbose});if(l.success){if(console.log(Y__default.default.green("=== Reward Computation Complete ===")),console.log(),console.log(` Log: ${l.log_file}`),l.warnings&&l.warnings.length>0){console.log(),console.log(Y__default.default.yellow("Warnings:"));for(let u of l.warnings)console.log(` - ${u}`);}console.log(),console.log(Y__default.default.gray("To view results:")),console.log(" viben task view <task>"),console.log(),B(n,J(l));}else throw ne.operationFailed("Compute Reward",l.error||"Unknown error")}catch(c){Z(n,c);}}),t.command("parse-reward").description("Parse reward agent output from log file and write results to task.json").argument("<task>","Task name or directory").action(async s=>{let i=bt(e),n=process.cwd();try{let a=wt(n),c=lt(s,a);if(!c)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(Y__default.default.blue("=== Parse Reward Result ===")),console.log(Y__default.default.cyan("[INFO]"),`Task: ${s}`),console.log();let o=Yve(a,c);if(o.success&&o.reward){console.log(Y__default.default.green("=== Reward Parsed Successfully ===")),console.log(),console.log(Y__default.default.cyan("Scores:"));for(let[l,u]of Object.entries(o.reward.scores))console.log(` ${l}: ${u.score.toFixed(3)}`),console.log(` ${Y__default.default.gray(u.reasoning)}`);console.log(),console.log(Y__default.default.cyan("Summary:")),console.log(` Total: ${o.reward.total.toFixed(3)}`),console.log(` Diff Lines: ${o.reward.diffLines}`),console.log(` Computed: ${o.reward.computedAt}`),console.log(),console.log(Y__default.default.green("Written to task.json")),B(i,J({reward:o.reward}));}else throw ne.operationFailed("Parse Reward",o.error||"Unknown error")}catch(a){Z(i,a);}}),t.command("create-worktree").description("Create isolated git worktree for a task").argument("<task>","Task name or directory").option("--skip-prd","Skip prd.md validation").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o||!Ne.existsSync(o))throw ne.notFound("Task",s);if(Mt(o)?.status==="rejected"){let d=qe.join(o,"REJECTED.md"),h="";throw Ne.existsSync(d)&&(h=Ne.readFileSync(d,"utf-8").trim()),ne.operationFailed("Create Worktree",`Task was rejected. ${h?`Reason: ${h}`:"Check REJECTED.md for details."}`)}if(!i.skipPrd){let d=qe.join(o,"prd.md");if(!Ne.existsSync(d))throw ne.operationFailed("Create Worktree","prd.md not found - planning may not have completed. Use --skip-prd to bypass this check.")}console.log(),console.log(Y__default.default.blue("=== Create Worktree ===")),console.log(Y__default.default.cyan("[INFO]"),`Task: ${s}`),console.log();let u=await iM(c,o);if(u.success)console.log(Y__default.default.green("=== Worktree Created ===")),console.log(),console.log(` Path: ${u.worktreePath}`),console.log(` Branch: ${u.branch}`),console.log(` Base Branch: ${u.baseBranch}`),console.log(),console.log(Y__default.default.yellow("Next step:")),console.log(` viben task work-phase ${s} --worktree ${u.worktreePath}`),console.log(),B(n,J(u));else throw ne.operationFailed("Create Worktree",u.error||"Unknown error")}catch(c){Z(n,c);}}),t.command("work-phase").description("Run work phase for a task (spawns work agent)").argument("<task>","Task name or directory").option("-p, --platform <platform>","Platform (claude, cursor, iflow, opencode)","claude").option("-v, --verbose","Enable verbose output").option("--detach","Run in background (default: foreground)").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=i.platform||"claude",l=lt(s,c);if(!l||!Ne.existsSync(l))throw ne.notFound("Task",s);let d=fs(o).getAgentConfigPath("work",c);if(!Ne.existsSync(d))throw ne.operationFailed("Work Phase",`work agent not found at ${d}. Platform: ${o}`);let h=Mt(l),_=h?.worktree_path,y=h?.worktree??!1;if(h?.status==="rejected"){let q=qe.join(l,"REJECTED.md"),O="";throw Ne.existsSync(q)&&(O=Ne.readFileSync(q,"utf-8").trim()),ne.operationFailed("Work Phase",`Task was rejected. ${O?`Reason: ${O}`:"Check REJECTED.md for details."}`)}let v=qe.join(l,"prd.md");if(!Ne.existsSync(v))throw ne.operationFailed("Work Phase","prd.md not found - planning must be completed before work phase.");let b,w,S,E;if(y||_){if(!_||!Ne.existsSync(_)){console.log(Y__default.default.cyan("[INFO]"),"Worktree not found, creating...");let q=await iM(c,l);if(!q.success)throw ne.operationFailed("Create Worktree",q.error||"Unknown error");_=q.worktreePath,console.log(Y__default.default.green("[OK]"),`Worktree created at ${_}`);}b=_,w=`worktree (${_})`,S="agent.log.jsonl",E=!0;}else b=c,w="current repo",S="work.log.jsonl",E=!1;let A;h?.id?A=h.id:h?.branch?A=h.branch.replace(/\//g,"-"):h?.name?A=h.name:A=`${E?"swarm":"work"}-${qe.basename(l)}`,console.log(),console.log(Y__default.default.blue("=== Work Phase ===")),console.log(Y__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(Y__default.default.cyan("[INFO]"),`Platform: ${o}`),console.log(Y__default.default.cyan("[INFO]"),`Working Dir: ${w}`),console.log(Y__default.default.cyan("[INFO]"),`Mode: ${i.detach?"background":"foreground"}`),console.log();let D=await D5({repoRoot:c,workingDir:b,task_dir:l,platform:o,verbose:i.verbose,detach:i.detach??!1,skipPermissions:!0,jsonOutput:!0,logFileName:S,agentId:A,skipNextActionValidation:E});if(D.success)console.log(Y__default.default.green("=== Work Agent Started ===")),console.log(),console.log(` ID: ${D.agentId}`),console.log(` PID: ${D.pid}`),D.sessionId&&console.log(` Session: ${D.sessionId}`),console.log(` Log: ${D.logFile}`),console.log(),console.log(Y__default.default.yellow("To monitor:")),console.log(` tail -f ${D.logFile}`),console.log(` viben swarm status ${s}`),console.log(),B(n,J(D));else throw ne.operationFailed("Work Phase",D.error||"Unknown error")}catch(c){Z(n,c);}}),t.command("validate-check-phase-passed").description("Validate check phase passed (runs verify commands or checks completion markers)").argument("<task>","Task name or directory").option("-o, --output <output>","Agent output text (for completion markers validation)").option("-f, --output-file <file>","File containing agent output").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a),o=lt(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);let l=i.output;!l&&i.outputFile&&Ne.existsSync(i.outputFile)&&(l=Ne.readFileSync(i.outputFile,"utf-8"));let u=jhe(c,o,l);if(n.json){B(n,J(u));return}if(console.log(),console.log(Y__default.default.blue("=== Check Phase Validation ===")),console.log(),console.log(` Method: ${u.method}`),console.log(` Result: ${u.success?Y__default.default.green("PASSED"):Y__default.default.red("FAILED")}`),console.log(),u.method==="verify_commands"){console.log(Y__default.default.cyan("Commands:"));for(let d of u.details.commands||[])console.log(` - ${d}`);if(u.details.outputs){console.log();for(let d of u.details.outputs){let h=d.exitCode===0?Y__default.default.green("\u2713"):Y__default.default.red("\u2717");console.log(` ${h} ${d.command} (exit: ${d.exitCode})`);}}}else {console.log(Y__default.default.cyan("Expected markers:"));for(let d of u.details.expectedMarkers||[]){let _=u.details.foundMarkers?.includes(d)?Y__default.default.green("\u2713"):Y__default.default.red("\u2717");console.log(` ${_} ${d}`);}}console.log(),u.success?(console.log(Y__default.default.green("Check phase validation passed.")),AS(o,"check_passed_at",new Date().toISOString())):(console.log(Y__default.default.red("Check phase validation failed:")),console.log(Y__default.default.red(` ${u.error}`))),B(n,J(u));}catch(c){Z(n,c);}}),t.command("cleanup").description("Cleanup worktrees and related resources").argument("[branch]","Branch name to cleanup").option("--keep-branch","Keep the git branch").option("-y, --yes","Skip confirmation prompts").option("--merged","Cleanup merged worktrees").option("--all","Cleanup all worktrees").option("--list","List all worktrees").action(async(s,i)=>{let n=bt(e),a=process.cwd();try{let c=wt(a);await B_t(n,c,s,i);}catch(c){Z(n,c);}}),t.command("check-stuck").description("Check if a task is stuck (no recovery, detection only)").argument("<task>","Task name or directory").option("-t, --threshold <ms>","Stuck threshold in milliseconds (default: 120000 = 2min)","120000").option("-v, --verbose","Show detailed log analysis").option("--json","Output in JSON format").action(async(s,i)=>{let n=bt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=wt(a),o=parseInt(i.threshold||"120000",10);if(isNaN(o)||o<=0){B(n,ot("INVALID_THRESHOLD","Threshold must be a positive number"),()=>{console.error(Y__default.default.red("Error: --threshold must be a positive number (milliseconds)"));}),process.exit(1);return}let l=Ant(c,s,{thresholdMs:o,verbose:i.verbose});if(!l.success){B(n,ot("CHECK_FAILED",l.error||"Unknown error"),()=>{console.error(Y__default.default.red(`Error: ${l.error}`));}),process.exit(1);return}if(n.json){B(n,J(l));return}console.log(Y__default.default.bold.cyan(`=== Stuck Check: ${l.taskDir} ===`)),console.log(),l.isStuck?(console.log(Y__default.default.red.bold("Status: STUCK")),console.log(Y__default.default.red(` ${l.summary}`))):(console.log(Y__default.default.green.bold("Status: OK")),console.log(Y__default.default.green(` ${l.summary}`))),console.log(),console.log(Y__default.default.cyan("Checks:"));for(let u of l.checks){let d=u.isStuck?Y__default.default.red("\u2717"):Y__default.default.green("\u2713"),h=u.isStuck?Y__default.default.red:Y__default.default.white;if(console.log(` ${d} ${h(u.name)}: ${u.reason}`),i.verbose&&u.data&&Object.keys(u.data).length>0){for(let[_,y]of Object.entries(u.data))if(y!=null){let v=typeof y=="object"?JSON.stringify(y):String(y);console.log(Y__default.default.gray(` ${_}: ${v}`));}}}console.log(),l.task&&(console.log(Y__default.default.cyan("Task Info:")),console.log(` Status: ${Um(l.task.status)}`),console.log(` Assignee: ${l.task.assignee||"-"}`),l.task.last_event&&console.log(` Last Event: ${l.task.last_event.type} @ ${l.task.last_event.timestamp}`),l.task.updated_at&&console.log(` Updated: ${l.task.updated_at}`));}catch(c){Z(n,c);}});}var xTe,H_t=$({"src/cli/commands/task.ts"(){wr(),Ou(),Vt(),_A(),gz(),$5(),Dve(),Ive(),Uf(),xTe={CLAUDE_CODE:"claude",CURSOR:"cursor",GEMINI:"gemini",OPENCODE:"opencode",IFLOW:"iflow",CODEX:"codex",KILO:"kilo",KIRO:"kiro",ANTIGRAVITY:"antigravity"};}}),ITe={};yt(ITe,{registerContextCommand:()=>Y_t});function V_t(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function K_t(e){let t=cn(e)||"",r=f5(e),s=0,i="";if(r&&t){s=iA(r);let u=r.split("/").pop()||"";i=`${Qt}/${Kn}/${t}/${u}`;}let n=Phe(e),a=NVe(e),c=a===0,o=Ahe(e,5),l=Cf(e).map(u=>({dir:u.dir,name:u.name,status:u.status}));return {developer:t,git:{branch:n,is_clean:c,uncommitted_changes:a,recent_commits:o},tasks:{active:l,directory:`${Qt}/${un}`},journal:{file:i,lines:s,near_limit:s>1800}}}function J_t(e){let t=[];t.push("========================================"),t.push("SESSION CONTEXT"),t.push("========================================"),t.push("");let r=cn(e);if(t.push("## DEVELOPER"),!r)return t.push("ERROR: Not initialized. Run: viben user init <name>"),t.join(`
|
|
1120
1120
|
`);t.push(`Name: ${r}`),t.push(""),t.push("## GIT STATUS");let s=Phe(e);t.push(`Branch: ${s}`);let i=RVe(e),n=i.length;if(n===0)t.push("Working directory: Clean");else {t.push(`Working directory: ${n} uncommitted change(s)`),t.push(""),t.push("Changes:");for(let d of i)t.push(d);}t.push(""),t.push("## RECENT COMMITS");let a=Ahe(e,5);if(a.length>0)for(let d of a)t.push(`${d.hash} ${d.message}`);else t.push("(no commits)");t.push(""),t.push("## LATEST TASK");let c=Cf(e),o=c.length>0?c[c.length-1]:null;if(o){let d=Fu(e),h=qe.join(d,o.dir),_=Mt(h);if(t.push(`Path: ${Qt}/${un}/${o.dir}`),_){let v=String(_.name??_.id??"unknown"),b=String(_.status??"unknown"),w=String(_.created_at??"unknown"),S=String(_.description??"");t.push(`Name: ${v}`),t.push(`Status: ${b}`),t.push(`Created: ${w}`),S&&t.push(`Description: ${S}`);}let y=qe.join(h,"prd.md");Ne.existsSync(y)&&(t.push(""),t.push("[!] This task has prd.md - read it for task details"));}else t.push("(none)");if(t.push(""),t.push("## ACTIVE TASKS"),c.length>0)for(let d of c)t.push(`- ${d.dir}/ (${d.status}) @${d.assignee}`);else t.push("(no active tasks)");t.push(`Total: ${c.length} active task(s)`),t.push(""),t.push("## MY TASKS (Assigned to me)");let l=c.filter(d=>d.assignee===r&&d.status!=="completed");if(l.length>0)for(let d of l)t.push(`- [${d.priority}] ${d.title} (${d.status})`);else t.push("(no tasks assigned to you)");t.push(""),t.push("## JOURNAL FILE");let u=f5(e);if(u&&r){let d=iA(u),h=u.split("/").pop()||"",_=`${Qt}/${Kn}/${r}/${h}`;t.push(`Active file: ${_}`),t.push(`Line count: ${d} / 2000`),d>1800&&t.push("[!] WARNING: Approaching 2000 line limit!");}else t.push("No journal file found");return t.push(""),t.push("## PATHS"),t.push(`Workspace: ${Qt}/${Kn}/${r}/`),t.push(`Tasks: ${Qt}/${un}/`),t.push("Spec: docs/specs/"),t.push(""),t.push("========================================"),t.join(`
|
|
@@ -1232,7 +1232,7 @@ Error: ${h}`));}),process.exit(1);}e.quiet||(a.stop(),console.log(Y__default.def
|
|
|
1232
1232
|
\u2713 Downloaded to ${c}`)),console.log()),e.quiet||console.log(Y__default.default.cyan("Installing..."));let o=await Ame(c);o.success||(B(e,ot("INSTALL_FAILED",o.error??"Installation failed"),()=>{console.log(Y__default.default.red(`Error: ${o.error}`)),console.log(),console.log(Y__default.default.gray("To install manually, run:")),console.log(Y__default.default.cyan(` ${gL(c)}`));}),process.exit(1)),e.quiet||(console.log(Y__default.default.green("\u2713 Installed successfully")),console.log()),e.quiet||console.log(Y__default.default.cyan("Launching Viben desktop app..."));let l=Hte();B(e,J({version:s.version,installed:true,launched:l,path:o.installedPath}),()=>{console.log(l?Y__default.default.green("\u2713 Viben desktop app launched"):Y__default.default.yellow("App installed but failed to launch automatically."));});}async function Kle(e,t,r){let s=Eme();Tme(s)||(B(e,ot("PLATFORM_NOT_SUPPORTED",`Platform ${s} is not supported`),()=>{console.log(Y__default.default.red(`Error: ${Zw(s)} is not supported.`)),console.log(Y__default.default.gray("Supported platforms: macOS, Windows (x64), Linux (x64)"));}),process.exit(1));let i=t?.replace(/^v/,"");e.quiet||console.log(Y__default.default.cyan("Checking version..."));let n;try{n=await xme(i);}catch(u){let d=u instanceof Error?u.message:"NETWORK_ERROR",h=d==="VERSION_NOT_FOUND"?`Version ${t} not found. Run 'viben app check' to see the latest version.`:"Failed to fetch release info. Please check your internet connection.";B(e,ot(d,h),()=>{console.log(Y__default.default.red(`Error: ${h}`));}),process.exit(1);}let a=Ime(n,s,r.format);if(r.check){B(e,J({version:n.version,tag:n.tag,date:n.date,platform:Zw(s),asset:a.name,size:a.size}),()=>{console.log(),console.log(` Version: ${Y__default.default.bold("v"+n.version)}`),console.log(` Platform: ${Zw(s)}`),console.log(` Package: ${a.name}`),a.size&&console.log(` Size: ${Op(a.size)}`),console.log();});return}e.quiet||(console.log(` Version: ${Y__default.default.bold("v"+n.version)}`),console.log(` Platform: ${Zw(s)}`),console.log());let c=r.output??q5(),o=KTe();e.quiet||(console.log(`Downloading ${Y__default.default.cyan(a.name)}...`),o.start(a.size??100,0,{downloaded:"0 B",total:Op(a.size??0)}));let l;try{l=await Pme(a,{outputDir:c,force:r.force??!1,format:r.format??"exe",onProgress:(u,d)=>{e.quiet||o.update(u,{downloaded:Op(u),total:Op(d)});}});}catch(u){e.quiet||o.stop();let{code:d,message:h}=JTe(u);B(e,ot(d,h),()=>{console.log(Y__default.default.red(`
|
|
1233
1233
|
Error: ${h}`));}),process.exit(1);}if(e.quiet||o.stop(),r.install){e.quiet||(console.log(Y__default.default.green(`
|
|
1234
1234
|
\u2713 Downloaded to ${l}`)),console.log(),console.log(Y__default.default.cyan("Installing...")));let u=await Ame(l);u.success||(B(e,ot("INSTALL_FAILED",u.error??"Installation failed"),()=>{console.log(Y__default.default.red(`Error: ${u.error}`)),console.log(),console.log(Y__default.default.gray("To install manually, run:")),console.log(Y__default.default.cyan(` ${gL(l)}`));}),process.exit(1)),B(e,J({version:n.version,platform:s,file:l,installed:true,installedPath:u.installedPath}),()=>{console.log(Y__default.default.green("\u2713 Installed successfully"));});return}B(e,J({version:n.version,platform:s,file:l,size:a.size}),()=>{console.log(Y__default.default.green(`
|
|
1235
|
-
\u2713 Downloaded to ${l}`)),console.log(),console.log(Y__default.default.gray("To install, run:")),console.log(Y__default.default.cyan(` ${gL(l)}`));});}function Obt(e){let t=e.command("app").description("Launch or install Viben desktop app").option("-y, --yes","Skip confirmation prompts").action(async r=>{let s={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{await Cbt(s,r);}catch(i){Z(s,i);}});t.command("install [version]").description("Download desktop app installer").option("-c, --check","Check version info only, don't download").option("-i, --install","Install after downloading").option("-o, --output <dir>","Output directory",q5()).option("-f, --force","Overwrite existing file").option("--format <type>","Windows installer format (exe or msi)","exe").action(async(r,s)=>{let i={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{await Kle(i,r,s);}catch(n){Z(i,n);}}),t.command("check").description("Check latest desktop app version").action(async()=>{let r={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{await Kle(r,void 0,{check:!0});}catch(s){Z(r,s);}});}var Fbt=$({"src/cli/commands/app.ts"(){wr(),Ome();}}),YTe={};yt(YTe,{registerPetCommand:()=>Dbt});function qn(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Dbt(e){let t=e.command("pet").description("Manage pets");t.command("list").alias("ls").description("List all pets (builtin + installed)").action(async function(){let s=qn(this);try{let[i,n]=await Promise.all([dr.listPets(),dr.getConfig()]);B(s,J({pets:i,current:n.current}),()=>{if(i.length===0){console.log(Y__default.default.gray("No pets installed"));return}gt(s,["ID","Name","Source","Current"],i.map(a=>[a.id,a.metadata.displayName,a.isBuiltin?"builtin":a.metadata.source??"local",n.current===a.id?Y__default.default.green("*"):""]));});}catch(i){Z(s,i);}}),t.command("show <id>").description("Show pet details").action(async function(s){let i=qn(this);try{let n=await dr.getPet(s);if(!n)throw new Wr(`Pet "${s}" not found`,"PET_NOT_FOUND");B(i,J({pet:n}),()=>{console.log(Y__default.default.bold(`Pet: ${n.metadata.displayName}`)),et(i,{ID:n.id,Description:n.metadata.description,Author:n.metadata.author??"-",Tags:n.metadata.tags?.join(", ")??"-",Builtin:n.isBuiltin?"Yes":"No",Path:n.localPath});});}catch(n){Z(i,n);}}),t.command("set <id>").description("Set current pet").action(async function(s){let i=qn(this);try{await dr.setCurrent(s),B(i,J({current:s}),()=>{Ue(i,`Set current pet to "${s}"`);});}catch(n){Z(i,n);}}),t.command("remove <id>").alias("rm").description("Remove an installed pet").option("-y, --yes","Skip confirmation").action(async function(s,i){let n=qn(this);try{if(!i.yes){let c=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(l=>{c.question(`Are you sure you want to remove "${s}"? [y/N] `,l);});if(c.close(),o.toLowerCase()!=="y"){console.log(Y__default.default.gray("Cancelled"));return}}await dr.removePet(s),B(n,J({removed:s}),()=>{Ue(n,`Removed pet "${s}"`);});}catch(a){Z(n,a);}}),t.command("import <path>").description("Import pet from local zip file").action(async function(s){let i=qn(this);try{let n=await dr.importPet(s);B(i,J({pet:n}),()=>{Ue(i,`Imported pet "${n.metadata.displayName}" (${n.id})`);});}catch(n){Z(i,n);}}),t.command("export <id>").description("Export pet to zip file").option("-o, --output <path>","Output path").action(async function(s,i){let n=qn(this);try{let a=i.output??`./${s}.zip`,c=await dr.exportPet(s,a);B(n,J({path:c}),()=>{Ue(n,`Exported pet to "${c}"`);});}catch(a){Z(n,a);}}),t.command("community").description("List community pets").option("-s, --source <source>","Filter by source").action(async function(s){let i=qn(this);try{let n=await dr.listCommunityPets(s.source);B(i,J({pets:n}),()=>{if(n.length===0){console.log(Y__default.default.gray("No community pets found"));return}gt(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Z(i,n);}}),t.command("search <query>").description("Search community pets").action(async function(s){let i=qn(this);try{let n=await dr.searchCommunityPets(s);B(i,J({pets:n}),()=>{if(n.length===0){console.log(Y__default.default.gray(`No pets found matching "${s}"`));return}gt(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Z(i,n);}}),t.command("preview <id>").description("Preview community pet info").option("-s, --source <source>","Specify source").action(async function(s,i){let n=qn(this);try{let a=await dr.previewPet(s,i.source);if(!a)throw new Wr(`Pet "${s}" not found`,"PET_NOT_FOUND");B(n,J({pet:a}),()=>{console.log(Y__default.default.bold(`Pet: ${a.displayName}`)),et(n,{ID:a.id,Description:a.description,Author:a.author??"-",Tags:a.tags?.join(", ")??"-",Source:a.source});});}catch(a){Z(n,a);}}),t.command("install <id>").description("Install community pet").option("-s, --source <source>","Specify source","codex-pet-share").action(async function(s,i){let n=qn(this);try{let a=await dr.installPet(s,i.source);B(n,J({pet:a}),()=>{Ue(n,`Installed pet "${a.metadata.displayName}" (${a.id})`);});}catch(a){Z(n,a);}});let r=t.command("sources").description("Manage pet sources");r.command("list").description("List all sources").action(async function(){let s=qn(this);try{let i=await dr.listSources();B(s,J({sources:i}),()=>{if(i.length===0){console.log(Y__default.default.gray("No sources configured"));return}gt(s,["Name","URL","Enabled","Builtin"],i.map(n=>[n.name,n.url.length>40?n.url.substring(0,37)+"...":n.url,n.enabled?Y__default.default.green("Yes"):Y__default.default.red("No"),n.builtin?"Yes":"No"]));});}catch(i){Z(s,i);}}),r.command("add").description("Add a new source").requiredOption("-n, --name <name>","Source name").requiredOption("-u, --url <url>","Source URL (must be HTTPS)").action(async function(s){let i=qn(this);try{let n=await dr.addSource(s.name,s.url);B(i,J({source:n}),()=>{Ue(i,`Added source "${n.name}"`);});}catch(n){Z(i,n);}}),r.command("remove <name>").description("Remove a source").action(async function(s){let i=qn(this);try{await dr.removeSource(s),B(i,J({removed:s}),()=>{Ue(i,`Removed source "${s}"`);});}catch(n){Z(i,n);}});}var $bt=$({"src/cli/commands/pet.ts"(){wr(),NP();}});Ek();Qn();Tk();th();Zp();xk();Ak();tA();Rf();y_();zk();s0e();KA();b_e();Ok();JA();zf();A_e();k_e();T_e();O_e();Wl();zf();JA();qA();Ive();Uf();i0e();Rf();rE();kbe();Ez();hn();var r2=[{name:"init",description:"Initialize a Viben workspace",loader:()=>Promise.resolve().then(()=>(Kot(),Bbe)).then(e=>({register:e.registerInitCommand}))},{name:"config",description:"Manage configuration",loader:()=>Promise.resolve().then(()=>(Zot(),Gbe)).then(e=>({register:e.registerConfigCommand}))},{name:"workspace",description:"Manage workspaces",loader:()=>Promise.resolve().then(()=>(tct(),Hbe)).then(e=>({register:e.registerWorkspaceCommand}))},{name:"executor",description:"Manage executors",loader:()=>Promise.resolve().then(()=>(act(),Wbe)).then(e=>({register:e.registerExecutorCommand}))},{name:"agent",description:"Manage AI agents",loader:()=>Promise.resolve().then(()=>(uct(),Vbe)).then(e=>({register:e.registerAgentCommand}))},{name:"provider",description:"Manage AI providers",loader:()=>Promise.resolve().then(()=>(dct(),Kbe)).then(e=>({register:e.registerProviderCommand}))},{name:"model",description:"Manage AI models",loader:()=>Promise.resolve().then(()=>(mct(),Jbe)).then(e=>({register:e.registerModelCommand}))},{name:"channel",description:"Manage channels",loader:()=>Promise.resolve().then(()=>(yct(),Ybe)).then(e=>({register:e.registerChannelCommand}))},{name:"service",description:"Manage services",loader:()=>Promise.resolve().then(()=>(Ect(),Qbe)).then(e=>({register:e.registerServiceCommand}))},{name:"gateway",description:"Gateway management",loader:()=>Promise.resolve().then(()=>(C0t(),cTe)).then(e=>({register:e.registerGatewayCommand}))},{name:"cron",description:"Manage cron jobs",loader:()=>Promise.resolve().then(()=>(U0t(),hTe)).then(e=>({register:e.registerCronCommand}))},{name:"mcp",description:"Manage MCP servers",loader:()=>Promise.resolve().then(()=>(V0t(),mTe)).then(e=>({register:e.registerMcpCommand}))},{name:"skill",description:"Manage skills",loader:()=>Promise.resolve().then(()=>(X0t(),fTe)).then(e=>({register:e.registerSkillCommand}))},{name:"telemetry",description:"Manage telemetry",loader:()=>Promise.resolve().then(()=>(e_t(),gTe)).then(e=>({register:e.registerTelemetryCommand}))},{name:"update",description:"Update Viben",loader:()=>Promise.resolve().then(()=>(p_t(),_Te)).then(e=>({register:e.registerUpdateCommand}))},{name:"queue",description:"Manage task queues",loader:()=>Promise.resolve().then(()=>(T_t(),vTe)).then(e=>({register:e.registerQueueCommand}))},{name:"swarm",description:"Manage agent swarms",loader:()=>Promise.resolve().then(()=>(L_t(),STe)).then(e=>({register:e.registerSwarmCommand}))},{name:"task",description:"Manage tasks",loader:()=>Promise.resolve().then(()=>(H_t(),TTe)).then(e=>({register:e.registerTaskCommand}))},{name:"context",description:"Manage context",loader:()=>Promise.resolve().then(()=>(Q_t(),ITe)).then(e=>({register:e.registerContextCommand}))},{name:"user",description:"Manage user settings",loader:()=>Promise.resolve().then(()=>(Dme(),Fme)).then(e=>({register:e.registerUserCommand}))},{name:"session",description:"Manage sessions",loader:()=>Promise.resolve().then(()=>(rvt(),PTe)).then(e=>({register:e.registerSessionCommand}))},{name:"idea",description:"Manage ideas",loader:()=>Promise.resolve().then(()=>(nvt(),CTe)).then(e=>({register:e.registerIdeaCommand}))},{name:"reward",description:"Manage rewards",loader:()=>Promise.resolve().then(()=>(uvt(),DTe)).then(e=>({register:e.registerRewardCommand}))},{name:"evo",description:"Manage evolution",loader:()=>Promise.resolve().then(()=>(hbt(),zTe)).then(e=>({register:e.registerEvoCommand}))},{name:"index",description:"Generate context index",loader:()=>Promise.resolve().then(()=>(fbt(),UTe)).then(e=>({register:e.registerIndexCommand}))},{name:"login",description:"Login to Viben",loader:()=>Promise.resolve().then(()=>(wbt(),BTe)).then(e=>({register:e.registerLoginCommand}))},{name:"page",description:"Manage workspace pages",loader:()=>Promise.resolve().then(()=>(Ebt(),HTe)).then(e=>({register:e.registerPageCommand}))},{name:"account",description:"Trading account management",loader:()=>Promise.resolve().then(()=>(xbt(),WTe)).then(e=>({register:e.registerAccountCommand}))},{name:"app",description:"Launch or install Viben desktop app",loader:()=>Promise.resolve().then(()=>(Fbt(),VTe)).then(e=>({register:e.registerAppCommand}))},{name:"pet",description:"Manage pets",loader:()=>Promise.resolve().then(()=>($bt(),YTe)).then(e=>({register:e.registerPetCommand}))}];function Lbt(){let e=process.argv.slice(2);for(let t of e)if(!t.startsWith("-"))return t;return null}async function Mbt(e){let t=Lbt(),r=new Set(r2.map(s=>s.name));if(t&&r.has(t)){let s=r2.find(n=>n.name===t),{register:i}=await s.loader();i(e);for(let n of r2)n.name!==t&&e.command(n.name).description(n.description);}else for(let s of r2)e.command(s.name).description(s.description);}var jbt="1.3.3";async function QTe(){let e=new commander.Command;return e.name("viben").description("Viben - Agent Swarm \xD7 Code Evolution").version(jbt,"-v, --version","Output the version number"),e.option("--json","Output in JSON format").option("--verbose","Verbose output").option("--quiet","Minimal output").option("--global","Use global config instead of workspace"),await Mbt(e),e}async function XTe(e=process.argv){await(await QTe()).parseAsync(e);}Ou();wr();As();NP();XTe(process.argv).catch(e=>{let t=e instanceof Error?e.message:"Failed to run Viben CLI";console.error(`\x1B[31m[ERROR]\x1B[0m ${t}`),process.exit(1);});/*! Bundled license information:
|
|
1235
|
+
\u2713 Downloaded to ${l}`)),console.log(),console.log(Y__default.default.gray("To install, run:")),console.log(Y__default.default.cyan(` ${gL(l)}`));});}function Obt(e){let t=e.command("app").description("Launch or install Viben desktop app").option("-y, --yes","Skip confirmation prompts").action(async r=>{let s={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{await Cbt(s,r);}catch(i){Z(s,i);}});t.command("install [version]").description("Download desktop app installer").option("-c, --check","Check version info only, don't download").option("-i, --install","Install after downloading").option("-o, --output <dir>","Output directory",q5()).option("-f, --force","Overwrite existing file").option("--format <type>","Windows installer format (exe or msi)","exe").action(async(r,s)=>{let i={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{await Kle(i,r,s);}catch(n){Z(i,n);}}),t.command("check").description("Check latest desktop app version").action(async()=>{let r={json:e.opts().json??false,verbose:e.opts().verbose??false,quiet:e.opts().quiet??false};try{await Kle(r,void 0,{check:!0});}catch(s){Z(r,s);}});}var Fbt=$({"src/cli/commands/app.ts"(){wr(),Ome();}}),YTe={};yt(YTe,{registerPetCommand:()=>Dbt});function qn(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Dbt(e){let t=e.command("pet").description("Manage pets");t.command("list").alias("ls").description("List all pets (builtin + installed)").action(async function(){let s=qn(this);try{let[i,n]=await Promise.all([dr.listPets(),dr.getConfig()]);B(s,J({pets:i,current:n.current}),()=>{if(i.length===0){console.log(Y__default.default.gray("No pets installed"));return}gt(s,["ID","Name","Source","Current"],i.map(a=>[a.id,a.metadata.displayName,a.isBuiltin?"builtin":a.metadata.source??"local",n.current===a.id?Y__default.default.green("*"):""]));});}catch(i){Z(s,i);}}),t.command("show <id>").description("Show pet details").action(async function(s){let i=qn(this);try{let n=await dr.getPet(s);if(!n)throw new Wr(`Pet "${s}" not found`,"PET_NOT_FOUND");B(i,J({pet:n}),()=>{console.log(Y__default.default.bold(`Pet: ${n.metadata.displayName}`)),et(i,{ID:n.id,Description:n.metadata.description,Author:n.metadata.author??"-",Tags:n.metadata.tags?.join(", ")??"-",Builtin:n.isBuiltin?"Yes":"No",Path:n.localPath});});}catch(n){Z(i,n);}}),t.command("set <id>").description("Set current pet").action(async function(s){let i=qn(this);try{await dr.setCurrent(s),B(i,J({current:s}),()=>{Ue(i,`Set current pet to "${s}"`);});}catch(n){Z(i,n);}}),t.command("remove <id>").alias("rm").description("Remove an installed pet").option("-y, --yes","Skip confirmation").action(async function(s,i){let n=qn(this);try{if(!i.yes){let c=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(l=>{c.question(`Are you sure you want to remove "${s}"? [y/N] `,l);});if(c.close(),o.toLowerCase()!=="y"){console.log(Y__default.default.gray("Cancelled"));return}}await dr.removePet(s),B(n,J({removed:s}),()=>{Ue(n,`Removed pet "${s}"`);});}catch(a){Z(n,a);}}),t.command("import <path>").description("Import pet from local zip file").action(async function(s){let i=qn(this);try{let n=await dr.importPet(s);B(i,J({pet:n}),()=>{Ue(i,`Imported pet "${n.metadata.displayName}" (${n.id})`);});}catch(n){Z(i,n);}}),t.command("export <id>").description("Export pet to zip file").option("-o, --output <path>","Output path").action(async function(s,i){let n=qn(this);try{let a=i.output??`./${s}.zip`,c=await dr.exportPet(s,a);B(n,J({path:c}),()=>{Ue(n,`Exported pet to "${c}"`);});}catch(a){Z(n,a);}}),t.command("community").description("List community pets").option("-s, --source <source>","Filter by source").action(async function(s){let i=qn(this);try{let n=await dr.listCommunityPets(s.source);B(i,J({pets:n}),()=>{if(n.length===0){console.log(Y__default.default.gray("No community pets found"));return}gt(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Z(i,n);}}),t.command("search <query>").description("Search community pets").action(async function(s){let i=qn(this);try{let n=await dr.searchCommunityPets(s);B(i,J({pets:n}),()=>{if(n.length===0){console.log(Y__default.default.gray(`No pets found matching "${s}"`));return}gt(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Z(i,n);}}),t.command("preview <id>").description("Preview community pet info").option("-s, --source <source>","Specify source").action(async function(s,i){let n=qn(this);try{let a=await dr.previewPet(s,i.source);if(!a)throw new Wr(`Pet "${s}" not found`,"PET_NOT_FOUND");B(n,J({pet:a}),()=>{console.log(Y__default.default.bold(`Pet: ${a.displayName}`)),et(n,{ID:a.id,Description:a.description,Author:a.author??"-",Tags:a.tags?.join(", ")??"-",Source:a.source});});}catch(a){Z(n,a);}}),t.command("install <id>").description("Install community pet").option("-s, --source <source>","Specify source","codex-pet-share").action(async function(s,i){let n=qn(this);try{let a=await dr.installPet(s,i.source);B(n,J({pet:a}),()=>{Ue(n,`Installed pet "${a.metadata.displayName}" (${a.id})`);});}catch(a){Z(n,a);}});let r=t.command("sources").description("Manage pet sources");r.command("list").description("List all sources").action(async function(){let s=qn(this);try{let i=await dr.listSources();B(s,J({sources:i}),()=>{if(i.length===0){console.log(Y__default.default.gray("No sources configured"));return}gt(s,["Name","URL","Enabled","Builtin"],i.map(n=>[n.name,n.url.length>40?n.url.substring(0,37)+"...":n.url,n.enabled?Y__default.default.green("Yes"):Y__default.default.red("No"),n.builtin?"Yes":"No"]));});}catch(i){Z(s,i);}}),r.command("add").description("Add a new source").requiredOption("-n, --name <name>","Source name").requiredOption("-u, --url <url>","Source URL (must be HTTPS)").action(async function(s){let i=qn(this);try{let n=await dr.addSource(s.name,s.url);B(i,J({source:n}),()=>{Ue(i,`Added source "${n.name}"`);});}catch(n){Z(i,n);}}),r.command("remove <name>").description("Remove a source").action(async function(s){let i=qn(this);try{await dr.removeSource(s),B(i,J({removed:s}),()=>{Ue(i,`Removed source "${s}"`);});}catch(n){Z(i,n);}});}var $bt=$({"src/cli/commands/pet.ts"(){wr(),NP();}});Ek();Qn();Tk();th();Zp();xk();Ak();tA();Rf();y_();zk();s0e();KA();b_e();Ok();JA();zf();A_e();k_e();T_e();O_e();Wl();zf();JA();qA();Ive();Uf();i0e();Rf();rE();kbe();Ez();hn();var r2=[{name:"init",description:"Initialize a Viben workspace",loader:()=>Promise.resolve().then(()=>(Kot(),Bbe)).then(e=>({register:e.registerInitCommand}))},{name:"config",description:"Manage configuration",loader:()=>Promise.resolve().then(()=>(Zot(),Gbe)).then(e=>({register:e.registerConfigCommand}))},{name:"workspace",description:"Manage workspaces",loader:()=>Promise.resolve().then(()=>(tct(),Hbe)).then(e=>({register:e.registerWorkspaceCommand}))},{name:"executor",description:"Manage executors",loader:()=>Promise.resolve().then(()=>(act(),Wbe)).then(e=>({register:e.registerExecutorCommand}))},{name:"agent",description:"Manage AI agents",loader:()=>Promise.resolve().then(()=>(uct(),Vbe)).then(e=>({register:e.registerAgentCommand}))},{name:"provider",description:"Manage AI providers",loader:()=>Promise.resolve().then(()=>(dct(),Kbe)).then(e=>({register:e.registerProviderCommand}))},{name:"model",description:"Manage AI models",loader:()=>Promise.resolve().then(()=>(mct(),Jbe)).then(e=>({register:e.registerModelCommand}))},{name:"channel",description:"Manage channels",loader:()=>Promise.resolve().then(()=>(yct(),Ybe)).then(e=>({register:e.registerChannelCommand}))},{name:"service",description:"Manage services",loader:()=>Promise.resolve().then(()=>(Ect(),Qbe)).then(e=>({register:e.registerServiceCommand}))},{name:"gateway",description:"Gateway management",loader:()=>Promise.resolve().then(()=>(C0t(),cTe)).then(e=>({register:e.registerGatewayCommand}))},{name:"cron",description:"Manage cron jobs",loader:()=>Promise.resolve().then(()=>(U0t(),hTe)).then(e=>({register:e.registerCronCommand}))},{name:"mcp",description:"Manage MCP servers",loader:()=>Promise.resolve().then(()=>(V0t(),mTe)).then(e=>({register:e.registerMcpCommand}))},{name:"skill",description:"Manage skills",loader:()=>Promise.resolve().then(()=>(X0t(),fTe)).then(e=>({register:e.registerSkillCommand}))},{name:"telemetry",description:"Manage telemetry",loader:()=>Promise.resolve().then(()=>(e_t(),gTe)).then(e=>({register:e.registerTelemetryCommand}))},{name:"update",description:"Update Viben",loader:()=>Promise.resolve().then(()=>(p_t(),_Te)).then(e=>({register:e.registerUpdateCommand}))},{name:"queue",description:"Manage task queues",loader:()=>Promise.resolve().then(()=>(T_t(),vTe)).then(e=>({register:e.registerQueueCommand}))},{name:"swarm",description:"Manage agent swarms",loader:()=>Promise.resolve().then(()=>(L_t(),STe)).then(e=>({register:e.registerSwarmCommand}))},{name:"task",description:"Manage tasks",loader:()=>Promise.resolve().then(()=>(H_t(),TTe)).then(e=>({register:e.registerTaskCommand}))},{name:"context",description:"Manage context",loader:()=>Promise.resolve().then(()=>(Q_t(),ITe)).then(e=>({register:e.registerContextCommand}))},{name:"user",description:"Manage user settings",loader:()=>Promise.resolve().then(()=>(Dme(),Fme)).then(e=>({register:e.registerUserCommand}))},{name:"session",description:"Manage sessions",loader:()=>Promise.resolve().then(()=>(rvt(),PTe)).then(e=>({register:e.registerSessionCommand}))},{name:"idea",description:"Manage ideas",loader:()=>Promise.resolve().then(()=>(nvt(),CTe)).then(e=>({register:e.registerIdeaCommand}))},{name:"reward",description:"Manage rewards",loader:()=>Promise.resolve().then(()=>(uvt(),DTe)).then(e=>({register:e.registerRewardCommand}))},{name:"evo",description:"Manage evolution",loader:()=>Promise.resolve().then(()=>(hbt(),zTe)).then(e=>({register:e.registerEvoCommand}))},{name:"index",description:"Generate context index",loader:()=>Promise.resolve().then(()=>(fbt(),UTe)).then(e=>({register:e.registerIndexCommand}))},{name:"login",description:"Login to Viben",loader:()=>Promise.resolve().then(()=>(wbt(),BTe)).then(e=>({register:e.registerLoginCommand}))},{name:"page",description:"Manage workspace pages",loader:()=>Promise.resolve().then(()=>(Ebt(),HTe)).then(e=>({register:e.registerPageCommand}))},{name:"account",description:"Trading account management",loader:()=>Promise.resolve().then(()=>(xbt(),WTe)).then(e=>({register:e.registerAccountCommand}))},{name:"app",description:"Launch or install Viben desktop app",loader:()=>Promise.resolve().then(()=>(Fbt(),VTe)).then(e=>({register:e.registerAppCommand}))},{name:"pet",description:"Manage pets",loader:()=>Promise.resolve().then(()=>($bt(),YTe)).then(e=>({register:e.registerPetCommand}))}];function Lbt(){let e=process.argv.slice(2);for(let t of e)if(!t.startsWith("-"))return t;return null}async function Mbt(e){let t=Lbt(),r=new Set(r2.map(s=>s.name));if(t&&r.has(t)){let s=r2.find(n=>n.name===t),{register:i}=await s.loader();i(e);for(let n of r2)n.name!==t&&e.command(n.name).description(n.description);}else for(let s of r2)e.command(s.name).description(s.description);}var jbt="1.3.4";async function QTe(){let e=new commander.Command;return e.name("viben").description("Viben - Agent Swarm \xD7 Code Evolution").version(jbt,"-v, --version","Output the version number"),e.option("--json","Output in JSON format").option("--verbose","Verbose output").option("--quiet","Minimal output").option("--global","Use global config instead of workspace"),await Mbt(e),e}async function XTe(e=process.argv){await(await QTe()).parseAsync(e);}Ou();wr();As();NP();XTe(process.argv).catch(e=>{let t=e instanceof Error?e.message:"Failed to run Viben CLI";console.error(`\x1B[31m[ERROR]\x1B[0m ${t}`),process.exit(1);});/*! Bundled license information:
|
|
1236
1236
|
|
|
1237
1237
|
mime-db/index.js:
|
|
1238
1238
|
(*!
|