viben 1.3.1 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +5 -5
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -799,7 +799,7 @@ ${u}
|
|
|
799
799
|
${l}`);let h=i.session,v=i.resume;i.newSession?(h=(await et.createSession(a)).id,n.verbose&&console.log(J__default.default.gray(`Created new session: ${h}`))):v&&(h=v,n.verbose&&console.log(J__default.default.gray(`Resuming session: ${h}`)));let y=i.model||c.model,_=i.sdk!==!1,b=await P4(o,_);if(n.verbose){let A=Lw.isSdkAvailable(o);console.log(J__default.default.gray(`Agent: ${a} (${o})`)),console.log(J__default.default.gray(`Using ${b.proxyType} proxy`)),A&&b.proxyType==="spawn"&&console.log(J__default.default.gray("SDK mode available but not used (--no-sdk or SDK not installed)")),y&&console.log(J__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:v,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 qu.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(J__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(J__default.default.red(`Error: ${S.error}`)),process.exit(S.exitCode);}catch(a){Q(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=xs(e);try{if(!await et.getAgent(n))throw ne.notFound("Agent",n);let o=await et.listSessions(n);j(a,V({sessions:o}),()=>{if(o.length===0){console.log(J__default.default.yellow(`No sessions found for agent: ${n}`));return}ht(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){Q(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=xs(e);try{if(!await et.getAgent(n))throw ne.notFound("Agent",n);let o=await et.createSession(n,i.sessionName);j(a,V({session:o}),()=>{Me(a,`Created session: ${o.id}`),a.verbose&&(console.log(),Qe(a,{ID:o.id,Agent:o.agent_id,Name:o.name||"-"}));});}catch(c){Q(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=xs(e);try{await et.removeSession(n,a),j(c,V({removed:a}),()=>{Me(c,`Removed session: ${a}`);});}catch(o){Q(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=xs(e);try{if(!await et.getAgent(n))throw ne.notFound("Agent",n);let o=await qu.getMemory(n),l=await qu.getMemoryStats(n),u=await qu.getRecentLogs(n,i.days),d={memory:o,stats:l,recentLogs:u.map(h=>({date:h.date,entriesCount:h.entries.length}))};j(a,V(d),()=>{if(console.log(J__default.default.bold(`Memory for agent: ${n}`)),console.log(),Qe(a,{"Main Memory Size":Cee(l.mainMemorySize),"Daily Logs Count":String(l.dailyLogsCount),"Total Size":Cee(l.totalSize)}),o.content){console.log(),console.log(J__default.default.bold("Main Memory (MEMORY.md):")),console.log(J__default.default.gray("\u2500".repeat(40)));let h=o.content.slice(0,500);console.log(h),o.content.length>500&&console.log(J__default.default.gray(`... (${o.content.length} bytes total)`));}else console.log(),console.log(J__default.default.gray("No main memory content"));if(u.length>0){console.log(),console.log(J__default.default.bold(`Recent Daily Logs (last ${i.days} days):`));for(let h of u)console.log(` ${J__default.default.cyan(h.date)}: ${h.entries.length} entries`);}});}catch(c){Q(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=xs(e);try{if(!await et.getAgent(a))throw ne.notFound("Agent",a);await qu.appendMemory(a,i),j(c,V({appended:!0}),()=>{Me(c,`Appended to memory for agent: ${a}`);});}catch(o){Q(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=xs(e);try{if(!await et.getAgent(n))throw ne.notFound("Agent",n);!i.force&&!a.json&&!a.quiet&&(console.log(J__default.default.yellow(`Warning: This will clear all memory for agent "${n}".`)),console.log(J__default.default.gray("Use --force to skip this warning"))),await qu.clearMemory(n),j(a,V({cleared:!0}),()=>{Me(a,`Cleared memory for agent: ${n}`);});}catch(c){Q(a,c);}});}function TXe(e,t){return t.concat([e])}function xXe(e){if(e==="true")return true;if(e==="false")return false;let t=Number(e);return isNaN(t)?e:t}function IXe(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 Cee(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 PXe=O({"src/cli/commands/agent.ts"(){Vc(),yr(),np(),kw(),jw();}}),Qme={};mt(Qme,{registerProviderCommand:()=>AXe});function Sc(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Oee(e,t){return [...t??[],e]}function mD(e){if(e!==void 0){if(GR.includes(e))return e;throw new Error(`Invalid provider category: ${e}. Valid categories: ${GR.join(", ")}`)}}function Fee(e){if(e!==void 0){for(let t of e)if(!pw.includes(t))throw new Error(`Invalid provider surface: ${t}. Valid surfaces: ${pw.join(", ")}`);return e}}function AXe(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=Sc(this);try{let i=mD(r.category),n=r.surface;if(n!==void 0&&!pw.includes(n))throw new Error(`Invalid provider surface: ${n}. Valid surfaces: ${pw.join(", ")}`);let a=await dt.listProviders();i&&(a=a.filter(o=>o.category===i)),n&&(a=a.filter(o=>o.surfaces.includes(n)));let c=await dt.getDefault();j(s,V({providers:a,default:c}),()=>{if(a.length===0){console.log(J__default.default.gray("No providers configured")),console.log(J__default.default.gray("Use 'viben provider create <id>' to add a provider"));return}ht(s,["ID","Category","Type","Surfaces","Base URL","Default","Enabled"],a.map(o=>[o.id,o.category,o.type,o.surfaces.join(",")||"-",o.base_url||J__default.default.gray("(default)"),o.isDefault?J__default.default.green("Yes"):"",o.enabled?"Yes":J__default.default.red("No")]));});}catch(i){Q(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 (${Dh.join(", ")})`).option("--category <category>","Provider category (llm, media)").option("--surface <surface>","Supported surface",Oee).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=Sc(this);try{let i=r.type||"openai";if(!Dh.includes(i))throw new Error(`Invalid provider type: ${i}. Valid types: ${Dh.join(", ")}`);let n=mD(r.category),a=Fee(r.surface),c=r.name||`${i}-${Date.now()}`,o=r.apiKey;!o&&qg[i]&&(o=process.env[qg[i]]);let l=await dt.createProvider({type:i,category:n,name:c,apiKey:o,base_url:r.baseUrl||u1[i],timeout:r.timeout,max_retries:r.maxRetries,surfaces:a,setAsDefault:r.default});j(s,V({provider:l}),()=>{Me(s,`Created provider "${l.id}"`),l.isDefault&&console.log(J__default.default.gray("Set as default provider")),!o&&qg[i]&&console.log(J__default.default.yellow(`Note: No API key provided. Set ${qg[i]} or update with 'viben provider update ${l.id} --api-key <key>'`));});}catch(i){Q(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=Sc(this);try{await dt.removeProvider(r.name),j(s,V({removed:r.name}),()=>{Me(s,`Removed provider "${r.name}"`);});}catch(i){Q(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=Sc(this);try{await dt.setDefault(r.name),j(s,V({default:r.name}),()=>{Me(s,`Set "${r.name}" as default provider`);});}catch(i){Q(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=Sc(this);try{if(r.name){let i=await dt.checkStatus(r.name);j(s,V({status:i}),()=>{console.log(J__default.default.bold(`Provider: ${r.name}`)),Qe(s,{Connected:i.connected?J__default.default.green("Yes"):J__default.default.red("No"),Latency:i.latency?`${i.latency}ms`:"-",Error:i.error||"-","Checked At":i.checked_at});});}else {let i=await dt.checkAllStatus(),n=Object.values(i);j(s,V({statuses:i}),()=>{if(n.length===0){console.log(J__default.default.gray("No providers configured"));return}ht(s,["Provider","Connected","Latency","Error"],n.map(a=>[a.id,a.connected?J__default.default.green("Yes"):J__default.default.red("No"),a.latency?`${a.latency}ms`:"-",a.error||"-"]));});}}catch(i){Q(s,i);}}),t.command("show").description("Show provider details").requiredOption("-n, --name <name>","Provider name to show").action(async function(r){let s=Sc(this);try{let i=await dt.getProvider(r.name);if(!i)throw new Error(`Provider "${r.name}" not found`);j(s,V({provider:i}),()=>{console.log(J__default.default.bold(`Provider: ${i.id}`)),Qe(s,{Type:i.type,Category:i.category,Name:i.name,Surfaces:i.surfaces.join(", ")||"-","Base URL":i.base_url||"(default)","API Key":i.apiKey?"********":J__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){Q(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",Oee).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=Sc(this);try{if(r.type&&!Dh.includes(r.type))throw new Error(`Invalid provider type: ${r.type}. Valid types: ${Dh.join(", ")}`);let i=mD(r.category),n=Fee(r.surface),a=await dt.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});j(s,V({provider:a}),()=>{Me(s,`Updated provider "${r.name}"`);});}catch(i){Q(s,i);}}),t.command("enable").description("Enable a provider").requiredOption("-n, --name <name>","Provider name to enable").action(async function(r){let s=Sc(this);try{await dt.setEnabled(r.name,!0),j(s,V({enabled:r.name}),()=>{Me(s,`Enabled provider "${r.name}"`);});}catch(i){Q(s,i);}}),t.command("disable").description("Disable a provider").requiredOption("-n, --name <name>","Provider name to disable").action(async function(r){let s=Sc(this);try{await dt.setEnabled(r.name,!1),j(s,V({disabled:r.name}),()=>{Me(s,`Disabled provider "${r.name}"`);});}catch(i){Q(s,i);}}),t.command("types").description("List supported provider types").action(function(){let r=Sc(this),s=Dh.map(i=>({type:i,defaultUrl:u1[i]||"(custom)",envVar:qg[i]||"-"}));j(r,V({types:s}),()=>{ht(r,["Type","Default Base URL","API Key Env Var"],s.map(i=>[i.type,i.defaultUrl,i.envVar]));});});}var Dh,GR,pw,CXe=O({"src/cli/commands/provider.ts"(){yr(),sp(),Dh=["openai","openai-responses","anthropic","azure","ollama","openrouter","google","volcengine","grok","nanobanana","imagerouter","fal","leonardo","minimax","elevenlabs","fishaudio","senseaudio","aihubmix","suno","udio"],GR=["llm","media"],pw=["chat","image","video","music","speech","sfx"];}}),Zme={};mt(Zme,{registerModelCommand:()=>FXe});function OXe(e,t){return [...t??[],e]}function $ee(e){if(e!==void 0){if(HR.includes(e))return e;throw new Error(`Invalid model category: ${e}. Valid categories: ${HR.join(", ")}`)}}function fD(e){if(e!==void 0){if(WR.includes(e))return e;throw new Error(`Invalid model surface: ${e}. Valid surfaces: ${WR.join(", ")}`)}}function ln(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Dee(e){return e===void 0?"-":`$${e.toFixed(2)}/1M`}function gD(e){return e===void 0?"-":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toString()}function FXe(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=ln(this);try{let a=$ee(i.category),c=fD(i.surface),o=await Ue.listModelsFiltered({provider:i.provider,category:a,surface:c}),l=await Ue.getDefault();j(n,V({models:o,default:l}),()=>{if(o.length===0){console.log(J__default.default.gray("No models found"));return}ht(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(",")??"-",gD(u.contextLength),l===u.id?J__default.default.green("Yes"):""]));});}catch(a){Q(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=ln(this);try{let c=await Ue.resolveAlias(n),o=Ue.getModelInfo(c),l=await Ue.getModelConfig(n),u=await Ue.getDefault();j(a,V({model:o,resolved:c!==n?c:void 0,config:l,isDefault:u===c}),()=>{if(!o){console.log(J__default.default.yellow(`Model "${n}" not found`)),c!==n&&console.log(J__default.default.gray(`Resolved alias: ${c}`));return}console.log(J__default.default.bold(`Model: ${o.id}`)),c!==n&&console.log(J__default.default.gray(`(resolved from alias: ${n})`)),Qe(a,{Name:o.name,Provider:o.provider,"Context Length":gD(o.contextLength),"Max Output":gD(o.maxOutputTokens),"Input Price":Dee(o.inputPrice),"Output Price":Dee(o.outputPrice),"Is Default":u===c?"Yes":"No"}),l&&(console.log(),console.log(J__default.default.bold("Custom Configuration:")),Qe(a,{Temperature:l.temperature??"-","Max Tokens":l.maxTokens??"-","Top P":l.topP??"-","Frequency Penalty":l.frequencyPenalty??"-","Presence Penalty":l.presencePenalty??"-"}));});}catch(c){Q(a,c);}}),t.command("status").description("Show model availability status").action(async function(){let i=ln(this);try{let n=await Ue.listModels(),a=await Ue.getAliases(),c=await Ue.getDefault(),o=[...new Set(n.map(l=>l.provider))];j(i,V({providers:o,modelCount:n.length,aliasCount:Object.keys(a).length,default:c}),()=>{console.log(J__default.default.bold("Model Status")),console.log(),Qe(i,{"Known Models":n.length.toString(),Providers:o.join(", "),"Configured Aliases":Object.keys(a).length.toString(),"Default Model":c||J__default.default.gray("(not set)")}),console.log(),console.log(J__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){Q(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=ln(this);try{let c=await Ue.resolveAlias(n),o=fD(i.surface);o?await Ue.setDefaultForSurface(o,c):await Ue.setDefault(c),j(a,V({default:c,surface:o}),()=>{Me(a,o?`Set "${c}" as default ${o} model`:`Set "${c}" as default model`),c!==n&&console.log(J__default.default.gray(`(resolved from alias: ${n})`));});}catch(c){Q(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",OXe).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=ln(this);try{let a=$ee(i.category),c=fD(i.surface),o=await dt.getProvider(i.provider);if(!o)throw new Error(`Provider not found: ${i.provider}`);let l=await Ue.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});j(n,V({model:l}),()=>{Me(n,`Created model "${l.id}"`);});}catch(a){Q(n,a);}});let r=t.command("alias").description("Manage model aliases");r.command("list").description("List all model aliases").action(async function(){let i=ln(this);try{let n=await Ue.getAliases(),a=Object.entries(n);j(i,V({aliases:n}),()=>{if(a.length===0){console.log(J__default.default.gray("No aliases configured"));return}console.log(J__default.default.bold("Model Aliases:")),ht(i,["Alias","Model","Built-in"],a.map(([c,o])=>[c,o,qo[c]?"Yes":""]));});}catch(n){Q(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=ln(this);try{await Ue.createAlias(n,a),j(c,V({alias:n,model:a}),()=>{Me(c,`Set alias "${n}" -> "${a}"`);});}catch(o){Q(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=ln(this);try{await Ue.removeAlias(n),j(a,V({removed:n}),()=>{Me(a,`Removed alias "${n}"`);});}catch(c){Q(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=ln(this);try{let c=await Ue.resolveAlias(n);j(a,V({alias:n,model:c}),()=>{console.log(c===n?J__default.default.gray(`"${n}" is not an alias, using as model ID`):`${n} -> ${c}`);});}catch(c){Q(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=ln(this);try{let c=await Ue.getModelConfig(n);j(a,V({model:n,config:c}),()=>{if(!c){console.log(J__default.default.gray(`No custom configuration for "${n}"`));return}console.log(J__default.default.bold(`Configuration for ${n}:`)),Qe(a,{Temperature:c.temperature??"-","Max Tokens":c.maxTokens??"-","Top P":c.topP??"-","Frequency Penalty":c.frequencyPenalty??"-","Presence Penalty":c.presencePenalty??"-"});});}catch(c){Q(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=ln(this);try{let c=await Ue.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 Ue.setModelConfig(n,o),j(a,V({model:n,config:o}),()=>{Me(a,`Updated configuration for "${n}"`);});}catch(c){Q(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=ln(this);try{await Ue.removeModelConfig(n),j(a,V({removed:n}),()=>{Me(a,`Removed configuration for "${n}"`);});}catch(c){Q(a,c);}}),t.command("providers").description("List available model providers").action(async function(){let i=ln(this);try{let n=await Ue.listModels(),c=[...new Set(n.map(o=>o.provider))].map(o=>({provider:o,modelCount:n.filter(l=>l.provider===o).length}));j(i,V({providers:c}),()=>{console.log(J__default.default.bold("Available Providers:")),ht(i,["Provider","Models"],c.map(o=>[o.provider,o.modelCount.toString()]));});}catch(n){Q(i,n);}});}var HR,WR,$Xe=O({"src/cli/commands/model.ts"(){yr(),Ew(),sp(),HR=["llm","media"],WR=["chat","image","video","music","speech","sfx"];}}),efe={};mt(efe,{registerChannelCommand:()=>DXe});function Ao(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function DXe(e){let t=e.command("channel").description("Manage notification channels");t.command("types").description("List supported channel types").action(async()=>{let r=Ao(e);try{let s=f4;j(r,V({types:s}),()=>{console.log(J__default.default.bold("Supported Channel Types:")),console.log(),ht(r,["Type","Name","Description","Difficulty"],s.map(i=>[i.id,i.name,i.description,i.setupDifficulty]));});}catch(s){Q(r,s);}}),t.command("list").description("List all configured channels").action(async()=>{let r=Ao(e);try{let s=await Qt.listChannels(),i=await Qt.getDefaultChannel();j(r,V({channels:s,default:i?.id,count:s.length}),()=>{if(s.length===0){console.log(J__default.default.gray("No channels configured.")),console.log(),console.log("Create a channel with:"),console.log(J__default.default.cyan(" viben channel create my-telegram --type telegram --token <BOT_TOKEN>"));return}console.log(J__default.default.bold("Channels:")),console.log(),ht(r,["ID","Name","Type","Status","Default"],s.map(n=>[n.id,n.name,n.type,n.enabled?J__default.default.green("enabled"):J__default.default.gray("disabled"),n.is_default?J__default.default.yellow("*"):""])),i&&(console.log(),console.log(J__default.default.yellow("* = default channel")));});}catch(s){Q(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=Ao(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 Qt.createChannel(c);j(i,V({channel:o}),()=>{Me(i,`Channel "${o.id}" created successfully`),console.log(),Qe(i,{ID:o.id,Name:o.name,Type:o.type,Status:o.enabled?"enabled":"disabled",Default:o.is_default?"yes":"no"});});}catch(n){Q(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=Ao(e),i=r.name;try{if(!await Qt.getChannel(i))throw new Error(`Channel "${i}" not found`);await Qt.removeChannel(i),j(s,V({removed:i}),()=>{Me(s,`Channel "${i}" removed successfully`);});}catch(n){Q(s,n);}}),t.command("enable").description("Enable a channel").requiredOption("-n, --name <id>","Channel ID to enable").action(async r=>{let s=Ao(e),i=r.name;try{let n=await Qt.enableChannel(i);j(s,V({channel:n}),()=>{Me(s,`Channel "${i}" enabled`);});}catch(n){Q(s,n);}}),t.command("disable").description("Disable a channel").requiredOption("-n, --name <id>","Channel ID to disable").action(async r=>{let s=Ao(e),i=r.name;try{let n=await Qt.disableChannel(i);j(s,V({channel:n}),()=>{Me(s,`Channel "${i}" disabled`);});}catch(n){Q(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=Ao(e),i=r.name;try{let n=await Qt.setDefaultChannel(i);j(s,V({channel:n}),()=>{Me(s,`Channel "${i}" set as default`);});}catch(n){Q(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=Ao(e),i=r.name;try{if(i){let n=await Qt.getChannelStatus(i);j(s,V({status:n}),()=>{console.log(J__default.default.bold(`Channel: ${n.id}`)),console.log(),Qe(s,{Name:n.name,Type:n.type,Enabled:n.enabled?"yes":"no",Default:n.is_default?"yes":"no",Status:Ree(n.status),Details:n.details||"-",Error:n.error||"-",Latency:n.latency_ms?`${n.latency_ms}ms`:"-"});});}else {let n=await Qt.getAllChannelStatuses();j(s,V({statuses:n,count:n.length}),()=>{if(n.length===0){console.log(J__default.default.gray("No channels configured."));return}console.log(J__default.default.bold("Channel Status:")),console.log(),ht(s,["ID","Type","Enabled","Status","Latency"],n.map(a=>[a.is_default?`${a.id}${J__default.default.yellow("*")}`:a.id,a.type,a.enabled?J__default.default.green("yes"):J__default.default.gray("no"),Ree(a.status),a.latency_ms?`${a.latency_ms}ms`:"-"]));});}}catch(n){Q(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=Ao(e),c=n.name;try{let o=await Qt.getChannel(c);if(!o)throw new Error(`Channel "${c}" not found`);if(r==="set"&&s){let l=await Qt.updateChannelConfig(c,s,i);j(a,V({channel:l}),()=>{Me(a,`Channel "${c}" config updated: ${s}=${i}`);});}else j(a,V({channel:o}),()=>{if(console.log(J__default.default.bold(`Channel: ${o.id}`)),console.log(),Qe(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(J__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?RXe(String(d)):"-":l[u]=d!=null?String(d):"-";Qe(a,l);}console.log(),console.log("To update a config value:"),console.log(J__default.default.cyan(` viben channel config ${c} set <key> <value>`));});}catch(o){Q(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=Ao(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 Qt.getChannel(s.name);if(!c)throw new Error(`Channel "${s.name}" not found`);if(c.type==="whatsapp"){console.log(J__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(J__default.default.gray(`Login flow for ${c.type} is not yet implemented.`)),console.log("Please configure credentials manually:"),console.log(J__default.default.cyan(` viben channel config ${c.id} set token <YOUR_TOKEN>`));return}j(i,V({type:a,guide:!0}),()=>{switch(console.log(J__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(J__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(J__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(J__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(J__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(J__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(J__default.default.cyan(" viben channel create my-webhook --type webhook --url <WEBHOOK_URL>"));break}});}catch(n){Q(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=Ao(e);try{let n=await Qt.getChannel(r);if(!n)throw new Error(`Channel "${r}" not found`);let a=Qt.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(J__default.default.gray("Testing channel connectivity..."));let c=await sde(a);if(!c.success)throw new Error(`Channel test failed: ${c.error}`);if(console.log(J__default.default.green("Connectivity test passed.")),s){console.log(J__default.default.gray("Sending test message..."));let o=await ide(a,s);if(!o.success)throw new Error(`Failed to send test message: ${o.error}`);j(i,V({test:"passed",message:"sent"}),()=>{Me(i,"Test message sent successfully!"),o.messageId&&console.log(J__default.default.gray(`Message ID: ${o.messageId}`));});}else j(i,V({test:"passed"}),()=>{Me(i,"Channel connectivity test passed!"),c.details&&console.log(J__default.default.gray(c.details)),console.log(),console.log("To send a test message:"),console.log(J__default.default.cyan(` viben channel test ${r} <CHAT_ID>`));});}catch(n){Q(i,n);}});}function Ree(e){switch(e){case "connected":return J__default.default.green("connected");case "disconnected":return J__default.default.gray("disconnected");case "error":return J__default.default.red("error");case "disabled":return J__default.default.gray("disabled");default:return e}}function RXe(e){return e.length<=8?"****":e.substring(0,4)+"****"+e.substring(e.length-4)}var qXe=O({"src/cli/commands/channel.ts"(){yr(),Uy();}}),tfe={};mt(tfe,{registerServiceCommand:()=>UXe});function qee(e){switch(e){case "running":return J__default.default.green("running");case "stopped":return J__default.default.gray("stopped");case "failed":return J__default.default.red("failed");default:return J__default.default.yellow("unknown")}}function A_(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}async function NXe(e,t){if(t){let i=await Ra.getServiceStatus(t);j(e,V(i),()=>{if(console.log(J__default.default.bold(`Service: ${i.name}`)),console.log(),console.log(` ${J__default.default.cyan("Type:")} ${i.type}`),console.log(` ${J__default.default.cyan("Status:")} ${qee(i.status)}`),i.pid&&console.log(` ${J__default.default.cyan("PID:")} ${i.pid}`),i.uptime&&console.log(` ${J__default.default.cyan("Uptime:")} ${i.uptime}`),i.command){let n=i.args?.length?`${i.command} ${i.args.join(" ")}`:i.command;console.log(` ${J__default.default.cyan("Command:")} ${n}`);}i.error&&console.log(` ${J__default.default.cyan("Error:")} ${J__default.default.red(i.error)}`);});return}let r=await Ra.listServices(),s=V({services:r.map(i=>({name:i.name,type:i.type,status:i.status,pid:i.pid,uptime:i.uptime})),count:r.length});j(e,s,()=>{if(console.log(J__default.default.bold("Services:")),console.log(),r.length===0){console.log(J__default.default.gray(" No services tracked."));return}let i=["Name","Type","Status","PID","Uptime"],n=r.map(a=>[a.name,a.type,qee(a.status),a.pid?.toString()||J__default.default.gray("-"),a.uptime||J__default.default.gray("-")]);ht(e,i,n);});}async function LXe(e,t,r,s){let i=await Ra.getServiceStatus(t);if(i.status==="running"){j(e,V({name:t,status:"running",message:"Service is already running",pid:i.pid,uptime:i.uptime}),()=>{console.log(J__default.default.yellow(`Service ${t} is already running`)),console.log(` PID: ${i.pid}`),console.log(` Uptime: ${i.uptime}`);});return}let n=await Ra.startService(t,r,s);n.status==="running"?j(e,V({name:t,status:"running",pid:n.pid,command:n.command,args:n.args}),()=>{if(console.log(J__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}`);}}):j(e,V({name:t,status:n.status,error:n.error}),()=>{console.error(J__default.default.red(`Failed to start service ${t}`)),n.error&&console.error(` Error: ${n.error}`);});}async function jXe(e,t){let r=await Ra.getServiceStatus(t);if(r.status!=="running"){j(e,V({name:t,status:"stopped",message:"Service is not running"}),()=>{console.log(J__default.default.yellow(`Service ${t} is not running`));});return}await Ra.stopService(t);j(e,V({name:t,status:"stopped",previousPid:r.pid}),()=>{console.log(J__default.default.green(`Stopped service ${t}`)),console.log(` Previous PID: ${r.pid}`);});}async function MXe(e,t,r,s){let i=await Ra.restartService(t,r,s);j(e,V({name:t,status:i.status,pid:i.pid}),()=>{i.status==="running"?(console.log(J__default.default.green(`Restarted service ${t}`)),console.log(` PID: ${i.pid}`)):(console.log(J__default.default.yellow(`Service ${t} status: ${i.status}`)),i.error&&console.log(` Error: ${i.error}`));});}async function zXe(e,t,r){let{follow:s,lines:i=100,clear:n}=r;if(n){await Ra.clearLogs(t),j(e,V({name:t,cleared:true}),()=>{console.log(J__default.default.green(`Cleared logs for service ${t}`));});return}let a=Ra.getLogPath(t);if(s){if(e.json){let u=await Ra.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(J__default.default.bold(`Logs for ${t}:`)),console.log(J__default.default.gray(`Path: ${a}`)),console.log(J__default.default.gray("Press Ctrl+C to stop following")),console.log();let o=await Ra.getServiceLogs(t,i);for(let u of o)console.log(u);let l=Ra.watchLogs({name:t,onLine:u=>{console.log(u);}});process.on("SIGINT",()=>{l(),console.log(),console.log(J__default.default.gray("Stopped following logs")),process.exit(0);}),await new Promise(()=>{});return}let c=await Ra.getServiceLogs(t,i);j(e,V({name:t,logPath:a,lines:c,count:c.length}),()=>{if(console.log(J__default.default.bold(`Logs for ${t}:`)),console.log(J__default.default.gray(`Path: ${a}`)),console.log(),c.length===0){console.log(J__default.default.gray("No logs available."));return}for(let o of c)console.log(o);});}function UXe(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=A_(e);try{await NXe(s,r);}catch(i){Q(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=A_(e);try{await LXe(n,r,i.command,s.length>0?s:void 0);}catch(a){Q(n,a);}}),t.command("stop").argument("<name>","Service name").description("Stop a service").action(async r=>{let s=A_(e);try{await jXe(s,r);}catch(i){Q(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=A_(e);try{await MXe(n,r,i.command,s.length>0?s:void 0);}catch(a){Q(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=A_(e);try{await zXe(i,r,{follow:s.follow,lines:s.lines?parseInt(s.lines,10):100,clear:s.clear});}catch(n){Q(i,n);}});}var BXe=O({"src/cli/commands/service.ts"(){yr(),a2();}}),rfe,Nee=O({"src/gateway/queue/types.ts"(){rfe={max_concurrency:3,default_max_retries:3,persist_debounce_ms:500,shutdown_timeout_ms:3e4};}});function ly(){return Re.join(zi.homedir(),".viben","queue")}function Lee(){return Re.join(ly(),"state.yaml")}function VR(){return Re.join(ly(),"tasks")}function jee(){return Re.join(ly(),"corrupted")}function LT(e){return Re.join(VR(),`task-${e}.yaml`)}function KXe(e){return Lx||(Lx=new afe(e)),Lx}var gh,afe,Lx,JXe=O({"src/gateway/queue/persistence.ts"(){Er(),Ke(),gh=je.child({module:"queue-persistence"}),afe=class{constructor(e=500){this.stateDebounceTimer=null,this.pendingState=null,this.taskDebounceTimers=new Map,this.pendingTasks=new Map,this.debounceMs=e;}async ensureDirectories(){await ft(ly()),await ft(VR());}async loadState(){let e=Lee();return Et(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=Lee();e.last_updated=Date.now(),await Sr(t,e);}async loadTask(e){let t=LT(e),r=await Et(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 gh.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=LT(e);await Sr(r,t);}async deleteTask(e){let t=LT(e);if(De.existsSync(t))try{await Ls.unlink(t);}catch(r){gh.warn({err:r,taskId:e},"Failed to delete task");}}async moveToCorrupted(e){let t=LT(e);if(!De.existsSync(t))return;await ft(jee());let r=Re.join(jee(),`task-${e}-${Date.now()}.yaml`);try{await Ls.rename(t,r),gh.warn({taskId:e,corruptedPath:r},"Moved corrupted task");}catch(s){gh.error({err:s,taskId:e},"Failed to move corrupted task");}}async loadAllTasks(){let e=new Map,t=VR();if(!De.existsSync(t))return e;try{let r=await Ls.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){gh.error({err:n,taskId:i},"Failed to load task"),await this.moveToCorrupted(i);}}}catch(r){gh.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=Re.join(ly(),"config.yaml");await Sr(t,e);}async loadConfig(){let e=Re.join(ly(),"config.yaml");return Et(e)}},Lx=null;}});function XXe(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 vD,sfe,QXe=O({"src/gateway/queue/worker.ts"(){cp(),Ke(),vD=je.child({module:"queue-worker"}),sfe=class extends GVe.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 Hc,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(),vD.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(),vD.info({taskId:e},"Force cancelled task");this.abortControllers.clear();}};}});function tQe(){return `task_${sw.randomUUID()}`}var Ca,ife,rQe=O({"src/gateway/queue/index.ts"(){Nee(),JXe(),QXe(),Ke(),Nee(),Tpe(),Ca=je.child({module:"task-queue"}),ife=class extends GVe.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={...rfe,...t},this.persistence=KXe(this.config.persist_debounce_ms),this.worker=new sfe,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||(Ca.info("Starting queue manager..."),await this.restore(),this.started=true,this.accepting=true,this.tryDequeue(),Ca.info("Queue manager started"));}async enqueue(e){if(!this.accepting)throw new Error("Queue is not accepting new tasks");let t=tQe(),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(),Ca.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(),Ca.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(Ca.info("Shutting down..."),this.accepting=false,!await this.worker.waitForAll(this.config.shutdown_timeout_ms)){Ca.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,Ca.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(),Ca.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}}),Ca.info({taskId:e.id,durationMs:t.duration},"Task completed")):e.retry_count<e.max_retries&&XXe(t.error,t.exit_code)?(e.status="retrying",e.retry_count++,e.error=t.error,Ca.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}}),Ca.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){Ca.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++,Ca.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++,Ca.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);Ca.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){Ca.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){Ca.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){Ca.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(),Ca.info({taskId:e,position:this.queue.length},"Task re-queued for retry"),this.tryDequeue(),r)}isTaskExecuting(e){return this.worker.isExecuting(e)}};}}),yd,Mee,KR,ui,b2=O({"src/gateway/sse/task-sse-manager.ts"(){Ke(),yd=je.child({module:"task-sse-manager"}),Mee={maxListeners:1e3,heartbeatIntervalMs:3e4,staleTimeoutMs:12e4,maxFailedSends:3,cleanupIntervalMs:6e4},KR=class{constructor(e){this.heartbeatIntervalId=null,this.cleanupIntervalId=null,this.config={...Mee,...e},this.emitter=new GVe.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++,yd.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),yd.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&&yd.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),yd.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),yd.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++,yd.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(),yd.info("Closed and cleaned up all resources");}getWorkspaceSubscriberCount(e){return this.workspaceSubscribers.get(e)?.size??0}getActiveWorkspaces(){return Array.from(this.workspaceSubscribers.keys())}},ui=new KR;}}),vd,nfe,oQe=O({"src/queue/core/promoter.ts"(){Ki(),Ke(),vd=je.child({module:"command-queue-promoter"}),nfe=class extends GVe.EventEmitter{constructor(){super(),this.intervalId=null,this.running=false;}start(){if(this.running)return;this.running=true;let e=Xu();vd.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,vd.debug("Promoter stopped");}tick(){try{let e=Xu(),t=xn(),r=e.max_concurrency-t.length;if(r<=0){vd.trace({runningCount:t.length,maxConcurrency:e.max_concurrency},"No slots available");return}let s=Bo();if(s.length===0)return;vd.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);vd.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));vd.error({itemId:a.id,err:o},"Failed to spawn process"),this.emit("item:spawn-error",a,o),n.unshift(a);}dm(n);}catch(e){let t=e instanceof Error?e:new Error(String(e));vd.error({err:t},"Promoter tick failed"),this.emit("error",t);}}spawnProcess(e){let t=JKe(e.id),r=De.openSync(t,"a"),s=De.openSync(t,"a"),i=`[${new Date().toISOString()}] Starting command: ${e.command}
|
|
800
800
|
`;De.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(),De.closeSync(r),De.closeSync(s);let a={...e,pid:n.pid,started_at:Date.now(),log_file:t};return Zpe(a),a}promoteOne(){let e=Bo();if(e.length===0)return null;let t=Xu();if(xn().length>=t.max_concurrency)return null;let s=e[0],i=e.slice(1);try{let n=this.spawnProcess(s);return dm(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 lQe(e){try{return process.kill(e,0),!0}catch{return false}}function dQe(e){return lQe(e.pid)?{running:true}:{running:false,exitCode:0}}var yh,ofe,pQe=O({"src/queue/core/monitor.ts"(){Ki(),Ke(),yh=je.child({module:"command-queue-monitor"}),ofe=class extends GVe.EventEmitter{constructor(){super(),this.intervalId=null,this.running=false;}start(){if(this.running)return;this.running=true;let e=Xu();yh.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,yh.debug("Monitor stopped");}tick(){try{let e=xn();e.length>0&&yh.trace({runningCount:e.length},"Checking running processes");for(let t of e){let r=dQe(t);r.running||(yh.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));yh.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=`
|
|
801
801
|
[${new Date().toISOString()}] Process exited with code ${t} (duration: ${s}ms)
|
|
802
|
-
`;De.appendFileSync(e.log_file,n);}catch{}let i={...e,completed_at:r,exit_code:t};VKe(e.id),DL(i),t===0?this.emit("item:completed",i):(this.shouldRetry(e)&&this.retryItem(e),this.emit("item:failed",i));}shouldRetry(e){let t=Xu(),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;yh.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=Bo();i.push(s),dm(i),this.emit("item:retried",s,e.id);}checkNow(){this.tick();}forceComplete(e,t=0){let s=xn().find(i=>i.id===e);return s?(this.handleCompletion(s,t),true):false}};}}),Ua,cfe,mQe=O({"src/queue/core/command-queue.ts"(){oQe(),pQe(),Ki(),Ke(),Ome(),NL(),Ame(),Fme(),Wme(),Lme(),jme(),Hme(),Cme(),Ua=je.child({module:"command-queue"}),cfe=class extends GVe.EventEmitter{constructor(){super(),this.started=false,fl(),this.promoter=new nfe,this.monitor=new ofe,this.promoter.on("item:promoted",e=>{Ua.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)=>{Ua.error({itemId:e.id,err:t},"Item spawn failed"),this.emit("error",t);}),this.promoter.on("error",e=>{Ua.error({err:e},"Promoter error"),this.emit("error",e);}),this.monitor.on("item:completed",e=>{let t=e.completed_at-e.started_at;Ua.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;Ua.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;Ua.info({itemId:e.id,retryCount:t},"Item queued for retry"),this.emit("item:retried",e),this.emit("queue:changed");}),this.monitor.on("error",e=>{Ua.error({err:e},"Monitor error"),this.emit("error",e);});}async start(){if(this.started)return;Ua.info("Starting command queue..."),this.started=true;let{recovered:e}=await this.recoverFromRestart();e>0&&Ua.info({recovered:e},"Recovered dead processes from previous run"),this.promoter.start(),this.monitor.start(),Ua.info("Command queue started");}async stop(){this.started&&(Ua.info("Stopping command queue..."),this.promoter.stop(),this.monitor.stop(),this.started=false,Ua.info("Command queue stopped (running processes will continue)"));}async recoverFromRestart(){let e=xn(),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=qL(e);if(t.success){Ua.info({itemId:t.id,command:e.command,cwd:e.cwd},"Item enqueued");let r=Cy({id:t.id});r.success&&r.item&&this.emit("item:enqueued",r.item),this.emit("queue:changed");}else Ua.warn({command:e.command,error:t.error},"Failed to enqueue item");return t}cancel(e,t=false){let r=Pme({id:e,force:t});return r.success?(Ua.info({itemId:e,force:t},"Item cancelled"),this.emit("item:cancelled",e),this.emit("queue:changed")):Ua.warn({itemId:e,error:r.error},"Failed to cancel item"),r}retry(e){let t=YL(e);return t.success?(Ua.info({itemId:e.id},"Item retry initiated"),this.emit("queue:changed")):Ua.warn({itemId:e.id,error:t.error},"Failed to retry item"),t}getStatus(){return _2()}list(e){return $m(e)}inspect(e){return Cy({id:e})}getLogs(e){return XL(e)}getConfig(){return QL()}updateConfig(e){let t=L1(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=Gme(e);return t.success&&t.cleaned>0&&this.emit("queue:changed"),t}isRunning(){return this.started}};}}),ufe,fQe=O({"src/devices/device-registry.ts"(){ufe=class{constructor(e,t){this.events=e,this.devices=new Map,this.peerDevices=new Map,this.gatewayId=t??sw.randomUUID();}getGatewayId(){return this.gatewayId}registerClient(e){let t={id:sw.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)}};}}),JR,vQe=O({"src/mesh/peer-connection.ts"(){JR=class extends GVe.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 hT__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);}};}}),lfe,_Qe=O({"src/mesh/mesh-service.ts"(){vQe(),lfe=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 JR(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 JR(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);}};}}),Gee,dfe,SQe=O({"src/mesh/peer-store.ts"(){Er(),Gee=Re.join(zi.homedir(),".viben","mesh","peers.yaml"),dfe=class{constructor(e=Gee){this.path=e;}async load(){return (await Et(this.path))?.peers??[]}async save(e){await Sr(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 Hee(){if(YR)return ib;YR=true;try{ib=(await import('bonjour-service')).Bonjour;}catch{ib=null;}return ib}var _D,ib,YR,pfe,kQe=O({"src/discovery/mdns.ts"(){_D="viben-gateway",ib=null,YR=false,pfe=class{constructor(){this.instance=null,this.browser=null,this.published=false,this.onDiscoverCallback=null;}async start(e){let t=await Hee();t&&(this.instance=new t,this.instance.publish({name:e.name,type:_D,port:e.port,txt:{gateway_id:e.gateway_id,name:e.name,version:e.version}}),this.published=true,this.browser=this.instance.find({type:_D},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 Hee()!==null}};}});async function EQe(){if(nb)return nb;if(XR)throw new Error("qrcode package not available");XR=true;try{return nb=await import('qrcode'),nb}catch{throw new Error("qrcode package not available. Install it with: pnpm add qrcode")}}async function TQe(e){let t=await EQe(),r=JSON.stringify(e);return t.toDataURL(r,{width:256,margin:2})}var nb,XR,xQe=O({"src/discovery/qr.ts"(){nb=null,XR=false;}}),hfe,IQe=O({"src/discovery/discovery-service.ts"(){kQe(),xQe(),hfe=class{constructor(e,t){this.events=e,this.mdns=new pfe,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 TQe(this.getQrPayload())}async isMdnsAvailable(){return this.mdns.isAvailable()}};}}),mfe={};mt(mfe,{generateKeyPair:()=>PQe,sign:()=>AQe,verify:()=>CQe});function QR(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function ZR(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 PQe(){let e=YM.randomSecretKey(),t=HM(e);return {publicKey:QR(t),privateKey:QR(e)}}async function AQe(e,t){let r=ZR(t),s=new TextEncoder().encode(e),i=await VM(s,r);return QR(i)}async function CQe(e,t,r){try{let s=ZR(r),i=ZR(t),n=new TextEncoder().encode(e);return await JM(i,n,s)}catch{return false}}var OQe=O({"src/utils/crypto.ts"(){}});function FQe(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 $Qe(e,t){let r=e+t.namespace+t.name+t.description+JSON.stringify(t.inputSchema??null)+JSON.stringify(t.outputSchema??null);return FQe(r)}var ai,Wee,Vee,Kee,ej,ffe=O({"src/gateway/client-store.ts"(){Ke(),ai=je.child({module:"client-store"}),Wee=3e4,Vee=1e3,Kee=1024*1024,ej=class{constructor(e={}){this.clients=new Map,this.nameIndex=new Map,this._globalTheme="light",this.config={gracePeriodMs:e.gracePeriodMs??Wee,maxActionsPerClient:e.maxActionsPerClient??Vee,maxPayloadSize:e.maxPayloadSize??Kee};}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 ai.warn({clientId:e,timestamp:s,now:i},"Signature timestamp expired"),false;try{let{verify:n}=await Promise.resolve().then(()=>(OQe(),mfe)),a=`${e}:${s}`;return await n(a,r,t)}catch(n){return ai.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,ai.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),ai.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()}),ai.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),ai.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),ai.info({clientId:e,action:i},"Action removed (socket disconnected)");}return {actionsRemoved:s,clientRemoved:false}}return ai.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),ai.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 ai.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=$Qe(e,r),a=s.actionStore.get(i);if(a&&a.hash===n)return a.socketId!==t&&(a.socketId=t,ai.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),ai.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&&ai.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(),ai.info("ClientStore shut down");}};}});function gfe(e={}){let{host:t="127.0.0.1",port:r=18790,runtime:s=true}=e,i=new I1,n=new Yb,a=new oL(i),c=new cL(i,n),o=new P1,l=new uL(i),u=new iue({events:i,channels:Qt,container:c,responseTimeout:12e4}),d=new ade({channelManager:Qt,messageBus:l,auto_start:true,pollingTimeout:30}),h=new ife(i),v=new KR({heartbeatIntervalMs:3e4,staleTimeoutMs:12e4,maxFailedSends:3,cleanupIntervalMs:6e4});s&&v.startHeartbeat();let y=new Dpe(er,v,{stuckThresholdMs:300*1e3,autoRecover:true}),_=new cfe,b=new ufe(i),w=b.getGatewayId(),S=new dfe,E={gateway_id:w,name:`viben-${w.slice(0,8)}`,version:"1.0.0",capabilities:["navigate","notify","ping"],address:`http://${t}:${r}`},A=new lfe(i,b,S,E),C=new ej,F=new hfe(i,{gateway_id:w,name:E.name,version:"1.0.0",port:r});return s&&F.onPeerDiscovered($=>{A.connectToPeer($);}),{events:i,sessionStore:n,cron:a,container:c,history:o,messageBus:l,channelRouter:u,channelRuntime:d,taskQueue:h,taskRecovery:y,taskSSEManager:v,commandQueue:_,deviceRegistry:b,mesh:A,discovery:F,clientStore:C}}var Jee=O({"src/gateway/state.ts"(){WI(),ip(),Sde(),kde(),Tde(),xde(),Uy(),rQe(),Rpe(),Om(),b2(),mQe(),fQe(),_Qe(),SQe(),IQe(),ffe();}});function yfe(e){let t=Re.join(zi.homedir(),".viben");rj={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 qQe(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()-vfe,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:tj,timestamp:new Date().toISOString(),uptime:a,uptime_seconds:r,startup:rj||void 0}});}var tj,rj,vfe,j1=O({"src/gateway/routes/health.ts"(){tj="1.3.1",rj=null,vfe=Date.now();}});function aj(e){return e.replace(/\//g,"-")}function sj(){return Re__namespace.join(zi__namespace.homedir(),".claude","projects")}async function NQe(e){let t=sj(),r=aj(e),s=Re__namespace.join(t,r);if(!De__namespace.existsSync(s))return [];let a=(await De__namespace.promises.readdir(s,{withFileTypes:true})).filter(o=>o.isFile()&&o.name.endsWith(".jsonl")).map(async o=>{let l=o.name.replace(".jsonl",""),u=Re__namespace.join(s,o.name);try{let[d,h]=await Promise.all([De__namespace.promises.stat(u),bfe(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 bfe(e){try{let t=De__namespace.createReadStream(e),r=Zq__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 wfe(e,t){if(!De__namespace.existsSync(e))throw new Error(`Session file not found: ${e}`);let r=[],s=new Map,n=(await De__namespace.promises.readFile(e,"utf-8")).split(`
|
|
802
|
+
`;De.appendFileSync(e.log_file,n);}catch{}let i={...e,completed_at:r,exit_code:t};VKe(e.id),DL(i),t===0?this.emit("item:completed",i):(this.shouldRetry(e)&&this.retryItem(e),this.emit("item:failed",i));}shouldRetry(e){let t=Xu(),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;yh.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=Bo();i.push(s),dm(i),this.emit("item:retried",s,e.id);}checkNow(){this.tick();}forceComplete(e,t=0){let s=xn().find(i=>i.id===e);return s?(this.handleCompletion(s,t),true):false}};}}),Ua,cfe,mQe=O({"src/queue/core/command-queue.ts"(){oQe(),pQe(),Ki(),Ke(),Ome(),NL(),Ame(),Fme(),Wme(),Lme(),jme(),Hme(),Cme(),Ua=je.child({module:"command-queue"}),cfe=class extends GVe.EventEmitter{constructor(){super(),this.started=false,fl(),this.promoter=new nfe,this.monitor=new ofe,this.promoter.on("item:promoted",e=>{Ua.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)=>{Ua.error({itemId:e.id,err:t},"Item spawn failed"),this.emit("error",t);}),this.promoter.on("error",e=>{Ua.error({err:e},"Promoter error"),this.emit("error",e);}),this.monitor.on("item:completed",e=>{let t=e.completed_at-e.started_at;Ua.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;Ua.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;Ua.info({itemId:e.id,retryCount:t},"Item queued for retry"),this.emit("item:retried",e),this.emit("queue:changed");}),this.monitor.on("error",e=>{Ua.error({err:e},"Monitor error"),this.emit("error",e);});}async start(){if(this.started)return;Ua.info("Starting command queue..."),this.started=true;let{recovered:e}=await this.recoverFromRestart();e>0&&Ua.info({recovered:e},"Recovered dead processes from previous run"),this.promoter.start(),this.monitor.start(),Ua.info("Command queue started");}async stop(){this.started&&(Ua.info("Stopping command queue..."),this.promoter.stop(),this.monitor.stop(),this.started=false,Ua.info("Command queue stopped (running processes will continue)"));}async recoverFromRestart(){let e=xn(),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=qL(e);if(t.success){Ua.info({itemId:t.id,command:e.command,cwd:e.cwd},"Item enqueued");let r=Cy({id:t.id});r.success&&r.item&&this.emit("item:enqueued",r.item),this.emit("queue:changed");}else Ua.warn({command:e.command,error:t.error},"Failed to enqueue item");return t}cancel(e,t=false){let r=Pme({id:e,force:t});return r.success?(Ua.info({itemId:e,force:t},"Item cancelled"),this.emit("item:cancelled",e),this.emit("queue:changed")):Ua.warn({itemId:e,error:r.error},"Failed to cancel item"),r}retry(e){let t=YL(e);return t.success?(Ua.info({itemId:e.id},"Item retry initiated"),this.emit("queue:changed")):Ua.warn({itemId:e.id,error:t.error},"Failed to retry item"),t}getStatus(){return _2()}list(e){return $m(e)}inspect(e){return Cy({id:e})}getLogs(e){return XL(e)}getConfig(){return QL()}updateConfig(e){let t=L1(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=Gme(e);return t.success&&t.cleaned>0&&this.emit("queue:changed"),t}isRunning(){return this.started}};}}),ufe,fQe=O({"src/devices/device-registry.ts"(){ufe=class{constructor(e,t){this.events=e,this.devices=new Map,this.peerDevices=new Map,this.gatewayId=t??sw.randomUUID();}getGatewayId(){return this.gatewayId}registerClient(e){let t={id:sw.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)}};}}),JR,vQe=O({"src/mesh/peer-connection.ts"(){JR=class extends GVe.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 hT__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);}};}}),lfe,_Qe=O({"src/mesh/mesh-service.ts"(){vQe(),lfe=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 JR(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 JR(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);}};}}),Gee,dfe,SQe=O({"src/mesh/peer-store.ts"(){Er(),Gee=Re.join(zi.homedir(),".viben","mesh","peers.yaml"),dfe=class{constructor(e=Gee){this.path=e;}async load(){return (await Et(this.path))?.peers??[]}async save(e){await Sr(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 Hee(){if(YR)return ib;YR=true;try{ib=(await import('bonjour-service')).Bonjour;}catch{ib=null;}return ib}var _D,ib,YR,pfe,kQe=O({"src/discovery/mdns.ts"(){_D="viben-gateway",ib=null,YR=false,pfe=class{constructor(){this.instance=null,this.browser=null,this.published=false,this.onDiscoverCallback=null;}async start(e){let t=await Hee();t&&(this.instance=new t,this.instance.publish({name:e.name,type:_D,port:e.port,txt:{gateway_id:e.gateway_id,name:e.name,version:e.version}}),this.published=true,this.browser=this.instance.find({type:_D},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 Hee()!==null}};}});async function EQe(){if(nb)return nb;if(XR)throw new Error("qrcode package not available");XR=true;try{return nb=await import('qrcode'),nb}catch{throw new Error("qrcode package not available. Install it with: pnpm add qrcode")}}async function TQe(e){let t=await EQe(),r=JSON.stringify(e);return t.toDataURL(r,{width:256,margin:2})}var nb,XR,xQe=O({"src/discovery/qr.ts"(){nb=null,XR=false;}}),hfe,IQe=O({"src/discovery/discovery-service.ts"(){kQe(),xQe(),hfe=class{constructor(e,t){this.events=e,this.mdns=new pfe,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 TQe(this.getQrPayload())}async isMdnsAvailable(){return this.mdns.isAvailable()}};}}),mfe={};mt(mfe,{generateKeyPair:()=>PQe,sign:()=>AQe,verify:()=>CQe});function QR(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function ZR(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 PQe(){let e=YM.randomSecretKey(),t=HM(e);return {publicKey:QR(t),privateKey:QR(e)}}async function AQe(e,t){let r=ZR(t),s=new TextEncoder().encode(e),i=await VM(s,r);return QR(i)}async function CQe(e,t,r){try{let s=ZR(r),i=ZR(t),n=new TextEncoder().encode(e);return await JM(i,n,s)}catch{return false}}var OQe=O({"src/utils/crypto.ts"(){}});function FQe(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 $Qe(e,t){let r=e+t.namespace+t.name+t.description+JSON.stringify(t.inputSchema??null)+JSON.stringify(t.outputSchema??null);return FQe(r)}var ai,Wee,Vee,Kee,ej,ffe=O({"src/gateway/client-store.ts"(){Ke(),ai=je.child({module:"client-store"}),Wee=3e4,Vee=1e3,Kee=1024*1024,ej=class{constructor(e={}){this.clients=new Map,this.nameIndex=new Map,this._globalTheme="light",this.config={gracePeriodMs:e.gracePeriodMs??Wee,maxActionsPerClient:e.maxActionsPerClient??Vee,maxPayloadSize:e.maxPayloadSize??Kee};}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 ai.warn({clientId:e,timestamp:s,now:i},"Signature timestamp expired"),false;try{let{verify:n}=await Promise.resolve().then(()=>(OQe(),mfe)),a=`${e}:${s}`;return await n(a,r,t)}catch(n){return ai.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,ai.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),ai.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()}),ai.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),ai.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),ai.info({clientId:e,action:i},"Action removed (socket disconnected)");}return {actionsRemoved:s,clientRemoved:false}}return ai.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),ai.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 ai.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=$Qe(e,r),a=s.actionStore.get(i);if(a&&a.hash===n)return a.socketId!==t&&(a.socketId=t,ai.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),ai.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&&ai.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(),ai.info("ClientStore shut down");}};}});function gfe(e={}){let{host:t="127.0.0.1",port:r=18790,runtime:s=true}=e,i=new I1,n=new Yb,a=new oL(i),c=new cL(i,n),o=new P1,l=new uL(i),u=new iue({events:i,channels:Qt,container:c,responseTimeout:12e4}),d=new ade({channelManager:Qt,messageBus:l,auto_start:true,pollingTimeout:30}),h=new ife(i),v=new KR({heartbeatIntervalMs:3e4,staleTimeoutMs:12e4,maxFailedSends:3,cleanupIntervalMs:6e4});s&&v.startHeartbeat();let y=new Dpe(er,v,{stuckThresholdMs:300*1e3,autoRecover:true}),_=new cfe,b=new ufe(i),w=b.getGatewayId(),S=new dfe,E={gateway_id:w,name:`viben-${w.slice(0,8)}`,version:"1.0.0",capabilities:["navigate","notify","ping"],address:`http://${t}:${r}`},A=new lfe(i,b,S,E),C=new ej,F=new hfe(i,{gateway_id:w,name:E.name,version:"1.0.0",port:r});return s&&F.onPeerDiscovered($=>{A.connectToPeer($);}),{events:i,sessionStore:n,cron:a,container:c,history:o,messageBus:l,channelRouter:u,channelRuntime:d,taskQueue:h,taskRecovery:y,taskSSEManager:v,commandQueue:_,deviceRegistry:b,mesh:A,discovery:F,clientStore:C}}var Jee=O({"src/gateway/state.ts"(){WI(),ip(),Sde(),kde(),Tde(),xde(),Uy(),rQe(),Rpe(),Om(),b2(),mQe(),fQe(),_Qe(),SQe(),IQe(),ffe();}});function yfe(e){let t=Re.join(zi.homedir(),".viben");rj={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 qQe(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()-vfe,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:tj,timestamp:new Date().toISOString(),uptime:a,uptime_seconds:r,startup:rj||void 0}});}var tj,rj,vfe,j1=O({"src/gateway/routes/health.ts"(){tj="1.3.2",rj=null,vfe=Date.now();}});function aj(e){return e.replace(/\//g,"-")}function sj(){return Re__namespace.join(zi__namespace.homedir(),".claude","projects")}async function NQe(e){let t=sj(),r=aj(e),s=Re__namespace.join(t,r);if(!De__namespace.existsSync(s))return [];let a=(await De__namespace.promises.readdir(s,{withFileTypes:true})).filter(o=>o.isFile()&&o.name.endsWith(".jsonl")).map(async o=>{let l=o.name.replace(".jsonl",""),u=Re__namespace.join(s,o.name);try{let[d,h]=await Promise.all([De__namespace.promises.stat(u),bfe(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 bfe(e){try{let t=De__namespace.createReadStream(e),r=Zq__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 wfe(e,t){if(!De__namespace.existsSync(e))throw new Error(`Session file not found: ${e}`);let r=[],s=new Map,n=(await De__namespace.promises.readFile(e,"utf-8")).split(`
|
|
803
803
|
`).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=LQe(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 LQe(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 Sfe(){return process.platform==="darwin"?Re__namespace.join(zi__namespace.homedir(),"Library","Application Support","codex","sessions"):process.platform==="win32"?Re__namespace.join(process.env.APPDATA||"","codex","sessions"):Re__namespace.join(zi__namespace.homedir(),".config","codex","sessions")}async function jQe(e){let t=Sfe();if(!De__namespace.existsSync(t))return [];let r=[];try{let s=await De__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=Re__namespace.join(t,i.name),c=await De__namespace.promises.stat(a),o=await bfe(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 MQe(e,t){if(!De__namespace.existsSync(e))return [];let r=[];try{let i=(await De__namespace.promises.readFile(e,"utf-8")).split(`
|
|
804
804
|
`).filter(n=>n.trim()!=="");for(let n of i)try{let a=JSON.parse(n),c=zQe(a);if(r.push(...c),t&&r.length>=t)break}catch{}}catch{}return r}function zQe(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 UQe(e,t){let r=zi__namespace.homedir();switch(e){case "CLAUDE_CODE":{let s=Re__namespace.join(r,".claude"),i=t?Re__namespace.join(t,".claude"):void 0;return {globalConfigPath:De__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&De__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "CODEX":{let s;process.platform==="darwin"?s=Re__namespace.join(r,"Library","Application Support","codex"):process.platform==="win32"?s=Re__namespace.join(process.env.APPDATA||"","codex"):s=Re__namespace.join(r,".config","codex");let i=t?Re__namespace.join(t,".codex"):void 0;return {globalConfigPath:De__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&De__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "CURSOR_AGENT":{let s;process.platform==="darwin"?s=Re__namespace.join(r,"Library","Application Support","Cursor","User"):process.platform==="win32"?s=Re__namespace.join(process.env.APPDATA||"","Cursor","User"):s=Re__namespace.join(r,".config","Cursor","User");let i=t?Re__namespace.join(t,".cursor"):void 0;return {globalConfigPath:De__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&De__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "GEMINI":{let s=Re__namespace.join(r,".gemini"),i=t?Re__namespace.join(t,".gemini"):void 0;return {globalConfigPath:De__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&De__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "AMP":{let s;process.platform==="darwin"?s=Re__namespace.join(r,"Library","Application Support","amp"):process.platform==="win32"?s=Re__namespace.join(process.env.APPDATA||"","amp"):s=Re__namespace.join(r,".config","amp");let i=t?Re__namespace.join(t,".amp"):void 0;return {globalConfigPath:De__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&De__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}case "OPENCLAW":{let s=Re__namespace.join(r,".openclaw"),i=Re__namespace.join(s,"openclaw.json"),n=t?Re__namespace.join(t,".openclaw"):void 0;return {globalConfigPath:De__namespace.existsSync(i)?i:De__namespace.existsSync(s)?s:void 0,workspaceConfigPath:n&&De__namespace.existsSync(n)?n:void 0,globalConfigDir:s,workspaceConfigDir:n}}default:{let s=Re__namespace.join(r,".viben"),i=t?Re__namespace.join(t,".viben"):void 0;return {globalConfigPath:De__namespace.existsSync(s)?s:void 0,workspaceConfigPath:i&&De__namespace.existsSync(i)?i:void 0,globalConfigDir:s,workspaceConfigDir:i}}}}function BQe(e,t){let r=kfe[e]||{name:e,description:`${e} executor`},s=UQe(e,t),i=!!(s.globalConfigPath||s.workspaceConfigPath),n=!!s.workspaceConfigPath,a;if(i)if(e==="CLAUDE_CODE"&&s.globalConfigPath){let l=Re__namespace.join(s.globalConfigPath,".credentials.json");if(De__namespace.existsSync(l))try{a={type:"LOGIN_DETECTED",last_auth_timestamp:De__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||zi__namespace.homedir()}}function GQe(e){return ["CLAUDE_CODE","CODEX","CURSOR_AGENT","GEMINI","AMP","OPENCLAW"].map(r=>BQe(r,e))}function HQe(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 _=y.query.workspace_path,b=y.query.include_global!=="false",w=GQe(_);return {executors:w,workspace_path:_||zi__namespace.homedir(),include_global:b,total:w.length}}),e.get("/api/executors/:type/discover-sessions",async(y,_)=>{let{type:b}=y.params,{workspace_path:w}=y.query;if(!w)return _.code(400),{error:"workspace_path query parameter is required"};let S=[];switch(b){case "CLAUDE_CODE":S=await NQe(w);break;case "CODEX":S=await jQe(w);break;default:return _.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,_)=>{let{type:b,sessionId:w}=y.params,{workspace_path:S,limit:E}=y.query;if(!S)return _.code(400),{error:"workspace_path query parameter is required"};let A=[];switch(b){case "CLAUDE_CODE":{let F=sj(),$=aj(S),U=Re__namespace.join(F,$,`${w}.jsonl`);A=await wfe(U,E);break}case "CODEX":{let F=Sfe(),$=Re__namespace.join(F,`${w}.jsonl`);De__namespace.existsSync($)&&(A=await MQe($,E));break}default:return _.code(404),{error:`Unknown executor type: ${b}. Use uppercase format like CLAUDE_CODE`}}return {messages:A,total:A.length}});function t(y,_){let b=y||zi__namespace.homedir();switch(_){case "CLAUDE_CODE":let w=Re__namespace.join(b,".mcp.json");return De__namespace.existsSync(w)?w:Re__namespace.join(zi__namespace.homedir(),".claude.json");case "CURSOR_AGENT":return Re__namespace.join(b,".cursor","mcp.json");default:return Re__namespace.join(b,".viben","mcp.json")}}function r(y,_){if(!De__namespace.existsSync(y))return [];try{let b=De__namespace.readFileSync(y,"utf-8"),w=JSON.parse(b);if(_==="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:_}=y.params,{workspace_path:b}=y.query,w=_,S=t(b,w);if(!S)return {servers:[],total:0};let E=r(S,w);return {servers:E,total:E.length}});function s(y,_){let b=y||zi__namespace.homedir();switch(_){case "CLAUDE_CODE":return {jsonPath:Re__namespace.join(b,".claude","skills.json"),folderPath:Re__namespace.join(b,".claude","skills")};case "CURSOR_AGENT":return {jsonPath:Re__namespace.join(b,".cursor","skills.json"),folderPath:Re__namespace.join(b,".cursor","skills")};default:return {jsonPath:Re__namespace.join(b,".viben","skills.json"),folderPath:Re__namespace.join(b,".viben","skills")}}}function i(y){try{let _=De__namespace.readFileSync(y,"utf-8"),b=Re__namespace.basename(Re__namespace.dirname(y)),w=_.match(/^---\n([\s\S]*?)\n---/),S=b,E;if(w){let A=w[1],C=A.match(/^name:\s*(.+)$/m);C&&(S=C[1].trim());let F=A.match(/^description:\s*(.+)$/m);F&&(E=F[1].trim());}return {id:b,name:S,version:"1.0.0",source:"local",path:Re__namespace.dirname(y),description:E}}catch{return null}}function n(y){let _=[];if(!De__namespace.existsSync(y))return _;try{let b=De__namespace.readdirSync(y);for(let w of b){let S=Re__namespace.join(y,w);if(De__namespace.statSync(S).isDirectory()){let A=Re__namespace.join(S,"skill.md");if(De__namespace.existsSync(A)){let C=i(A);C&&_.push(C);}}}}catch{}return _}e.get("/api/executors/:type/skills",async y=>{let{type:_}=y.params,{workspace_path:b,include_global:w}=y.query,S=_,E=w!=="false",A=[];if(b){let{jsonPath:C,folderPath:F}=s(b,S);if(C&&De__namespace.existsSync(C))try{let $=De__namespace.readFileSync(C,"utf-8"),U=JSON.parse($);Array.isArray(U.skills)&&A.push(...U.skills);}catch{}if(F){let $=n(F);for(let U of $)A.find(D=>D.id===U.id)||A.push(U);}}if(E){let C=zi__namespace.homedir();if(!(!b||b===C)){let{jsonPath:$,folderPath:U}=s(void 0,S);if($&&De__namespace.existsSync($))try{let D=De__namespace.readFileSync($,"utf-8"),M=JSON.parse(D);if(Array.isArray(M.skills))for(let K of M.skills)A.find(R=>R.id===K.id)||A.push(K);}catch{}if(U){let D=n(U);for(let M of D)A.find(K=>K.id===M.id)||A.push(M);}}}if(!b){let{jsonPath:C,folderPath:F}=s(void 0,S);if(C&&De__namespace.existsSync(C))try{let $=De__namespace.readFileSync(C,"utf-8"),U=JSON.parse($);if(Array.isArray(U.skills))for(let D of U.skills)A.find(M=>M.id===D.id)||A.push(D);}catch{}if(F){let $=n(F);for(let U of $)A.find(D=>D.id===U.id)||A.push(U);}}return {skills:A,total:A.length}});function a(y,_){let b=y||zi__namespace.homedir();switch(_){case "CLAUDE_CODE":return Re__namespace.join(b,".claude","agents");case "CURSOR_AGENT":return Re__namespace.join(b,".cursor","agents");default:return Re__namespace.join(b,".viben","agents")}}function c(y,_){let b=Re__namespace.basename(y,".md"),w=b,S="",E=[],A="",C=_,F=_.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(F){let $=F[1];C=F[2].trim();let U=$.match(/^name:\s*(.+)$/m);U&&(w=U[1].trim());let D=$.match(/^description:\s*(.+)$/m);D&&(S=D[1].trim());let M=$.match(/^tools:\s*(.+)$/m);M&&(E=M[1].split(",").map(R=>R.trim()).filter(Boolean));let K=$.match(/^model:\s*(.+)$/m);K&&(A=K[1].trim());}return {id:b,name:w,description:S,tools:E,model:A,path:y,content:C}}function o(y){let _=[];if(!De__namespace.existsSync(y))return _;try{let b=De__namespace.readdirSync(y);for(let w of b){let S=Re__namespace.join(y,w);if(De__namespace.statSync(S).isFile()&&w.endsWith(".md"))try{let A=De__namespace.readFileSync(S,"utf-8");_.push(c(S,A));}catch{}}}catch{}return _}e.get("/api/executors/:type/subagents",async y=>{let{type:_}=y.params,{workspace_path:b}=y.query,S=a(b,_);return S?{configs:o(S)}:{configs:[]}}),e.get("/api/executors/:type/subagents/:config_id",async(y,_)=>{let{type:b,config_id:w}=y.params,{workspace_path:S}=y.query,A=a(S,b);if(!A)return _.code(404),{error:"Subagents path not found"};let C=Re__namespace.join(A,`${w}.md`);if(!De__namespace.existsSync(C))return _.code(404),{error:"Subagent file not found"};try{let F=De__namespace.readFileSync(C,"utf-8");return {config:c(C,F)}}catch(F){return _.code(500),{error:F instanceof Error?F.message:"Failed to read subagent"}}});function l(y,_){let b=y||zi__namespace.homedir();switch(_){case "CLAUDE_CODE":return Re__namespace.join(b,".claude","commands");case "CURSOR_AGENT":return Re__namespace.join(b,".cursor","commands");default:return Re__namespace.join(b,".viben","commands")}}function u(y){let _=[];if(!De__namespace.existsSync(y))return _;try{let b=De__namespace.readdirSync(y);for(let w of b){let S=Re__namespace.join(y,w),E=De__namespace.statSync(S);if(E.isDirectory())try{let A=De__namespace.readdirSync(S);for(let C of A)if(C.endsWith(".md")){let F=Re__namespace.join(S,C),$=C.replace(/\.md$/,"");try{let U=De__namespace.readFileSync(F,"utf-8");_.push({id:`${w}/${$}`,namespace:w,name:$,path:F,content:U});}catch{}}}catch{}else if(E.isFile()&&w.endsWith(".md")){let A=w.replace(/\.md$/,"");try{let C=De__namespace.readFileSync(S,"utf-8");_.push({id:A,namespace:"",name:A,path:S,content:C});}catch{}}}}catch{}return _}e.get("/api/executors/:type/commands",async y=>{let{type:_}=y.params,{workspace_path:b}=y.query,S=l(b,_);return S?{commands:u(S)}:{commands:[]}}),e.get("/api/executors/:type/commands/:command_id",async(y,_)=>{let{type:b,command_id:w}=y.params,{workspace_path:S}=y.query,A=l(S,b);if(!A)return _.code(404),{error:"Commands path not found"};let C=w.split("/"),F,$="",U=w;if(C.length===2?($=C[0],U=C[1],F=Re__namespace.join(A,$,`${U}.md`)):F=Re__namespace.join(A,`${w}.md`),!De__namespace.existsSync(F))return _.code(404),{error:"Command file not found"};try{let D=De__namespace.readFileSync(F,"utf-8");return {command:{id:w,namespace:$,name:U,path:F,content:D}}}catch(D){return _.code(500),{error:D instanceof Error?D.message:"Failed to read command"}}});function d(y,_){let b=y||zi__namespace.homedir();switch(_){case "CLAUDE_CODE":return Re__namespace.join(b,".claude","prompts");case "CURSOR_AGENT":return Re__namespace.join(b,".cursor","prompts");default:return Re__namespace.join(b,".viben","prompts")}}function h(y,_){let b=Re__namespace.basename(y,".md"),w=b,S="",E=_,A=_.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(A){let C=A[1];E=A[2].trim();let F=C.match(/^name:\s*(.+)$/m);F&&(w=F[1].trim());let $=C.match(/^description:\s*(.+)$/m);$&&(S=$[1].trim());}return {id:b,name:w,description:S,path:y,content:E}}function v(y){let _=[];if(!De__namespace.existsSync(y))return _;try{let b=De__namespace.readdirSync(y);for(let w of b){let S=Re__namespace.join(y,w);if(De__namespace.statSync(S).isFile()&&w.endsWith(".md"))try{let A=De__namespace.readFileSync(S,"utf-8");_.push(h(S,A));}catch{}}}catch{}return _}e.get("/api/executors/:type/prompts",async y=>{let{type:_}=y.params,{workspace_path:b}=y.query,S=d(b,_);return S?{prompts:v(S)}:{prompts:[]}}),e.get("/api/executors/:type/prompts/:prompt_id",async(y,_)=>{let{type:b,prompt_id:w}=y.params,{workspace_path:S}=y.query,A=d(S,b);if(!A)return _.code(404),{error:"Prompts path not found"};let C=Re__namespace.join(A,`${w}.md`);if(!De__namespace.existsSync(C))return _.code(404),{error:"Prompt file not found"};try{let F=De__namespace.readFileSync(C,"utf-8");return {prompt:h(C,F)}}catch(F){return _.code(500),{error:F instanceof Error?F.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:_,port:b,token:w,password:S}=y.body;try{let{loadGatewayConfig:E}=await Promise.resolve().then(()=>(Ey(),Z3)),{loadOrCreateDeviceIdentity:A,publicKeyToBase64Url:C}=await Promise.resolve().then(()=>(wce(),pce)),F=E({host:_,port:b,token:w,password:S}),$=A(),U=C($.publicKeyPem),D=(await import('ws')).default,M=`ws://${F.host}:${F.port}`;return await new Promise(K=>{let R=setTimeout(()=>{ee.close(),K({status:"failed",message:`Connection timeout (5s) to ${_}:${b}`});},5e3),ee=new D(M);ee.on("open",()=>{let de={type:"req",id:"test-"+Date.now(),method:"connect",params:{protocolVersion:3,clientId:"viben-desktop-test",clientMode:"operator",role:"operator",scopes:["operator.admin"],device:{id:$.deviceId,publicKey:U}}};ee.send(JSON.stringify(de));}),ee.on("message",de=>{try{let ye=JSON.parse(de.toString());ye.type==="res"?(clearTimeout(R),ee.close(1e3),ye.ok?K({status:"connected",device_id:$.deviceId}):ye.error?.code==="PAIRING_REQUIRED"?K({status:"pairing_required",device_id:$.deviceId,message:ye.error.message}):K({status:"failed",message:ye.error?.message||"Auth rejected"})):ye.type==="event"&&ye.event;}catch{}}),ee.on("error",de=>{clearTimeout(R),K({status:"failed",message:`Connection error: ${de.message}`});}),ee.on("close",(de,ye)=>{clearTimeout(R),de!==1e3&&K({status:"failed",message:`Connection closed: ${ye||`code ${de}`}`});});})}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(()=>(Ey(),Z3)),_=y();return {host:_.host,port:_.port,has_auth:_.auth?.mode!=="none"&&!!_.auth?.mode,cli_path:_.cliPath||void 0,config_source:"~/.openclaw/openclaw.json"}}catch{return {host:"127.0.0.1",port:18789,has_auth:false,config_source:"defaults"}}});}var kfe,eq=O({"src/gateway/routes/executors.ts"(){kfe={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 kg(e,t){if(t){let s=Re.join(t,".viben","agents"),i=await et.getAgentFromDir(s,e);if(i?.path)return i.path}let r=await et.getAgent(e);if(r?.path)return r.path}function KQe(e){try{return child_process.execFileSync("which",[e],{stdio:"ignore"}),!0}catch{return false}}function bD(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 Xee(e){return {timestamp:e.timestamp,role:e.role,content:e.content,tool_calls:e.toolCalls,tool_result:e.toolResult}}function JQe(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 YQe(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=zi.homedir(),c=(u,d,h)=>{if(!u)return null;let v=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:v,agent_dir:u.path,workspace_path:v==="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 et.listAgents();for(let d of u){let h=c(d,"global");h&&o.set(d.id,h);}}if(s){let u=Re.join(s,".viben","agents"),d=await et.listAgentsFromDir(u);for(let h of d){let v=c(h,"workspace",s);v&&o.set(h.id,v);}}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 et.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=zi.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 et.getDefault()||null})),e.put("/api/agent/default",async(r,s)=>{let{agent_id:i}=r.body;try{return await et.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 et.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 et.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 et.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 et.createFromTemplate(i,n,{name:a,base_path:c},o);s.code(201);let u=zi.homedir(),d=l.path&&l.path.startsWith(u)&&l.path.includes("/.viben/agents/"),h=d?"global":"workspace",v=!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:v,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 et.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=Re.join(n,".viben","agents"),u=await et.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 et.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(bD),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||sw.randomUUID();try{let c=n.agent_dir||await kg(i,n.workspace_path),o=_ie(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),bD(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 kg(i,a),o=await t.sessionStore.getSession(i,n,c);return bD(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 kg(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 kg(i,a),o=await t.sessionStore.readMessages(i,n,c);return {messages:o.map(Xee),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 kg(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),Xee(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 kg(i,a),o=await t.sessionStore.readUIMessages(i,n,c);if(o.length>0)return {messages:o.map(JQe),total:o.length};if(a)try{let l=sj(),u=aj(a),d=Re.join(l,u,`${n}.jsonl`);if(De.existsSync(d)){let h=await wfe(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=zi.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=Re.join(n,".claude"),d=Re.join(u,"config.json");if(De.existsSync(d))try{let h=De.statSync(d);l={type:"LOGIN_DETECTED",last_auth_timestamp:Math.floor(h.mtimeMs)};}catch{l={type:"INSTALLATION_FOUND"};}else De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "CODEX":{let u=Re.join(n,".codex");KQe("codex")?l={type:"INSTALLATION_FOUND"}:De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "CURSOR_AGENT":{let u=[Re.join(n,".cursor"),Re.join(n,"Library/Application Support/Cursor")];for(let d of u)if(De.existsSync(d)){l={type:"INSTALLATION_FOUND"};break}break}case "AMP":{let u=Re.join(n,".amp");De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "GEMINI":{let u=Re.join(n,".gemini");De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "OPENCLAW":{let u=Re.join(n,".openclaw"),d=Re.join(u,"openclaw.json");if(De.existsSync(d))try{let h=De.statSync(d);l={type:"LOGIN_DETECTED",last_auth_timestamp:Math.floor(h.mtimeMs)};}catch{l={type:"INSTALLATION_FOUND"};}else De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "WINDSURF":{let u=Re.join(n,".windsurf");De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "GOOSE":{let u=Re.join(n,".goose");De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}case "AIDER":{let u=Re.join(n,".aider");De.existsSync(u)&&(l={type:"INSTALLATION_FOUND"});break}}return l}let o=await et.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=zi.homedir(),c=null,o="global";if(n){let u=Re.join(n,".viben","agents");c=await et.getAgentFromDir(u,i),c&&(o="workspace");}if(c||(c=await et.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 et.updateAgent(i,c,n),l=zi.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 et.removeAgent(i,n),{success:!0,deleted:i}}catch(a){return s.code(400),{error:a instanceof Error?a.message:"Failed to delete agent"}}});}var Qee=O({"src/gateway/routes/agents.ts"(){np(),ip(),eq();}});function Zee(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 QQe(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 Rh(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||dI,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:QQe(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 Gg(e){let t=zd.get(e);if(!t)return null;let r=Date.now();return r-t.created_at>Efe?(zd.delete(e),null):(t.last_accessed=r,t)}function qh(e,t,r){let s=Date.now();if(zd.size>=Tfe){let i=null,n=1/0;for(let[a,c]of zd)c.last_accessed<n&&(n=c.last_accessed,i=a);i&&zd.delete(i);}zd.set(e,{workspace_path:t,task_dir:r,last_accessed:s,created_at:s});}function jx(e){zd.delete(e);}function ZQe(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 Fe.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 Fe.findTaskById(n,o.id);l&&qh(o.id,n,l);}return {tasks:c.map(Rh)}}),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=Gg(n);if(l?(c=l.task_dir,l.workspace_path):a&&(c=await Fe.findTaskById(a,n),c&&qh(n,a,c)),!c)return i.code(404),{error:`Task not found: ${n}. Provide workspace_path parameter.`};let u=await Fe.getTask(c);return u?Rh(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 Fe.findTaskById(a,n.copy_from);if(u&&(c=await Fe.getTask(u)),!c)return i.code(400),{error:`Source task not found: ${n.copy_from}`}}let o="backlog";n.status&&(o=Fe.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??dI,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 Fe.createTask(a,l);return qh(d.id,a,u),t.events.taskCreated(Zee(d)),i.code(201),Rh(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=Gg(n);if(u?(o=u.task_dir,l=u.workspace_path):c&&(o=await Fe.findTaskById(c,n),o&&qh(n,c,o)),!o)return i.code(404),{error:`Task not found: ${n}. Provide workspace_path parameter.`};let d=await Fe.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=Fe.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 v=await Fe.updateTask(o,h);return t.events.taskUpdated(Zee(v)),a.status&&d.status!==v.status&&t.events.taskStatusChanged(n,d.status,v.status),Rh(v)}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=Gg(n);return o?c=o.task_dir:a&&(c=await Fe.findTaskById(a,n)),c?await Fe.deleteTask(c)?(jx(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 Fe.listTasks(a)).filter(l=>l.agent===n).map(Rh)}:(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 Fe.listTasks(a)).filter(l=>l.session_id===n);return o.sort((l,u)=>(l.task_index??0)-(u.task_index??0)),{tasks:o.map(Rh)}}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 ms.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;Id.info({taskId:n,workspacePath:a},"Getting specs for task");let c=null,l=Gg(n);if(l?(Id.debug({taskDir:l.task_dir},"Found in cache"),c=l.task_dir,l.workspace_path):a&&(Id.debug("Searching for task by ID..."),c=await Fe.findTaskById(a,n),Id.debug({taskDir:c},"findTaskById result"),c&&qh(n,a,c)),!c)return Id.warn({taskId:n},"Task not found"),i.code(404),{error:`Task not found: ${n}. Provide workspace_path parameter.`};try{let u=await Fe.getTaskSpecsData(c);return Id.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 Id.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(!g1(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 v=h.includes("/")?h:await Fe.findTaskById(n,h);if(!v)return {task_dir:h,success:!1,error:"Task not found"};let y=await Fe.getTask(v);if(!y)return {task_dir:h,success:!1,error:"Task not found"};let _=(y.last_event?.sequence??0)+1,b={event_id:sw.randomUUID(),sequence:_,type:c,timestamp:new Date().toISOString(),payload:o},w=await er.applyEvent(v,b);return w.success?{task_dir:h,success:!0,new_state:w.newState}:{task_dir:h,success:!1,error:w.error}}catch(v){return {task_dir:h,success:false,error:v instanceof Error?v.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=Gg(n);if(l?(c=l.task_dir,l.workspace_path):a&&(c=await Fe.findTaskById(a,n),c&&qh(n,a,c)),!c)return i.code(404),{success:false,error:`Task not found: ${n}`};let u=await Fe.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 Id,Efe,Tfe,zd,tq=O({"src/gateway/routes/tasks.ts"(){sl(),Ke(),ip(),Om(),Aw(),Id=je.child({module:"tasks"}),Efe=300*1e3,Tfe=1e3,zd=new Map;}});function rZe(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=_he(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=bhe(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=whe(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=ML(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=che(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=uhe(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=lhe(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=dhe(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:v}=s.body;if(!n)return i.code(400),{error:"workspace_path is required"};let y=a.includes("/")?a:await Fe.findTaskById(n,a);if(!y)return i.code(404),{error:`Task not found: ${a}`};let _=await Fe.getTask(y);if(!_)return i.code(404),{error:`Task not found: ${a}`};let b=c||_.agent,w=o||_.prompt||_.description||_.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:_.session_id,input:w,cwd:S,agent_config_path:u,resume_session:d,max_retries:h,attachments:v});return await Fe.updateTask(y,{status:"queue",session_id:_.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 Fe.findTaskById(n,a);if(!c)return i.code(404),{error:`Task not found: ${a}`};let o=await Fe.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(_=>_.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 Fe.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 Fe.findTaskById(n,a);if(!c)return i.code(404),{error:`Task not found: ${a}`};let o=await Fe.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(_=>_.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 Fe.findTaskById(i,u);if(!d){c.push({task_dir:u,success:!1,error:"Task not found"}),l++;continue}let h=await Fe.getTask(d);if(!h){c.push({task_dir:u,success:!1,error:"Task not found"}),l++;continue}let v=a||h.agent;if(!v){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 _=await t.taskQueue.enqueue({agent_id:v,session_id:h.session_id,input:y,cwd:i});await Fe.updateTask(d,{status:"queue"}),c.push({task_dir:u,success:!0,queue_task_id:_.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 Fe.findTaskById(n,a);if(!o)return i.code(404),{error:`Task not found: ${a}`};let l=await Fe.getTask(o);if(!l)return i.code(404),{error:`Task not found: ${a}`};let u=await er.getEventHistory(o,c),d=await er.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 Fe.findTaskById(n,a);if(!c)return i.code(404),{error:`Task not found: ${a}`};try{let o=await Fe.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 v=await Fe.findTaskById(n,h);if(v){let y=await er.getEventHistory(v,u);for(let _ of y){let b={type:"STATE_CHANGED",task_id:h,workspace_path:n,timestamp:new Date(_.timestamp).getTime(),event:_,replay:!0};i.raw.write(`event: STATE_CHANGED
|
|
805
805
|
data: ${JSON.stringify(b)}
|
|
@@ -1099,8 +1099,8 @@ ${e.code_for_interpreter}
|
|
|
1099
1099
|
]))`;continue}else if(s[o]==="$"){i+=`($|(?=[\r
|
|
1100
1100
|
]))`;continue}}if(r.s&&s[o]==="."){i+=a?`${s[o]}\r
|
|
1101
1101
|
`:`[${s[o]}\r
|
|
1102
|
-
]`;continue}i+=s[o],s[o]==="\\"?n=true:a&&s[o]==="]"?a=false:!a&&s[o]==="["&&(a=true);}try{new RegExp(i);}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}var nx,io,q0e,zj=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/string.js"(){Lm(),nx=void 0,io={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(nx===void 0&&(nx=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nx),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/},q0e=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");}});function N0e(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((s,i)=>({...s,[i]:hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??Wi(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:s,...i}=R0e(e.keyType._def,t);return {...r,propertyNames:i}}else {if(e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodEnum)return {...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:s,...i}=k0e(e.keyType._def,t);return {...r,propertyNames:i}}}return r}var Uj=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/record.js"(){Ja(),zj(),Mj(),ec();}});function rot(e,t){if(t.mapStrategy==="record")return N0e(e,t);let r=hr(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Wi(t),s=hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Wi(t);return {type:"array",maxItems:125,items:{type:"array",items:[r,s],minItems:2,maxItems:2}}}var L0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/map.js"(){Ja(),Uj(),ec();}});function aot(e){let t=e.values,s=Object.keys(e.values).filter(n=>typeof t[t[n]]!="number").map(n=>t[n]),i=Array.from(new Set(s.map(n=>typeof n)));return {type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:s}}var j0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"(){}});function sot(e){return e.target==="openAi"?void 0:{not:Wi({...e,currentPath:[...e.currentPath,"not"]})}}var M0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/never.js"(){ec();}});function iot(e){return e.target==="openApi3"?{enum:["null"],nullable:true}:{type:"null"}}var z0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/null.js"(){}});function not(e,t){if(t.target==="openApi3")return Gq(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(s=>s._def.typeName in bw&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((i,n)=>{let a=bw[n._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return {type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((i,n)=>{let a=typeof n._def.value;switch(a){case "string":case "number":case "boolean":return [...i,a];case "bigint":return [...i,"integer"];case "object":if(n._def.value===null)return [...i,"null"];default:return i}},[]);if(s.length===r.length){let i=s.filter((n,a,c)=>c.indexOf(n)===a);return {type:i.length>1?i:i[0],enum:r.reduce((n,a)=>n.includes(a._def.value)?n:[...n,a._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return {type:"string",enum:r.reduce((s,i)=>[...s,...i._def.values.filter(n=>!s.includes(n))],[])};return Gq(e,t)}var bw,Gq,Bj=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/union.js"(){Ja(),bw={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},Gq=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((s,i)=>hr(s._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(s=>!!s&&(!t.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};}});function oot(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:bw[e.innerType._def.typeName],nullable:true}:{type:[bw[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let s=hr(e.innerType._def,{...t,currentPath:[...t.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:true}:s&&{...s,nullable:true}}let r=hr(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var U0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"(){Ja(),Bj();}});function cot(e,t){let r={type:"number"};if(!e.checks)return r;for(let s of e.checks)switch(s.kind){case "int":r.type="integer",_0e(r,"type",s.message,t);break;case "min":t.target==="jsonSchema7"?s.inclusive?br(r,"minimum",s.value,s.message,t):br(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=true),br(r,"minimum",s.value,s.message,t));break;case "max":t.target==="jsonSchema7"?s.inclusive?br(r,"maximum",s.value,s.message,t):br(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=true),br(r,"maximum",s.value,s.message,t));break;case "multipleOf":br(r,"multipleOf",s.value,s.message,t);break}return r}var B0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/number.js"(){Lm();}});function uot(e,t){let r=t.target==="openAi",s={type:"object",properties:{}},i=[],n=e.shape();for(let c in n){let o=n[c];if(o===void 0||o._def===void 0)continue;let l=dot(o);l&&r&&(o._def.typeName==="ZodOptional"&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),l=false);let u=hr(o._def,{...t,currentPath:[...t.currentPath,"properties",c],propertyPath:[...t.currentPath,"properties",c]});u!==void 0&&(s.properties[c]=u,l||i.push(c));}i.length&&(s.required=i);let a=lot(e,t);return a!==void 0&&(s.additionalProperties=a),s}function lot(e,t){if(e.catchall._def.typeName!=="ZodNever")return hr(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case "passthrough":return t.allowedAdditionalProperties;case "strict":return t.rejectedAdditionalProperties;case "strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function dot(e){try{return e.isOptional()}catch{return true}}var G0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/object.js"(){Ja();}}),H0e,W0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"(){Ja(),ec(),H0e=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return hr(e.innerType._def,t);let r=hr(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Wi(t)},r]}:Wi(t)};}}),V0e,K0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"(){Ja(),V0e=(e,t)=>{if(t.pipeStrategy==="input")return hr(e.in._def,t);if(t.pipeStrategy==="output")return hr(e.out._def,t);let r=hr(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),s=hr(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return {allOf:[r,s].filter(i=>i!==void 0)}};}});function pot(e,t){return hr(e.type._def,t)}var J0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"(){Ja();}});function hot(e,t){let s={type:"array",uniqueItems:true,items:hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&br(s,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&br(s,"maxItems",e.maxSize.value,e.maxSize.message,t),s}var Y0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/set.js"(){Lm(),Ja();}});function mot(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,s)=>hr(r._def,{...t,currentPath:[...t.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[]),additionalItems:hr(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,s)=>hr(r._def,{...t,currentPath:[...t.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}var X0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"(){Ja();}});function fot(e){return {not:Wi(e)}}var Q0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"(){ec();}});function got(e){return Wi(e)}var Z0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"(){ec();}}),eve,tve=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"(){Ja(),eve=(e,t)=>hr(e.innerType._def,t);}}),rve,ave=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/selectParser.js"(){ec(),b0e(),w0e(),S0e(),Mj(),T0e(),P0e(),A0e(),C0e(),O0e(),$0e(),D0e(),L0e(),j0e(),M0e(),z0e(),U0e(),B0e(),G0e(),W0e(),K0e(),J0e(),Uj(),Y0e(),zj(),X0e(),Q0e(),Bj(),Z0e(),tve(),rve=(e,t,r)=>{switch(t){case v3$1.ZodFirstPartyTypeKind.ZodString:return R0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodNumber:return cot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodObject:return uot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodBigInt:return Knt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodBoolean:return Jnt();case v3$1.ZodFirstPartyTypeKind.ZodDate:return x0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodUndefined:return fot(r);case v3$1.ZodFirstPartyTypeKind.ZodNull:return iot(r);case v3$1.ZodFirstPartyTypeKind.ZodArray:return Vnt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodUnion:case v3$1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return not(e,r);case v3$1.ZodFirstPartyTypeKind.ZodIntersection:return Znt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodTuple:return mot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodRecord:return N0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodLiteral:return eot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodEnum:return Qnt(e);case v3$1.ZodFirstPartyTypeKind.ZodNativeEnum:return aot(e);case v3$1.ZodFirstPartyTypeKind.ZodNullable:return oot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodOptional:return H0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodMap:return rot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodSet:return hot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodLazy:return ()=>e.getter()._def;case v3$1.ZodFirstPartyTypeKind.ZodPromise:return pot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodNaN:case v3$1.ZodFirstPartyTypeKind.ZodNever:return sot(r);case v3$1.ZodFirstPartyTypeKind.ZodEffects:return Xnt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodAny:return Wi(r);case v3$1.ZodFirstPartyTypeKind.ZodUnknown:return got(r);case v3$1.ZodFirstPartyTypeKind.ZodDefault:return Ynt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodBranded:return k0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodReadonly:return eve(e,r);case v3$1.ZodFirstPartyTypeKind.ZodCatch:return E0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodPipeline:return V0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodFunction:case v3$1.ZodFirstPartyTypeKind.ZodVoid:case v3$1.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (s=>{})()}};}});function hr(e,t,r=false){let s=t.seen.get(e);if(t.override){let c=t.override?.(e,t,s,r);if(c!==f0e)return c}if(s&&!r){let c=sve(s,t);if(c!==void 0)return c}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=rve(e,e.typeName,t),a=typeof n=="function"?hr(n(),t):n;if(a&&ive(e,t,a),t.postProcess){let c=t.postProcess(a,e,t);return i.jsonSchema=a,c}return i.jsonSchema=a,a}var sve,ive,Ja=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parseDef.js"(){Nj(),ave(),jj(),ec(),sve=(e,t)=>{switch(t.$refStrategy){case "root":return {$ref:e.path.join("/")};case "relative":return {$ref:Lj(t.currentPath,e.path)};case "none":case "seen":return e.path.length<t.currentPath.length&&e.path.every((r,s)=>t.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Wi(t)):t.$refStrategy==="seen"?Wi(t):void 0}},ive=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);}}),yot=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parseTypes.js"(){}}),nve,Iae=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"(){Ja(),v0e(),ec(),nve=(e,t)=>{let r=y0e(t),s=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[l,u])=>({...o,[l]:hr(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},true)??Wi(r)}),{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,n=hr(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},false)??Wi(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(n.title=a),r.flags.hasReferencedOpenAiAnyType&&(s||(s={}),s[r.openAiAnyTypeName]||(s[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let c=i===void 0?s?{...n,[r.definitionPath]:s}:n:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...s,[i]:n}};return r.target==="jsonSchema7"?c.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c};}}),vot=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/index.js"(){Nj(),v0e(),Lm(),jj(),Ja(),yot(),ec(),b0e(),w0e(),S0e(),Mj(),T0e(),P0e(),A0e(),C0e(),O0e(),$0e(),D0e(),L0e(),j0e(),M0e(),z0e(),U0e(),B0e(),G0e(),W0e(),K0e(),J0e(),tve(),Uj(),Y0e(),zj(),X0e(),Q0e(),Bj(),Z0e(),ave(),Iae(),Iae();}}),ove={};mt(ove,{DEFAULT_WS_PORT:()=>Gj,TAURI_MCP_PATH:()=>Yh,closeAllTauriMcpSessions:()=>Tot,getActiveTauriMcpSessionCount:()=>xot,registerTauriMcpServerRoutes:()=>Iot});async function kot(){if(yb)return;yb=(await import('@hypothesi/tauri-mcp-server')).TOOLS,Hj=yb.map(t=>({name:t.name,description:t.description,inputSchema:nve(t.schema),annotations:t.annotations})),Wj=new Map(yb.map(t=>[t.name,t]));}function a3(e,t){let r=e.headers.origin||"*";t.raw.setHeader("Access-Control-Allow-Origin",r),t.raw.setHeader("Access-Control-Allow-Credentials","true"),t.raw.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Accept, Mcp-Session-Id, Last-Event-Id, mcp-protocol-version"),t.raw.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id, mcp-protocol-version"),t.raw.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS");}function s3(e){let t=e.headers["mcp-session-id"];return Array.isArray(t)?t.at(-1):t}function Eot(){let e=new index_js.Server({name:"tauri-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return e.setRequestHandler(types_js.ListToolsRequestSchema,async()=>({tools:Hj})),e.setRequestHandler(types_js.CallToolRequestSchema,async t=>{let r=Wj.get(t.params.name);if(!r)return {content:[{type:"text",text:`Error: Unknown tool: ${t.params.name}`}],isError:true};try{let s=await r.handler(t.params.arguments);return typeof s=="string"?{content:[{type:"text",text:s}]}:Array.isArray(s)?{content:s.map(i=>i.type==="text"?{type:"text",text:i.text}:{type:"image",data:i.data,mimeType:i.mimeType})}:s.type==="text"?{content:[{type:"text",text:s.text}]}:{content:[{type:"image",data:s.data,mimeType:s.mimeType}]}}catch(s){return {content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:true}}}),e}function Tot(){for(let e of Fs.values())e.transport.close?.().catch(t=>{W1.warn({err:t,sessionId:e.id},"Failed to close tauri MCP transport");});Fs.clear();}function xot(){return Fs.size}async function Iot(e,t={}){await kot();let r=t.port??Gj,s=t.createServer??(()=>Eot()),i=t.createTransport??(n=>new streamableHttp_js.StreamableHTTPServerTransport({sessionIdGenerator:sw.randomUUID,onsessioninitialized:a=>{let c=Fs.get(n);c&&(Fs.delete(n),Fs.set(a,{...c,id:a}),W1.info({sessionId:a},"Tauri MCP session initialized"));},onsessionclosed:a=>{Fs.get(a)&&(W1.info({sessionId:a},"Tauri MCP session closed"),Fs.delete(a));}}));e.get(`${Yh}/status`,{schema:{description:"Check tauri-plugin-mcp-bridge connection status",tags:["mcp","tauri"],response:{200:{type:"object",properties:{available:{type:"boolean"},port:{type:"number"},connected:{type:"boolean"},error:{type:"string"}}}}}},async()=>{let{default:n}=await import('ws');return new Promise(a=>{let c=false,o=new n(`ws://127.0.0.1:${r}`),l=d=>{c||(c=true,clearTimeout(u),o.close(),a(d));},u=setTimeout(()=>{l({available:false,port:r,connected:false,error:"Connection timeout. Is the Tauri app running?"});},2e3);o.once("open",()=>{l({available:true,port:r,connected:true});}),o.once("error",d=>{l({available:false,port:r,connected:false,error:`Cannot connect: ${d.message}`});});})}),e.get(Yh,async(n,a)=>{a3(n,a);let c=s3(n);if(!c)return a.code(400),{error:"Mcp-Session-Id header required"};let o=Fs.get(c);if(!o)return a.code(404),{error:"Session not found"};await o.transport.handleRequest(n.raw,a.raw);}),e.post(Yh,async(n,a)=>{a3(n,a);let c=s3(n);if(c){let h=Fs.get(c);if(!h)return a.code(404),{error:"Session not found"};await h.transport.handleRequest(n.raw,a.raw,n.body);return}let o=`pending-${sw.randomUUID()}`,l=i(o),u=s(),d=l.sessionId??o;Fs.set(d,{id:d,server:u,transport:l}),l.onclose=()=>{Fs.delete(d),l.sessionId&&Fs.delete(l.sessionId);},await u.connect(l),await l.handleRequest(n.raw,a.raw,n.body);}),e.delete(Yh,async(n,a)=>{a3(n,a);let c=s3(n);if(!c)return a.code(400),{error:"Mcp-Session-Id header required"};let o=Fs.get(c);if(!o)return a.code(404),{error:"Session not found"};await o.transport.handleRequest(n.raw,a.raw),Fs.delete(c);}),e.options(`${Yh}/*`,{schema:{hide:true}},async(n,a)=>{a.header("Access-Control-Allow-Origin","*"),a.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),a.header("Access-Control-Allow-Headers","Content-Type, Authorization, Accept, Mcp-Session-Id, Last-Event-Id, mcp-protocol-version"),a.header("Access-Control-Expose-Headers","Mcp-Session-Id, mcp-protocol-version"),a.header("Access-Control-Max-Age","86400"),a.code(204).send();});}var W1,Yh,Gj,yb,Hj,Wj,Fs,Pot=O({"src/gateway/routes/mcp-server/tauri-mcp-server.ts"(){vot(),Ke(),W1=je.child({module:"tauri-mcp-server"}),Yh="/api/mcp-server/tauri",Gj=9223,yb=null,Hj=null,Wj=null,Fs=new Map;}});async function cve(e,t){qQe(e),YQe(e,t),ZQe(e,t),rZe(e,t),iZe(e,t),nZe(e,t),oZe(e,t),uZe(e),HQe(e),gZe(e),yZe(e),kZe(e,t),IZe(e),PZe(e),DZe(e),XZe(e),GZe(e,t),tet(e),set(e),pet(e),yet(e),vet(e),Yst(e,t),Ret(e),qet(e),Net(e),Get(e),stt(e),dtt(e),gtt(e),xtt(e),Ltt(e),Ytt(e),irt(e),frt(e),_rt(e),krt(e),Trt(e),Brt(e),Hrt(e,t),Hat(e);try{let{registerTauriMcpServerRoutes:r}=await Promise.resolve().then(()=>(Pot(),ove));await r(e);}catch{}Wat(e),Vat(e),Jat(e),Yat(e,t),Xat(e),Zat(e),est(e),Hst(e),Wst(e,t),Kst(e,t),vit(e),tnt(e),lnt(e,t),Snt(e),Hnt(e);}var Aae=O({"src/gateway/routes/index.ts"(){j1(),Qee(),tq(),ite(),nte(),ote(),cte(),ute(),eq(),lte(),dte(),iq(),hte(),mte(),fte(),yte(),_te(),Ste(),kte(),Ite(),Ate(),Cte(),Dte(),Rte(),qte(),Lte(),Bte(),Hte(),Jte(),Xte(),_q(),ere(),are(),sre(),nre(),Ert(),lre(),mre(),fre(),Sre(),Tre(),xre(),Ire(),Pre(),Are(),Cre(),Ore(),Hre(),Wre(),Vre(),Kre(),tae(),dae(),mae(),yae(),Tae(),j1(),Qee(),tq(),ite(),nte(),ote(),cte(),ute(),eq(),lte(),dte(),iq(),hte(),mte(),fte(),_te(),yte(),Ste(),kte(),Ite(),Ate(),Cte(),Dte(),Rte(),qte(),Lte(),Bte(),Hte(),Jte(),Xte(),_q(),ere(),are(),sre(),nre(),lre(),mre(),fre(),Sre(),Tre(),xre(),Ire(),Pre(),Are(),Cre(),Ore(),Hre(),Wre(),Vre(),Kre(),tae(),dae(),mae(),yae(),Tae(),b2();}}),Dr,i3,n3,Cae,ox,o3,Oae,Vj,Fae=O({"src/gateway/client-socket-server.ts"(){Ke(),Dr=je.child({module:"client-socket-server"}),i3="/socket.io/client",n3=3e4,Cae=6e4,ox=10*1024*1024,o3=1e3,Oae=100,Vj=class{constructor(e,t){this.pendingExecutes=new Map,this.pendingApprovals=new Map,this.seenRequestIds=new Map,this.rateLimits=new Map,this.cleanupTimer=null,this.clientStore=t,this.io=new socket_io.Server(e,{path:i3,cors:{origin:"*"},maxHttpBufferSize:ox}),this.setupEventHandlers(),this.startCleanup(),Dr.info({path:i3},"ClientSocketServer initialized");}checkRateLimit(e){let t=Date.now(),r=this.rateLimits.get(e);return !r||t-r.windowStart>o3?(r={count:1,windowStart:t},this.rateLimits.set(e,r),true):r.count>=Oae?(Dr.warn({socketId:e,count:r.count},"Rate limit exceeded"),false):(r.count++,true)}validatePayloadSize(e){try{let t=JSON.stringify(e);return t.length>ox?{valid:!1,error:`Payload too large: ${t.length} bytes (max: ${ox})`}:{valid:!0}}catch{return {valid:false,error:"Invalid payload (not serializable)"}}}setupEventHandlers(){this.io.on("connection",e=>{Dr.debug({socketId:e.id},"Socket connected"),e.on("client:connect",async(t,r)=>{if(!this.checkRateLimit(e.id)){r?.({success:false,error:"Rate limit exceeded"});return}await this.handleClientConnect(e,t,r);}),e.on("action:register",t=>{this.checkRateLimit(e.id)&&this.handleActionRegister(e,t);}),e.on("action:unregister",t=>{this.checkRateLimit(e.id)&&this.handleActionUnregister(e,t);}),e.on("action:result",t=>{this.checkRateLimit(e.id)&&this.handleActionResult(t);}),e.on("action:approval:request",t=>{this.checkRateLimit(e.id)&&this.handleApprovalRequest(e,t);}),e.on("action:approval:response",t=>{this.checkRateLimit(e.id)&&this.handleApprovalResponse(t);}),e.on("client:theme:set",t=>{this.checkRateLimit(e.id)&&this.handleThemeSet(e,t);}),e.on("action:list",(t,r)=>{if(!this.checkRateLimit(e.id))return;let s=e.clientId;if(!s||!r)return;let i=this.clientStore.getClient(s);if(!i){r({actions:[]});return}let n=[];for(let a of i.actionStore.values())a.socketId!==e.id&&n.push({namespace:a.namespace,name:a.name,description:a.description});r({actions:n});}),e.on("disconnect",()=>{this.handleDisconnect(e),this.rateLimits.delete(e.id);});});}async handleClientConnect(e,t,r){if(!t.clientId||typeof t.clientId!="string"){r?.({success:false,error:"clientId is required"});return}if(!t.source){r?.({success:false,error:"source is required"});return}if(!t.publicKey||!t.signature||!t.timestamp){r?.({success:false,error:"publicKey, signature, and timestamp are required"});return}try{let s=await this.clientStore.registerClient(t.clientId,{source:t.source,socketId:e.id,pageUid:t.pageUid,publicKey:t.publicKey,signature:t.signature,timestamp:t.timestamp});e.clientId=t.clientId,e.join(`client:${t.clientId}`),t.source==="main_window"&&s.metadata.theme!=="light"&&this.clientStore.setGlobalTheme(s.metadata.theme);let i={theme:t.source==="main_window"?s.metadata.theme:this.clientStore.globalTheme};t.source==="main_window"&&(i.workspacePath=s.metadata.workspacePath),e.emit("client:init",i),r?.({success:!0}),Dr.info({clientId:t.clientId,socketId:e.id,source:t.source},"Client connected");}catch(s){let i=s instanceof Error?s.message:"Unknown error";Dr.warn({clientId:t.clientId,error:i},"Client connect failed"),r?.({success:false,error:i});}}handleThemeSet(e,t){let r=e.clientId;if(!r)return;let s=this.clientStore.getClient(r);if(!s)return;let i=s.sockets.get(e.id);if(!(!i||i.source!=="main_window")&&t.theme!==this.clientStore.globalTheme){this.clientStore.setGlobalTheme(t.theme),Dr.info({theme:t.theme},"Global theme updated");for(let[,n]of this.io.sockets.sockets)n.id!==e.id&&n.emit("client:theme",{theme:t.theme});}}handleActionRegister(e,t){let r=e.clientId;if(!r){Dr.warn({socketId:e.id},"Action register without client connect"),e.emit("action:register:result",{namespace:t.namespace,accepted:[],rejected:[{action:"*",reason:"Not connected as client"}]});return}if(!t.namespace||typeof t.namespace!="string"){Dr.warn({clientId:r,socketId:e.id},"Invalid namespace");return}let s=new Set(Object.keys(t.actions||{})),i=this.clientStore.removeStaleActions(r,t.namespace,e.id,s);i.length>0&&Dr.info({clientId:r,removed:i},"Stale actions removed during reconciliation");let n=[],a=[];for(let[c,o]of Object.entries(t.actions||{})){let l=this.clientStore.registerAction(r,e.id,{namespace:t.namespace,name:c,description:o.description,inputSchema:o.inputSchema,outputSchema:o.outputSchema,timeout:o.timeout});l.error?a.push({action:c,reason:l.error}):n.push(c);}e.emit("action:register:result",{namespace:t.namespace,accepted:n,rejected:a});}handleActionUnregister(e,t){let r=e.clientId;r&&this.clientStore.unregisterAction(r,t.namespace,e.id);}handleActionResult(e){let t=this.pendingExecutes.get(e.requestId);if(!t){Dr.debug({requestId:e.requestId},"Result for unknown request (possibly timed out)");return}clearTimeout(t.timer),this.pendingExecutes.delete(e.requestId),t.resolve(e.result);}handleApprovalRequest(e,t){let r=e.clientId;if(!r){Dr.warn({socketId:e.id},"Approval request without client connect");return}if(!t.requestId||!t.executeRequestId||!t.message){Dr.warn({clientId:r,socketId:e.id},"Invalid approval request data");return}let s=this.clientStore.getClient(r);if(!s){Dr.warn({clientId:r},"Client not found for approval request");return}let i;for(let[c,o]of s.sockets)if(o.source==="main_window"){let l=this.io.sockets.sockets.get(c);if(l){i=l;break}}if(!i){Dr.warn({clientId:r},"No UI-capable socket found for approval request"),e.emit("action:approval:result",{requestId:t.requestId,approved:false,error:"No UI socket available"});return}let n=t.options?.timeout??n3,a=setTimeout(()=>{this.pendingApprovals.delete(t.requestId);let c=this.io.sockets.sockets.get(e.id);c&&c.emit("action:approval:result",{requestId:t.requestId,approved:false,error:"Approval timeout"}),Dr.debug({requestId:t.requestId,clientId:r},"Approval request timed out");},n);this.pendingApprovals.set(t.requestId,{requestId:t.requestId,originSocketId:e.id,timer:a}),i.emit("action:approval:request",{requestId:t.requestId,executeRequestId:t.executeRequestId,message:t.message,options:t.options}),Dr.debug({requestId:t.requestId,clientId:r,uiSocketId:i.id},"Approval request forwarded to UI");}handleApprovalResponse(e){let t=this.pendingApprovals.get(e.requestId);if(!t){Dr.debug({requestId:e.requestId},"Approval response for unknown request (possibly timed out)");return}clearTimeout(t.timer),this.pendingApprovals.delete(e.requestId);let r=this.io.sockets.sockets.get(t.originSocketId);r?(r.emit("action:approval:result",{requestId:e.requestId,approved:e.approved}),Dr.debug({requestId:e.requestId,originSocketId:t.originSocketId,approved:e.approved},"Approval result sent to originator")):Dr.debug({requestId:e.requestId,originSocketId:t.originSocketId},"Origin socket disconnected, approval result dropped");}handleDisconnect(e){let t=e.clientId;if(t){for(let[r,s]of this.pendingExecutes)s.socketId===e.id&&(clearTimeout(s.timer),this.pendingExecutes.delete(r),s.resolve({content:[{type:"text",text:"Socket disconnected during execution"}],isError:true}));for(let[r,s]of this.pendingApprovals)if(s.originSocketId===e.id)clearTimeout(s.timer),this.pendingApprovals.delete(r),Dr.debug({requestId:r,socketId:e.id},"Pending approval cleaned up (originator disconnected)");else {let i=this.clientStore.getClient(t);if(i){let n=i.sockets.get(e.id);if(n&&n.source==="main_window"){let a=this.io.sockets.sockets.get(s.originSocketId);a&&a.clientId===t&&(clearTimeout(s.timer),this.pendingApprovals.delete(r),a.emit("action:approval:result",{requestId:r,approved:false,error:"Approver disconnected"}),Dr.debug({requestId:r,socketId:e.id},"Approval rejected (UI socket disconnected)"));}}}this.clientStore.removeSocket(t,e.id),Dr.info({clientId:t,socketId:e.id},"Socket disconnected");}}async executeAction(e,t,r,s,i){let n=this.clientStore.findAction(e,t,r);if(!n)return {content:[{type:"text",text:`Action not found: ${t}.${r}`}],isError:true};let a=this.validatePayloadSize(s);if(!a.valid)return {content:[{type:"text",text:`Invalid payload: ${a.error}`}],isError:true};let c=this.clientStore.getClient(e);if(!c||c.sockets.size===0)return Dr.warn({targetClientId:e,namespace:t,actionName:r,clientExists:!!c,socketsSize:c?.sockets.size??0},"executeAction: client offline"),{content:[{type:"text",text:`Client offline: ${e}`}],isError:true};if(!c.sockets.get(n.socketId)){let h=[...c.sockets.keys()];return Dr.warn({targetClientId:e,namespace:t,actionName:r,actionSocketId:n.socketId,currentSocketIds:h},"executeAction: action socket disconnected (socketId mismatch \u2014 action was registered on a now-stale socket)"),{content:[{type:"text",text:`Action socket disconnected (registered on ${n.socketId}, current sockets: [${h.join(", ")}])`}],isError:true}}let l=this.io.sockets.sockets.get(n.socketId);if(!l)return Dr.warn({targetClientId:e,actionSocketId:n.socketId},"executeAction: socket.io instance not found"),{content:[{type:"text",text:"Socket not found"}],isError:true};let u=sw.randomUUID();if(this.seenRequestIds.has(u))return {content:[{type:"text",text:"Duplicate request"}],isError:true};this.seenRequestIds.set(u,Date.now());let d=n.timeout??n3;return new Promise(h=>{let v=setTimeout(()=>{this.pendingExecutes.delete(u),h({content:[{type:"text",text:`Execution timeout after ${d}ms`}],isError:true});},d);this.pendingExecutes.set(u,{requestId:u,clientId:e,socketId:n.socketId,resolve:h,reject:()=>{},timer:v}),l.emit("action:execute",{requestId:u,namespace:t,action:r,payload:s,context:i});})}startCleanup(){this.cleanupTimer=setInterval(()=>{let e=Date.now();for(let[t,r]of this.seenRequestIds)e-r>Cae&&this.seenRequestIds.delete(t);for(let[t,r]of this.rateLimits)e-r.windowStart>o3*10&&this.rateLimits.delete(t);},6e4);}shutdown(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null);for(let e of this.pendingExecutes.values())clearTimeout(e.timer),e.resolve({content:[{type:"text",text:"Server shutdown"}],isError:true});this.pendingExecutes.clear();for(let e of this.pendingApprovals.values()){clearTimeout(e.timer);let t=this.io.sockets.sockets.get(e.originSocketId);t&&t.emit("action:approval:result",{requestId:e.requestId,approved:false,error:"Server shutdown"});}this.pendingApprovals.clear(),this.rateLimits.clear(),this.io.close(),Dr.info("ClientSocketServer shut down");}};}}),uve={};mt(uve,{ClientSocketServer:()=>Vj,ClientStore:()=>ej,createAppState:()=>gfe,createGateway:()=>Kj,getLogger:()=>Not,registerRoutes:()=>cve,resetCleanupStaleAcpSessionsForTests:()=>jot,runGateway:()=>Mot,setCleanupStaleAcpSessionsForTests:()=>Lot,setGatewayStartupConfig:()=>yfe});function qot(e){return lve.some(t=>e===t||e.startsWith(`${t}/`))}function Not(){return Xh?.logger||null}function Lot(e){q2=e;}function jot(){q2=Fie;}async function Kj(e={}){let{host:t="127.0.0.1",port:r=18790,cors:s=true,telemetry:i=process.env.VIBEN_TELEMETRY!=="false",telemetryDir:n=Zh(),runtime:a=true}=e;i&&!Xh&&(Xh=aNe({serviceName:"viben-gateway",serviceVersion:"1.0.0",baseDir:n,enabled:i,trace:{flushDelayMs:5e3,batchSize:100},metrics:{exportIntervalMs:6e4},log:{level:process.env.LOG_LEVEL||"info"}}));let c=Oot__default.default({logger:true});try{await c.register(Dot__default.default,{openapi:{info:{title:"Viben Gateway API",description:"Agent Swarm \xD7 Code Evolution - Multi-agent orchestration and code evolution API",version:tj},servers:[{url:`http://${t}:${r}`,description:"Local development server"}],tags:[{name:"health",description:"Health check endpoints"},{name:"agents",description:"Agent management"},{name:"sessions",description:"Session management"},{name:"tasks",description:"Task management"},{name:"models",description:"Model configuration"},{name:"providers",description:"Provider configuration"},{name:"workspaces",description:"Workspace management"},{name:"cron",description:"Scheduled jobs"},{name:"channels",description:"Channel management"},{name:"mcp",description:"MCP server management"},{name:"executors",description:"Executor configuration"}]},transform:({schema:l,url:u})=>({schema:qot(u)?{...l,hide:!0}:l,url:u})}),c.get("/openapi.json",async()=>c.swagger()),c.get("/openapi.yaml",async(l,u)=>{let d=c.swagger({yaml:!0});u.type("application/x-yaml").send(d);}),Ct.info("Swagger plugin registered (OpenAPI spec at /openapi.json, /openapi.yaml)");}catch(l){Ct.warn({err:l},"Failed to register Swagger plugin");}s&&await c.register(Fot__default.default,{origin:true,methods:["GET","POST","PUT","PATCH","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Accept","X-MCP-Proxy-Auth","MCP-Session-Id","X-Custom-Auth-Header","X-Custom-Auth-Headers","Last-Event-Id","mcp-protocol-version"],exposedHeaders:["MCP-Session-Id","mcp-protocol-version"],credentials:true});try{await c.register($ot__default.default,{limits:{fileSize:100*1024*1024,files:10}}),Ct.info("Multipart plugin registered");}catch(l){Ct.warn({err:l},"Failed to register multipart plugin");}try{await c.register(Rot__default.default),Ct.info("WebSocket plugin registered");}catch(l){Ct.warn({err:l},"Failed to register WebSocket plugin");}let o=gfe({host:t,port:r,runtime:a});await cve(c,o);try{await q2(Wa.storage);}catch(l){Ct.warn({err:l},"Stale ACP session cleanup failed");}if(a&&c.addHook("onReady",async()=>{let l=c.server;o.clientSocketServer=new Vj(l,o.clientStore),Ct.info("Client Socket.io server started");}),yfe({host:t,port:r,cors:s}),a){try{await o.cron.start(),Ct.info("Cron scheduler started");}catch(l){Ct.warn({err:l},"Failed to start cron scheduler");}try{await o.channelRouter.start(),Ct.info("Channel router started");}catch(l){Ct.warn({err:l},"Failed to start channel router");}try{await o.channelRuntime.start();let l=o.channelRuntime.getActivePollers();Ct.info({activePollerCount:l.length},"Channel runtime started");}catch(l){Ct.warn({err:l},"Failed to start channel runtime");}try{await o.taskQueue.start();let l=o.taskQueue.getStatus();Ct.info({pending:l.pending_count,running:l.running_count},"Task queue manager started");}catch(l){Ct.warn({err:l},"Failed to start task queue manager");}try{o.taskSSEManager.startHeartbeat(),Ct.info("Task SSE Manager heartbeat started");}catch(l){Ct.warn({err:l},"Failed to start SSE heartbeat");}try{await o.commandQueue.start();let l=o.commandQueue.getStatus();Ct.info({pending:l.pending,running:l.running,maxConcurrency:l.max_concurrency},"Command queue started");}catch(l){Ct.warn({err:l},"Failed to start command queue");}try{await o.discovery.start(),Ct.info({mdnsAvailable:await o.discovery.isMdnsAvailable()},"Discovery service started");}catch(l){Ct.warn({err:l},"Failed to start discovery service");}try{await o.mesh.reconnectKnownPeers(),Ct.info("Mesh peer reconnection initiated");}catch(l){Ct.warn({err:l},"Failed to reconnect known peers");}try{let l=await wn.listWorkspaces(),u=0,d=0;for(let h of l)try{let v=await o.taskRecovery.recoverOnStartup(h.path);d+=v.totalChecked,u+=v.recovered,v.recovered>0&&Ct.info({workspace:h.path,recovered:v.recovered,checked:v.totalChecked},"Task recovery completed for workspace");}catch(v){Ct.warn({workspace:h.path,err:v},"Failed to recover tasks for workspace");}d>0&&Ct.info({totalChecked:d,totalRecovered:u,workspaceCount:l.length},"Task recovery completed");}catch(l){Ct.warn({err:l},"Failed to run task recovery");}i&&(Jqe({getActiveAgentSessions:()=>ar.getActiveSessionCount(),getActiveWsConnections:()=>bZe(),getCronJobCounts:()=>o.cron.getJobStats()}),Ct.info("Metrics gauge callbacks registered"));}return a&&c.addHook("onClose",async()=>{Ct.info("Shutting down gateway..."),o.clientSocketServer?.shutdown(),o.clientStore.shutdown(),o.channelRouter.stop(),await o.channelRuntime.stop(),await o.cron.shutdown(),await o.taskQueue.shutdown(),await o.commandQueue.stop(),o.taskSSEManager.stopHeartbeat(),o.taskSSEManager.close(),o.discovery.stop(),o.mesh.shutdown(),o.container.killAllRunningProcesses(),Xh&&(await Xh.shutdown(),Xh=null),Ct.info("Shutdown complete");}),c}async function Mot(e={}){let{host:t="127.0.0.1",port:r=18790,telemetry:s=process.env.VIBEN_TELEMETRY!=="false",telemetryDir:i=Zh()}=e,n=await Kj(e),a=false,c=async o=>{if(a){Ct.debug({signal:o},"Already shutting down, ignoring signal");return}a=true,Ct.info({signal:o},"Received shutdown signal, shutting down gracefully...");try{let l=n.close(),u=new Promise((d,h)=>setTimeout(()=>h(new Error("Shutdown timeout")),5e3));await Promise.race([l,u]),Ct.info("Server closed successfully");}catch(l){Ct.warn({err:l},"Shutdown timed out or failed, forcing exit");}process.exit(0);};process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM"));try{await n.listen({host:t,port:r}),Ct.info({host:t,port:r,telemetryEnabled:s,telemetryDir:i},"Gateway server started"),console.log(`
|
|
1103
|
-
[Gateway] Server running on http://${t}:${r}`),console.log("[Gateway] API: /health, /api/agent, /api/tasks, /api/sessions"),s&&console.log(`[Gateway] Telemetry: ${i}`),console.log(""),await new Promise(()=>{});}catch(o){
|
|
1102
|
+
]`;continue}i+=s[o],s[o]==="\\"?n=true:a&&s[o]==="]"?a=false:!a&&s[o]==="["&&(a=true);}try{new RegExp(i);}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}var nx,io,q0e,zj=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/string.js"(){Lm(),nx=void 0,io={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(nx===void 0&&(nx=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nx),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/},q0e=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");}});function N0e(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((s,i)=>({...s,[i]:hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??Wi(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:s,...i}=R0e(e.keyType._def,t);return {...r,propertyNames:i}}else {if(e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodEnum)return {...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===v3$1.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:s,...i}=k0e(e.keyType._def,t);return {...r,propertyNames:i}}}return r}var Uj=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/record.js"(){Ja(),zj(),Mj(),ec();}});function rot(e,t){if(t.mapStrategy==="record")return N0e(e,t);let r=hr(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Wi(t),s=hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Wi(t);return {type:"array",maxItems:125,items:{type:"array",items:[r,s],minItems:2,maxItems:2}}}var L0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/map.js"(){Ja(),Uj(),ec();}});function aot(e){let t=e.values,s=Object.keys(e.values).filter(n=>typeof t[t[n]]!="number").map(n=>t[n]),i=Array.from(new Set(s.map(n=>typeof n)));return {type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:s}}var j0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"(){}});function sot(e){return e.target==="openAi"?void 0:{not:Wi({...e,currentPath:[...e.currentPath,"not"]})}}var M0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/never.js"(){ec();}});function iot(e){return e.target==="openApi3"?{enum:["null"],nullable:true}:{type:"null"}}var z0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/null.js"(){}});function not(e,t){if(t.target==="openApi3")return Gq(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(s=>s._def.typeName in bw&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((i,n)=>{let a=bw[n._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return {type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((i,n)=>{let a=typeof n._def.value;switch(a){case "string":case "number":case "boolean":return [...i,a];case "bigint":return [...i,"integer"];case "object":if(n._def.value===null)return [...i,"null"];default:return i}},[]);if(s.length===r.length){let i=s.filter((n,a,c)=>c.indexOf(n)===a);return {type:i.length>1?i:i[0],enum:r.reduce((n,a)=>n.includes(a._def.value)?n:[...n,a._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return {type:"string",enum:r.reduce((s,i)=>[...s,...i._def.values.filter(n=>!s.includes(n))],[])};return Gq(e,t)}var bw,Gq,Bj=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/union.js"(){Ja(),bw={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},Gq=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((s,i)=>hr(s._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(s=>!!s&&(!t.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};}});function oot(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:bw[e.innerType._def.typeName],nullable:true}:{type:[bw[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let s=hr(e.innerType._def,{...t,currentPath:[...t.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:true}:s&&{...s,nullable:true}}let r=hr(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var U0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"(){Ja(),Bj();}});function cot(e,t){let r={type:"number"};if(!e.checks)return r;for(let s of e.checks)switch(s.kind){case "int":r.type="integer",_0e(r,"type",s.message,t);break;case "min":t.target==="jsonSchema7"?s.inclusive?br(r,"minimum",s.value,s.message,t):br(r,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(r.exclusiveMinimum=true),br(r,"minimum",s.value,s.message,t));break;case "max":t.target==="jsonSchema7"?s.inclusive?br(r,"maximum",s.value,s.message,t):br(r,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(r.exclusiveMaximum=true),br(r,"maximum",s.value,s.message,t));break;case "multipleOf":br(r,"multipleOf",s.value,s.message,t);break}return r}var B0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/number.js"(){Lm();}});function uot(e,t){let r=t.target==="openAi",s={type:"object",properties:{}},i=[],n=e.shape();for(let c in n){let o=n[c];if(o===void 0||o._def===void 0)continue;let l=dot(o);l&&r&&(o._def.typeName==="ZodOptional"&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),l=false);let u=hr(o._def,{...t,currentPath:[...t.currentPath,"properties",c],propertyPath:[...t.currentPath,"properties",c]});u!==void 0&&(s.properties[c]=u,l||i.push(c));}i.length&&(s.required=i);let a=lot(e,t);return a!==void 0&&(s.additionalProperties=a),s}function lot(e,t){if(e.catchall._def.typeName!=="ZodNever")return hr(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case "passthrough":return t.allowedAdditionalProperties;case "strict":return t.rejectedAdditionalProperties;case "strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function dot(e){try{return e.isOptional()}catch{return true}}var G0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/object.js"(){Ja();}}),H0e,W0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"(){Ja(),ec(),H0e=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return hr(e.innerType._def,t);let r=hr(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Wi(t)},r]}:Wi(t)};}}),V0e,K0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"(){Ja(),V0e=(e,t)=>{if(t.pipeStrategy==="input")return hr(e.in._def,t);if(t.pipeStrategy==="output")return hr(e.out._def,t);let r=hr(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),s=hr(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return {allOf:[r,s].filter(i=>i!==void 0)}};}});function pot(e,t){return hr(e.type._def,t)}var J0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"(){Ja();}});function hot(e,t){let s={type:"array",uniqueItems:true,items:hr(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&br(s,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&br(s,"maxItems",e.maxSize.value,e.maxSize.message,t),s}var Y0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/set.js"(){Lm(),Ja();}});function mot(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,s)=>hr(r._def,{...t,currentPath:[...t.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[]),additionalItems:hr(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,s)=>hr(r._def,{...t,currentPath:[...t.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}var X0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"(){Ja();}});function fot(e){return {not:Wi(e)}}var Q0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"(){ec();}});function got(e){return Wi(e)}var Z0e=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"(){ec();}}),eve,tve=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"(){Ja(),eve=(e,t)=>hr(e.innerType._def,t);}}),rve,ave=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/selectParser.js"(){ec(),b0e(),w0e(),S0e(),Mj(),T0e(),P0e(),A0e(),C0e(),O0e(),$0e(),D0e(),L0e(),j0e(),M0e(),z0e(),U0e(),B0e(),G0e(),W0e(),K0e(),J0e(),Uj(),Y0e(),zj(),X0e(),Q0e(),Bj(),Z0e(),tve(),rve=(e,t,r)=>{switch(t){case v3$1.ZodFirstPartyTypeKind.ZodString:return R0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodNumber:return cot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodObject:return uot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodBigInt:return Knt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodBoolean:return Jnt();case v3$1.ZodFirstPartyTypeKind.ZodDate:return x0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodUndefined:return fot(r);case v3$1.ZodFirstPartyTypeKind.ZodNull:return iot(r);case v3$1.ZodFirstPartyTypeKind.ZodArray:return Vnt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodUnion:case v3$1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return not(e,r);case v3$1.ZodFirstPartyTypeKind.ZodIntersection:return Znt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodTuple:return mot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodRecord:return N0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodLiteral:return eot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodEnum:return Qnt(e);case v3$1.ZodFirstPartyTypeKind.ZodNativeEnum:return aot(e);case v3$1.ZodFirstPartyTypeKind.ZodNullable:return oot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodOptional:return H0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodMap:return rot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodSet:return hot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodLazy:return ()=>e.getter()._def;case v3$1.ZodFirstPartyTypeKind.ZodPromise:return pot(e,r);case v3$1.ZodFirstPartyTypeKind.ZodNaN:case v3$1.ZodFirstPartyTypeKind.ZodNever:return sot(r);case v3$1.ZodFirstPartyTypeKind.ZodEffects:return Xnt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodAny:return Wi(r);case v3$1.ZodFirstPartyTypeKind.ZodUnknown:return got(r);case v3$1.ZodFirstPartyTypeKind.ZodDefault:return Ynt(e,r);case v3$1.ZodFirstPartyTypeKind.ZodBranded:return k0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodReadonly:return eve(e,r);case v3$1.ZodFirstPartyTypeKind.ZodCatch:return E0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodPipeline:return V0e(e,r);case v3$1.ZodFirstPartyTypeKind.ZodFunction:case v3$1.ZodFirstPartyTypeKind.ZodVoid:case v3$1.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (s=>{})()}};}});function hr(e,t,r=false){let s=t.seen.get(e);if(t.override){let c=t.override?.(e,t,s,r);if(c!==f0e)return c}if(s&&!r){let c=sve(s,t);if(c!==void 0)return c}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=rve(e,e.typeName,t),a=typeof n=="function"?hr(n(),t):n;if(a&&ive(e,t,a),t.postProcess){let c=t.postProcess(a,e,t);return i.jsonSchema=a,c}return i.jsonSchema=a,a}var sve,ive,Ja=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parseDef.js"(){Nj(),ave(),jj(),ec(),sve=(e,t)=>{switch(t.$refStrategy){case "root":return {$ref:e.path.join("/")};case "relative":return {$ref:Lj(t.currentPath,e.path)};case "none":case "seen":return e.path.length<t.currentPath.length&&e.path.every((r,s)=>t.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Wi(t)):t.$refStrategy==="seen"?Wi(t):void 0}},ive=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);}}),yot=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parseTypes.js"(){}}),nve,Iae=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"(){Ja(),v0e(),ec(),nve=(e,t)=>{let r=y0e(t),s=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[l,u])=>({...o,[l]:hr(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},true)??Wi(r)}),{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,n=hr(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},false)??Wi(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(n.title=a),r.flags.hasReferencedOpenAiAnyType&&(s||(s={}),s[r.openAiAnyTypeName]||(s[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let c=i===void 0?s?{...n,[r.definitionPath]:s}:n:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...s,[i]:n}};return r.target==="jsonSchema7"?c.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c};}}),vot=O({"../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/index.js"(){Nj(),v0e(),Lm(),jj(),Ja(),yot(),ec(),b0e(),w0e(),S0e(),Mj(),T0e(),P0e(),A0e(),C0e(),O0e(),$0e(),D0e(),L0e(),j0e(),M0e(),z0e(),U0e(),B0e(),G0e(),W0e(),K0e(),J0e(),tve(),Uj(),Y0e(),zj(),X0e(),Q0e(),Bj(),Z0e(),ave(),Iae(),Iae();}}),ove={};mt(ove,{DEFAULT_WS_PORT:()=>Gj,TAURI_MCP_PATH:()=>Yh,closeAllTauriMcpSessions:()=>Tot,getActiveTauriMcpSessionCount:()=>xot,registerTauriMcpServerRoutes:()=>Iot});async function kot(){if(yb)return;yb=(await import('@hypothesi/tauri-mcp-server')).TOOLS,Hj=yb.map(t=>({name:t.name,description:t.description,inputSchema:nve(t.schema),annotations:t.annotations})),Wj=new Map(yb.map(t=>[t.name,t]));}function a3(e,t){let r=e.headers.origin||"*";t.raw.setHeader("Access-Control-Allow-Origin",r),t.raw.setHeader("Access-Control-Allow-Credentials","true"),t.raw.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Accept, Mcp-Session-Id, Last-Event-Id, mcp-protocol-version"),t.raw.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id, mcp-protocol-version"),t.raw.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS");}function s3(e){let t=e.headers["mcp-session-id"];return Array.isArray(t)?t.at(-1):t}function Eot(){let e=new index_js.Server({name:"tauri-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return e.setRequestHandler(types_js.ListToolsRequestSchema,async()=>({tools:Hj})),e.setRequestHandler(types_js.CallToolRequestSchema,async t=>{let r=Wj.get(t.params.name);if(!r)return {content:[{type:"text",text:`Error: Unknown tool: ${t.params.name}`}],isError:true};try{let s=await r.handler(t.params.arguments);return typeof s=="string"?{content:[{type:"text",text:s}]}:Array.isArray(s)?{content:s.map(i=>i.type==="text"?{type:"text",text:i.text}:{type:"image",data:i.data,mimeType:i.mimeType})}:s.type==="text"?{content:[{type:"text",text:s.text}]}:{content:[{type:"image",data:s.data,mimeType:s.mimeType}]}}catch(s){return {content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:true}}}),e}function Tot(){for(let e of Fs.values())e.transport.close?.().catch(t=>{W1.warn({err:t,sessionId:e.id},"Failed to close tauri MCP transport");});Fs.clear();}function xot(){return Fs.size}async function Iot(e,t={}){await kot();let r=t.port??Gj,s=t.createServer??(()=>Eot()),i=t.createTransport??(n=>new streamableHttp_js.StreamableHTTPServerTransport({sessionIdGenerator:sw.randomUUID,onsessioninitialized:a=>{let c=Fs.get(n);c&&(Fs.delete(n),Fs.set(a,{...c,id:a}),W1.info({sessionId:a},"Tauri MCP session initialized"));},onsessionclosed:a=>{Fs.get(a)&&(W1.info({sessionId:a},"Tauri MCP session closed"),Fs.delete(a));}}));e.get(`${Yh}/status`,{schema:{description:"Check tauri-plugin-mcp-bridge connection status",tags:["mcp","tauri"],response:{200:{type:"object",properties:{available:{type:"boolean"},port:{type:"number"},connected:{type:"boolean"},error:{type:"string"}}}}}},async()=>{let{default:n}=await import('ws');return new Promise(a=>{let c=false,o=new n(`ws://127.0.0.1:${r}`),l=d=>{c||(c=true,clearTimeout(u),o.close(),a(d));},u=setTimeout(()=>{l({available:false,port:r,connected:false,error:"Connection timeout. Is the Tauri app running?"});},2e3);o.once("open",()=>{l({available:true,port:r,connected:true});}),o.once("error",d=>{l({available:false,port:r,connected:false,error:`Cannot connect: ${d.message}`});});})}),e.get(Yh,async(n,a)=>{a3(n,a);let c=s3(n);if(!c)return a.code(400),{error:"Mcp-Session-Id header required"};let o=Fs.get(c);if(!o)return a.code(404),{error:"Session not found"};await o.transport.handleRequest(n.raw,a.raw);}),e.post(Yh,async(n,a)=>{a3(n,a);let c=s3(n);if(c){let h=Fs.get(c);if(!h)return a.code(404),{error:"Session not found"};await h.transport.handleRequest(n.raw,a.raw,n.body);return}let o=`pending-${sw.randomUUID()}`,l=i(o),u=s(),d=l.sessionId??o;Fs.set(d,{id:d,server:u,transport:l}),l.onclose=()=>{Fs.delete(d),l.sessionId&&Fs.delete(l.sessionId);},await u.connect(l),await l.handleRequest(n.raw,a.raw,n.body);}),e.delete(Yh,async(n,a)=>{a3(n,a);let c=s3(n);if(!c)return a.code(400),{error:"Mcp-Session-Id header required"};let o=Fs.get(c);if(!o)return a.code(404),{error:"Session not found"};await o.transport.handleRequest(n.raw,a.raw),Fs.delete(c);}),e.options(`${Yh}/*`,{schema:{hide:true}},async(n,a)=>{a.header("Access-Control-Allow-Origin","*"),a.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),a.header("Access-Control-Allow-Headers","Content-Type, Authorization, Accept, Mcp-Session-Id, Last-Event-Id, mcp-protocol-version"),a.header("Access-Control-Expose-Headers","Mcp-Session-Id, mcp-protocol-version"),a.header("Access-Control-Max-Age","86400"),a.code(204).send();});}var W1,Yh,Gj,yb,Hj,Wj,Fs,Pot=O({"src/gateway/routes/mcp-server/tauri-mcp-server.ts"(){vot(),Ke(),W1=je.child({module:"tauri-mcp-server"}),Yh="/api/mcp-server/tauri",Gj=9223,yb=null,Hj=null,Wj=null,Fs=new Map;}});async function cve(e,t){qQe(e),YQe(e,t),ZQe(e,t),rZe(e,t),iZe(e,t),nZe(e,t),oZe(e,t),uZe(e),HQe(e),gZe(e),yZe(e),kZe(e,t),IZe(e),PZe(e),DZe(e),XZe(e),GZe(e,t),tet(e),set(e),pet(e),yet(e),vet(e),Yst(e,t),Ret(e),qet(e),Net(e),Get(e),stt(e),dtt(e),gtt(e),xtt(e),Ltt(e),Ytt(e),irt(e),frt(e),_rt(e),krt(e),Trt(e),Brt(e),Hrt(e,t),Hat(e);try{let{registerTauriMcpServerRoutes:r}=await Promise.resolve().then(()=>(Pot(),ove));await r(e);}catch{}Wat(e),Vat(e),Jat(e),Yat(e,t),Xat(e),Zat(e),est(e),Hst(e),Wst(e,t),Kst(e,t),vit(e),tnt(e),lnt(e,t),Snt(e),Hnt(e);}var Aae=O({"src/gateway/routes/index.ts"(){j1(),Qee(),tq(),ite(),nte(),ote(),cte(),ute(),eq(),lte(),dte(),iq(),hte(),mte(),fte(),yte(),_te(),Ste(),kte(),Ite(),Ate(),Cte(),Dte(),Rte(),qte(),Lte(),Bte(),Hte(),Jte(),Xte(),_q(),ere(),are(),sre(),nre(),Ert(),lre(),mre(),fre(),Sre(),Tre(),xre(),Ire(),Pre(),Are(),Cre(),Ore(),Hre(),Wre(),Vre(),Kre(),tae(),dae(),mae(),yae(),Tae(),j1(),Qee(),tq(),ite(),nte(),ote(),cte(),ute(),eq(),lte(),dte(),iq(),hte(),mte(),fte(),_te(),yte(),Ste(),kte(),Ite(),Ate(),Cte(),Dte(),Rte(),qte(),Lte(),Bte(),Hte(),Jte(),Xte(),_q(),ere(),are(),sre(),nre(),lre(),mre(),fre(),Sre(),Tre(),xre(),Ire(),Pre(),Are(),Cre(),Ore(),Hre(),Wre(),Vre(),Kre(),tae(),dae(),mae(),yae(),Tae(),b2();}}),Dr,i3,n3,Cae,ox,o3,Oae,Vj,Fae=O({"src/gateway/client-socket-server.ts"(){Ke(),Dr=je.child({module:"client-socket-server"}),i3="/socket.io/client",n3=3e4,Cae=6e4,ox=10*1024*1024,o3=1e3,Oae=100,Vj=class{constructor(e,t){this.pendingExecutes=new Map,this.pendingApprovals=new Map,this.seenRequestIds=new Map,this.rateLimits=new Map,this.cleanupTimer=null,this.clientStore=t,this.io=new socket_io.Server(e,{path:i3,cors:{origin:"*"},maxHttpBufferSize:ox}),this.setupEventHandlers(),this.startCleanup(),Dr.info({path:i3},"ClientSocketServer initialized");}checkRateLimit(e){let t=Date.now(),r=this.rateLimits.get(e);return !r||t-r.windowStart>o3?(r={count:1,windowStart:t},this.rateLimits.set(e,r),true):r.count>=Oae?(Dr.warn({socketId:e,count:r.count},"Rate limit exceeded"),false):(r.count++,true)}validatePayloadSize(e){try{let t=JSON.stringify(e);return t.length>ox?{valid:!1,error:`Payload too large: ${t.length} bytes (max: ${ox})`}:{valid:!0}}catch{return {valid:false,error:"Invalid payload (not serializable)"}}}setupEventHandlers(){this.io.on("connection",e=>{Dr.debug({socketId:e.id},"Socket connected"),e.on("client:connect",async(t,r)=>{if(!this.checkRateLimit(e.id)){r?.({success:false,error:"Rate limit exceeded"});return}await this.handleClientConnect(e,t,r);}),e.on("action:register",t=>{this.checkRateLimit(e.id)&&this.handleActionRegister(e,t);}),e.on("action:unregister",t=>{this.checkRateLimit(e.id)&&this.handleActionUnregister(e,t);}),e.on("action:result",t=>{this.checkRateLimit(e.id)&&this.handleActionResult(t);}),e.on("action:approval:request",t=>{this.checkRateLimit(e.id)&&this.handleApprovalRequest(e,t);}),e.on("action:approval:response",t=>{this.checkRateLimit(e.id)&&this.handleApprovalResponse(t);}),e.on("client:theme:set",t=>{this.checkRateLimit(e.id)&&this.handleThemeSet(e,t);}),e.on("action:list",(t,r)=>{if(!this.checkRateLimit(e.id))return;let s=e.clientId;if(!s||!r)return;let i=this.clientStore.getClient(s);if(!i){r({actions:[]});return}let n=[];for(let a of i.actionStore.values())a.socketId!==e.id&&n.push({namespace:a.namespace,name:a.name,description:a.description});r({actions:n});}),e.on("disconnect",()=>{this.handleDisconnect(e),this.rateLimits.delete(e.id);});});}async handleClientConnect(e,t,r){if(!t.clientId||typeof t.clientId!="string"){r?.({success:false,error:"clientId is required"});return}if(!t.source){r?.({success:false,error:"source is required"});return}if(!t.publicKey||!t.signature||!t.timestamp){r?.({success:false,error:"publicKey, signature, and timestamp are required"});return}try{let s=await this.clientStore.registerClient(t.clientId,{source:t.source,socketId:e.id,pageUid:t.pageUid,publicKey:t.publicKey,signature:t.signature,timestamp:t.timestamp});e.clientId=t.clientId,e.join(`client:${t.clientId}`),t.source==="main_window"&&s.metadata.theme!=="light"&&this.clientStore.setGlobalTheme(s.metadata.theme);let i={theme:t.source==="main_window"?s.metadata.theme:this.clientStore.globalTheme};t.source==="main_window"&&(i.workspacePath=s.metadata.workspacePath),e.emit("client:init",i),r?.({success:!0}),Dr.info({clientId:t.clientId,socketId:e.id,source:t.source},"Client connected");}catch(s){let i=s instanceof Error?s.message:"Unknown error";Dr.warn({clientId:t.clientId,error:i},"Client connect failed"),r?.({success:false,error:i});}}handleThemeSet(e,t){let r=e.clientId;if(!r)return;let s=this.clientStore.getClient(r);if(!s)return;let i=s.sockets.get(e.id);if(!(!i||i.source!=="main_window")&&t.theme!==this.clientStore.globalTheme){this.clientStore.setGlobalTheme(t.theme),Dr.info({theme:t.theme},"Global theme updated");for(let[,n]of this.io.sockets.sockets)n.id!==e.id&&n.emit("client:theme",{theme:t.theme});}}handleActionRegister(e,t){let r=e.clientId;if(!r){Dr.warn({socketId:e.id},"Action register without client connect"),e.emit("action:register:result",{namespace:t.namespace,accepted:[],rejected:[{action:"*",reason:"Not connected as client"}]});return}if(!t.namespace||typeof t.namespace!="string"){Dr.warn({clientId:r,socketId:e.id},"Invalid namespace");return}let s=new Set(Object.keys(t.actions||{})),i=this.clientStore.removeStaleActions(r,t.namespace,e.id,s);i.length>0&&Dr.info({clientId:r,removed:i},"Stale actions removed during reconciliation");let n=[],a=[];for(let[c,o]of Object.entries(t.actions||{})){let l=this.clientStore.registerAction(r,e.id,{namespace:t.namespace,name:c,description:o.description,inputSchema:o.inputSchema,outputSchema:o.outputSchema,timeout:o.timeout});l.error?a.push({action:c,reason:l.error}):n.push(c);}e.emit("action:register:result",{namespace:t.namespace,accepted:n,rejected:a});}handleActionUnregister(e,t){let r=e.clientId;r&&this.clientStore.unregisterAction(r,t.namespace,e.id);}handleActionResult(e){let t=this.pendingExecutes.get(e.requestId);if(!t){Dr.debug({requestId:e.requestId},"Result for unknown request (possibly timed out)");return}clearTimeout(t.timer),this.pendingExecutes.delete(e.requestId),t.resolve(e.result);}handleApprovalRequest(e,t){let r=e.clientId;if(!r){Dr.warn({socketId:e.id},"Approval request without client connect");return}if(!t.requestId||!t.executeRequestId||!t.message){Dr.warn({clientId:r,socketId:e.id},"Invalid approval request data");return}let s=this.clientStore.getClient(r);if(!s){Dr.warn({clientId:r},"Client not found for approval request");return}let i;for(let[c,o]of s.sockets)if(o.source==="main_window"){let l=this.io.sockets.sockets.get(c);if(l){i=l;break}}if(!i){Dr.warn({clientId:r},"No UI-capable socket found for approval request"),e.emit("action:approval:result",{requestId:t.requestId,approved:false,error:"No UI socket available"});return}let n=t.options?.timeout??n3,a=setTimeout(()=>{this.pendingApprovals.delete(t.requestId);let c=this.io.sockets.sockets.get(e.id);c&&c.emit("action:approval:result",{requestId:t.requestId,approved:false,error:"Approval timeout"}),Dr.debug({requestId:t.requestId,clientId:r},"Approval request timed out");},n);this.pendingApprovals.set(t.requestId,{requestId:t.requestId,originSocketId:e.id,timer:a}),i.emit("action:approval:request",{requestId:t.requestId,executeRequestId:t.executeRequestId,message:t.message,options:t.options}),Dr.debug({requestId:t.requestId,clientId:r,uiSocketId:i.id},"Approval request forwarded to UI");}handleApprovalResponse(e){let t=this.pendingApprovals.get(e.requestId);if(!t){Dr.debug({requestId:e.requestId},"Approval response for unknown request (possibly timed out)");return}clearTimeout(t.timer),this.pendingApprovals.delete(e.requestId);let r=this.io.sockets.sockets.get(t.originSocketId);r?(r.emit("action:approval:result",{requestId:e.requestId,approved:e.approved}),Dr.debug({requestId:e.requestId,originSocketId:t.originSocketId,approved:e.approved},"Approval result sent to originator")):Dr.debug({requestId:e.requestId,originSocketId:t.originSocketId},"Origin socket disconnected, approval result dropped");}handleDisconnect(e){let t=e.clientId;if(t){for(let[r,s]of this.pendingExecutes)s.socketId===e.id&&(clearTimeout(s.timer),this.pendingExecutes.delete(r),s.resolve({content:[{type:"text",text:"Socket disconnected during execution"}],isError:true}));for(let[r,s]of this.pendingApprovals)if(s.originSocketId===e.id)clearTimeout(s.timer),this.pendingApprovals.delete(r),Dr.debug({requestId:r,socketId:e.id},"Pending approval cleaned up (originator disconnected)");else {let i=this.clientStore.getClient(t);if(i){let n=i.sockets.get(e.id);if(n&&n.source==="main_window"){let a=this.io.sockets.sockets.get(s.originSocketId);a&&a.clientId===t&&(clearTimeout(s.timer),this.pendingApprovals.delete(r),a.emit("action:approval:result",{requestId:r,approved:false,error:"Approver disconnected"}),Dr.debug({requestId:r,socketId:e.id},"Approval rejected (UI socket disconnected)"));}}}this.clientStore.removeSocket(t,e.id),Dr.info({clientId:t,socketId:e.id},"Socket disconnected");}}async executeAction(e,t,r,s,i){let n=this.clientStore.findAction(e,t,r);if(!n)return {content:[{type:"text",text:`Action not found: ${t}.${r}`}],isError:true};let a=this.validatePayloadSize(s);if(!a.valid)return {content:[{type:"text",text:`Invalid payload: ${a.error}`}],isError:true};let c=this.clientStore.getClient(e);if(!c||c.sockets.size===0)return Dr.warn({targetClientId:e,namespace:t,actionName:r,clientExists:!!c,socketsSize:c?.sockets.size??0},"executeAction: client offline"),{content:[{type:"text",text:`Client offline: ${e}`}],isError:true};if(!c.sockets.get(n.socketId)){let h=[...c.sockets.keys()];return Dr.warn({targetClientId:e,namespace:t,actionName:r,actionSocketId:n.socketId,currentSocketIds:h},"executeAction: action socket disconnected (socketId mismatch \u2014 action was registered on a now-stale socket)"),{content:[{type:"text",text:`Action socket disconnected (registered on ${n.socketId}, current sockets: [${h.join(", ")}])`}],isError:true}}let l=this.io.sockets.sockets.get(n.socketId);if(!l)return Dr.warn({targetClientId:e,actionSocketId:n.socketId},"executeAction: socket.io instance not found"),{content:[{type:"text",text:"Socket not found"}],isError:true};let u=sw.randomUUID();if(this.seenRequestIds.has(u))return {content:[{type:"text",text:"Duplicate request"}],isError:true};this.seenRequestIds.set(u,Date.now());let d=n.timeout??n3;return new Promise(h=>{let v=setTimeout(()=>{this.pendingExecutes.delete(u),h({content:[{type:"text",text:`Execution timeout after ${d}ms`}],isError:true});},d);this.pendingExecutes.set(u,{requestId:u,clientId:e,socketId:n.socketId,resolve:h,reject:()=>{},timer:v}),l.emit("action:execute",{requestId:u,namespace:t,action:r,payload:s,context:i});})}startCleanup(){this.cleanupTimer=setInterval(()=>{let e=Date.now();for(let[t,r]of this.seenRequestIds)e-r>Cae&&this.seenRequestIds.delete(t);for(let[t,r]of this.rateLimits)e-r.windowStart>o3*10&&this.rateLimits.delete(t);},6e4);}shutdown(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null);for(let e of this.pendingExecutes.values())clearTimeout(e.timer),e.resolve({content:[{type:"text",text:"Server shutdown"}],isError:true});this.pendingExecutes.clear();for(let e of this.pendingApprovals.values()){clearTimeout(e.timer);let t=this.io.sockets.sockets.get(e.originSocketId);t&&t.emit("action:approval:result",{requestId:e.requestId,approved:false,error:"Server shutdown"});}this.pendingApprovals.clear(),this.rateLimits.clear(),this.io.close(),Dr.info("ClientSocketServer shut down");}};}}),uve={};mt(uve,{ClientSocketServer:()=>Vj,ClientStore:()=>ej,createAppState:()=>gfe,createGateway:()=>Kj,getLogger:()=>Not,registerRoutes:()=>cve,resetCleanupStaleAcpSessionsForTests:()=>jot,runGateway:()=>Mot,setCleanupStaleAcpSessionsForTests:()=>Lot,setGatewayStartupConfig:()=>yfe});function qot(e){return lve.some(t=>e===t||e.startsWith(`${t}/`))}function Not(){return Xh?.logger||null}function Lot(e){q2=e;}function jot(){q2=Fie;}async function Kj(e={}){let{host:t="127.0.0.1",port:r=18790,cors:s=true,telemetry:i=process.env.VIBEN_TELEMETRY!=="false",telemetryDir:n=Zh(),runtime:a=true}=e;i&&!Xh&&(Xh=aNe({serviceName:"viben-gateway",serviceVersion:"1.0.0",baseDir:n,enabled:i,trace:{flushDelayMs:5e3,batchSize:100},metrics:{exportIntervalMs:6e4},log:{level:process.env.LOG_LEVEL||"info"}}));let c=Oot__default.default({logger:true});try{await c.register(Dot__default.default,{openapi:{info:{title:"Viben Gateway API",description:"Agent Swarm \xD7 Code Evolution - Multi-agent orchestration and code evolution API",version:tj},servers:[{url:`http://${t}:${r}`,description:"Local development server"}],tags:[{name:"health",description:"Health check endpoints"},{name:"agents",description:"Agent management"},{name:"sessions",description:"Session management"},{name:"tasks",description:"Task management"},{name:"models",description:"Model configuration"},{name:"providers",description:"Provider configuration"},{name:"workspaces",description:"Workspace management"},{name:"cron",description:"Scheduled jobs"},{name:"channels",description:"Channel management"},{name:"mcp",description:"MCP server management"},{name:"executors",description:"Executor configuration"}]},transform:({schema:l,url:u})=>({schema:qot(u)?{...l,hide:!0}:l,url:u})}),c.get("/openapi.json",async()=>c.swagger()),c.get("/openapi.yaml",async(l,u)=>{let d=c.swagger({yaml:!0});u.type("application/x-yaml").send(d);}),At.info("Swagger plugin registered (OpenAPI spec at /openapi.json, /openapi.yaml)");}catch(l){At.warn({err:l},"Failed to register Swagger plugin");}s&&await c.register(Fot__default.default,{origin:true,methods:["GET","POST","PUT","PATCH","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Accept","X-MCP-Proxy-Auth","MCP-Session-Id","X-Custom-Auth-Header","X-Custom-Auth-Headers","Last-Event-Id","mcp-protocol-version"],exposedHeaders:["MCP-Session-Id","mcp-protocol-version"],credentials:true});try{await c.register($ot__default.default,{limits:{fileSize:100*1024*1024,files:10}}),At.info("Multipart plugin registered");}catch(l){At.warn({err:l},"Failed to register multipart plugin");}let o=gfe({host:t,port:r,runtime:a});if(a){let l=c.server;o.clientSocketServer=new Vj(l,o.clientStore),At.info("Client Socket.io server started");}try{await c.register(Rot__default.default),At.info("WebSocket plugin registered");}catch(l){At.warn({err:l},"Failed to register WebSocket plugin");}if(a){let l=c.server.listeners("upgrade"),u=l[0],d=l[1];u&&d&&(c.server.removeAllListeners("upgrade"),c.server.on("upgrade",(h,v,y)=>{(h.url||"").startsWith("/socket.io/client")?u(h,v,y):d(h,v,y);}),At.info("WebSocket upgrade dispatcher installed (Socket.io + Fastify)"));}await cve(c,o);try{await q2(Wa.storage);}catch(l){At.warn({err:l},"Stale ACP session cleanup failed");}if(yfe({host:t,port:r,cors:s}),a){try{await o.cron.start(),At.info("Cron scheduler started");}catch(l){At.warn({err:l},"Failed to start cron scheduler");}try{await o.channelRouter.start(),At.info("Channel router started");}catch(l){At.warn({err:l},"Failed to start channel router");}try{await o.channelRuntime.start();let l=o.channelRuntime.getActivePollers();At.info({activePollerCount:l.length},"Channel runtime started");}catch(l){At.warn({err:l},"Failed to start channel runtime");}try{await o.taskQueue.start();let l=o.taskQueue.getStatus();At.info({pending:l.pending_count,running:l.running_count},"Task queue manager started");}catch(l){At.warn({err:l},"Failed to start task queue manager");}try{o.taskSSEManager.startHeartbeat(),At.info("Task SSE Manager heartbeat started");}catch(l){At.warn({err:l},"Failed to start SSE heartbeat");}try{await o.commandQueue.start();let l=o.commandQueue.getStatus();At.info({pending:l.pending,running:l.running,maxConcurrency:l.max_concurrency},"Command queue started");}catch(l){At.warn({err:l},"Failed to start command queue");}try{await o.discovery.start(),At.info({mdnsAvailable:await o.discovery.isMdnsAvailable()},"Discovery service started");}catch(l){At.warn({err:l},"Failed to start discovery service");}try{await o.mesh.reconnectKnownPeers(),At.info("Mesh peer reconnection initiated");}catch(l){At.warn({err:l},"Failed to reconnect known peers");}try{let l=await wn.listWorkspaces(),u=0,d=0;for(let h of l)try{let v=await o.taskRecovery.recoverOnStartup(h.path);d+=v.totalChecked,u+=v.recovered,v.recovered>0&&At.info({workspace:h.path,recovered:v.recovered,checked:v.totalChecked},"Task recovery completed for workspace");}catch(v){At.warn({workspace:h.path,err:v},"Failed to recover tasks for workspace");}d>0&&At.info({totalChecked:d,totalRecovered:u,workspaceCount:l.length},"Task recovery completed");}catch(l){At.warn({err:l},"Failed to run task recovery");}i&&(Jqe({getActiveAgentSessions:()=>ar.getActiveSessionCount(),getActiveWsConnections:()=>bZe(),getCronJobCounts:()=>o.cron.getJobStats()}),At.info("Metrics gauge callbacks registered"));}return a&&c.addHook("onClose",async()=>{At.info("Shutting down gateway..."),o.clientSocketServer?.shutdown(),o.clientStore.shutdown(),o.channelRouter.stop(),await o.channelRuntime.stop(),await o.cron.shutdown(),await o.taskQueue.shutdown(),await o.commandQueue.stop(),o.taskSSEManager.stopHeartbeat(),o.taskSSEManager.close(),o.discovery.stop(),o.mesh.shutdown(),o.container.killAllRunningProcesses(),Xh&&(await Xh.shutdown(),Xh=null),At.info("Shutdown complete");}),c}async function Mot(e={}){let{host:t="127.0.0.1",port:r=18790,telemetry:s=process.env.VIBEN_TELEMETRY!=="false",telemetryDir:i=Zh()}=e,n=await Kj(e),a=false,c=async o=>{if(a){At.debug({signal:o},"Already shutting down, ignoring signal");return}a=true,At.info({signal:o},"Received shutdown signal, shutting down gracefully...");try{let l=n.close(),u=new Promise((d,h)=>setTimeout(()=>h(new Error("Shutdown timeout")),5e3));await Promise.race([l,u]),At.info("Server closed successfully");}catch(l){At.warn({err:l},"Shutdown timed out or failed, forcing exit");}process.exit(0);};process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM"));try{await n.listen({host:t,port:r}),At.info({host:t,port:r,telemetryEnabled:s,telemetryDir:i},"Gateway server started"),console.log(`
|
|
1103
|
+
[Gateway] Server running on http://${t}:${r}`),console.log("[Gateway] API: /health, /api/agent, /api/tasks, /api/sessions"),s&&console.log(`[Gateway] Telemetry: ${i}`),console.log(""),await new Promise(()=>{});}catch(o){At.error({err:o},"Failed to start gateway"),process.exit(1);}}var Xh,At,lve,q2,dve=O({"src/gateway/index.ts"(){Jee(),Aae(),j1(),Ke(),QI(),iq(),Tm(),Fae(),Sw(),Jee(),Aae(),j1(),ffe(),Fae(),Xh=null,At=je.child({module:"gateway"}),lve=["/api/mcp-server","/api/python-mcp"],q2=Fie;}}),pve={};mt(pve,{registerGatewayCommand:()=>Yot});function $y(e){try{let t=process.platform==="win32",r;if(t){r=child_process.execSync(`netstat -ano | findstr :${e} | findstr LISTENING`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]});let s=r.trim().split(`
|
|
1104
1104
|
`);if(s.length>0){let i=s[0].trim().split(/\s+/),n=parseInt(i[i.length-1],10);return isNaN(n)?null:n}return null}else {r=child_process.execSync(`lsof -ti :${e}`,{encoding:"utf-8"});let s=parseInt(r.trim().split(`
|
|
1105
1105
|
`)[0],10);return isNaN(s)?null:s}}catch{return null}}function mve(e){try{return process.kill(e,"SIGTERM"),!0}catch{return false}}function Dae(e){try{return process.kill(e,"SIGKILL"),!0}catch{return false}}function Got(e){switch(e){case "running":return J__default.default.green("running");case "stopped":return J__default.default.gray("stopped");case "failed":return J__default.default.red("failed");default:return J__default.default.yellow("unknown")}}function $g(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}async function fve(e){let{host:t,port:r}=e,s=`${t}:${r}`;console.log(`Starting gateway on ${s}...`);try{let{runGateway:i}=await Promise.resolve().then(()=>(dve(),uve));await i({host:t,port:r,cors:!0});}catch(i){console.warn(`[Gateway] Fastify not available, using simple HTTP server: ${i instanceof Error?i.message:i}`),await Wot(e);}}async function Hot(e){let t=await Kj({host:Qd,port:0,cors:false,telemetry:false,runtime:false});try{await t.ready();let r=t.swagger;if(!r)throw new Error("Swagger plugin is not registered");return e==="yaml"?String(r({yaml:!0})):JSON.stringify(r(),null,2)}finally{await t.close();}}async function Rae(e,t,r){if(!t.out)throw new Error("--out is required");let s=Re.resolve(process.cwd(),t.out),i=Re.dirname(s);De__namespace.existsSync(i)||De__namespace.mkdirSync(i,{recursive:true});let n=await Hot(r);De__namespace.writeFileSync(s,n,"utf-8"),j(e,V({path:s,format:r}),()=>{let a=r==="json"?"JSON":"YAML";console.log(J__default.default.green(`OpenAPI ${a} exported: ${s}`));});}async function Wot(e){let{host:t,port:r}=e,s=`${t}:${r}`,i=$7e.createServer((a,c)=>{let o=new URL(a.url||"/",`http://${s}`);if(c.setHeader("Access-Control-Allow-Origin","*"),c.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, DELETE, OPTIONS"),c.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),a.method==="OPTIONS"){c.writeHead(204),c.end();return}if(o.pathname==="/health"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({status:"ok",version:"1.0.0",timestamp:new Date().toISOString(),uptime:"running"}));return}if(o.pathname==="/api"||o.pathname==="/api/"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({version:"1.0.0",endpoints:["/health","/api/agent","/api/tasks","/api/sessions","/api/cron","/api/channels","/api/executors","/api/events"],note:"Running in simple mode - install fastify for full functionality"}));return}if(o.pathname==="/api/agent"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({agents:[]}));return}if(o.pathname==="/api/tasks"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({tasks:[]}));return}if(o.pathname==="/api/sessions"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({sessions:[]}));return}if(o.pathname==="/api/cron"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({jobs:[]}));return}if(o.pathname==="/api/channels"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({channels:[]}));return}if(o.pathname==="/api/executors"){c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({executors:[{type:"CLAUDE_CODE",name:"Claude Code",available:true}]}));return}if(o.pathname==="/api/events"){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
|
|
1106
1106
|
data: ${JSON.stringify({timestamp:Date.now()})}
|
|
@@ -1113,7 +1113,7 @@ ${J__default.default.bold("Available dates")}:
|
|
|
1113
1113
|
`),ht(s,["Date","Traces"],a.map(c=>[c.date,String(c.count)])),console.log(`
|
|
1114
1114
|
Telemetry directory: ${J__default.default.cyan(i)}`);});}}catch(n){Q(s,n);}}),t.command("view <traceId> [date]").description("View a trace as tree. Date defaults to today").action(async function(r,s){let i=cx(this),n=Zh(),a=s||new Date().toISOString().split("T")[0];try{let c=Re__namespace.join(n,"traces",a,`${r}.jsonl`),o=Mqe(c),l=bse(o);l||(console.log(J__default.default.red("No spans found in trace")),process.exit(1)),j(i,V({tree:l,stats:m3(l)}),()=>{console.log(zqe(l)),console.log("");let u=m3(l);console.log(J__default.default.bold("\u7EDF\u8BA1\u4FE1\u606F:")),console.log(` \u603B spans: ${u.totalSpans}`),console.log(` \u6210\u529F: ${J__default.default.green(u.successSpans)}`),console.log(` \u9519\u8BEF: ${J__default.default.red(u.errorSpans)}`),console.log(` \u6700\u5927\u6DF1\u5EA6: ${u.maxDepth}`),console.log(""),console.log(J__default.default.bold("\u64CD\u4F5C\u8017\u65F6:"));for(let[d,h]of u.operations){let v=(h.totalDuration/h.count).toFixed(2);console.log(` ${d}: ${h.count}\u6B21, \u5E73\u5747 ${J__default.default.yellow(v+"ms")}`);}});}catch(c){Q(i,c);}}),t.command("stats").description("Show telemetry statistics").action(async function(){let r=cx(this),s=Zh();try{let i=Dd(s),n=0,a=0;for(let o of i){let l=await Nc(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)};j(r,V(c),()=>{console.log(`
|
|
1115
1115
|
${J__default.default.bold("Telemetry \u7EDF\u8BA1")}:
|
|
1116
|
-
`),console.log(` \u76EE\u5F55: ${J__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){Q(r,i);}}),t.command("clean [days]").description("Clean old telemetry files. Default: 7 days retention").action(async function(r){let s=cx(this),i=Zh(),n=parseInt(r||"7",10);(isNaN(n)||n<1)&&(console.log(J__default.default.red("Invalid retention days. Must be a positive number.")),process.exit(1));try{let a=Dd(i),c=0;for(let d of a)c+=(await Nc(i,d)).length;Dse(i,n);let o=Dd(i),l=0;for(let d of o)l+=(await Nc(i,d)).length;let u={retentionDays:n,datesRemoved:a.length-o.length,tracesRemoved:c-l};j(s,V(u),()=>{console.log(J__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){Q(s,a);}});}var wct=O({"src/cli/commands/telemetry.ts"(){Ke(),yr();}}),Sve={};mt(Sve,{registerUpdateCommand:()=>Fct});function xct(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 Ict(){try{let e=await Ot(`https://api.github.com/repos/${J1}/releases`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":`viben/${Mo}`}});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:xct(s,Mo)>0,currentVersion:Mo}}catch{return null}}async function Pct(){try{let{stdout:t}=await zh("npm config get prefix"),{stdout:r}=await zh("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 zh(`which ${t}`),t==="pnpm"){let{stdout:r}=await zh("pnpm list -g viben").catch(()=>({stdout:""}));if(r.includes("viben"))return "pnpm"}else if(t==="yarn"){let{stdout:r}=await zh("yarn global list").catch(()=>({stdout:""}));if(r.includes("viben"))return "yarn"}else if(t==="bun"){let{stdout:r}=await zh("bun pm ls -g").catch(()=>({stdout:""}));if(r.includes("viben"))return "bun"}}catch{}return "npm"}function Hq(e){switch(e){case "pnpm":return ["pnpm","add","-g",_b];case "yarn":return ["yarn","global","add",_b];case "bun":return ["bun","add","-g",_b];default:return ["npm","install","-g","--force",_b]}}async function Act(e,t){let[r,...s]=Hq(t);return new Promise(i=>{e.quiet||(console.log(J__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 Cct(e,t){e.quiet||(console.log(J__default.default.cyan("Checking for updates...")),console.log(J__default.default.gray(` Current version: v${Mo}`)),console.log());let r=await Ict();if(r||(j(e,it("FETCH_FAILED","Failed to fetch release information from GitHub"),()=>{console.log(J__default.default.red("Error: Failed to check for updates.")),console.log(J__default.default.gray(" Please check your internet connection and try again."));}),process.exit(1)),!r.hasUpdate){j(e,V({status:"up_to_date",currentVersion:Mo,latestVersion:r.version}),()=>{console.log(J__default.default.green(`\u2713 You're already on the latest version (v${Mo})`));});return}if(t){j(e,V({status:"update_available",currentVersion:Mo,latestVersion:r.version,releaseDate:r.date}),()=>{console.log(J__default.default.yellow(`\u2B06 Update available: v${Mo} \u2192 v${r.version}`)),console.log(),console.log("To update, run:"),console.log(J__default.default.cyan(" viben update")),console.log(),console.log(J__default.default.gray(`Release date: ${new Date(r.date).toLocaleDateString()}`)),console.log(J__default.default.gray(`Changelog: https://github.com/${J1}/releases/tag/${r.tag}`));});return}e.quiet||(console.log(J__default.default.yellow(`\u2B06 Updating: v${Mo} \u2192 v${r.version}`)),console.log());let s=await Pct();s||(j(e,it("NO_PACKAGE_MANAGER","Could not detect package manager. Please update manually."),()=>{console.log(J__default.default.red("Error: Could not detect how viben was installed.")),console.log(),console.log("Please update manually using one of:"),console.log(J__default.default.cyan(" npm install -g viben")),console.log(J__default.default.cyan(" pnpm add -g viben")),console.log(J__default.default.cyan(" yarn global add viben")),console.log(J__default.default.cyan(" bun add -g viben"));}),process.exit(1)),e.quiet||(console.log(J__default.default.gray(` Detected package manager: ${s}`)),console.log()),await Act(e,s)?j(e,V({status:"updated",previousVersion:Mo,newVersion:r.version,packageManager:s}),()=>{console.log(),console.log(J__default.default.green(`\u2713 Successfully updated to v${r.version}`)),console.log(),console.log("What's new:"),console.log(J__default.default.gray(` https://github.com/${J1}/releases/tag/${r.tag}`));}):(j(e,it("UPDATE_FAILED","Failed to update viben"),()=>{console.log(),console.log(J__default.default.red("Error: Update failed.")),console.log(),console.log("Please try updating manually:"),console.log(J__default.default.cyan(` ${Hq(s).join(" ")}`)),console.log(),console.log(J__default.default.gray("If you encounter permission issues, try running with sudo:")),console.log(J__default.default.gray(` sudo ${Hq(s).join(" ")}`));}),process.exit(1));}async function Oct(e,t,r){let s=Re.resolve(t),i=[],n={force:r.force,skipExisting:r.skipExisting};e.quiet||(console.log(J__default.default.cyan("Updating Viben workspace...")),console.log(J__default.default.gray(` Target: ${s}`)),console.log()),r.ideaTypes&&(e.quiet||console.log(J__default.default.gray(" Updating idea-types templates...")),await Nze(s,n,i)),r.rewardTypes&&(e.quiet||console.log(J__default.default.gray(" Updating reward-types templates...")),await Lze(s,n,i)),j(e,V({path:s,files:i,count:i.length}),()=>{if(console.log(J__default.default.green("\u2713 Workspace updated successfully!")),console.log(),i.length>0){console.log(`Updated ${J__default.default.bold(i.length)} files:`);for(let a of i)console.log(J__default.default.gray(` ${a}`));}else console.log(J__default.default.gray("No files were updated (all files already exist)."));});}function Fct(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 Oct(s,t,r):await Cct(s,r.check??!1);}catch(i){Q(s,i);}});}var zh,Mo,J1,_b,$ct=O({"src/cli/commands/update.ts"(){yr(),Joe(),Ms(),zh=VY.promisify(child_process.exec),Mo="1.3.1",J1="LinXueyuanStdio/viben",_b="viben";}}),kve={};mt(kve,{registerQueueCommand:()=>Hct});function Eve(e){switch(e){case "pending":return J__default.default.yellow("pending");case "running":return J__default.default.blue("running");case "completed":return J__default.default.green("completed");case "failed":return J__default.default.red("failed");case "cancelled":return J__default.default.gray("cancelled");default:return J__default.default.gray(e)}}function r1(e){return new Date(e).toLocaleString()}function Wq(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 Ic(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}function Dct(e){let t=e.opts();return new Tve(t.gateway||Y1,t.timeout||X1)}async function Rct(e){let t=_2({include_items:true});if(!t.success){j(e,it("QUEUE_ERROR",t.error||"Failed to get queue status"),()=>{console.error(J__default.default.red(`Error: ${t.error}`));});return}j(e,V(t),()=>{if(console.log(J__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} ${Wq(s)}`);}}console.log(),console.log(`Storage: ${ml()}`);});}async function qct(e,t){let r;t.status?r=[t.status]:t.all||(r=["pending","running"]);let s=$m({status:r,limit:t.limit||50});if(!s.success){j(e,it("QUEUE_ERROR",s.error||"Failed to list items"),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{if(s.items.length===0){console.log(J__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,Eve(c),o,l,r1(a.created_at).split(" ")[1]]});ht(e,i,n),console.log(),console.log(`Showing ${s.items.length} of ${s.total} items`);});}async function Nct(e,t){let r=Cy({id:t});if(!r.success){j(e,it("NOT_FOUND",r.error||`Item not found: ${t}`),()=>{console.error(J__default.default.red(r.error||`Item not found: ${t}`));});return}let s=r.item,i=r.status;j(e,V({item:s,status:i}),()=>{if(console.log(J__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: ${Eve(i)}`),console.log(`Command: ${s.command}`),console.log(`CWD: ${s.cwd}`),console.log(`Created: ${r1(s.created_at)}`),"pid"in s){let n=s;if(console.log(),console.log("Execution:"),console.log(` PID: ${n.pid}`),console.log(` Started: ${r1(n.started_at)}`),console.log(` Log file: ${n.log_file}`),"completed_at"in s){let a=s;console.log(` Completed: ${r1(a.completed_at)}`),console.log(` Exit code: ${a.exit_code}`),console.log(` Duration: ${Wq(a.completed_at-n.started_at)}`);}else {let a=Date.now()-n.started_at;console.log(` Elapsed: ${Wq(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 Lct(e,t){let r=qL({command:t.command,cwd:t.cwd,metadata:t.metadata});if(!r.success){j(e,it("ENQUEUE_ERROR",r.error||"Failed to enqueue command"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(r),()=>{console.log(J__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 jct(e,t,r){let s=Pme({id:t,force:r.force});if(!s.success){j(e,it("CANCEL_ERROR",s.error||`Failed to cancel: ${t}`),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{console.log(J__default.default.green("Item cancelled successfully")),console.log(` ID: ${s.cancelled}`);});}async function Mct(e,t,r){let s=YL({id:t,reset_count:r.resetCount});if(!s.success){j(e,it("RETRY_ERROR",s.error||`Failed to retry: ${t}`),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{console.log(J__default.default.green("Item queued for retry")),console.log(` New ID: ${s.id}`),console.log(` Position: ${s.position}`);});}async function zct(e,t,r){let s=XL({id:t,tail:r.tail!==void 0,lines:r.tail});if(!s.success){j(e,it("LOGS_ERROR",s.error||`Failed to get logs: ${t}`),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}e.json?j(e,V(s),()=>{}):(s.content?console.log(s.content):console.log(J__default.default.gray("No log content available")),s.truncated&&(console.log(),console.log(J__default.default.yellow(`(Truncated - ${s.size} bytes total)`))));}async function Uct(e,t){if(t.reset){let r=L1({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){j(e,it("CONFIG_ERROR",r.error||"Failed to reset config"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(r),()=>{console.log(J__default.default.green("Queue configuration reset to defaults")),r.config&&Qe(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){j(e,it("VALIDATION_ERROR",`Invalid setting format: ${i}`),()=>{console.error(J__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=L1(r);if(!s.success){j(e,it("CONFIG_ERROR",s.error||"Failed to update config"),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{console.log(J__default.default.green("Queue configuration updated")),s.config&&Qe(e,s.config);});}else {let r=QL();if(!r.success){j(e,it("CONFIG_ERROR",r.error||"Failed to get config"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(r),()=>{console.log(J__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&&Qe(e,r.config),console.log(),console.log(`Config file: ${ml()}/config.json`);});}}async function Bct(e,t){let r=Gme({dry_run:t.dryRun});if(!r.success){j(e,it("CLEAN_ERROR",r.error||"Failed to clean items"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(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(J__default.default.green(`Cleaned ${r.cleaned} item(s)`)),console.log(` Removed from ${ml()}/`);});}async function Gct(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=_2();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 Hct(e){let t=e.command("queue").description("Manage command queue").option("--gateway <url>","Gateway URL (for watch/stream)",Y1).option("--timeout <ms>","Request timeout in milliseconds (default: 30000)",String(X1));t.command("status").description("Show queue status").action(async()=>{let r=Ic(e);try{await Rct(r);}catch(s){Q(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=Ic(e);try{await qct(s,r);}catch(i){Q(s,i);}}),t.command("inspect").argument("<id>","Item ID").description("Show item details").action(async r=>{let s=Ic(e);try{await Nct(s,r);}catch(i){Q(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=Ic(e);try{let i;if(r.metadata)try{i=JSON.parse(r.metadata);}catch{j(s,it("VALIDATION_ERROR","Invalid JSON in metadata"),()=>{console.error(J__default.default.red("Invalid JSON in metadata"));});return}await Lct(s,{command:r.command,cwd:r.cwd,metadata:i});}catch(i){Q(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=Ic(e);try{await jct(i,r,s);}catch(n){Q(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=Ic(e);try{await Mct(i,r,s);}catch(n){Q(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=Ic(e);try{await zct(i,r,s);}catch(n){Q(i,n);}}),t.command("watch").description("Watch queue events").action(async()=>{let r=Ic(e),s=Dct(e);try{await Gct(r,s);}catch(i){Q(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=Ic(e);try{await Uct(s,r);}catch(i){Q(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=Ic(e);try{await Bct(s,r);}catch(i){Q(s,i);}});}var Y1,X1,Tve,Wct=O({"src/cli/commands/queue.ts"(){yr(),ZL(),Ki(),Y1="http://127.0.0.1:18790",X1=3e4,Tve=class{constructor(e=Y1,t=X1){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}}};}}),xve={};mt(xve,{registerSwarmCommand:()=>sut});function Dg(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Ive(e,t){let r=e.agents.find(s=>s.id===t);return r||e.agents.find(s=>s.task_dir.includes(t))}function Qct(e,t){let r=Re.join(e,".viben","tasks");if(!De.existsSync(r))return null;let s=Re.basename(t);if(De.existsSync(Re.join(r,s)))return Re.join(".viben","tasks",s);try{let i=De.readdirSync(r);for(let n of i)if(n.includes(s)||s.includes(n))return Re.join(".viben","tasks",n)}catch{}return null}async function Zct(e,t){let r=Nw(t),s=Wo(t);if(e.json){j(e,V({worktrees:r,agents:s.agents}));return}if(console.log(J__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(J__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=Sy(i.pid)?J__default.default.green("\u25CF"):J__default.default.red("\u25CB");console.log(` ${n} ${i.id} (PID: ${i.pid})`),console.log(J__default.default.dim(` Worktree: ${i.worktree_path}`)),console.log(J__default.default.dim(` Started: ${i.started_at}`)),console.log();}}async function eut(e,t,r,s){let i=Qct(t,r);if(!i){j(e,it("TASK_NOT_FOUND",`Task not found: ${r}`),()=>{console.error(J__default.default.red(`Error: Task not found: ${r}`)),console.log(J__default.default.gray("Use 'viben task list' to see available tasks"));}),process.exit(1);return}if(s.resume){let c=Wo(t),o=Ive(c,r);if(!o){j(e,it("AGENT_NOT_FOUND",`No agent found for task: ${r}`),()=>{console.error(J__default.default.red(`Error: No agent found for task: ${r}`)),console.log(J__default.default.gray("The agent may not have been started yet"));}),process.exit(1);return}let l=s.session;if(!l){let y=Re.isAbsolute(o.task_dir)?o.task_dir:Re.join(t,o.task_dir);l=TI(y)||void 0;}if(!l){j(e,it("NO_SESSION","No session ID found for resume"),()=>{console.error(J__default.default.red("Error: No session ID found for resume")),console.log(J__default.default.gray("No session_id in task.json and no --session provided"));}),process.exit(1);return}let u=o.platform||"claude",h=ss(u).buildResumeCommand(l);e.quiet||(console.log(J__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&&Pve[s.executor.toUpperCase()]||"claude";e.quiet||(console.log(J__default.default.blue("=== Multi-Agent Pipeline: Start ===")),console.log(`[INFO] Task: ${i}`),console.log(`[INFO] Platform: ${n}`));let a=await T8e(t,i,{platform:n,detach:s.detach??true,skipPermissions:true,verbose:e.verbose,jsonOutput:true});if(e.json)a.success?j(e,V(a)):j(e,it("START_FAILED",a.error||"Unknown error"));else if(a.success){if(console.log(),console.log(J__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(J__default.default.yellow(`To monitor: tail -f ${a.log_file}`)),console.log(J__default.default.yellow(`To stop: kill ${a.pid}`)),a.session_id){let o=ss(n).getResumeCommandStr(a.session_id,a.worktreePath);console.log(J__default.default.yellow(`To resume: ${o}`));}}else console.error(J__default.default.red(`Error: ${a.error}`)),process.exit(1);}async function tut(e,t,r,s){let i=Wo(t);if(s.all){let a=i.agents.filter(l=>Sy(l.pid));if(a.length===0){j(e,V({stopped:[]}),()=>{console.log(J__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(J__default.default.green(`Stopped: ${l.id} (PID: ${l.pid})`));}catch{o.push(l.id),e.quiet||console.log(J__default.default.red(`Failed to stop: ${l.id} (PID: ${l.pid})`));}j(e,V({stopped:c,failed:o}));return}if(!r){j(e,it("MISSING_TASK","Task name required"),()=>{console.error(J__default.default.red("Error: Task name is required")),console.log(J__default.default.gray("Usage: viben swarm stop <task>")),console.log(J__default.default.gray(" viben swarm stop --all"));}),process.exit(1);return}let n=Ive(i,r);if(!n){j(e,it("AGENT_NOT_FOUND",`Agent not found: ${r}`),()=>{console.error(J__default.default.red(`Error: Agent not found: ${r}`));}),process.exit(1);return}if(!Sy(n.pid)){j(e,V({agent:n,status:"already_stopped"}),()=>{console.log(J__default.default.yellow(`Agent ${n.id} is not running (PID: ${n.pid})`));});return}try{process.kill(n.pid,s.force?"SIGKILL":"SIGTERM"),j(e,V({agent:n,status:"stopped"}),()=>{console.log(J__default.default.green(`Stopped agent: ${n.id} (PID: ${n.pid})`));});}catch(a){j(e,it("STOP_FAILED",`Failed to stop agent: ${a}`),()=>{console.error(J__default.default.red(`Error: Failed to stop agent ${n.id}: ${a}`));}),process.exit(1);}}async function rut(e,t,r,s){if(s.watch&&r){let u=NF(r,t);if(!u){console.error(J__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=Re.join(u.worktree_path,"agent.log.jsonl");if(!De.existsSync(d)){console.error(J__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(J__default.default.blue(`Watching: ${d}`)),console.log(J__default.default.dim("Press Ctrl+C to stop")),console.log(),N8e(d);return}if(s.log&&r){let u=NF(r,t);if(!u){console.error(J__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=Re.join(u.worktree_path,"agent.log.jsonl");if(!De.existsSync(d)){console.error(J__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(J__default.default.blue(`=== Recent Log: ${r} ===`)),console.log(J__default.default.dim(`Platform: ${u.platform}`)),console.log();let h=R8e(d,50,u.platform);for(let v of h)console.log(v);return}if((s.detail||r)&&r){let u=NF(r,t);if(!u){console.error(J__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}if(e.json){j(e,V(u));return}if(console.log(J__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: ${J__default.default.green("Running")}`);else if(console.log(` Status: ${J__default.default.red("Stopped")}`),u.session_id){let h=ss(u.platform).getResumeCommandStr(u.session_id,u.worktree_path);console.log(),console.log(J__default.default.yellow(` Resume: ${h}`));}if(De.existsSync(u.worktree_path)){console.log(),console.log(J__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(`
|
|
1116
|
+
`),console.log(` \u76EE\u5F55: ${J__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){Q(r,i);}}),t.command("clean [days]").description("Clean old telemetry files. Default: 7 days retention").action(async function(r){let s=cx(this),i=Zh(),n=parseInt(r||"7",10);(isNaN(n)||n<1)&&(console.log(J__default.default.red("Invalid retention days. Must be a positive number.")),process.exit(1));try{let a=Dd(i),c=0;for(let d of a)c+=(await Nc(i,d)).length;Dse(i,n);let o=Dd(i),l=0;for(let d of o)l+=(await Nc(i,d)).length;let u={retentionDays:n,datesRemoved:a.length-o.length,tracesRemoved:c-l};j(s,V(u),()=>{console.log(J__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){Q(s,a);}});}var wct=O({"src/cli/commands/telemetry.ts"(){Ke(),yr();}}),Sve={};mt(Sve,{registerUpdateCommand:()=>Fct});function xct(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 Ict(){try{let e=await Ot(`https://api.github.com/repos/${J1}/releases`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":`viben/${Mo}`}});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:xct(s,Mo)>0,currentVersion:Mo}}catch{return null}}async function Pct(){try{let{stdout:t}=await zh("npm config get prefix"),{stdout:r}=await zh("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 zh(`which ${t}`),t==="pnpm"){let{stdout:r}=await zh("pnpm list -g viben").catch(()=>({stdout:""}));if(r.includes("viben"))return "pnpm"}else if(t==="yarn"){let{stdout:r}=await zh("yarn global list").catch(()=>({stdout:""}));if(r.includes("viben"))return "yarn"}else if(t==="bun"){let{stdout:r}=await zh("bun pm ls -g").catch(()=>({stdout:""}));if(r.includes("viben"))return "bun"}}catch{}return "npm"}function Hq(e){switch(e){case "pnpm":return ["pnpm","add","-g",_b];case "yarn":return ["yarn","global","add",_b];case "bun":return ["bun","add","-g",_b];default:return ["npm","install","-g","--force",_b]}}async function Act(e,t){let[r,...s]=Hq(t);return new Promise(i=>{e.quiet||(console.log(J__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 Cct(e,t){e.quiet||(console.log(J__default.default.cyan("Checking for updates...")),console.log(J__default.default.gray(` Current version: v${Mo}`)),console.log());let r=await Ict();if(r||(j(e,it("FETCH_FAILED","Failed to fetch release information from GitHub"),()=>{console.log(J__default.default.red("Error: Failed to check for updates.")),console.log(J__default.default.gray(" Please check your internet connection and try again."));}),process.exit(1)),!r.hasUpdate){j(e,V({status:"up_to_date",currentVersion:Mo,latestVersion:r.version}),()=>{console.log(J__default.default.green(`\u2713 You're already on the latest version (v${Mo})`));});return}if(t){j(e,V({status:"update_available",currentVersion:Mo,latestVersion:r.version,releaseDate:r.date}),()=>{console.log(J__default.default.yellow(`\u2B06 Update available: v${Mo} \u2192 v${r.version}`)),console.log(),console.log("To update, run:"),console.log(J__default.default.cyan(" viben update")),console.log(),console.log(J__default.default.gray(`Release date: ${new Date(r.date).toLocaleDateString()}`)),console.log(J__default.default.gray(`Changelog: https://github.com/${J1}/releases/tag/${r.tag}`));});return}e.quiet||(console.log(J__default.default.yellow(`\u2B06 Updating: v${Mo} \u2192 v${r.version}`)),console.log());let s=await Pct();s||(j(e,it("NO_PACKAGE_MANAGER","Could not detect package manager. Please update manually."),()=>{console.log(J__default.default.red("Error: Could not detect how viben was installed.")),console.log(),console.log("Please update manually using one of:"),console.log(J__default.default.cyan(" npm install -g viben")),console.log(J__default.default.cyan(" pnpm add -g viben")),console.log(J__default.default.cyan(" yarn global add viben")),console.log(J__default.default.cyan(" bun add -g viben"));}),process.exit(1)),e.quiet||(console.log(J__default.default.gray(` Detected package manager: ${s}`)),console.log()),await Act(e,s)?j(e,V({status:"updated",previousVersion:Mo,newVersion:r.version,packageManager:s}),()=>{console.log(),console.log(J__default.default.green(`\u2713 Successfully updated to v${r.version}`)),console.log(),console.log("What's new:"),console.log(J__default.default.gray(` https://github.com/${J1}/releases/tag/${r.tag}`));}):(j(e,it("UPDATE_FAILED","Failed to update viben"),()=>{console.log(),console.log(J__default.default.red("Error: Update failed.")),console.log(),console.log("Please try updating manually:"),console.log(J__default.default.cyan(` ${Hq(s).join(" ")}`)),console.log(),console.log(J__default.default.gray("If you encounter permission issues, try running with sudo:")),console.log(J__default.default.gray(` sudo ${Hq(s).join(" ")}`));}),process.exit(1));}async function Oct(e,t,r){let s=Re.resolve(t),i=[],n={force:r.force,skipExisting:r.skipExisting};e.quiet||(console.log(J__default.default.cyan("Updating Viben workspace...")),console.log(J__default.default.gray(` Target: ${s}`)),console.log()),r.ideaTypes&&(e.quiet||console.log(J__default.default.gray(" Updating idea-types templates...")),await Nze(s,n,i)),r.rewardTypes&&(e.quiet||console.log(J__default.default.gray(" Updating reward-types templates...")),await Lze(s,n,i)),j(e,V({path:s,files:i,count:i.length}),()=>{if(console.log(J__default.default.green("\u2713 Workspace updated successfully!")),console.log(),i.length>0){console.log(`Updated ${J__default.default.bold(i.length)} files:`);for(let a of i)console.log(J__default.default.gray(` ${a}`));}else console.log(J__default.default.gray("No files were updated (all files already exist)."));});}function Fct(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 Oct(s,t,r):await Cct(s,r.check??!1);}catch(i){Q(s,i);}});}var zh,Mo,J1,_b,$ct=O({"src/cli/commands/update.ts"(){yr(),Joe(),Ms(),zh=VY.promisify(child_process.exec),Mo="1.3.2",J1="LinXueyuanStdio/viben",_b="viben";}}),kve={};mt(kve,{registerQueueCommand:()=>Hct});function Eve(e){switch(e){case "pending":return J__default.default.yellow("pending");case "running":return J__default.default.blue("running");case "completed":return J__default.default.green("completed");case "failed":return J__default.default.red("failed");case "cancelled":return J__default.default.gray("cancelled");default:return J__default.default.gray(e)}}function r1(e){return new Date(e).toLocaleString()}function Wq(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 Ic(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}function Dct(e){let t=e.opts();return new Tve(t.gateway||Y1,t.timeout||X1)}async function Rct(e){let t=_2({include_items:true});if(!t.success){j(e,it("QUEUE_ERROR",t.error||"Failed to get queue status"),()=>{console.error(J__default.default.red(`Error: ${t.error}`));});return}j(e,V(t),()=>{if(console.log(J__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} ${Wq(s)}`);}}console.log(),console.log(`Storage: ${ml()}`);});}async function qct(e,t){let r;t.status?r=[t.status]:t.all||(r=["pending","running"]);let s=$m({status:r,limit:t.limit||50});if(!s.success){j(e,it("QUEUE_ERROR",s.error||"Failed to list items"),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{if(s.items.length===0){console.log(J__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,Eve(c),o,l,r1(a.created_at).split(" ")[1]]});ht(e,i,n),console.log(),console.log(`Showing ${s.items.length} of ${s.total} items`);});}async function Nct(e,t){let r=Cy({id:t});if(!r.success){j(e,it("NOT_FOUND",r.error||`Item not found: ${t}`),()=>{console.error(J__default.default.red(r.error||`Item not found: ${t}`));});return}let s=r.item,i=r.status;j(e,V({item:s,status:i}),()=>{if(console.log(J__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: ${Eve(i)}`),console.log(`Command: ${s.command}`),console.log(`CWD: ${s.cwd}`),console.log(`Created: ${r1(s.created_at)}`),"pid"in s){let n=s;if(console.log(),console.log("Execution:"),console.log(` PID: ${n.pid}`),console.log(` Started: ${r1(n.started_at)}`),console.log(` Log file: ${n.log_file}`),"completed_at"in s){let a=s;console.log(` Completed: ${r1(a.completed_at)}`),console.log(` Exit code: ${a.exit_code}`),console.log(` Duration: ${Wq(a.completed_at-n.started_at)}`);}else {let a=Date.now()-n.started_at;console.log(` Elapsed: ${Wq(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 Lct(e,t){let r=qL({command:t.command,cwd:t.cwd,metadata:t.metadata});if(!r.success){j(e,it("ENQUEUE_ERROR",r.error||"Failed to enqueue command"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(r),()=>{console.log(J__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 jct(e,t,r){let s=Pme({id:t,force:r.force});if(!s.success){j(e,it("CANCEL_ERROR",s.error||`Failed to cancel: ${t}`),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{console.log(J__default.default.green("Item cancelled successfully")),console.log(` ID: ${s.cancelled}`);});}async function Mct(e,t,r){let s=YL({id:t,reset_count:r.resetCount});if(!s.success){j(e,it("RETRY_ERROR",s.error||`Failed to retry: ${t}`),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{console.log(J__default.default.green("Item queued for retry")),console.log(` New ID: ${s.id}`),console.log(` Position: ${s.position}`);});}async function zct(e,t,r){let s=XL({id:t,tail:r.tail!==void 0,lines:r.tail});if(!s.success){j(e,it("LOGS_ERROR",s.error||`Failed to get logs: ${t}`),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}e.json?j(e,V(s),()=>{}):(s.content?console.log(s.content):console.log(J__default.default.gray("No log content available")),s.truncated&&(console.log(),console.log(J__default.default.yellow(`(Truncated - ${s.size} bytes total)`))));}async function Uct(e,t){if(t.reset){let r=L1({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){j(e,it("CONFIG_ERROR",r.error||"Failed to reset config"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(r),()=>{console.log(J__default.default.green("Queue configuration reset to defaults")),r.config&&Qe(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){j(e,it("VALIDATION_ERROR",`Invalid setting format: ${i}`),()=>{console.error(J__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=L1(r);if(!s.success){j(e,it("CONFIG_ERROR",s.error||"Failed to update config"),()=>{console.error(J__default.default.red(`Error: ${s.error}`));});return}j(e,V(s),()=>{console.log(J__default.default.green("Queue configuration updated")),s.config&&Qe(e,s.config);});}else {let r=QL();if(!r.success){j(e,it("CONFIG_ERROR",r.error||"Failed to get config"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(r),()=>{console.log(J__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&&Qe(e,r.config),console.log(),console.log(`Config file: ${ml()}/config.json`);});}}async function Bct(e,t){let r=Gme({dry_run:t.dryRun});if(!r.success){j(e,it("CLEAN_ERROR",r.error||"Failed to clean items"),()=>{console.error(J__default.default.red(`Error: ${r.error}`));});return}j(e,V(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(J__default.default.green(`Cleaned ${r.cleaned} item(s)`)),console.log(` Removed from ${ml()}/`);});}async function Gct(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=_2();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 Hct(e){let t=e.command("queue").description("Manage command queue").option("--gateway <url>","Gateway URL (for watch/stream)",Y1).option("--timeout <ms>","Request timeout in milliseconds (default: 30000)",String(X1));t.command("status").description("Show queue status").action(async()=>{let r=Ic(e);try{await Rct(r);}catch(s){Q(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=Ic(e);try{await qct(s,r);}catch(i){Q(s,i);}}),t.command("inspect").argument("<id>","Item ID").description("Show item details").action(async r=>{let s=Ic(e);try{await Nct(s,r);}catch(i){Q(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=Ic(e);try{let i;if(r.metadata)try{i=JSON.parse(r.metadata);}catch{j(s,it("VALIDATION_ERROR","Invalid JSON in metadata"),()=>{console.error(J__default.default.red("Invalid JSON in metadata"));});return}await Lct(s,{command:r.command,cwd:r.cwd,metadata:i});}catch(i){Q(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=Ic(e);try{await jct(i,r,s);}catch(n){Q(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=Ic(e);try{await Mct(i,r,s);}catch(n){Q(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=Ic(e);try{await zct(i,r,s);}catch(n){Q(i,n);}}),t.command("watch").description("Watch queue events").action(async()=>{let r=Ic(e),s=Dct(e);try{await Gct(r,s);}catch(i){Q(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=Ic(e);try{await Uct(s,r);}catch(i){Q(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=Ic(e);try{await Bct(s,r);}catch(i){Q(s,i);}});}var Y1,X1,Tve,Wct=O({"src/cli/commands/queue.ts"(){yr(),ZL(),Ki(),Y1="http://127.0.0.1:18790",X1=3e4,Tve=class{constructor(e=Y1,t=X1){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}}};}}),xve={};mt(xve,{registerSwarmCommand:()=>sut});function Dg(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function Ive(e,t){let r=e.agents.find(s=>s.id===t);return r||e.agents.find(s=>s.task_dir.includes(t))}function Qct(e,t){let r=Re.join(e,".viben","tasks");if(!De.existsSync(r))return null;let s=Re.basename(t);if(De.existsSync(Re.join(r,s)))return Re.join(".viben","tasks",s);try{let i=De.readdirSync(r);for(let n of i)if(n.includes(s)||s.includes(n))return Re.join(".viben","tasks",n)}catch{}return null}async function Zct(e,t){let r=Nw(t),s=Wo(t);if(e.json){j(e,V({worktrees:r,agents:s.agents}));return}if(console.log(J__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(J__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=Sy(i.pid)?J__default.default.green("\u25CF"):J__default.default.red("\u25CB");console.log(` ${n} ${i.id} (PID: ${i.pid})`),console.log(J__default.default.dim(` Worktree: ${i.worktree_path}`)),console.log(J__default.default.dim(` Started: ${i.started_at}`)),console.log();}}async function eut(e,t,r,s){let i=Qct(t,r);if(!i){j(e,it("TASK_NOT_FOUND",`Task not found: ${r}`),()=>{console.error(J__default.default.red(`Error: Task not found: ${r}`)),console.log(J__default.default.gray("Use 'viben task list' to see available tasks"));}),process.exit(1);return}if(s.resume){let c=Wo(t),o=Ive(c,r);if(!o){j(e,it("AGENT_NOT_FOUND",`No agent found for task: ${r}`),()=>{console.error(J__default.default.red(`Error: No agent found for task: ${r}`)),console.log(J__default.default.gray("The agent may not have been started yet"));}),process.exit(1);return}let l=s.session;if(!l){let y=Re.isAbsolute(o.task_dir)?o.task_dir:Re.join(t,o.task_dir);l=TI(y)||void 0;}if(!l){j(e,it("NO_SESSION","No session ID found for resume"),()=>{console.error(J__default.default.red("Error: No session ID found for resume")),console.log(J__default.default.gray("No session_id in task.json and no --session provided"));}),process.exit(1);return}let u=o.platform||"claude",h=ss(u).buildResumeCommand(l);e.quiet||(console.log(J__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&&Pve[s.executor.toUpperCase()]||"claude";e.quiet||(console.log(J__default.default.blue("=== Multi-Agent Pipeline: Start ===")),console.log(`[INFO] Task: ${i}`),console.log(`[INFO] Platform: ${n}`));let a=await T8e(t,i,{platform:n,detach:s.detach??true,skipPermissions:true,verbose:e.verbose,jsonOutput:true});if(e.json)a.success?j(e,V(a)):j(e,it("START_FAILED",a.error||"Unknown error"));else if(a.success){if(console.log(),console.log(J__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(J__default.default.yellow(`To monitor: tail -f ${a.log_file}`)),console.log(J__default.default.yellow(`To stop: kill ${a.pid}`)),a.session_id){let o=ss(n).getResumeCommandStr(a.session_id,a.worktreePath);console.log(J__default.default.yellow(`To resume: ${o}`));}}else console.error(J__default.default.red(`Error: ${a.error}`)),process.exit(1);}async function tut(e,t,r,s){let i=Wo(t);if(s.all){let a=i.agents.filter(l=>Sy(l.pid));if(a.length===0){j(e,V({stopped:[]}),()=>{console.log(J__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(J__default.default.green(`Stopped: ${l.id} (PID: ${l.pid})`));}catch{o.push(l.id),e.quiet||console.log(J__default.default.red(`Failed to stop: ${l.id} (PID: ${l.pid})`));}j(e,V({stopped:c,failed:o}));return}if(!r){j(e,it("MISSING_TASK","Task name required"),()=>{console.error(J__default.default.red("Error: Task name is required")),console.log(J__default.default.gray("Usage: viben swarm stop <task>")),console.log(J__default.default.gray(" viben swarm stop --all"));}),process.exit(1);return}let n=Ive(i,r);if(!n){j(e,it("AGENT_NOT_FOUND",`Agent not found: ${r}`),()=>{console.error(J__default.default.red(`Error: Agent not found: ${r}`));}),process.exit(1);return}if(!Sy(n.pid)){j(e,V({agent:n,status:"already_stopped"}),()=>{console.log(J__default.default.yellow(`Agent ${n.id} is not running (PID: ${n.pid})`));});return}try{process.kill(n.pid,s.force?"SIGKILL":"SIGTERM"),j(e,V({agent:n,status:"stopped"}),()=>{console.log(J__default.default.green(`Stopped agent: ${n.id} (PID: ${n.pid})`));});}catch(a){j(e,it("STOP_FAILED",`Failed to stop agent: ${a}`),()=>{console.error(J__default.default.red(`Error: Failed to stop agent ${n.id}: ${a}`));}),process.exit(1);}}async function rut(e,t,r,s){if(s.watch&&r){let u=NF(r,t);if(!u){console.error(J__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=Re.join(u.worktree_path,"agent.log.jsonl");if(!De.existsSync(d)){console.error(J__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(J__default.default.blue(`Watching: ${d}`)),console.log(J__default.default.dim("Press Ctrl+C to stop")),console.log(),N8e(d);return}if(s.log&&r){let u=NF(r,t);if(!u){console.error(J__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}let d=Re.join(u.worktree_path,"agent.log.jsonl");if(!De.existsSync(d)){console.error(J__default.default.red(`Log file not found: ${d}`)),process.exit(1);return}console.log(J__default.default.blue(`=== Recent Log: ${r} ===`)),console.log(J__default.default.dim(`Platform: ${u.platform}`)),console.log();let h=R8e(d,50,u.platform);for(let v of h)console.log(v);return}if((s.detail||r)&&r){let u=NF(r,t);if(!u){console.error(J__default.default.red(`Agent not found: ${r}`)),process.exit(1);return}if(e.json){j(e,V(u));return}if(console.log(J__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: ${J__default.default.green("Running")}`);else if(console.log(` Status: ${J__default.default.red("Stopped")}`),u.session_id){let h=ss(u.platform).getResumeCommandStr(u.session_id,u.worktree_path);console.log(),console.log(J__default.default.yellow(` Resume: ${h}`));}if(De.existsSync(u.worktree_path)){console.log(),console.log(J__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
1117
|
`);for(let v of h.slice(0,10))console.log(` ${v}`);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=q8e(t),n=i;if(s.running?n=i.filter(u=>u.running):s.stopped&&(n=i.filter(u=>!u.running)),e.json){j(e,V({agents:n}));return}let a=i.filter(u=>u.running).length,c=i.length;console.log(J__default.default.blue("=== Swarm Status ===")),console.log(`Agents: ${J__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(J__default.default.cyan("Running:"));for(let u of o)console.log(` ${J__default.default.green("\u25B6")} ${J__default.default.cyan(u.id)} ${J__default.default.green("[running]")}`),u.phase&&console.log(` Phase: ${u.phase}`),console.log(` Elapsed: ${u.elapsed}`),u.branch&&console.log(` Branch: ${J__default.default.dim(u.branch)}`),console.log(` Modified: ${u.modifiedFiles} file(s)`),u.last_tool&&console.log(` Activity: ${J__default.default.yellow(u.last_tool)}`),console.log(` PID: ${J__default.default.dim(u.pid.toString())}`),console.log();}if(l.length>0){console.log(J__default.default.red("Stopped:"));for(let u of l){if(console.log(` ${J__default.default.red("\u25CB")} ${u.id} ${J__default.default.red("[stopped]")}`),u.last_message&&console.log(` ${J__default.default.dim(`"${u.last_message}"`)}`),u.session_id){let h=ss(u.platform).getResumeCommandStr(u.session_id,u.worktree_path);console.log(` ${J__default.default.yellow(h)}`);}console.log();}}}async function aut(e,t){let r=i4(t),s=Wo(t);if(e.json){j(e,V({path:r,...s}));return}console.log(J__default.default.blue("=== Agent Registry ===")),console.log(),console.log(`File: ${r}`),console.log(),console.log(JSON.stringify(s,null,2));}function sut(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=Dg(e),s=Rs();if(!s){Q(r,new Error("Not in a Viben workspace"));return}try{await Zct(r,s);}catch(i){Q(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=Dg(e),n=Rs();if(console.log(J__default.default.yellow("\u26A0\uFE0F DEPRECATED: 'viben swarm start' is deprecated.")),console.log(J__default.default.yellow(" Please use 'viben task work-phase <task>' instead.")),console.log(J__default.default.yellow(" This command will be removed in a future version.")),console.log(),!n){Q(i,new Error("Not in a Viben workspace"));return}try{await eut(i,n,r,s);}catch(a){Q(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=Dg(e),n=Rs();if(!n){Q(i,new Error("Not in a Viben workspace"));return}try{await tut(i,n,r,s);}catch(a){Q(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=Dg(e),n=Rs();if(!n){Q(i,new Error("Not in a Viben workspace"));return}try{await rut(i,n,r,s);}catch(a){Q(i,a);}}),t.command("registry").description("Show agent registry").action(async()=>{let r=Dg(e),s=Rs();if(!s){Q(r,new Error("Not in a Viben workspace"));return}try{await aut(r,s);}catch(i){Q(r,i);}}),t.command("cleanup-registry").description("Remove dead agents from registry").action(async()=>{let r=Dg(e),s=Rs();if(!s){Q(r,new Error("Not in a Viben workspace"));return}try{let i=koe(s);j(r,V({removedCount:i.removedCount,removedIds:i.removedIds}),()=>{if(i.removedCount===0)console.log(J__default.default.gray("No dead agents to clean up"));else {console.log(J__default.default.green(`Removed ${i.removedCount} dead agent(s) from registry:`));for(let n of i.removedIds)console.log(J__default.default.gray(` - ${n}`));}});}catch(i){Q(r,i);}});}var Pve,iut=O({"src/cli/commands/swarm.ts"(){yr(),II(),Gt(),Pve={CLAUDE_CODE:"claude",CURSOR:"cursor",GEMINI:"gemini",OPENCODE:"opencode",IFLOW:"iflow",CODEX:"codex",KILO:"kilo",KIRO:"kiro",ANTIGRAVITY:"antigravity"};}}),Ave={};mt(Ave,{registerTaskCommand:()=>dut});async function uut(e,t){let r=Nw(t),s=Wo(t);if(e.json){j(e,V({worktrees:r,agents:s.agents}));return}if(console.log(J__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(J__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=Sy(i.pid)?J__default.default.green("\u25CF"):J__default.default.red("\u25CB");console.log(` ${n} ${i.id} (PID: ${i.pid})`),console.log(J__default.default.dim(` Worktree: ${i.worktree_path}`)),console.log(J__default.default.dim(` Started: ${i.started_at}`)),console.log();}}async function lut(e,t,r,s){if(s.list){await uut(e,t);return}if(s.merged){e.quiet||(console.log(J__default.default.blue("=== Cleaning Merged Worktrees ===")),console.log());let n=await G8e(t,{keepBranch:s.keepBranch,skipConfirm:s.yes});if(e.json){j(e,V({results:n}));return}if(n.length===0)console.log("No merged worktrees found");else for(let a of n)a.success?console.log(J__default.default.green(`Cleaned: ${a.branch}`)):console.log(J__default.default.red(`Failed: ${a.branch} - ${a.error}`));return}if(s.all){e.quiet||(console.log(J__default.default.blue("=== Cleaning All Worktrees ===")),console.log(J__default.default.red("WARNING: This will remove ALL worktrees!")),console.log());let n=await H8e(t,{keepBranch:s.keepBranch,skipConfirm:s.yes});if(e.json){j(e,V({results:n}));return}if(n.length===0)console.log("No worktrees to remove");else for(let a of n)a.success?console.log(J__default.default.green(`Cleaned: ${a.branch}`)):console.log(J__default.default.red(`Failed: ${a.branch} - ${a.error}`));return}if(!r){j(e,it("MISSING_ARG","Branch name or --merged/--all required"),()=>{console.error(J__default.default.red("Error: Branch name or --merged/--all required")),console.log(),console.log("Usage:"),console.log(J__default.default.gray(" viben task cleanup <branch> Remove specific worktree")),console.log(J__default.default.gray(" viben task cleanup --merged Remove merged worktrees")),console.log(J__default.default.gray(" viben task cleanup --all Remove all worktrees")),console.log(J__default.default.gray(" viben task cleanup --list List all worktrees"));}),process.exit(1);return}e.quiet||(console.log(J__default.default.blue(`=== Cleaning Worktree: ${r} ===`)),console.log());let i=await xI(t,r,{keepBranch:s.keepBranch,skipConfirm:s.yes});if(e.json){i.success?j(e,V(i)):j(e,it("CLEANUP_FAILED",i.error||"Unknown error"));return}i.success?(console.log(J__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(J__default.default.red(`Error: ${i.error}`)),process.exit(1));}function yt(e){let t=e.opts();return {json:t.json||false,verbose:t.verbose||false,quiet:t.quiet||false}}function vt(e){let t=Rs(e);if(!t)throw ne.operationFailed("Task command",'Not a Viben workspace (.viben not found). Run "viben init" first.');return t}function dut(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=yt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=vt(a);if(s){let u=el(c,s);if(!u.success)throw ne.notFound("Task",s);let d=u.task,h=u.files;j(n,V({task:d,task_dir:u.task_dir,dir_name:u.dir_name,files:h,runtime:u.runtime}),()=>{if(console.log(J__default.default.bold.cyan(`=== ${d.title} ===`)),console.log(),Qe(n,{Status:$h(d.status),Priority:cD(d.priority),Assignee:d.assignee||"-",Branch:d.branch||"-",Phase:`${d.current_phase||0}`,"PR URL":d.pr_url||J__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(J__default.default.gray(`Files: ${y.join(", ")}`));}d.description&&(console.log(),console.log(J__default.default.gray(d.description))),console.log(),console.log(J__default.default.dim(`Use 'viben task view ${u.dir_name}' for full details`));});return}let o=hhe(c,{mine:i.mine,status:i.status});if(!o.success)throw ne.operationFailed("List tasks",o.error);let{tasks:l}=o;j(n,V({tasks:l}),()=>{if(i.mine){let u=Bi(c);console.log(J__default.default.blue(`My tasks (assignee: ${u}):`));}else console.log(J__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}/ (${$h(u.status)})`):console.log(` - ${u.dir}/ (${$h(u.status)}) [${J__default.default.cyan(u.assignee)}]`);console.log(),console.log(`Total: ${l.length} task(s)`);});}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=h2(c,s,i);if(!o.success)throw ne.operationFailed("Create task",o.error);let{dir_name:l,status:u,context_initialized:d}=o,h=`${Jt}/${Gi}/${l}`;if(i.start&&l){let v=await F1(c,l,{agent:i.agent,executor:i.executor,model:i.model,priority:i.priority,skipQueue:!1});if(!v.success){j(n,it("ENQUEUE_FAILED",v.error||"Failed to enqueue task"),()=>{console.log(J__default.default.yellow(`Created task: ${l}`)),console.log(J__default.default.red(`Failed to enqueue: ${v.error}`)),console.log(J__default.default.gray(`Run manually: viben task enqueue ${l}`));});return}let y=v.additionalData?.queue_id;j(n,V({task_dir:h,status:"queue",context_initialized:d,queueId:y}),()=>{console.log(J__default.default.green(`Created and enqueued: ${l}`)),console.log(J__default.default.gray("Status: backlog -> queue")),y&&console.log(J__default.default.gray(`Queue ID: ${y}`)),i.worktree&&console.log(J__default.default.gray("Worktree: enabled")),d&&console.log(J__default.default.gray("Context: initialized (empty)"));});}else j(n,V({task_dir:h,context_initialized:d}),()=>{console.log(J__default.default.green(`Created task: ${l}`)),console.log(),i.branch&&(console.log(J__default.default.blue("Configured:")),console.log(` Branch: ${i.branch}`),console.log()),console.log(J__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){Q(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=yt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=vt(a),o=el(c,s);if(!o.success)throw ne.notFound("Task",s);let l=o.task,u=o.files,d=o.worktree;j(n,V({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(J__default.default.bold.cyan(`=== Task: ${l.title} ===`)),console.log(),console.log(J__default.default.bold("Basic Info")),Qe(n,{ID:l.id||"-",Directory:o.dir_name||"-",Status:$h(l.status),Priority:cD(l.priority)}),console.log(),console.log(J__default.default.bold("People")),Qe(n,{Creator:l.creator||"-",Assignee:l.assignee||"-"}),console.log(),console.log(J__default.default.bold("Git")),Qe(n,{Branch:l.branch||"-","Base Branch":l.base_branch||"-","PR URL":l.pr_url||J__default.default.gray("(none)")}),console.log(),console.log(J__default.default.bold("Worktree")),d?.enabled||d?.path){let E=d.path?d.exists?d.isDirty?J__default.default.yellow("active (dirty)"):J__default.default.green("active (clean)"):J__default.default.red("missing"):J__default.default.gray("(not created)");Qe(n,{Mode:d.enabled?J__default.default.green("enabled"):J__default.default.gray("disabled"),Status:E}),d.path&&console.log(` Path: ${J__default.default.gray(d.path)}`),d.branch&&console.log(` Branch: ${J__default.default.cyan(d.branch)}`),d.isDirty&&d.uncommittedFiles&&console.log(` Changes: ${J__default.default.yellow(`${d.uncommittedFiles} uncommitted file(s)`)}`);}else console.log(J__default.default.gray(" (not using worktree)"));console.log(),console.log(J__default.default.bold("Progress"));let h=["plan","implement","check","finish"],v=l.current_phase||0,y=h.map((E,A)=>A<v?J__default.default.green(`${E} \u2713`):A===v?J__default.default.yellow(`${E} \u25CF`):J__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: ${J__default.default.gray(E)}`);}console.log(),console.log(J__default.default.bold("Files"));let _=(E,A)=>{if(!E.exists)return J__default.default.gray("(missing)");let C=E.size?`${(E.size/1024).toFixed(1)}KB`:"";return J__default.default.green("\u2713")+" "+J__default.default.gray(C)};console.log(` prd.md: ${_(u.prd,"prd.md")}`),console.log(` implement.jsonl: ${_(u.implement_jsonl,"implement.jsonl")}`),console.log(` check.jsonl: ${_(u.check_jsonl,"check.jsonl")}`),console.log(` fix.jsonl: ${_(u.fix_jsonl,"fix.jsonl")}`),console.log(),console.log(J__default.default.bold("Logs"));let b=E=>{if(!E.exists)return J__default.default.gray("-");let A=E.size?`${(E.size/1024).toFixed(1)}KB`:"",C=E.modifiedAt?new Date(E.modifiedAt).toLocaleString():"";return `${J__default.default.green("\u2713")} ${J__default.default.gray(A)} ${J__default.default.dim(C)}`};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(J__default.default.gray(" (no logs yet)")),console.log(),console.log(J__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),Qe(n,w);let S=o.timing;if(S){console.log(),console.log(J__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=J__default.default.yellow(S.idleDurationStr)),Object.keys(E).length>0?Qe(n,E):console.log(J__default.default.gray(" (no timing data yet)"));}o.runtime?.session_id&&(console.log(),console.log(J__default.default.bold("Session")),Qe(n,{"Session ID":o.runtime.session_id})),l.description&&(console.log(),console.log(J__default.default.bold("Description")),console.log(J__default.default.gray(l.description))),l.notes&&(console.log(),console.log(J__default.default.bold("Notes")),console.log(J__default.default.gray(l.notes))),console.log();});}catch(c){Q(n,c);}}),t.command("edit").description("Edit task (opens editor)").argument("<task>","Task name or directory").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),{result:c}=EJe(a,s,{onClose:o=>{o===0&&Me(i,`Edited task: ${s}`);}});if(!c.success)throw ne.notFound("Task",s)}catch(a){Q(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=yt(e),a=process.cwd();try{let c=vt(a);if(!el(c,s).success)throw ne.notFound("Task",s);if(!i.force&&!n.quiet){console.log(J__default.default.yellow(`Warning: This will permanently delete task "${s}".`)),console.log(J__default.default.gray("Use --force to skip this warning"));return}let l=mhe(c,s);if(!l.success)throw ne.operationFailed("Delete task",l.error);j(n,V({deleted:s}),()=>{Me(n,`Deleted task: ${s}`);});}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o||!De.existsSync(o))throw ne.notFound("Task",s);let l=qt(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){j(n,it("NO_FIELDS","No fields to update. Use --help to see available options."),()=>{console.log(J__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(),!fs(o,l))throw ne.operationFailed("Update task","Failed to write task.json");j(n,V({task:s,updated_fields:u}),()=>{console.log(J__default.default.green(`Updated task: ${s}`)),console.log(),console.log(J__default.default.blue("Updated fields:"));for(let[d,h]of Object.entries(u))console.log(` ${d}: ${h}`);});}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o||!De.existsSync(o)){j(n,it("TASK_NOT_FOUND",`Task not found: ${s}`),()=>{console.error(J__default.default.red(`Error: Task not found: ${s}`)),console.log(J__default.default.gray("Use 'viben task list' to see available tasks"));}),process.exit(1);return}let l;try{l=Re.relative(c,o);}catch{l=o;}let u=qt(o);if(i.resume){let v=i.session;if(!v&&u?.session_id&&(v=u.session_id),!v){j(n,it("NO_SESSION","No session ID found for resume"),()=>{console.error(J__default.default.red("Error: No session ID found for resume")),console.log(J__default.default.gray("No sessionId in task.json and no --session provided"));}),process.exit(1);return}let y=u?.executor||"claude",b=ss(y).buildResumeCommand(v);n.quiet||(console.log(J__default.default.blue("=== Resuming Agent ===")),console.log(` Session: ${v}`),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&&Cve[i.executor.toUpperCase()]||"claude";n.quiet||(console.log(J__default.default.blue("=== Task Start ===")),console.log(`[INFO] Task: ${l}`),console.log(`[INFO] Platform: ${d}`));let h=await Rhe(c,l,{platform:d,detach:i.detach??!0,skipPermissions:!0,verbose:n.verbose});if(n.json)h.success?j(n,V(h)):j(n,it("START_FAILED",h.error||"Unknown error"));else if(h.success){if(console.log(),console.log(J__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(J__default.default.yellow(`To monitor: tail -f ${h.log_file}`)),console.log(J__default.default.yellow(`To stop: kill ${h.pid}`)),h.session_id){let y=ss(d).getResumeCommandStr(h.session_id,h.working_dir);console.log(J__default.default.yellow(`To resume: ${y}`));}}else console.error(J__default.default.red(`Error: ${h.error}`)),process.exit(1);}catch(c){Q(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=yt(e),n=process.cwd();try{let a=vt(n),c=fhe(a,s);if(!c.success)throw ne.operationFailed("Finish task",c.error);j(i,V({finished:c.cleared}),()=>{console.log(J__default.default.green(`Finished task: ${c.cleared}`));});}catch(a){Q(i,a);}}),t.command("archive").description("Archive completed task").argument("<task>","Task name").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=ghe(a,s);if(!c.success)throw ne.operationFailed("Archive task",c.error);j(i,V({archived:c.archived,to:c.destination}),()=>{console.log(J__default.default.green(`Archived: ${c.archived} -> ${c.destination}`));});}catch(a){Q(i,a);}}),t.command("list-archive").description("List archived tasks").argument("[month]","Filter by month (YYYY-MM)").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=yhe(a,s),{archived:o}=c;j(i,V({archived:Object.fromEntries(o)}),()=>{if(console.log(J__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){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=await F1(c,s,i);if(!o.success)throw ne.operationFailed("Enqueue task",o.error);j(n,V({task:o.task,status:o.status}),()=>{console.log(J__default.default.green(`Enqueued: ${o.task}`)),console.log(J__default.default.gray(`Status: ${o.fromStatus} -> ${o.status}`)),i.agent&&console.log(J__default.default.gray(`Agent: ${i.agent}`)),i.executor&&console.log(J__default.default.gray(`Executor: ${i.executor}`)),i.model&&console.log(J__default.default.gray(`Model: ${i.model}`));});}catch(c){Q(n,c);}}),t.command("dequeue").description("Remove task from queue back to backlog").argument("<task>","Task name or directory").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=await ahe(a,s);if(!c.success)throw ne.operationFailed("Dequeue task",c.error);j(i,V({task:c.task,status:c.status}),()=>{console.log(J__default.default.green(`Dequeued: ${c.task}`)),console.log(J__default.default.gray(`Status: ${c.fromStatus} -> ${c.status}`));});}catch(a){Q(i,a);}}),t.command("pause").description("Pause execution of a task").argument("<task>","Task name or directory").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=await she(a,s);if(!c.success)throw ne.operationFailed("Pause task",c.error);j(i,V({task:c.task,status:c.status,fromState:c.fromStatus}),()=>{console.log(J__default.default.green(`Paused: ${c.task}`)),console.log(J__default.default.gray(`Status: ${c.fromStatus} -> paused`));});}catch(a){Q(i,a);}}),t.command("resume").description("Resume a paused task").argument("<task>","Task name or directory").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=await ihe(a,s);if(!c.success)throw ne.operationFailed("Resume task",c.error);j(i,V({task:c.task,status:c.status}),()=>{console.log(J__default.default.green(`Resumed: ${c.task}`)),console.log(J__default.default.gray(`Status: paused -> ${c.status}`));});}catch(a){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=_he(c,s,i.branch);if(!o.success)throw ne.operationFailed("Set branch",o.error);j(n,V({task:s,branch:i.branch}),()=>{console.log(J__default.default.green(`Branch set to: ${i.branch}`)),console.log(),console.log(J__default.default.blue("Now you can start the multi-agent pipeline:")),console.log(` viben task plan --name ${s} ...`);});}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=bhe(c,s,i.branch);if(!o.success)throw ne.operationFailed("Set base branch",o.error);j(n,V({task:s,base_branch:i.branch}),()=>{console.log(J__default.default.green(`Base branch set to: ${i.branch}`)),console.log(` PR will target: ${i.branch}`);});}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=whe(c,s,i.agent);if(!o.success)throw ne.operationFailed("Set agent",o.error);j(n,V({task:s,agent:i.agent}),()=>{Me(n,`Set agent "${i.agent}" for task "${s}"`);});}catch(c){Q(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=yt(e),n=process.cwd();try{let a=vt(n),c=ML(a,s);if(!c.success)throw ne.operationFailed("Initialize context",c.error);j(i,V({task_dir:c.taskDir,files:c.files}),()=>{console.log(J__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(J__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){Q(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=yt(e),c=process.cwd();try{let o=vt(c),l=che(o,s,i,n);if(!l.success)throw ne.operationFailed("Add context",l.error);j(a,V({added:l.added,skipped:l.skipped,total:l.total}),()=>{l.skipped>0&&console.log(J__default.default.yellow(`Skipped ${l.skipped} existing file(s)`)),console.log(J__default.default.blue(`Added ${l.added}/${l.total} file(s) to implement.jsonl`));});}catch(o){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=uhe(c,s,i);if(!o.success)throw ne.operationFailed("Remove context",o.error);j(n,V({removed:o.removed}),()=>{Me(n,`Removed ${o.removed.length} context file(s) from task "${s}"`);});}catch(c){Q(n,c);}}),t.command("list-context").description("List context entries for task").argument("<task>","Task name or directory").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=lhe(a,s);if(!c.success)throw ne.operationFailed("List context",c.error);j(i,V(c.context),()=>{console.log(J__default.default.blue(`Context entries for task: ${s}`)),console.log();for(let[o,l]of Object.entries(c.context)){if(console.log(J__default.default.cyan(`[${o}]`)),l.length===0)console.log(" (empty)");else for(let u of l){let d=u.type?J__default.default.gray(` [${u.type}]`):"";console.log(` - ${u.file}${d}`),u.reason&&console.log(J__default.default.gray(` Reason: ${u.reason}`));}console.log();}});}catch(a){Q(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=yt(e),n=process.cwd();try{let a=vt(n),c=dhe(a,s);if(c.error)throw ne.operationFailed("Validate context",c.error);j(i,V({valid:c.valid.length,missing:c.missing}),()=>{if(console.log(J__default.default.blue(`Validating context files for task: ${s}`)),console.log(),c.success)console.log(J__default.default.green(`All ${c.valid.length} referenced files exist.`));else {console.log(J__default.default.yellow(`Found ${c.missing.length} missing file(s):`));for(let o of c.missing)console.log(J__default.default.red(` - ${o}`));console.log(),console.log(J__default.default.gray(`Valid: ${c.valid.length}, Missing: ${c.missing.length}`));}});}catch(a){Q(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=yt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=vt(a);if(i.registry){MKe(c,n);return}if(i.list){NKe(c,n);return}if(s){i.detail?See(s,c,n):i.watch?LKe(s,c,n):i.log?jKe(s,c,n):See(s,c,n);return}qKe(c,{filter_assignee:i.assignee,filter_status:i.status,only_running:i.running},n);}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=i.dryRun||!1;console.log(J__default.default.blue("=== Create PR ===")),o&&console.log(J__default.default.yellow("[DRY-RUN MODE] No actual changes will be made")),console.log();let l=The(c,s,{dry_run:o});if(!l.success)throw console.log(J__default.default.red(`Error: ${l.error}`)),l.help&&(console.log(),console.log(J__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(J__default.default.yellow(`=== Local-Only Mode (${d}) ===`)),console.log(),l.had_staged_changes?console.log(J__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(J__default.default.green(`Pushed to origin/${l.current_branch}`)),console.log(J__default.default.green("Task status updated to 'review'")),l.help&&(console.log(),console.log(J__default.default.cyan("Next steps:")),console.log(l.help));}else l.had_staged_changes?console.log(J__default.default.green(`Committed: ${l.commit_message}`)):l.unpushed_commits&&console.log(`Found ${l.unpushed_commits} unpushed commit(s)`),console.log(J__default.default.green(`Pushed to origin/${l.current_branch}`)),console.log(J__default.default.green("Task status updated to 'review'"));console.log(),l.local_only?console.log(J__default.default.green("=== Ready for Review (Local) ===")):(console.log(J__default.default.green("=== PR Created Successfully ===")),console.log(`PR URL: ${l.pr_url}`));}catch(c){Q(n,c);}}),t.command("review").description("View task details for review").argument("<task>","Task name or directory").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=khe(a,s);if(!c.success)throw ne.notFound("Task",s);let{task:o,dirName:l,prInfo:u}=c;j(i,V({task:l,...o,prInfo:u}),()=>{console.log(J__default.default.bold(`=== Task Review: ${l} ===`)),console.log(),console.log(`Title: ${o.title}`),console.log(`Status: ${$h(o.status)}`),console.log(`Priority: ${cD(o.priority)}`),console.log(),o.pr_url&&(console.log(`PR URL: ${J__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(J__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(J__default.default.blue("Next steps:")),console.log(` viben task retry ${l} # Retry failed task`));});}catch(a){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o)throw ne.notFound("Task",s);let l=qt(o);if(!l)throw ne.operationFailed("Read task","Cannot read task.json");n.quiet||(console.log(J__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 LL(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,v=u.additionalData?.pullResult;j(n,V({task:u.task,status:u.status,merge_commit:d,merged_at:u.additionalData?.merged_at,worktree_cleanup:h,pull_result:v}),()=>{console.log(J__default.default.green(`Approved: ${u.task}`)),console.log(J__default.default.gray(`Status: ${u.fromStatus} -> completed`)),d&&console.log(J__default.default.gray(`Merge commit: ${d}`)),v?.success&&console.log(J__default.default.gray("Git pull: synced")),h&&(h.worktreeRemoved&&console.log(J__default.default.gray("Worktree: removed")),h.branchDeleted&&console.log(J__default.default.gray("Local branch: deleted"))),console.log(),console.log(J__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){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=await nhe(c,s,i.reason);if(!o.success)throw ne.operationFailed("Reject task",o.error);j(n,V({task:o.task,status:o.status,reason:i.reason}),()=>{console.log(J__default.default.yellow(`Rejected: ${o.task}`)),console.log(J__default.default.gray(`Status: ${o.fromStatus} -> backlog`)),i.reason&&console.log(J__default.default.gray(`Reason: ${i.reason}`));});}catch(c){Q(n,c);}}),t.command("retry").description("Retry a failed task").argument("<task>","Task name or directory").action(async s=>{let i=yt(e),n=process.cwd();try{let a=vt(n),c=await ohe(a,s);if(!c.success)throw ne.operationFailed("Retry task",c.error);j(i,V({task:c.task,status:c.status}),()=>{console.log(J__default.default.green(`Retrying: ${c.task}`)),console.log(J__default.default.gray(`Status: ${c.fromStatus} -> queue`));});}catch(a){Q(i,a);}});let r=async(s,i)=>{let n=yt(e),a=process.cwd();try{let c=vt(a),o=await jL(c,s,i);if(!o.success)throw ne.operationFailed("Cancel task",o.error);j(n,V({task:o.task,status:o.status,reason:i.reason}),()=>{console.log(J__default.default.red(`Cancelled: ${o.task}`)),console.log(J__default.default.gray(`Status: ${o.fromStatus} -> cancelled`)),i.reason&&console.log(J__default.default.gray(`Reason: ${i.reason}`));});}catch(c){Q(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=yt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o||!De.existsSync(o))throw ne.notFound("Task",s);if(n.json){let l=Wpe(c,o);j(n,V(l),()=>{});}else {let l=Vpe(c,o);j(n,V({context:l}),()=>{console.log(l);});}}catch(c){Q(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=yt(e),n=process.cwd(),a=2e3;try{let c=vt(n),o=Bi(c);if(!o)throw ne.operationFailed("Add session","Developer not initialized. Run 'viben init' first.");let l=Re.join(c,Jt,En,o);if(!De.existsSync(l))throw ne.operationFailed("Add session",`Workspace directory not found: ${l}`);let u=Re.join(l,"index.md"),d=wy(),h=jpe(l),y=Mpe(u)+1,_=zpe({session_num:y,title:s.title,commit:s.commit,summary:s.summary,extra_content:s.content,date:d}),b=_.split(`
|
|
1118
1118
|
`).length;console.log(J__default.default.blue("========================================")),console.log(J__default.default.blue("ADD SESSION")),console.log(J__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(J__default.default.yellow(`[!] Exceeds ${a} lines, creating journal-${S}.md`)),w=O1(l,S,o,d,h.number),console.log(`Created: ${w}`)),w||(S=1,w=O1(l,S,o,d,0),console.log(`Created initial: ${w}`));let E=De.readFileSync(w,"utf-8");De.writeFileSync(w,E+_,"utf-8"),console.log(J__default.default.green(`[OK] Appended session to ${Re.basename(w)}`)),console.log(),console.log("Updating index.md...");let A=`journal-${S}.md`,C=Upe({index_path:u,dev_dir:l,session_num:y,title:s.title,commit:s.commit,active_file:A,date:d});console.log(C?J__default.default.green("[OK] Updated index.md successfully!"):J__default.default.yellow("[!] Could not update index.md (markers not found or file missing)")),console.log(),console.log(J__default.default.green("========================================")),console.log(J__default.default.green(`[OK] Session ${y} added successfully!`)),console.log(J__default.default.green("========================================")),console.log(),console.log("Files updated:"),console.log(` - ${Re.basename(w)}`),console.log(" - index.md"),j(i,V({session:y,journalFile:A,title:s.title}),()=>{});}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(J__default.default.blue("=== Plan Phase ===")),console.log(J__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(J__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log(J__default.default.cyan("[INFO]"),`Mode: ${i.detach?"background":"foreground"}`),console.log();let l=await Fhe(c,o,{platform:i.platform,verbose:i.verbose,detach:i.detach??!1});if(l.success)console.log(J__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(J__default.default.yellow("To monitor:")),console.log(` tail -f ${l.logFile}`),console.log(),j(n,V(l));else throw ne.operationFailed("Plan Phase",l.error||"Unknown error")}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(J__default.default.blue("=== Implement Phase ===")),console.log(J__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(J__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log();let l=await $he(c,o,{platform:i.platform,verbose:i.verbose});if(l.success)console.log(J__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(J__default.default.yellow("To monitor:")),console.log(` tail -f ${l.logFile}`),console.log(),j(n,V(l));else throw ne.operationFailed("Implement Phase",l.error||"Unknown error")}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(J__default.default.blue("=== Check Phase ===")),console.log(J__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(J__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log();let l=await Dhe(c,o,{platform:i.platform,verbose:i.verbose});if(l.success)console.log(J__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(J__default.default.yellow("To monitor:")),console.log(` tail -f ${l.logFile}`),console.log(),j(n,V(l));else throw ne.operationFailed("Check Phase",l.error||"Unknown error")}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(J__default.default.blue("=== Compute Reward Phase ===")),console.log(J__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(J__default.default.cyan("[INFO]"),`Platform: ${i.platform||"claude"}`),console.log();let l=Zw(c,o,{platform:i.platform,verbose:i.verbose});if(l.success){if(console.log(J__default.default.green("=== Reward Computation Complete ===")),console.log(),console.log(` Log: ${l.log_file}`),l.warnings&&l.warnings.length>0){console.log(),console.log(J__default.default.yellow("Warnings:"));for(let u of l.warnings)console.log(` - ${u}`);}console.log(),console.log(J__default.default.gray("To view results:")),console.log(" viben task view <task>"),console.log(),j(n,V(l));}else throw ne.operationFailed("Compute Reward",l.error||"Unknown error")}catch(c){Q(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=yt(e),n=process.cwd();try{let a=vt(n),c=ot(s,a);if(!c)throw ne.invalidArgument("task",`Task not found: ${s}`);console.log(),console.log(J__default.default.blue("=== Parse Reward Result ===")),console.log(J__default.default.cyan("[INFO]"),`Task: ${s}`),console.log();let o=eme(a,c);if(o.success&&o.reward){console.log(J__default.default.green("=== Reward Parsed Successfully ===")),console.log(),console.log(J__default.default.cyan("Scores:"));for(let[l,u]of Object.entries(o.reward.scores))console.log(` ${l}: ${u.score.toFixed(3)}`),console.log(` ${J__default.default.gray(u.reasoning)}`);console.log(),console.log(J__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(J__default.default.green("Written to task.json")),j(i,V({reward:o.reward}));}else throw ne.operationFailed("Parse Reward",o.error||"Unknown error")}catch(a){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o||!De.existsSync(o))throw ne.notFound("Task",s);if(qt(o)?.status==="rejected"){let d=Re.join(o,"REJECTED.md"),h="";throw De.existsSync(d)&&(h=De.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=Re.join(o,"prd.md");if(!De.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(J__default.default.blue("=== Create Worktree ===")),console.log(J__default.default.cyan("[INFO]"),`Task: ${s}`),console.log();let u=await qR(c,o);if(u.success)console.log(J__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(J__default.default.yellow("Next step:")),console.log(` viben task work-phase ${s} --worktree ${u.worktreePath}`),console.log(),j(n,V(u));else throw ne.operationFailed("Create Worktree",u.error||"Unknown error")}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=i.platform||"claude",l=ot(s,c);if(!l||!De.existsSync(l))throw ne.notFound("Task",s);let d=ss(o).getAgentConfigPath("work",c);if(!De.existsSync(d))throw ne.operationFailed("Work Phase",`work agent not found at ${d}. Platform: ${o}`);let h=qt(l),v=h?.worktree_path,y=h?.worktree??!1;if(h?.status==="rejected"){let F=Re.join(l,"REJECTED.md"),$="";throw De.existsSync(F)&&($=De.readFileSync(F,"utf-8").trim()),ne.operationFailed("Work Phase",`Task was rejected. ${$?`Reason: ${$}`:"Check REJECTED.md for details."}`)}let _=Re.join(l,"prd.md");if(!De.existsSync(_))throw ne.operationFailed("Work Phase","prd.md not found - planning must be completed before work phase.");let b,w,S,E;if(y||v){if(!v||!De.existsSync(v)){console.log(J__default.default.cyan("[INFO]"),"Worktree not found, creating...");let F=await qR(c,l);if(!F.success)throw ne.operationFailed("Create Worktree",F.error||"Unknown error");v=F.worktreePath,console.log(J__default.default.green("[OK]"),`Worktree created at ${v}`);}b=v,w=`worktree (${v})`,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"}-${Re.basename(l)}`,console.log(),console.log(J__default.default.blue("=== Work Phase ===")),console.log(J__default.default.cyan("[INFO]"),`Task: ${s}`),console.log(J__default.default.cyan("[INFO]"),`Platform: ${o}`),console.log(J__default.default.cyan("[INFO]"),`Working Dir: ${w}`),console.log(J__default.default.cyan("[INFO]"),`Mode: ${i.detach?"background":"foreground"}`),console.log();let C=await c4({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(C.success)console.log(J__default.default.green("=== Work Agent Started ===")),console.log(),console.log(` ID: ${C.agentId}`),console.log(` PID: ${C.pid}`),C.sessionId&&console.log(` Session: ${C.sessionId}`),console.log(` Log: ${C.logFile}`),console.log(),console.log(J__default.default.yellow("To monitor:")),console.log(` tail -f ${C.logFile}`),console.log(` viben swarm status ${s}`),console.log(),j(n,V(C));else throw ne.operationFailed("Work Phase",C.error||"Unknown error")}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a),o=ot(s,c);if(!o)throw ne.invalidArgument("task",`Task not found: ${s}`);let l=i.output;!l&&i.outputFile&&De.existsSync(i.outputFile)&&(l=De.readFileSync(i.outputFile,"utf-8"));let u=Wne(c,o,l);if(n.json){j(n,V(u));return}if(console.log(),console.log(J__default.default.blue("=== Check Phase Validation ===")),console.log(),console.log(` Method: ${u.method}`),console.log(` Result: ${u.success?J__default.default.green("PASSED"):J__default.default.red("FAILED")}`),console.log(),u.method==="verify_commands"){console.log(J__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?J__default.default.green("\u2713"):J__default.default.red("\u2717");console.log(` ${h} ${d.command} (exit: ${d.exitCode})`);}}}else {console.log(J__default.default.cyan("Expected markers:"));for(let d of u.details.expectedMarkers||[]){let v=u.details.foundMarkers?.includes(d)?J__default.default.green("\u2713"):J__default.default.red("\u2717");console.log(` ${v} ${d}`);}}console.log(),u.success?(console.log(J__default.default.green("Check phase validation passed.")),Ib(o,"check_passed_at",new Date().toISOString())):(console.log(J__default.default.red("Check phase validation failed:")),console.log(J__default.default.red(` ${u.error}`))),j(n,V(u));}catch(c){Q(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=yt(e),a=process.cwd();try{let c=vt(a);await lut(n,c,s,i);}catch(c){Q(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=yt(e);i.json&&(n.json=true);let a=process.cwd();try{let c=vt(a),o=parseInt(i.threshold||"120000",10);if(isNaN(o)||o<=0){j(n,it("INVALID_THRESHOLD","Threshold must be a positive number"),()=>{console.error(J__default.default.red("Error: --threshold must be a positive number (milliseconds)"));}),process.exit(1);return}let l=KJe(c,s,{thresholdMs:o,verbose:i.verbose});if(!l.success){j(n,it("CHECK_FAILED",l.error||"Unknown error"),()=>{console.error(J__default.default.red(`Error: ${l.error}`));}),process.exit(1);return}if(n.json){j(n,V(l));return}console.log(J__default.default.bold.cyan(`=== Stuck Check: ${l.taskDir} ===`)),console.log(),l.isStuck?(console.log(J__default.default.red.bold("Status: STUCK")),console.log(J__default.default.red(` ${l.summary}`))):(console.log(J__default.default.green.bold("Status: OK")),console.log(J__default.default.green(` ${l.summary}`))),console.log(),console.log(J__default.default.cyan("Checks:"));for(let u of l.checks){let d=u.isStuck?J__default.default.red("\u2717"):J__default.default.green("\u2713"),h=u.isStuck?J__default.default.red:J__default.default.white;if(console.log(` ${d} ${h(u.name)}: ${u.reason}`),i.verbose&&u.data&&Object.keys(u.data).length>0){for(let[v,y]of Object.entries(u.data))if(y!=null){let _=typeof y=="object"?JSON.stringify(y):String(y);console.log(J__default.default.gray(` ${v}: ${_}`));}}}console.log(),l.task&&(console.log(J__default.default.cyan("Task Info:")),console.log(` Status: ${$h(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){Q(n,c);}});}var Cve,put=O({"src/cli/commands/task.ts"(){yr(),Vc(),Gt(),II(),HL(),u4(),Nhe(),Ohe(),Fm(),Cve={CLAUDE_CODE:"claude",CURSOR:"cursor",GEMINI:"gemini",OPENCODE:"opencode",IFLOW:"iflow",CODEX:"codex",KILO:"kilo",KIRO:"kiro",ANTIGRAVITY:"antigravity"};}}),Ove={};mt(Ove,{registerContextCommand:()=>yut});function mut(e){let t=e.opts();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function fut(e){let t=Bi(e)||"",r=GN(e),s=0,i="";if(r&&t){s=mI(r);let u=r.split("/").pop()||"";i=`${Jt}/${En}/${t}/${u}`;}let n=Dne(e),a=a5e(e),c=a===0,o=Rne(e,5),l=bm(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:`${Jt}/${Gi}`},journal:{file:i,lines:s,near_limit:s>1800}}}function gut(e){let t=[];t.push("========================================"),t.push("SESSION CONTEXT"),t.push("========================================"),t.push("");let r=Bi(e);if(t.push("## DEVELOPER"),!r)return t.push("ERROR: Not initialized. Run: viben user init <name>"),t.join(`
|
|
1119
1119
|
`);t.push(`Name: ${r}`),t.push(""),t.push("## GIT STATUS");let s=Dne(e);t.push(`Branch: ${s}`);let i=r5e(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=Rne(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=bm(e),o=c.length>0?c[c.length-1]:null;if(o){let d=Kc(e),h=Re.join(d,o.dir),v=qt(h);if(t.push(`Path: ${Jt}/${Gi}/${o.dir}`),v){let _=String(v.name??v.id??"unknown"),b=String(v.status??"unknown"),w=String(v.created_at??"unknown"),S=String(v.description??"");t.push(`Name: ${_}`),t.push(`Status: ${b}`),t.push(`Created: ${w}`),S&&t.push(`Description: ${S}`);}let y=Re.join(h,"prd.md");De.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=GN(e);if(u&&r){let d=mI(u),h=u.split("/").pop()||"",v=`${Jt}/${En}/${r}/${h}`;t.push(`Active file: ${v}`),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: ${Jt}/${En}/${r}/`),t.push(`Tasks: ${Jt}/${Gi}/`),t.push("Spec: docs/specs/"),t.push(""),t.push("========================================"),t.join(`
|
|
@@ -1231,7 +1231,7 @@ Error: ${h}`));}),process.exit(1);}e.quiet||(a.stop(),console.log(J__default.def
|
|
|
1231
1231
|
\u2713 Downloaded to ${c}`)),console.log()),e.quiet||console.log(J__default.default.cyan("Installing..."));let o=await Roe(c);o.success||(j(e,it("INSTALL_FAILED",o.error??"Installation failed"),()=>{console.log(J__default.default.red(`Error: ${o.error}`)),console.log(),console.log(J__default.default.gray("To install manually, run:")),console.log(J__default.default.cyan(` ${V3(c)}`));}),process.exit(1)),e.quiet||(console.log(J__default.default.green("\u2713 Installed successfully")),console.log()),e.quiet||console.log(J__default.default.cyan("Launching Viben desktop app..."));let l=YK();j(e,V({version:s.version,installed:true,launched:l,path:o.installedPath}),()=>{console.log(l?J__default.default.green("\u2713 Viben desktop app launched"):J__default.default.yellow("App installed but failed to launch automatically."));});}async function Qae(e,t,r){let s=Coe();Ooe(s)||(j(e,it("PLATFORM_NOT_SUPPORTED",`Platform ${s} is not supported`),()=>{console.log(J__default.default.red(`Error: ${X_(s)} is not supported.`)),console.log(J__default.default.gray("Supported platforms: macOS, Windows (x64), Linux (x64)"));}),process.exit(1));let i=t?.replace(/^v/,"");e.quiet||console.log(J__default.default.cyan("Checking version..."));let n;try{n=await Foe(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.";j(e,it(d,h),()=>{console.log(J__default.default.red(`Error: ${h}`));}),process.exit(1);}let a=$oe(n,s,r.format);if(r.check){j(e,V({version:n.version,tag:n.tag,date:n.date,platform:X_(s),asset:a.name,size:a.size}),()=>{console.log(),console.log(` Version: ${J__default.default.bold("v"+n.version)}`),console.log(` Platform: ${X_(s)}`),console.log(` Package: ${a.name}`),a.size&&console.log(` Size: ${qd(a.size)}`),console.log();});return}e.quiet||(console.log(` Version: ${J__default.default.bold("v"+n.version)}`),console.log(` Platform: ${X_(s)}`),console.log());let c=r.output??p4(),o=Qve();e.quiet||(console.log(`Downloading ${J__default.default.cyan(a.name)}...`),o.start(a.size??100,0,{downloaded:"0 B",total:qd(a.size??0)}));let l;try{l=await Doe(a,{outputDir:c,force:r.force??!1,format:r.format??"exe",onProgress:(u,d)=>{e.quiet||o.update(u,{downloaded:qd(u),total:qd(d)});}});}catch(u){e.quiet||o.stop();let{code:d,message:h}=Zve(u);j(e,it(d,h),()=>{console.log(J__default.default.red(`
|
|
1232
1232
|
Error: ${h}`));}),process.exit(1);}if(e.quiet||o.stop(),r.install){e.quiet||(console.log(J__default.default.green(`
|
|
1233
1233
|
\u2713 Downloaded to ${l}`)),console.log(),console.log(J__default.default.cyan("Installing...")));let u=await Roe(l);u.success||(j(e,it("INSTALL_FAILED",u.error??"Installation failed"),()=>{console.log(J__default.default.red(`Error: ${u.error}`)),console.log(),console.log(J__default.default.gray("To install manually, run:")),console.log(J__default.default.cyan(` ${V3(l)}`));}),process.exit(1)),j(e,V({version:n.version,platform:s,file:l,installed:true,installedPath:u.installedPath}),()=>{console.log(J__default.default.green("\u2713 Installed successfully"));});return}j(e,V({version:n.version,platform:s,file:l,size:a.size}),()=>{console.log(J__default.default.green(`
|
|
1234
|
-
\u2713 Downloaded to ${l}`)),console.log(),console.log(J__default.default.gray("To install, run:")),console.log(J__default.default.cyan(` ${V3(l)}`));});}function Qlt(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 Xlt(s,r);}catch(i){Q(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",p4()).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 Qae(i,r,s);}catch(n){Q(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 Qae(r,void 0,{check:!0});}catch(s){Q(r,s);}});}var Zlt=O({"src/cli/commands/app.ts"(){yr(),Noe();}}),e_e={};mt(e_e,{registerPetCommand:()=>edt});function pn(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function edt(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=pn(this);try{let[i,n]=await Promise.all([ur.listPets(),ur.getConfig()]);j(s,V({pets:i,current:n.current}),()=>{if(i.length===0){console.log(J__default.default.gray("No pets installed"));return}ht(s,["ID","Name","Source","Current"],i.map(a=>[a.id,a.metadata.displayName,a.isBuiltin?"builtin":a.metadata.source??"local",n.current===a.id?J__default.default.green("*"):""]));});}catch(i){Q(s,i);}}),t.command("show <id>").description("Show pet details").action(async function(s){let i=pn(this);try{let n=await ur.getPet(s);if(!n)throw new Ur(`Pet "${s}" not found`,"PET_NOT_FOUND");j(i,V({pet:n}),()=>{console.log(J__default.default.bold(`Pet: ${n.metadata.displayName}`)),Qe(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){Q(i,n);}}),t.command("set <id>").description("Set current pet").action(async function(s){let i=pn(this);try{await ur.setCurrent(s),j(i,V({current:s}),()=>{Me(i,`Set current pet to "${s}"`);});}catch(n){Q(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=pn(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(J__default.default.gray("Cancelled"));return}}await ur.removePet(s),j(n,V({removed:s}),()=>{Me(n,`Removed pet "${s}"`);});}catch(a){Q(n,a);}}),t.command("import <path>").description("Import pet from local zip file").action(async function(s){let i=pn(this);try{let n=await ur.importPet(s);j(i,V({pet:n}),()=>{Me(i,`Imported pet "${n.metadata.displayName}" (${n.id})`);});}catch(n){Q(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=pn(this);try{let a=i.output??`./${s}.zip`,c=await ur.exportPet(s,a);j(n,V({path:c}),()=>{Me(n,`Exported pet to "${c}"`);});}catch(a){Q(n,a);}}),t.command("community").description("List community pets").option("-s, --source <source>","Filter by source").action(async function(s){let i=pn(this);try{let n=await ur.listCommunityPets(s.source);j(i,V({pets:n}),()=>{if(n.length===0){console.log(J__default.default.gray("No community pets found"));return}ht(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Q(i,n);}}),t.command("search <query>").description("Search community pets").action(async function(s){let i=pn(this);try{let n=await ur.searchCommunityPets(s);j(i,V({pets:n}),()=>{if(n.length===0){console.log(J__default.default.gray(`No pets found matching "${s}"`));return}ht(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Q(i,n);}}),t.command("preview <id>").description("Preview community pet info").option("-s, --source <source>","Specify source").action(async function(s,i){let n=pn(this);try{let a=await ur.previewPet(s,i.source);if(!a)throw new Ur(`Pet "${s}" not found`,"PET_NOT_FOUND");j(n,V({pet:a}),()=>{console.log(J__default.default.bold(`Pet: ${a.displayName}`)),Qe(n,{ID:a.id,Description:a.description,Author:a.author??"-",Tags:a.tags?.join(", ")??"-",Source:a.source});});}catch(a){Q(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=pn(this);try{let a=await ur.installPet(s,i.source);j(n,V({pet:a}),()=>{Me(n,`Installed pet "${a.metadata.displayName}" (${a.id})`);});}catch(a){Q(n,a);}});let r=t.command("sources").description("Manage pet sources");r.command("list").description("List all sources").action(async function(){let s=pn(this);try{let i=await ur.listSources();j(s,V({sources:i}),()=>{if(i.length===0){console.log(J__default.default.gray("No sources configured"));return}ht(s,["Name","URL","Enabled","Builtin"],i.map(n=>[n.name,n.url.length>40?n.url.substring(0,37)+"...":n.url,n.enabled?J__default.default.green("Yes"):J__default.default.red("No"),n.builtin?"Yes":"No"]));});}catch(i){Q(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=pn(this);try{let n=await ur.addSource(s.name,s.url);j(i,V({source:n}),()=>{Me(i,`Added source "${n.name}"`);});}catch(n){Q(i,n);}}),r.command("remove <name>").description("Remove a source").action(async function(s){let i=pn(this);try{await ur.removeSource(s),j(i,V({removed:s}),()=>{Me(i,`Removed source "${s}"`);});}catch(n){Q(i,n);}});}var tdt=O({"src/cli/commands/pet.ts"(){yr(),H1();}});Sw();In();kw();np();sp();Ew();Iw();lI();Tm();Uy();jw();lde();a2();Epe();Aw();s2();Om();$pe();Ipe();Ape();Rpe();sl();Om();s2();WI();Ohe();Fm();dde();Tm();eS();Ime();ZL();Ki();var px=[{name:"init",description:"Initialize a Viben workspace",loader:()=>Promise.resolve().then(()=>(hXe(),Vme)).then(e=>({register:e.registerInitCommand}))},{name:"config",description:"Manage configuration",loader:()=>Promise.resolve().then(()=>(vXe(),Kme)).then(e=>({register:e.registerConfigCommand}))},{name:"workspace",description:"Manage workspaces",loader:()=>Promise.resolve().then(()=>(bXe(),Jme)).then(e=>({register:e.registerWorkspaceCommand}))},{name:"executor",description:"Manage executors",loader:()=>Promise.resolve().then(()=>(SXe(),Yme)).then(e=>({register:e.registerExecutorCommand}))},{name:"agent",description:"Manage AI agents",loader:()=>Promise.resolve().then(()=>(PXe(),Xme)).then(e=>({register:e.registerAgentCommand}))},{name:"provider",description:"Manage AI providers",loader:()=>Promise.resolve().then(()=>(CXe(),Qme)).then(e=>({register:e.registerProviderCommand}))},{name:"model",description:"Manage AI models",loader:()=>Promise.resolve().then(()=>($Xe(),Zme)).then(e=>({register:e.registerModelCommand}))},{name:"channel",description:"Manage channels",loader:()=>Promise.resolve().then(()=>(qXe(),efe)).then(e=>({register:e.registerChannelCommand}))},{name:"service",description:"Manage services",loader:()=>Promise.resolve().then(()=>(BXe(),tfe)).then(e=>({register:e.registerServiceCommand}))},{name:"gateway",description:"Gateway management",loader:()=>Promise.resolve().then(()=>(Xot(),pve)).then(e=>({register:e.registerGatewayCommand}))},{name:"cron",description:"Manage cron jobs",loader:()=>Promise.resolve().then(()=>(uct(),yve)).then(e=>({register:e.registerCronCommand}))},{name:"mcp",description:"Manage MCP servers",loader:()=>Promise.resolve().then(()=>(mct(),vve)).then(e=>({register:e.registerMcpCommand}))},{name:"skill",description:"Manage skills",loader:()=>Promise.resolve().then(()=>(_ct(),_ve)).then(e=>({register:e.registerSkillCommand}))},{name:"telemetry",description:"Manage telemetry",loader:()=>Promise.resolve().then(()=>(wct(),bve)).then(e=>({register:e.registerTelemetryCommand}))},{name:"update",description:"Update Viben",loader:()=>Promise.resolve().then(()=>($ct(),Sve)).then(e=>({register:e.registerUpdateCommand}))},{name:"queue",description:"Manage task queues",loader:()=>Promise.resolve().then(()=>(Wct(),kve)).then(e=>({register:e.registerQueueCommand}))},{name:"swarm",description:"Manage agent swarms",loader:()=>Promise.resolve().then(()=>(iut(),xve)).then(e=>({register:e.registerSwarmCommand}))},{name:"task",description:"Manage tasks",loader:()=>Promise.resolve().then(()=>(put(),Ave)).then(e=>({register:e.registerTaskCommand}))},{name:"context",description:"Manage context",loader:()=>Promise.resolve().then(()=>(vut(),Ove)).then(e=>({register:e.registerContextCommand}))},{name:"user",description:"Manage user settings",loader:()=>Promise.resolve().then(()=>(joe(),Loe)).then(e=>({register:e.registerUserCommand}))},{name:"session",description:"Manage sessions",loader:()=>Promise.resolve().then(()=>(kut(),Fve)).then(e=>({register:e.registerSessionCommand}))},{name:"idea",description:"Manage ideas",loader:()=>Promise.resolve().then(()=>(Iut(),Dve)).then(e=>({register:e.registerIdeaCommand}))},{name:"reward",description:"Manage rewards",loader:()=>Promise.resolve().then(()=>(Cut(),Nve)).then(e=>({register:e.registerRewardCommand}))},{name:"evo",description:"Manage evolution",loader:()=>Promise.resolve().then(()=>(Dlt(),Hve)).then(e=>({register:e.registerEvoCommand}))},{name:"index",description:"Generate context index",loader:()=>Promise.resolve().then(()=>(qlt(),Wve)).then(e=>({register:e.registerIndexCommand}))},{name:"login",description:"Login to Viben",loader:()=>Promise.resolve().then(()=>(Ult(),Vve)).then(e=>({register:e.registerLoginCommand}))},{name:"page",description:"Manage workspace pages",loader:()=>Promise.resolve().then(()=>(Hlt(),Jve)).then(e=>({register:e.registerPageCommand}))},{name:"account",description:"Trading account management",loader:()=>Promise.resolve().then(()=>(Vlt(),Yve)).then(e=>({register:e.registerAccountCommand}))},{name:"app",description:"Launch or install Viben desktop app",loader:()=>Promise.resolve().then(()=>(Zlt(),Xve)).then(e=>({register:e.registerAppCommand}))},{name:"pet",description:"Manage pets",loader:()=>Promise.resolve().then(()=>(tdt(),e_e)).then(e=>({register:e.registerPetCommand}))}];function idt(){let e=process.argv.slice(2);for(let t of e)if(!t.startsWith("-"))return t;return null}async function ndt(e){let t=idt(),r=new Set(px.map(s=>s.name));if(t&&r.has(t)){let s=px.find(n=>n.name===t),{register:i}=await s.loader();i(e);for(let n of px)n.name!==t&&e.command(n.name).description(n.description);}else for(let s of px)e.command(s.name).description(s.description);}var odt="1.3.1";async function t_e(){let e=new commander.Command;return e.name("viben").description("Viben - Agent Swarm \xD7 Code Evolution").version(odt,"-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 ndt(e),e}async function r_e(e=process.argv){await(await t_e()).parseAsync(e);}Vc();yr();Ms();H1();r_e(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:
|
|
1234
|
+
\u2713 Downloaded to ${l}`)),console.log(),console.log(J__default.default.gray("To install, run:")),console.log(J__default.default.cyan(` ${V3(l)}`));});}function Qlt(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 Xlt(s,r);}catch(i){Q(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",p4()).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 Qae(i,r,s);}catch(n){Q(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 Qae(r,void 0,{check:!0});}catch(s){Q(r,s);}});}var Zlt=O({"src/cli/commands/app.ts"(){yr(),Noe();}}),e_e={};mt(e_e,{registerPetCommand:()=>edt});function pn(e){let t=e.optsWithGlobals();return {json:t.json??false,verbose:t.verbose??false,quiet:t.quiet??false}}function edt(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=pn(this);try{let[i,n]=await Promise.all([ur.listPets(),ur.getConfig()]);j(s,V({pets:i,current:n.current}),()=>{if(i.length===0){console.log(J__default.default.gray("No pets installed"));return}ht(s,["ID","Name","Source","Current"],i.map(a=>[a.id,a.metadata.displayName,a.isBuiltin?"builtin":a.metadata.source??"local",n.current===a.id?J__default.default.green("*"):""]));});}catch(i){Q(s,i);}}),t.command("show <id>").description("Show pet details").action(async function(s){let i=pn(this);try{let n=await ur.getPet(s);if(!n)throw new Ur(`Pet "${s}" not found`,"PET_NOT_FOUND");j(i,V({pet:n}),()=>{console.log(J__default.default.bold(`Pet: ${n.metadata.displayName}`)),Qe(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){Q(i,n);}}),t.command("set <id>").description("Set current pet").action(async function(s){let i=pn(this);try{await ur.setCurrent(s),j(i,V({current:s}),()=>{Me(i,`Set current pet to "${s}"`);});}catch(n){Q(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=pn(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(J__default.default.gray("Cancelled"));return}}await ur.removePet(s),j(n,V({removed:s}),()=>{Me(n,`Removed pet "${s}"`);});}catch(a){Q(n,a);}}),t.command("import <path>").description("Import pet from local zip file").action(async function(s){let i=pn(this);try{let n=await ur.importPet(s);j(i,V({pet:n}),()=>{Me(i,`Imported pet "${n.metadata.displayName}" (${n.id})`);});}catch(n){Q(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=pn(this);try{let a=i.output??`./${s}.zip`,c=await ur.exportPet(s,a);j(n,V({path:c}),()=>{Me(n,`Exported pet to "${c}"`);});}catch(a){Q(n,a);}}),t.command("community").description("List community pets").option("-s, --source <source>","Filter by source").action(async function(s){let i=pn(this);try{let n=await ur.listCommunityPets(s.source);j(i,V({pets:n}),()=>{if(n.length===0){console.log(J__default.default.gray("No community pets found"));return}ht(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Q(i,n);}}),t.command("search <query>").description("Search community pets").action(async function(s){let i=pn(this);try{let n=await ur.searchCommunityPets(s);j(i,V({pets:n}),()=>{if(n.length===0){console.log(J__default.default.gray(`No pets found matching "${s}"`));return}ht(i,["ID","Name","Author","Source"],n.map(a=>[a.id,a.displayName,a.author??"-",a.source]));});}catch(n){Q(i,n);}}),t.command("preview <id>").description("Preview community pet info").option("-s, --source <source>","Specify source").action(async function(s,i){let n=pn(this);try{let a=await ur.previewPet(s,i.source);if(!a)throw new Ur(`Pet "${s}" not found`,"PET_NOT_FOUND");j(n,V({pet:a}),()=>{console.log(J__default.default.bold(`Pet: ${a.displayName}`)),Qe(n,{ID:a.id,Description:a.description,Author:a.author??"-",Tags:a.tags?.join(", ")??"-",Source:a.source});});}catch(a){Q(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=pn(this);try{let a=await ur.installPet(s,i.source);j(n,V({pet:a}),()=>{Me(n,`Installed pet "${a.metadata.displayName}" (${a.id})`);});}catch(a){Q(n,a);}});let r=t.command("sources").description("Manage pet sources");r.command("list").description("List all sources").action(async function(){let s=pn(this);try{let i=await ur.listSources();j(s,V({sources:i}),()=>{if(i.length===0){console.log(J__default.default.gray("No sources configured"));return}ht(s,["Name","URL","Enabled","Builtin"],i.map(n=>[n.name,n.url.length>40?n.url.substring(0,37)+"...":n.url,n.enabled?J__default.default.green("Yes"):J__default.default.red("No"),n.builtin?"Yes":"No"]));});}catch(i){Q(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=pn(this);try{let n=await ur.addSource(s.name,s.url);j(i,V({source:n}),()=>{Me(i,`Added source "${n.name}"`);});}catch(n){Q(i,n);}}),r.command("remove <name>").description("Remove a source").action(async function(s){let i=pn(this);try{await ur.removeSource(s),j(i,V({removed:s}),()=>{Me(i,`Removed source "${s}"`);});}catch(n){Q(i,n);}});}var tdt=O({"src/cli/commands/pet.ts"(){yr(),H1();}});Sw();In();kw();np();sp();Ew();Iw();lI();Tm();Uy();jw();lde();a2();Epe();Aw();s2();Om();$pe();Ipe();Ape();Rpe();sl();Om();s2();WI();Ohe();Fm();dde();Tm();eS();Ime();ZL();Ki();var px=[{name:"init",description:"Initialize a Viben workspace",loader:()=>Promise.resolve().then(()=>(hXe(),Vme)).then(e=>({register:e.registerInitCommand}))},{name:"config",description:"Manage configuration",loader:()=>Promise.resolve().then(()=>(vXe(),Kme)).then(e=>({register:e.registerConfigCommand}))},{name:"workspace",description:"Manage workspaces",loader:()=>Promise.resolve().then(()=>(bXe(),Jme)).then(e=>({register:e.registerWorkspaceCommand}))},{name:"executor",description:"Manage executors",loader:()=>Promise.resolve().then(()=>(SXe(),Yme)).then(e=>({register:e.registerExecutorCommand}))},{name:"agent",description:"Manage AI agents",loader:()=>Promise.resolve().then(()=>(PXe(),Xme)).then(e=>({register:e.registerAgentCommand}))},{name:"provider",description:"Manage AI providers",loader:()=>Promise.resolve().then(()=>(CXe(),Qme)).then(e=>({register:e.registerProviderCommand}))},{name:"model",description:"Manage AI models",loader:()=>Promise.resolve().then(()=>($Xe(),Zme)).then(e=>({register:e.registerModelCommand}))},{name:"channel",description:"Manage channels",loader:()=>Promise.resolve().then(()=>(qXe(),efe)).then(e=>({register:e.registerChannelCommand}))},{name:"service",description:"Manage services",loader:()=>Promise.resolve().then(()=>(BXe(),tfe)).then(e=>({register:e.registerServiceCommand}))},{name:"gateway",description:"Gateway management",loader:()=>Promise.resolve().then(()=>(Xot(),pve)).then(e=>({register:e.registerGatewayCommand}))},{name:"cron",description:"Manage cron jobs",loader:()=>Promise.resolve().then(()=>(uct(),yve)).then(e=>({register:e.registerCronCommand}))},{name:"mcp",description:"Manage MCP servers",loader:()=>Promise.resolve().then(()=>(mct(),vve)).then(e=>({register:e.registerMcpCommand}))},{name:"skill",description:"Manage skills",loader:()=>Promise.resolve().then(()=>(_ct(),_ve)).then(e=>({register:e.registerSkillCommand}))},{name:"telemetry",description:"Manage telemetry",loader:()=>Promise.resolve().then(()=>(wct(),bve)).then(e=>({register:e.registerTelemetryCommand}))},{name:"update",description:"Update Viben",loader:()=>Promise.resolve().then(()=>($ct(),Sve)).then(e=>({register:e.registerUpdateCommand}))},{name:"queue",description:"Manage task queues",loader:()=>Promise.resolve().then(()=>(Wct(),kve)).then(e=>({register:e.registerQueueCommand}))},{name:"swarm",description:"Manage agent swarms",loader:()=>Promise.resolve().then(()=>(iut(),xve)).then(e=>({register:e.registerSwarmCommand}))},{name:"task",description:"Manage tasks",loader:()=>Promise.resolve().then(()=>(put(),Ave)).then(e=>({register:e.registerTaskCommand}))},{name:"context",description:"Manage context",loader:()=>Promise.resolve().then(()=>(vut(),Ove)).then(e=>({register:e.registerContextCommand}))},{name:"user",description:"Manage user settings",loader:()=>Promise.resolve().then(()=>(joe(),Loe)).then(e=>({register:e.registerUserCommand}))},{name:"session",description:"Manage sessions",loader:()=>Promise.resolve().then(()=>(kut(),Fve)).then(e=>({register:e.registerSessionCommand}))},{name:"idea",description:"Manage ideas",loader:()=>Promise.resolve().then(()=>(Iut(),Dve)).then(e=>({register:e.registerIdeaCommand}))},{name:"reward",description:"Manage rewards",loader:()=>Promise.resolve().then(()=>(Cut(),Nve)).then(e=>({register:e.registerRewardCommand}))},{name:"evo",description:"Manage evolution",loader:()=>Promise.resolve().then(()=>(Dlt(),Hve)).then(e=>({register:e.registerEvoCommand}))},{name:"index",description:"Generate context index",loader:()=>Promise.resolve().then(()=>(qlt(),Wve)).then(e=>({register:e.registerIndexCommand}))},{name:"login",description:"Login to Viben",loader:()=>Promise.resolve().then(()=>(Ult(),Vve)).then(e=>({register:e.registerLoginCommand}))},{name:"page",description:"Manage workspace pages",loader:()=>Promise.resolve().then(()=>(Hlt(),Jve)).then(e=>({register:e.registerPageCommand}))},{name:"account",description:"Trading account management",loader:()=>Promise.resolve().then(()=>(Vlt(),Yve)).then(e=>({register:e.registerAccountCommand}))},{name:"app",description:"Launch or install Viben desktop app",loader:()=>Promise.resolve().then(()=>(Zlt(),Xve)).then(e=>({register:e.registerAppCommand}))},{name:"pet",description:"Manage pets",loader:()=>Promise.resolve().then(()=>(tdt(),e_e)).then(e=>({register:e.registerPetCommand}))}];function idt(){let e=process.argv.slice(2);for(let t of e)if(!t.startsWith("-"))return t;return null}async function ndt(e){let t=idt(),r=new Set(px.map(s=>s.name));if(t&&r.has(t)){let s=px.find(n=>n.name===t),{register:i}=await s.loader();i(e);for(let n of px)n.name!==t&&e.command(n.name).description(n.description);}else for(let s of px)e.command(s.name).description(s.description);}var odt="1.3.2";async function t_e(){let e=new commander.Command;return e.name("viben").description("Viben - Agent Swarm \xD7 Code Evolution").version(odt,"-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 ndt(e),e}async function r_e(e=process.argv){await(await t_e()).parseAsync(e);}Vc();yr();Ms();H1();r_e(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
1235
|
|
|
1236
1236
|
mime-db/index.js:
|
|
1237
1237
|
(*!
|