@automagik/genie 4.260409.2 → 4.260409.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/genie.js CHANGED
@@ -333,7 +333,7 @@ Next steps:`),console.log(" 1. Reload tmux: tmux source ~/.tmux.conf"),console.
333
333
 
334
334
  ${content}`;if(params.extraArgs){let fileIdx=params.extraArgs.indexOf("--append-system-prompt-file");if(fileIdx!==-1&&params.extraArgs[fileIdx+1])content=`${content}
335
335
 
336
- ${readFileSync9(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(fileIdx,2)}writeFileSync9(promptFile,content);let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(promptFile))}else if(params.systemPromptFile){let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(params.systemPromptFile))}}function appendOtelEnv(env,params){if(!params.otelPort||process.env.OTEL_EXPORTER_OTLP_ENDPOINT)return;if(env.CLAUDE_CODE_ENABLE_TELEMETRY="1",env.OTEL_LOGS_EXPORTER="otlp",env.OTEL_METRICS_EXPORTER="otlp",env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",env.OTEL_EXPORTER_OTLP_ENDPOINT=`http://127.0.0.1:${params.otelPort}`,env.OTEL_LOG_TOOL_DETAILS="1",params.otelLogPrompts!==!1)env.OTEL_LOG_USER_PROMPTS="1";let resourceParts=[];if(params.role)resourceParts.push(`agent.name=${params.role}`);if(params.team)resourceParts.push(`team.name=${params.team}`);if(params.otelWishSlug)resourceParts.push(`wish.slug=${params.otelWishSlug}`);if(params.role)resourceParts.push(`agent.role=${params.role}`);if(resourceParts.length>0)env.OTEL_RESOURCE_ATTRIBUTES=resourceParts.join(",")}function buildClaudeCommand(params){preflightCheck("claude");let parts=[resolveShellBinary("claude")??"claude","--dangerously-skip-permissions"],env={};if(env.GENIE_WORKER="1",params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(appendOtelEnv(env,params),params.nativeTeam?.enabled)appendNativeTeamFlags(parts,env,params.nativeTeam,params);if(params.resume)parts.push("--resume",escapeShellArg2(params.resume));else if(params.sessionId)parts.push("--session-id",escapeShellArg2(params.sessionId));if(params.role)parts.push("--agent",escapeShellArg2(params.role));if(params.model)parts.push("--model",escapeShellArg2(params.model));if(params.name)parts.push("--name",escapeShellArg2(params.name));appendSystemPromptFlags(parts,params);let hookEntry={type:"command",command:buildDispatchCommand(),timeout:15},hooksSettings=JSON.stringify({hooks:{PreToolUse:[{matcher:"*",hooks:[hookEntry]}],PostToolUse:[{matcher:"*",hooks:[hookEntry]}],UserPromptSubmit:[{hooks:[hookEntry]}],Stop:[{hooks:[hookEntry]}]}});if(parts.push("--settings",escapeShellArg2(hooksSettings)),params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));if(params.initialPrompt)parts.push(escapeShellArg2(params.initialPrompt));return{command:parts.join(" "),provider:"claude",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildCodexCommand(params){preflightCheck("codex");let parts=["codex"];if(parts.push("--yolo"),parts.push("--no-alt-screen"),params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));let promptParts=[`Genie worker. Team: ${params.team}.`];if(params.role)promptParts.push(`Role: ${params.role}.`);if(params.skill)promptParts.push(`Execute the ${params.skill} skill instructions.`);let prompt2=promptParts.join(" ");return parts.push(escapeShellArg2(prompt2)),{command:parts.join(" "),provider:"codex",meta:{role:params.role,skill:params.skill}}}function buildLaunchCommand(params){let validated=validateSpawnParams(params);switch(validated.provider){case"claude":return buildClaudeCommand(validated);case"codex":return buildCodexCommand(validated);case"claude-sdk":return{command:"claude-sdk-in-process",provider:"claude-sdk",meta:{role:validated.role,skill:validated.skill}};default:throw Error(`Unknown provider "${validated.provider}". Valid providers: claude, codex, claude-sdk`)}}var CLAUDE_TEAM_COLORS,spawnParamsSchema;var init_provider_adapters=__esm(()=>{init_zod();init_inject();CLAUDE_TEAM_COLORS=["red","blue","green","yellow","purple","orange","pink","cyan"],spawnParamsSchema=exports_external.object({provider:exports_external.enum(["claude","codex","claude-sdk","app-pty"]),team:exports_external.string().min(1,"Team name is required"),role:exports_external.string().optional(),skill:exports_external.string().optional(),extraArgs:exports_external.array(exports_external.string()).optional(),nativeTeam:exports_external.object({enabled:exports_external.boolean(),parentSessionId:exports_external.string().optional(),color:exports_external.string().optional(),agentType:exports_external.string().optional(),planModeRequired:exports_external.boolean().optional(),permissionMode:exports_external.string().optional(),agentName:exports_external.string().optional()}).optional(),sessionId:exports_external.string().uuid().optional(),resume:exports_external.string().optional(),systemPromptFile:exports_external.string().optional(),systemPrompt:exports_external.string().optional(),promptMode:exports_external.enum(["system","append"]).optional(),model:exports_external.string().optional(),initialPrompt:exports_external.string().optional(),name:exports_external.string().optional(),otelPort:exports_external.number().optional(),otelLogPrompts:exports_external.boolean().optional(),otelWishSlug:exports_external.string().optional(),newWindow:exports_external.boolean().optional(),windowTarget:exports_external.string().optional()})});var exports_claude_native_teams={};__export(exports_claude_native_teams,{writeNativeInbox:()=>writeNativeInbox,unregisterNativeMember:()=>unregisterNativeMember,sanitizeTeamName:()=>sanitizeTeamName,resolveNativeMemberName:()=>resolveNativeMemberName,registerNativeMember:()=>registerNativeMember,registerAsTeamLead:()=>registerAsTeamLead,loadConfig:()=>loadConfig,listTeamsWithUnreadInbox:()=>listTeamsWithUnreadInbox,listTeams:()=>listTeams,isInsideClaudeCode:()=>isInsideClaudeCode,ensureNativeTeam:()=>ensureNativeTeam,discoverTeamName:()=>discoverTeamName,discoverClaudeParentSessionId:()=>discoverClaudeParentSessionId,deleteNativeTeam:()=>deleteNativeTeam,clearNativeInbox:()=>clearNativeInbox,assignColor:()=>assignColor});import{existsSync as existsSync14}from"fs";import{mkdir as mkdir3,open,readFile as readFile3,readdir as readdir2,rm,stat,unlink as unlink2,writeFile as writeFile2}from"fs/promises";import{homedir as homedir14}from"os";import{join as join15}from"path";function claudeConfigDir2(){return process.env.CLAUDE_CONFIG_DIR??join15(homedir14(),".claude")}function teamsBaseDir(){return join15(claudeConfigDir2(),"teams")}function sanitizeTeamName(name){return name.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}async function listTeams(){try{return(await readdir2(teamsBaseDir())).filter((e)=>!e.startsWith("."))}catch{return[]}}function teamDir(teamName){return join15(teamsBaseDir(),sanitizeTeamName(teamName))}function configPath(teamName){return join15(teamDir(teamName),"config.json")}function inboxesDir(teamName){return join15(teamDir(teamName),"inboxes")}function inboxPath(teamName,agentName){return join15(inboxesDir(teamName),`${sanitizeTeamName(agentName)}.json`)}function lockPath(filePath){return`${filePath}.lock`}function isPidAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function acquireLock(path2){let lock=lockPath(path2),deadline=Date.now()+LOCK_TIMEOUT_MS;while(Date.now()<deadline)try{await writeFile2(lock,String(process.pid),{flag:"wx"});return}catch{try{let content=await readFile3(lock,"utf-8"),holderPid=Number.parseInt(content.trim(),10);if(!Number.isNaN(holderPid)&&!isPidAlive(holderPid)){try{await unlink2(lock)}catch{}continue}}catch{continue}let jitter=Math.floor(Math.random()*LOCK_POLL_MS);await new Promise((r)=>setTimeout(r,LOCK_POLL_MS+jitter))}console.warn(`[claude-native-teams] Force-acquiring stale lock: ${lock}`),await writeFile2(lock,String(process.pid))}async function releaseLock(path2){try{await unlink2(lockPath(path2))}catch{}}async function loadConfig(teamName){try{let content=await readFile3(configPath(teamName),"utf-8");return JSON.parse(content)}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return null;let message=err instanceof Error?err.message:String(err);return console.warn(`[claude-native-teams] Failed to load config for "${teamName}": ${message}`),null}}async function saveConfig(teamName,config){await writeFile2(configPath(teamName),JSON.stringify(config,null,2))}async function countLeadSessionRefs(){let counts=new Map,teams=await listTeams();for(let team of teams){let leadSessionId=(await loadConfig(team))?.leadSessionId;if(!leadSessionId)continue;counts.set(leadSessionId,(counts.get(leadSessionId)??0)+1)}return counts}async function ensureNativeTeam(teamName,description,leadSessionId,leaderName){let dir=teamDir(teamName),inboxDir=inboxesDir(teamName);await mkdir3(dir,{recursive:!0}),await mkdir3(inboxDir,{recursive:!0}),ensureTeammateBypassPermissions();let existing=await loadConfig(teamName);if(existing)return existing;let sanitized=sanitizeTeamName(teamName),resolvedLeader=sanitizeTeamName(leaderName??teamName),config={name:sanitized,description,createdAt:Date.now(),leadAgentId:`${resolvedLeader}@${sanitized}`,leadSessionId,members:[]};return await saveConfig(teamName,config),config}async function registerNativeMember(teamName,member){let config=await loadConfig(teamName);if(!config)throw Error(`Native team "${teamName}" not found`);let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(member.agentName)}@${sanitized}`;config.members=config.members.filter((m)=>m.agentId!==agentId),config.members.push({agentId,name:sanitizeTeamName(member.agentName),agentType:member.agentType??"general-purpose",joinedAt:Date.now(),tmuxPaneId:member.tmuxPaneId,cwd:member.cwd??process.cwd(),backendType:"tmux",color:member.color,planModeRequired:member.planModeRequired??!1,isActive:!0}),await saveConfig(teamName,config);let inbox=inboxPath(teamName,member.agentName);if(!existsSync14(inbox))await writeFile2(inbox,"[]")}async function unregisterNativeMember(teamName,agentName){let config=await loadConfig(teamName);if(!config)return;let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(agentName)}@${sanitized}`,member=config.members.find((m)=>m.agentId===agentId);if(member)member.isActive=!1;await saveConfig(teamName,config)}async function writeNativeInbox(teamName,agentName,message){let path2=inboxPath(teamName,agentName);await mkdir3(inboxesDir(teamName),{recursive:!0}),await acquireLock(path2);try{let messages2=[];try{let content=await readFile3(path2,"utf-8");messages2=JSON.parse(content)}catch{}messages2.push(message),await writeFile2(path2,JSON.stringify(messages2,null,2))}finally{await releaseLock(path2)}}async function resolveNativeMemberName(teamName,genieWorkerId){let config=await loadConfig(teamName);if(!config||config.members.length===0)return null;let sanitizedId=sanitizeTeamName(genieWorkerId),sanitizedTeam=sanitizeTeamName(teamName),exactMatch=config.members.find((m)=>m.name===sanitizedId&&m.isActive);if(exactMatch)return exactMatch.name;let agentIdMatch=config.members.find((m)=>m.agentId===`${sanitizedId}@${sanitizedTeam}`&&m.isActive);if(agentIdMatch)return agentIdMatch.name;let teamPrefix=`${sanitizedTeam}-`;if(sanitizedId.startsWith(teamPrefix)){let stripped=sanitizedId.slice(teamPrefix.length),prefixMatch=config.members.find((m)=>m.name===stripped&&m.isActive);if(prefixMatch)return prefixMatch.name}let inactiveMatch=config.members.find((m)=>m.name===sanitizedId);if(inactiveMatch)return inactiveMatch.name;return null}async function assignColor(teamName){let config=await loadConfig(teamName);if(!config)return CLAUDE_TEAM_COLORS[0];let usedColors=new Set(config.members.map((m)=>m.color));for(let color of CLAUDE_TEAM_COLORS)if(!usedColors.has(color))return color;return CLAUDE_TEAM_COLORS[config.members.length%CLAUDE_TEAM_COLORS.length]}async function clearNativeInbox(teamName,agentName){let path2=inboxPath(teamName,agentName);await acquireLock(path2);try{await writeFile2(path2,"[]")}finally{await releaseLock(path2)}}async function deleteNativeTeam(teamName){let dir=teamDir(teamName);if(!existsSync14(dir))return!1;return await rm(dir,{recursive:!0,force:!0}),!0}function extractLeaderInboxName(config,teamName){if(!config?.leadAgentId)return teamName??"unknown";let atIdx=config.leadAgentId.indexOf("@");return atIdx>0?config.leadAgentId.slice(0,atIdx):teamName??"unknown"}async function scanTeamInbox(base,name){let config=null;try{let cfgContent=await readFile3(join15(base,name,"config.json"),"utf-8");config=JSON.parse(cfgContent)}catch{}let leaderInboxName=extractLeaderInboxName(config,name),inboxFile=join15(base,name,"inboxes",`${leaderInboxName}.json`),messages2;try{let content=await readFile3(inboxFile,"utf-8");messages2=JSON.parse(content)}catch{return null}if(!Array.isArray(messages2))return null;let unread=messages2.filter((m)=>m.read===!1);if(unread.length===0)return null;let workingDir=null;if(config){let leadMember=config.members.find((m)=>m.agentId===config?.leadAgentId||m.name===leaderInboxName);if(leadMember?.cwd)workingDir=leadMember.cwd}return{teamName:name,unreadCount:unread.length,workingDir,firstUnreadText:unread[0]?.text??null}}async function listTeamsWithUnreadInbox(){let base=teamsBaseDir(),teamDirs;try{teamDirs=await readdir2(base)}catch{return[]}let results=[];for(let name of teamDirs){let entry=await scanTeamInbox(base,name);if(entry)results.push(entry)}return results}function sanitizePath(p){return p.replace(/[^a-zA-Z0-9]/g,"-")}async function discoverClaudeSessionId(cwd){let envSessionId=process.env.CLAUDE_CODE_SESSION_ID;if(envSessionId)return envSessionId;let projectDir=join15(claudeConfigDir2(),"projects",sanitizePath(cwd??process.cwd()));try{let jsonls=(await readdir2(projectDir)).filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let newest=null;for(let name of jsonls){let s=await stat(join15(projectDir,name));if(!newest||s.mtimeMs>newest.mtime)newest={name,mtime:s.mtimeMs}}if(!newest)return null;return newest.name.replace(".jsonl","")}catch{return null}}async function readSessionMetadata(filePath){let handle=null;try{handle=await open(filePath,"r");let buffer2=Buffer.alloc(8192),{bytesRead}=await handle.read(buffer2,0,buffer2.length,0),head=buffer2.toString("utf-8",0,bytesRead);for(let line of head.split(`
336
+ ${readFileSync9(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(fileIdx,2)}writeFileSync9(promptFile,content);let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(promptFile))}else if(params.systemPromptFile){let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(params.systemPromptFile))}}function appendOtelEnv(env,params){if(!params.otelPort||process.env.OTEL_EXPORTER_OTLP_ENDPOINT)return;if(env.CLAUDE_CODE_ENABLE_TELEMETRY="1",env.OTEL_LOGS_EXPORTER="otlp",env.OTEL_METRICS_EXPORTER="otlp",env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",env.OTEL_EXPORTER_OTLP_ENDPOINT=`http://127.0.0.1:${params.otelPort}`,env.OTEL_LOG_TOOL_DETAILS="1",params.otelLogPrompts!==!1)env.OTEL_LOG_USER_PROMPTS="1";let resourceParts=[];if(params.role)resourceParts.push(`agent.name=${params.role}`);if(params.team)resourceParts.push(`team.name=${params.team}`);if(params.otelWishSlug)resourceParts.push(`wish.slug=${params.otelWishSlug}`);if(params.role)resourceParts.push(`agent.role=${params.role}`);if(resourceParts.length>0)env.OTEL_RESOURCE_ATTRIBUTES=resourceParts.join(",")}function buildClaudeCommand(params){preflightCheck("claude");let parts=[resolveShellBinary("claude")??"claude","--dangerously-skip-permissions"],env={};if(env.GENIE_WORKER="1",params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(appendOtelEnv(env,params),params.nativeTeam?.enabled)appendNativeTeamFlags(parts,env,params.nativeTeam,params);if(params.resume)parts.push("--resume",escapeShellArg2(params.resume));else if(params.sessionId)parts.push("--session-id",escapeShellArg2(params.sessionId));if(params.role)parts.push("--agent",escapeShellArg2(params.role));if(params.model)parts.push("--model",escapeShellArg2(params.model));if(params.name)parts.push("--name",escapeShellArg2(params.name));appendSystemPromptFlags(parts,params);let hookEntry={type:"command",command:buildDispatchCommand(),timeout:15},settingsObj={hooks:{PreToolUse:[{matcher:"*",hooks:[hookEntry]}],PostToolUse:[{matcher:"*",hooks:[hookEntry]}],UserPromptSubmit:[{hooks:[hookEntry]}],Stop:[{hooks:[hookEntry]}]}};if(params.permissions){let perms={};if(params.permissions.allow?.length)perms.allow=params.permissions.allow;if(params.permissions.deny?.length)perms.deny=params.permissions.deny;if(Object.keys(perms).length>0)settingsObj.permissions=perms}if(parts.push("--settings",escapeShellArg2(JSON.stringify(settingsObj))),params.disallowedTools?.length)for(let tool of params.disallowedTools)parts.push("--disallowedTools",escapeShellArg2(tool));if(params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));if(params.initialPrompt)parts.push(escapeShellArg2(params.initialPrompt));return{command:parts.join(" "),provider:"claude",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildCodexCommand(params){preflightCheck("codex");let parts=["codex"];if(parts.push("--yolo"),parts.push("--no-alt-screen"),params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));let promptParts=[`Genie worker. Team: ${params.team}.`];if(params.role)promptParts.push(`Role: ${params.role}.`);if(params.skill)promptParts.push(`Execute the ${params.skill} skill instructions.`);let prompt2=promptParts.join(" ");return parts.push(escapeShellArg2(prompt2)),{command:parts.join(" "),provider:"codex",meta:{role:params.role,skill:params.skill}}}function buildLaunchCommand(params){let validated=validateSpawnParams(params);switch(validated.provider){case"claude":return buildClaudeCommand(validated);case"codex":return buildCodexCommand(validated);case"claude-sdk":return{command:"claude-sdk-in-process",provider:"claude-sdk",meta:{role:validated.role,skill:validated.skill}};default:throw Error(`Unknown provider "${validated.provider}". Valid providers: claude, codex, claude-sdk`)}}var CLAUDE_TEAM_COLORS,spawnParamsSchema;var init_provider_adapters=__esm(()=>{init_zod();init_inject();CLAUDE_TEAM_COLORS=["red","blue","green","yellow","purple","orange","pink","cyan"],spawnParamsSchema=exports_external.object({provider:exports_external.enum(["claude","codex","claude-sdk","app-pty"]),team:exports_external.string().min(1,"Team name is required"),role:exports_external.string().optional(),skill:exports_external.string().optional(),extraArgs:exports_external.array(exports_external.string()).optional(),nativeTeam:exports_external.object({enabled:exports_external.boolean(),parentSessionId:exports_external.string().optional(),color:exports_external.string().optional(),agentType:exports_external.string().optional(),planModeRequired:exports_external.boolean().optional(),permissionMode:exports_external.string().optional(),agentName:exports_external.string().optional()}).optional(),sessionId:exports_external.string().uuid().optional(),resume:exports_external.string().optional(),systemPromptFile:exports_external.string().optional(),systemPrompt:exports_external.string().optional(),promptMode:exports_external.enum(["system","append"]).optional(),model:exports_external.string().optional(),initialPrompt:exports_external.string().optional(),name:exports_external.string().optional(),otelPort:exports_external.number().optional(),otelLogPrompts:exports_external.boolean().optional(),otelWishSlug:exports_external.string().optional(),newWindow:exports_external.boolean().optional(),windowTarget:exports_external.string().optional()})});var exports_claude_native_teams={};__export(exports_claude_native_teams,{writeNativeInbox:()=>writeNativeInbox,unregisterNativeMember:()=>unregisterNativeMember,sanitizeTeamName:()=>sanitizeTeamName,resolveNativeMemberName:()=>resolveNativeMemberName,registerNativeMember:()=>registerNativeMember,registerAsTeamLead:()=>registerAsTeamLead,loadConfig:()=>loadConfig,listTeamsWithUnreadInbox:()=>listTeamsWithUnreadInbox,listTeams:()=>listTeams,isInsideClaudeCode:()=>isInsideClaudeCode,ensureNativeTeam:()=>ensureNativeTeam,discoverTeamName:()=>discoverTeamName,discoverClaudeParentSessionId:()=>discoverClaudeParentSessionId,deleteNativeTeam:()=>deleteNativeTeam,clearNativeInbox:()=>clearNativeInbox,assignColor:()=>assignColor});import{existsSync as existsSync14}from"fs";import{mkdir as mkdir3,open,readFile as readFile3,readdir as readdir2,rm,stat,unlink as unlink2,writeFile as writeFile2}from"fs/promises";import{homedir as homedir14}from"os";import{join as join15}from"path";function claudeConfigDir2(){return process.env.CLAUDE_CONFIG_DIR??join15(homedir14(),".claude")}function teamsBaseDir(){return join15(claudeConfigDir2(),"teams")}function sanitizeTeamName(name){return name.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}async function listTeams(){try{return(await readdir2(teamsBaseDir())).filter((e)=>!e.startsWith("."))}catch{return[]}}function teamDir(teamName){return join15(teamsBaseDir(),sanitizeTeamName(teamName))}function configPath(teamName){return join15(teamDir(teamName),"config.json")}function inboxesDir(teamName){return join15(teamDir(teamName),"inboxes")}function inboxPath(teamName,agentName){return join15(inboxesDir(teamName),`${sanitizeTeamName(agentName)}.json`)}function lockPath(filePath){return`${filePath}.lock`}function isPidAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function acquireLock(path2){let lock=lockPath(path2),deadline=Date.now()+LOCK_TIMEOUT_MS;while(Date.now()<deadline)try{await writeFile2(lock,String(process.pid),{flag:"wx"});return}catch{try{let content=await readFile3(lock,"utf-8"),holderPid=Number.parseInt(content.trim(),10);if(!Number.isNaN(holderPid)&&!isPidAlive(holderPid)){try{await unlink2(lock)}catch{}continue}}catch{continue}let jitter=Math.floor(Math.random()*LOCK_POLL_MS);await new Promise((r)=>setTimeout(r,LOCK_POLL_MS+jitter))}console.warn(`[claude-native-teams] Force-acquiring stale lock: ${lock}`),await writeFile2(lock,String(process.pid))}async function releaseLock(path2){try{await unlink2(lockPath(path2))}catch{}}async function loadConfig(teamName){try{let content=await readFile3(configPath(teamName),"utf-8");return JSON.parse(content)}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return null;let message=err instanceof Error?err.message:String(err);return console.warn(`[claude-native-teams] Failed to load config for "${teamName}": ${message}`),null}}async function saveConfig(teamName,config){await writeFile2(configPath(teamName),JSON.stringify(config,null,2))}async function countLeadSessionRefs(){let counts=new Map,teams=await listTeams();for(let team of teams){let leadSessionId=(await loadConfig(team))?.leadSessionId;if(!leadSessionId)continue;counts.set(leadSessionId,(counts.get(leadSessionId)??0)+1)}return counts}async function ensureNativeTeam(teamName,description,leadSessionId,leaderName){let dir=teamDir(teamName),inboxDir=inboxesDir(teamName);await mkdir3(dir,{recursive:!0}),await mkdir3(inboxDir,{recursive:!0}),ensureTeammateBypassPermissions();let existing=await loadConfig(teamName);if(existing)return existing;let sanitized=sanitizeTeamName(teamName),resolvedLeader=sanitizeTeamName(leaderName??teamName),config={name:sanitized,description,createdAt:Date.now(),leadAgentId:`${resolvedLeader}@${sanitized}`,leadSessionId,members:[]};return await saveConfig(teamName,config),config}async function registerNativeMember(teamName,member){let config=await loadConfig(teamName);if(!config)throw Error(`Native team "${teamName}" not found`);let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(member.agentName)}@${sanitized}`;config.members=config.members.filter((m)=>m.agentId!==agentId),config.members.push({agentId,name:sanitizeTeamName(member.agentName),agentType:member.agentType??"general-purpose",joinedAt:Date.now(),tmuxPaneId:member.tmuxPaneId,cwd:member.cwd??process.cwd(),backendType:"tmux",color:member.color,planModeRequired:member.planModeRequired??!1,isActive:!0}),await saveConfig(teamName,config);let inbox=inboxPath(teamName,member.agentName);if(!existsSync14(inbox))await writeFile2(inbox,"[]")}async function unregisterNativeMember(teamName,agentName){let config=await loadConfig(teamName);if(!config)return;let sanitized=sanitizeTeamName(teamName),agentId=`${sanitizeTeamName(agentName)}@${sanitized}`,member=config.members.find((m)=>m.agentId===agentId);if(member)member.isActive=!1;await saveConfig(teamName,config)}async function writeNativeInbox(teamName,agentName,message){let path2=inboxPath(teamName,agentName);await mkdir3(inboxesDir(teamName),{recursive:!0}),await acquireLock(path2);try{let messages2=[];try{let content=await readFile3(path2,"utf-8");messages2=JSON.parse(content)}catch{}messages2.push(message),await writeFile2(path2,JSON.stringify(messages2,null,2))}finally{await releaseLock(path2)}}async function resolveNativeMemberName(teamName,genieWorkerId){let config=await loadConfig(teamName);if(!config||config.members.length===0)return null;let sanitizedId=sanitizeTeamName(genieWorkerId),sanitizedTeam=sanitizeTeamName(teamName),exactMatch=config.members.find((m)=>m.name===sanitizedId&&m.isActive);if(exactMatch)return exactMatch.name;let agentIdMatch=config.members.find((m)=>m.agentId===`${sanitizedId}@${sanitizedTeam}`&&m.isActive);if(agentIdMatch)return agentIdMatch.name;let teamPrefix=`${sanitizedTeam}-`;if(sanitizedId.startsWith(teamPrefix)){let stripped=sanitizedId.slice(teamPrefix.length),prefixMatch=config.members.find((m)=>m.name===stripped&&m.isActive);if(prefixMatch)return prefixMatch.name}let inactiveMatch=config.members.find((m)=>m.name===sanitizedId);if(inactiveMatch)return inactiveMatch.name;return null}async function assignColor(teamName){let config=await loadConfig(teamName);if(!config)return CLAUDE_TEAM_COLORS[0];let usedColors=new Set(config.members.map((m)=>m.color));for(let color of CLAUDE_TEAM_COLORS)if(!usedColors.has(color))return color;return CLAUDE_TEAM_COLORS[config.members.length%CLAUDE_TEAM_COLORS.length]}async function clearNativeInbox(teamName,agentName){let path2=inboxPath(teamName,agentName);await acquireLock(path2);try{await writeFile2(path2,"[]")}finally{await releaseLock(path2)}}async function deleteNativeTeam(teamName){let dir=teamDir(teamName);if(!existsSync14(dir))return!1;return await rm(dir,{recursive:!0,force:!0}),!0}function extractLeaderInboxName(config,teamName){if(!config?.leadAgentId)return teamName??"unknown";let atIdx=config.leadAgentId.indexOf("@");return atIdx>0?config.leadAgentId.slice(0,atIdx):teamName??"unknown"}async function scanTeamInbox(base,name){let config=null;try{let cfgContent=await readFile3(join15(base,name,"config.json"),"utf-8");config=JSON.parse(cfgContent)}catch{}let leaderInboxName=extractLeaderInboxName(config,name),inboxFile=join15(base,name,"inboxes",`${leaderInboxName}.json`),messages2;try{let content=await readFile3(inboxFile,"utf-8");messages2=JSON.parse(content)}catch{return null}if(!Array.isArray(messages2))return null;let unread=messages2.filter((m)=>m.read===!1);if(unread.length===0)return null;let workingDir=null;if(config){let leadMember=config.members.find((m)=>m.agentId===config?.leadAgentId||m.name===leaderInboxName);if(leadMember?.cwd)workingDir=leadMember.cwd}return{teamName:name,unreadCount:unread.length,workingDir,firstUnreadText:unread[0]?.text??null}}async function listTeamsWithUnreadInbox(){let base=teamsBaseDir(),teamDirs;try{teamDirs=await readdir2(base)}catch{return[]}let results=[];for(let name of teamDirs){let entry=await scanTeamInbox(base,name);if(entry)results.push(entry)}return results}function sanitizePath(p){return p.replace(/[^a-zA-Z0-9]/g,"-")}async function discoverClaudeSessionId(cwd){let envSessionId=process.env.CLAUDE_CODE_SESSION_ID;if(envSessionId)return envSessionId;let projectDir=join15(claudeConfigDir2(),"projects",sanitizePath(cwd??process.cwd()));try{let jsonls=(await readdir2(projectDir)).filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let newest=null;for(let name of jsonls){let s=await stat(join15(projectDir,name));if(!newest||s.mtimeMs>newest.mtime)newest={name,mtime:s.mtimeMs}}if(!newest)return null;return newest.name.replace(".jsonl","")}catch{return null}}async function readSessionMetadata(filePath){let handle=null;try{handle=await open(filePath,"r");let buffer2=Buffer.alloc(8192),{bytesRead}=await handle.read(buffer2,0,buffer2.length,0),head=buffer2.toString("utf-8",0,bytesRead);for(let line of head.split(`
337
337
  `).slice(0,20)){let trimmed=line.trim();if(!trimmed)continue;try{let entry=JSON.parse(trimmed),teamName=typeof entry.teamName==="string"?entry.teamName:void 0,agentName=typeof entry.agentName==="string"?entry.agentName:void 0;if(teamName||agentName)return{teamName,agentName}}catch{}}}catch{return{}}finally{await handle?.close().catch(()=>{})}return{}}function rootScore(metadata){if(!metadata.teamName&&!metadata.agentName)return 2;if(metadata.teamName&&!metadata.agentName)return 1;return 0}function compareSessionRanking(a,b2,leadRefs){let aLeadRefs=leadRefs.get(a.name.replace(".jsonl",""))??0,bLeadRefs=leadRefs.get(b2.name.replace(".jsonl",""))??0;if(aLeadRefs!==bLeadRefs)return bLeadRefs-aLeadRefs;let aRoot=rootScore(a.metadata),bRoot=rootScore(b2.metadata);if(aRoot!==bRoot)return bRoot-aRoot;return b2.mtime-a.mtime}async function discoverClaudeParentSessionId(cwd){let envSessionId=process.env.CLAUDE_CODE_SESSION_ID;if(envSessionId)return envSessionId;let projectDir=join15(claudeConfigDir2(),"projects",sanitizePath(cwd??process.cwd()));try{let jsonls=(await readdir2(projectDir)).filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let ranked=await Promise.all(jsonls.map(async(name)=>{let filePath=join15(projectDir,name),s=await stat(filePath),metadata=await readSessionMetadata(filePath);return{name,mtime:s.mtimeMs,metadata}})),leadRefs=await countLeadSessionRefs();return ranked.sort((a,b2)=>compareSessionRanking(a,b2,leadRefs)),ranked[0]?.name.replace(".jsonl","")??null}catch{return null}}function isInsideClaudeCode(){return process.env.CLAUDECODE==="1"}async function discoverTeamName(cwd){let envTeam=process.env.GENIE_TEAM;if(envTeam)return envTeam;let sessionId=await discoverClaudeSessionId(cwd);if(!sessionId)return null;let base=teamsBaseDir();try{let teams=await readdir2(base);for(let name of teams){let cfgPath=join15(base,name,"config.json");try{let content=await readFile3(cfgPath,"utf-8"),config=JSON.parse(content);if(config.leadSessionId===sessionId)return config.name}catch{}}}catch{}return null}async function registerAsTeamLead(teamName,opts){let sessionId=await discoverClaudeSessionId(opts?.cwd);if(!sessionId)throw Error("Could not discover Claude Code session ID. Are you running inside Claude Code with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1?");let resolvedLeaderName=opts?.leaderName??teamName,config=await ensureNativeTeam(teamName,`Genie team: ${teamName}`,sessionId,resolvedLeaderName);if(config.leadSessionId!==sessionId)config.leadSessionId=sessionId,await saveConfig(teamName,config);let sanitized=sanitizeTeamName(teamName),leadAgentId=`${sanitizeTeamName(resolvedLeaderName)}@${sanitized}`,existingLead=config.members.find((m)=>m.agentId===leadAgentId),resolvedPaneId=opts?.tmuxPaneId??process.env.TMUX_PANE;if(!existingLead||!existingLead.isActive)await registerNativeMember(teamName,{agentName:resolvedLeaderName,agentType:"general-purpose",color:opts?.color??"blue",tmuxPaneId:resolvedPaneId,cwd:opts?.cwd??process.cwd()});else if(resolvedPaneId&&existingLead.tmuxPaneId!==resolvedPaneId)existingLead.tmuxPaneId=resolvedPaneId,await saveConfig(teamName,config);let inbox=inboxPath(teamName,resolvedLeaderName);if(!existsSync14(inbox))await writeFile2(inbox,"[]");let finalConfig=await loadConfig(teamName);if(!finalConfig)throw Error(`Failed to load config for team "${teamName}" after creation`);return{sessionId,config:finalConfig}}var LOCK_TIMEOUT_MS=5000,LOCK_POLL_MS=50;var init_claude_native_teams=__esm(()=>{init_claude_settings();init_provider_adapters()});var exports_team_lead_command={};__export(exports_team_lead_command,{shellQuote:()=>shellQuote,sessionExists:()=>sessionExists,ccProjectDirName:()=>ccProjectDirName,buildTeamLeadCommand:()=>buildTeamLeadCommand});import{readFileSync as readFileSync9,readdirSync as readdirSync3}from"fs";import{basename,join as join16}from"path";function shellQuote(s){return`'${s.replace(/'/g,"'\\''")}'`}function buildTeamLeadCommand(teamName,options){let sanitized=sanitizeTeamName(teamName),qTeam=shellQuote(sanitized),folderName=basename(process.cwd()),resolvedLeader=options?.leaderName??teamName,sanitizedLeader=sanitizeTeamName(resolvedLeader),parts=["GENIE_WORKER=1","CLAUDECODE=1","CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1",`GENIE_TEAM=${qTeam}`,`GENIE_AGENT_NAME=${shellQuote(folderName)}`,"claude",`--agent-id ${shellQuote(`${sanitizedLeader}@${sanitized}`)}`,`--agent-name ${shellQuote(sanitizedLeader)}`,`--team-name ${qTeam}`,"--agent-type team-lead","--dangerously-skip-permissions"];if(parts.push(`--name ${shellQuote(sanitized)}`),options?.continueName)parts.push(`--resume ${shellQuote(options.continueName)}`);else if(options?.sessionId)parts.push(`--session-id ${shellQuote(options.sessionId)}`);if(options?.systemPromptFile){let promptFlag=(options?.promptMode??loadGenieConfigSync().promptMode)==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(`${promptFlag} ${shellQuote(options.systemPromptFile)}`)}return parts.join(" ")}function ccProjectDirName(dir){return dir.replace(/\//g,"-")}function fileHasSessionName(filePath,needle){try{let lines=readFileSync9(filePath,"utf-8").split(`
338
338
  `).slice(0,10);for(let line of lines){if(!line.includes("custom-title"))continue;let entry=JSON.parse(line);if(entry.type==="custom-title"&&entry.customTitle?.toLowerCase()===needle)return!0}}catch{}return!1}function sessionExists(name,cwd){try{let home=process.env.HOME??"/root",projectDir=ccProjectDirName(cwd??process.cwd()),projectPath=join16(home,".claude","projects",projectDir),files;try{files=readdirSync3(projectPath).filter((f)=>f.endsWith(".jsonl"))}catch{return!1}let needle=name.toLowerCase();return files.some((file)=>{let full=join16(projectPath,file);return fileHasSessionName(full,needle)||fileHasSessionName(full,`${needle}-${needle}`)})}catch{return!1}}var init_team_lead_command=__esm(()=>{init_claude_native_teams();init_genie_config2()});var exports_tmux_wrapper={};__export(exports_tmux_wrapper,{genieTmuxPrefix:()=>genieTmuxPrefix,genieTmuxCmd:()=>genieTmuxCmd,executeTmux:()=>executeTmux});import{exec as execCallback}from"child_process";import{existsSync as existsSync15,mkdirSync as mkdirSync8}from"fs";import{homedir as homedir15}from"os";import{join as join17}from"path";import{promisify}from"util";function resolveGenieTmuxConf(){let home=homedir15(),genieHome2=process.env.GENIE_HOME??join17(home,".genie");return[join17(genieHome2,"tmux.conf"),join17(__dirname,"..","..","scripts","tmux","genie.tmux.conf"),join17(home,".bun","install","global","node_modules","@automagik","genie","scripts","tmux","genie.tmux.conf")].find((p)=>existsSync15(p))??"/dev/null"}function genieTmuxPrefix(){return["-L",GENIE_TMUX_SOCKET,"-f",resolveGenieTmuxConf()]}function genieTmuxCmd(subcommand){return`${tmuxBin()} ${genieTmuxPrefix().join(" ")} ${subcommand}`}function getLogDir(){let logDir=join17(homedir15(),".genie","logs","tmux");if(!existsSync15(logDir))mkdirSync8(logDir,{recursive:!0});return logDir}function stripVerboseFlags(args){return args.filter((arg)=>!/^-v+$/.test(arg))}function isTmuxDebugEnabled(){return process.env.GENIE_TMUX_DEBUG==="1"}async function executeTmux(args){let argList=typeof args==="string"?args.split(/\s+/).filter(Boolean):args,finalArgs=stripVerboseFlags(argList),debugMode=isTmuxDebugEnabled(),options={};if(debugMode)finalArgs=["-v",...finalArgs],options.cwd=getLogDir();finalArgs=[...genieTmuxPrefix(),...finalArgs];let command=`${tmuxBin()} ${finalArgs.join(" ")}`,{stdout}=await exec(command,options);return stdout.trim()}var __dirname="/home/runner/_work/genie/genie/src/lib",exec,GENIE_TMUX_SOCKET;var init_tmux_wrapper=__esm(()=>{init_ensure_tmux();exec=promisify(execCallback),GENIE_TMUX_SOCKET=process.env.GENIE_TMUX_SOCKET||"genie"});var exports_tmux={};__export(exports_tmux,{setWindowEnv:()=>setWindowEnv,resolveRepoSession:()=>resolveRepoSession,listWindows:()=>listWindows,listPanes:()=>listPanes,killWindow:()=>killWindow,killSession:()=>killSession,isPaneProcessRunning:()=>isPaneProcessRunning,isPaneAlive:()=>isPaneAlive,getWindowEnv:()=>getWindowEnv,getCurrentSessionName:()=>getCurrentSessionName,findWindowByName:()=>findWindowByName,findSessionByName:()=>findSessionByName,executeTmux:()=>executeTmux2,ensureTeamWindow:()=>ensureTeamWindow,createSession:()=>createSession,capturePaneContent:()=>capturePaneContent,applyPaneColor:()=>applyPaneColor,TmuxUnreachableError:()=>TmuxUnreachableError});import{basename as basename2}from"path";async function executeTmux2(tmuxCommand){let{executeTmux:wrapperExec}=await Promise.resolve().then(() => (init_tmux_wrapper(),exports_tmux_wrapper));try{return await wrapperExec(tmuxCommand)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);throw Error(`Failed to execute tmux command: ${message}`)}}async function getCurrentSessionName(hint){if(process.env.TMUX)try{return(await executeTmux2("display-message -p '#{session_name}'")).trim()||null}catch{return null}try{let sessions=await listSessions();if(sessions.length===0)return null;if(hint){let match=sessions.find((s)=>s.name.includes(hint));if(match)return match.name}return sessions[0].name}catch{return null}}async function listSessions(){try{let output=await executeTmux2("list-sessions -F '#{session_id}:#{session_name}:#{?session_attached,1,0}:#{session_windows}'");if(!output)return[];return output.split(`
339
339
  `).map((line)=>{let[id,name,attached,windows]=line.split(":");return{id,name,attached:attached==="1",windows:Number.parseInt(windows,10)}})}catch(error2){if((error2 instanceof Error?error2.message:String(error2)).includes("no server running"))return[];throw error2}}async function findSessionByName(name){try{return(await listSessions()).find((session)=>session.name===name)||null}catch(_error){return null}}async function getWindowEnv(target,varName){try{let output=await executeTmux2(`show-environment -t ${shellQuote(target)} ${shellQuote(varName)}`),prefix=`${varName}=`;if(output?.startsWith(prefix))return output.slice(prefix.length).trim();return null}catch{return null}}async function setWindowEnv(target,varName,value){await executeTmux2(`set-environment -t ${shellQuote(target)} ${shellQuote(varName)} ${shellQuote(value)}`)}async function killSession(sessionId){await executeTmux2(`kill-session -t '${sessionId}'`)}async function listWindows(sessionId){try{let output=await executeTmux2(`list-windows -t '${sessionId}' -F '#{window_id}:#{window_name}:#{window_index}:#{?window_active,1,0}'`);if(!output)return[];return output.split(`
@@ -434,7 +434,7 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
434
434
  `,line.length-start>width&&curr>start)result2+=line.slice(start,curr)+`
435
435
  `+line.slice(curr+1);else result2+=line.slice(start);return result2.slice(1)}function escapeString(string){var result2="",char=0,escapeSeq;for(var i2=0;i2<string.length;char>=65536?i2+=2:i2++)if(char=codePointAt(string,i2),escapeSeq=ESCAPE_SEQUENCES[char],!escapeSeq&&isPrintable(char)){if(result2+=string[i2],char>=65536)result2+=string[i2+1]}else result2+=escapeSeq||encodeHex(char);return result2}function writeFlowSequence(state,level,object){var _result="",_tag=state.tag,index,length,value;for(index=0,length=object.length;index<length;index+=1){if(value=object[index],state.replacer)value=state.replacer.call(object,String(index),value);if(writeNode(state,level,value,!1,!1)||typeof value>"u"&&writeNode(state,level,null,!1,!1)){if(_result!=="")_result+=","+(!state.condenseFlow?" ":"");_result+=state.dump}}state.tag=_tag,state.dump="["+_result+"]"}function writeBlockSequence(state,level,object,compact){var _result="",_tag=state.tag,index,length,value;for(index=0,length=object.length;index<length;index+=1){if(value=object[index],state.replacer)value=state.replacer.call(object,String(index),value);if(writeNode(state,level+1,value,!0,!0,!1,!0)||typeof value>"u"&&writeNode(state,level+1,null,!0,!0,!1,!0)){if(!compact||_result!=="")_result+=generateNextLine(state,level);if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))_result+="-";else _result+="- ";_result+=state.dump}}state.tag=_tag,state.dump=_result||"[]"}function writeFlowMapping(state,level,object){var _result="",_tag=state.tag,objectKeyList=Object.keys(object),index,length,objectKey,objectValue,pairBuffer;for(index=0,length=objectKeyList.length;index<length;index+=1){if(pairBuffer="",_result!=="")pairBuffer+=", ";if(state.condenseFlow)pairBuffer+='"';if(objectKey=objectKeyList[index],objectValue=object[objectKey],state.replacer)objectValue=state.replacer.call(object,objectKey,objectValue);if(!writeNode(state,level,objectKey,!1,!1))continue;if(state.dump.length>1024)pairBuffer+="? ";if(pairBuffer+=state.dump+(state.condenseFlow?'"':"")+":"+(state.condenseFlow?"":" "),!writeNode(state,level,objectValue,!1,!1))continue;pairBuffer+=state.dump,_result+=pairBuffer}state.tag=_tag,state.dump="{"+_result+"}"}function writeBlockMapping(state,level,object,compact){var _result="",_tag=state.tag,objectKeyList=Object.keys(object),index,length,objectKey,objectValue,explicitPair,pairBuffer;if(state.sortKeys===!0)objectKeyList.sort();else if(typeof state.sortKeys==="function")objectKeyList.sort(state.sortKeys);else if(state.sortKeys)throw new exception("sortKeys must be a boolean or a function");for(index=0,length=objectKeyList.length;index<length;index+=1){if(pairBuffer="",!compact||_result!=="")pairBuffer+=generateNextLine(state,level);if(objectKey=objectKeyList[index],objectValue=object[objectKey],state.replacer)objectValue=state.replacer.call(object,objectKey,objectValue);if(!writeNode(state,level+1,objectKey,!0,!0,!0))continue;if(explicitPair=state.tag!==null&&state.tag!=="?"||state.dump&&state.dump.length>1024,explicitPair)if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))pairBuffer+="?";else pairBuffer+="? ";if(pairBuffer+=state.dump,explicitPair)pairBuffer+=generateNextLine(state,level);if(!writeNode(state,level+1,objectValue,!0,explicitPair))continue;if(state.dump&&CHAR_LINE_FEED===state.dump.charCodeAt(0))pairBuffer+=":";else pairBuffer+=": ";pairBuffer+=state.dump,_result+=pairBuffer}state.tag=_tag,state.dump=_result||"{}"}function detectType(state,object,explicit){var _result,typeList,index,length,type2,style;typeList=explicit?state.explicitTypes:state.implicitTypes;for(index=0,length=typeList.length;index<length;index+=1)if(type2=typeList[index],(type2.instanceOf||type2.predicate)&&(!type2.instanceOf||typeof object==="object"&&object instanceof type2.instanceOf)&&(!type2.predicate||type2.predicate(object))){if(explicit)if(type2.multi&&type2.representName)state.tag=type2.representName(object);else state.tag=type2.tag;else state.tag="?";if(type2.represent){if(style=state.styleMap[type2.tag]||type2.defaultStyle,_toString.call(type2.represent)==="[object Function]")_result=type2.represent(object,style);else if(_hasOwnProperty.call(type2.represent,style))_result=type2.represent[style](object,style);else throw new exception("!<"+type2.tag+'> tag resolver accepts not "'+style+'" style');state.dump=_result}return!0}return!1}function writeNode(state,level,object,block,compact,iskey,isblockseq){if(state.tag=null,state.dump=object,!detectType(state,object,!1))detectType(state,object,!0);var type2=_toString.call(state.dump),inblock=block,tagStr;if(block)block=state.flowLevel<0||state.flowLevel>level;var objectOrArray=type2==="[object Object]"||type2==="[object Array]",duplicateIndex,duplicate;if(objectOrArray)duplicateIndex=state.duplicates.indexOf(object),duplicate=duplicateIndex!==-1;if(state.tag!==null&&state.tag!=="?"||duplicate||state.indent!==2&&level>0)compact=!1;if(duplicate&&state.usedDuplicates[duplicateIndex])state.dump="*ref_"+duplicateIndex;else{if(objectOrArray&&duplicate&&!state.usedDuplicates[duplicateIndex])state.usedDuplicates[duplicateIndex]=!0;if(type2==="[object Object]"){if(block&&Object.keys(state.dump).length!==0){if(writeBlockMapping(state,level,state.dump,compact),duplicate)state.dump="&ref_"+duplicateIndex+state.dump}else if(writeFlowMapping(state,level,state.dump),duplicate)state.dump="&ref_"+duplicateIndex+" "+state.dump}else if(type2==="[object Array]"){if(block&&state.dump.length!==0){if(state.noArrayIndent&&!isblockseq&&level>0)writeBlockSequence(state,level-1,state.dump,compact);else writeBlockSequence(state,level,state.dump,compact);if(duplicate)state.dump="&ref_"+duplicateIndex+state.dump}else if(writeFlowSequence(state,level,state.dump),duplicate)state.dump="&ref_"+duplicateIndex+" "+state.dump}else if(type2==="[object String]"){if(state.tag!=="?")writeScalar(state,state.dump,level,iskey,inblock)}else if(type2==="[object Undefined]")return!1;else{if(state.skipInvalid)return!1;throw new exception("unacceptable kind of an object to dump "+type2)}if(state.tag!==null&&state.tag!=="?"){if(tagStr=encodeURI(state.tag[0]==="!"?state.tag.slice(1):state.tag).replace(/!/g,"%21"),state.tag[0]==="!")tagStr="!"+tagStr;else if(tagStr.slice(0,18)==="tag:yaml.org,2002:")tagStr="!!"+tagStr.slice(18);else tagStr="!<"+tagStr+">";state.dump=tagStr+" "+state.dump}}return!0}function getDuplicateReferences(object,state){var objects=[],duplicatesIndexes=[],index,length;inspectNode(object,objects,duplicatesIndexes);for(index=0,length=duplicatesIndexes.length;index<length;index+=1)state.duplicates.push(objects[duplicatesIndexes[index]]);state.usedDuplicates=Array(length)}function inspectNode(object,objects,duplicatesIndexes){var objectKeyList,index,length;if(object!==null&&typeof object==="object")if(index=objects.indexOf(object),index!==-1){if(duplicatesIndexes.indexOf(index)===-1)duplicatesIndexes.push(index)}else if(objects.push(object),Array.isArray(object))for(index=0,length=object.length;index<length;index+=1)inspectNode(object[index],objects,duplicatesIndexes);else{objectKeyList=Object.keys(object);for(index=0,length=objectKeyList.length;index<length;index+=1)inspectNode(object[objectKeyList[index]],objects,duplicatesIndexes)}}function dump$1(input,options){options=options||{};var state=new State(options);if(!state.noRefs)getDuplicateReferences(input,state);var value=input;if(state.replacer)value=state.replacer.call({"":value},"",value);if(writeNode(state,0,value,!0,!0))return state.dump+`
436
436
  `;return""}function renamed(from,to){return function(){throw Error("Function yaml."+from+" is removed in js-yaml 4. Use yaml."+to+" instead, which is now safe by default.")}}var isNothing_1,isObject_1,toArray_1,repeat_1,isNegativeZero_1,extend_1,common2,exception,snippet,TYPE_CONSTRUCTOR_OPTIONS,YAML_NODE_KINDS,type,schema,str,seq,map,failsafe,_null,bool,int,YAML_FLOAT_PATTERN,SCIENTIFIC_WITHOUT_DOT,float,json,core,YAML_DATE_REGEXP,YAML_TIMESTAMP_REGEXP,timestamp,merge,BASE64_MAP=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
437
- \r`,binary,_hasOwnProperty$3,_toString$2,omap,_toString$1,pairs,_hasOwnProperty$2,set,_default,_hasOwnProperty$1,CONTEXT_FLOW_IN=1,CONTEXT_FLOW_OUT=2,CONTEXT_BLOCK_IN=3,CONTEXT_BLOCK_OUT=4,CHOMPING_CLIP=1,CHOMPING_STRIP=2,CHOMPING_KEEP=3,PATTERN_NON_PRINTABLE,PATTERN_NON_ASCII_LINE_BREAKS,PATTERN_FLOW_INDICATORS,PATTERN_TAG_HANDLE,PATTERN_TAG_URI,simpleEscapeCheck,simpleEscapeMap,i,directiveHandlers,loadAll_1,load_1,loader,_toString,_hasOwnProperty,CHAR_BOM=65279,CHAR_TAB=9,CHAR_LINE_FEED=10,CHAR_CARRIAGE_RETURN=13,CHAR_SPACE=32,CHAR_EXCLAMATION=33,CHAR_DOUBLE_QUOTE=34,CHAR_SHARP=35,CHAR_PERCENT=37,CHAR_AMPERSAND=38,CHAR_SINGLE_QUOTE=39,CHAR_ASTERISK=42,CHAR_COMMA=44,CHAR_MINUS=45,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_GREATER_THAN=62,CHAR_QUESTION=63,CHAR_COMMERCIAL_AT=64,CHAR_LEFT_SQUARE_BRACKET=91,CHAR_RIGHT_SQUARE_BRACKET=93,CHAR_GRAVE_ACCENT=96,CHAR_LEFT_CURLY_BRACKET=123,CHAR_VERTICAL_LINE=124,CHAR_RIGHT_CURLY_BRACKET=125,ESCAPE_SEQUENCES,DEPRECATED_BOOLEANS_SYNTAX,DEPRECATED_BASE60_SYNTAX,QUOTING_TYPE_SINGLE=1,QUOTING_TYPE_DOUBLE=2,STYLE_PLAIN=1,STYLE_SINGLE=2,STYLE_LITERAL=3,STYLE_FOLDED=4,STYLE_DOUBLE=5,dump_1,dumper,Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load2,loadAll,dump,YAMLException,types3,safeLoad,safeLoadAll,safeDump,jsYaml;var init_js_yaml=__esm(()=>{/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */isNothing_1=isNothing,isObject_1=isObject,toArray_1=toArray,repeat_1=repeat,isNegativeZero_1=isNegativeZero,extend_1=extend,common2={isNothing:isNothing_1,isObject:isObject_1,toArray:toArray_1,repeat:repeat_1,isNegativeZero:isNegativeZero_1,extend:extend_1};YAMLException$1.prototype=Object.create(Error.prototype);YAMLException$1.prototype.constructor=YAMLException$1;YAMLException$1.prototype.toString=function(compact){return this.name+": "+formatError(this,compact)};exception=YAMLException$1;snippet=makeSnippet,TYPE_CONSTRUCTOR_OPTIONS=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],YAML_NODE_KINDS=["scalar","sequence","mapping"];type=Type$1;Schema$1.prototype.extend=function(definition){var implicit=[],explicit=[];if(definition instanceof type)explicit.push(definition);else if(Array.isArray(definition))explicit=explicit.concat(definition);else if(definition&&(Array.isArray(definition.implicit)||Array.isArray(definition.explicit))){if(definition.implicit)implicit=implicit.concat(definition.implicit);if(definition.explicit)explicit=explicit.concat(definition.explicit)}else throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");implicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(type$1.loadKind&&type$1.loadKind!=="scalar")throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(type$1.multi)throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),explicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var result2=Object.create(Schema$1.prototype);return result2.implicit=(this.implicit||[]).concat(implicit),result2.explicit=(this.explicit||[]).concat(explicit),result2.compiledImplicit=compileList(result2,"implicit"),result2.compiledExplicit=compileList(result2,"explicit"),result2.compiledTypeMap=compileMap(result2.compiledImplicit,result2.compiledExplicit),result2};schema=Schema$1,str=new type("tag:yaml.org,2002:str",{kind:"scalar",construct:function(data){return data!==null?data:""}}),seq=new type("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(data){return data!==null?data:[]}}),map=new type("tag:yaml.org,2002:map",{kind:"mapping",construct:function(data){return data!==null?data:{}}}),failsafe=new schema({explicit:[str,seq,map]});_null=new type("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});bool=new type("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:function(object){return object?"true":"false"},uppercase:function(object){return object?"TRUE":"FALSE"},camelcase:function(object){return object?"True":"False"}},defaultStyle:"lowercase"});int=new type("tag:yaml.org,2002:int",{kind:"scalar",resolve:resolveYamlInteger,construct:constructYamlInteger,predicate:isInteger,represent:{binary:function(obj){return obj>=0?"0b"+obj.toString(2):"-0b"+obj.toString(2).slice(1)},octal:function(obj){return obj>=0?"0o"+obj.toString(8):"-0o"+obj.toString(8).slice(1)},decimal:function(obj){return obj.toString(10)},hexadecimal:function(obj){return obj>=0?"0x"+obj.toString(16).toUpperCase():"-0x"+obj.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),YAML_FLOAT_PATTERN=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");SCIENTIFIC_WITHOUT_DOT=/^[-+]?[0-9]+e/;float=new type("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat,represent:representYamlFloat,defaultStyle:"lowercase"}),json=failsafe.extend({implicit:[_null,bool,int,float]}),core=json,YAML_DATE_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),YAML_TIMESTAMP_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");timestamp=new type("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:resolveYamlTimestamp,construct:constructYamlTimestamp,instanceOf:Date,represent:representYamlTimestamp});merge=new type("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge});binary=new type("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary}),_hasOwnProperty$3=Object.prototype.hasOwnProperty,_toString$2=Object.prototype.toString;omap=new type("tag:yaml.org,2002:omap",{kind:"sequence",resolve:resolveYamlOmap,construct:constructYamlOmap}),_toString$1=Object.prototype.toString;pairs=new type("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:resolveYamlPairs,construct:constructYamlPairs}),_hasOwnProperty$2=Object.prototype.hasOwnProperty;set=new type("tag:yaml.org,2002:set",{kind:"mapping",resolve:resolveYamlSet,construct:constructYamlSet}),_default=core.extend({implicit:[timestamp,merge],explicit:[binary,omap,pairs,set]}),_hasOwnProperty$1=Object.prototype.hasOwnProperty,PATTERN_NON_PRINTABLE=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,PATTERN_NON_ASCII_LINE_BREAKS=/[\x85\u2028\u2029]/,PATTERN_FLOW_INDICATORS=/[,\[\]\{\}]/,PATTERN_TAG_HANDLE=/^(?:!|!!|![a-z\-]+!)$/i,PATTERN_TAG_URI=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;simpleEscapeCheck=Array(256),simpleEscapeMap=Array(256);for(i=0;i<256;i++)simpleEscapeCheck[i]=simpleEscapeSequence(i)?1:0,simpleEscapeMap[i]=simpleEscapeSequence(i);directiveHandlers={YAML:function(state,name,args){var match,major,minor;if(state.version!==null)throwError(state,"duplication of %YAML directive");if(args.length!==1)throwError(state,"YAML directive accepts exactly one argument");if(match=/^([0-9]+)\.([0-9]+)$/.exec(args[0]),match===null)throwError(state,"ill-formed argument of the YAML directive");if(major=parseInt(match[1],10),minor=parseInt(match[2],10),major!==1)throwError(state,"unacceptable YAML version of the document");if(state.version=args[0],state.checkLineBreaks=minor<2,minor!==1&&minor!==2)throwWarning(state,"unsupported YAML version of the document")},TAG:function(state,name,args){var handle,prefix;if(args.length!==2)throwError(state,"TAG directive accepts exactly two arguments");if(handle=args[0],prefix=args[1],!PATTERN_TAG_HANDLE.test(handle))throwError(state,"ill-formed tag handle (first argument) of the TAG directive");if(_hasOwnProperty$1.call(state.tagMap,handle))throwError(state,'there is a previously declared suffix for "'+handle+'" tag handle');if(!PATTERN_TAG_URI.test(prefix))throwError(state,"ill-formed tag prefix (second argument) of the TAG directive");try{prefix=decodeURIComponent(prefix)}catch(err){throwError(state,"tag prefix is malformed: "+prefix)}state.tagMap[handle]=prefix}};loadAll_1=loadAll$1,load_1=load$1,loader={loadAll:loadAll_1,load:load_1},_toString=Object.prototype.toString,_hasOwnProperty=Object.prototype.hasOwnProperty,ESCAPE_SEQUENCES={};ESCAPE_SEQUENCES[0]="\\0";ESCAPE_SEQUENCES[7]="\\a";ESCAPE_SEQUENCES[8]="\\b";ESCAPE_SEQUENCES[9]="\\t";ESCAPE_SEQUENCES[10]="\\n";ESCAPE_SEQUENCES[11]="\\v";ESCAPE_SEQUENCES[12]="\\f";ESCAPE_SEQUENCES[13]="\\r";ESCAPE_SEQUENCES[27]="\\e";ESCAPE_SEQUENCES[34]="\\\"";ESCAPE_SEQUENCES[92]="\\\\";ESCAPE_SEQUENCES[133]="\\N";ESCAPE_SEQUENCES[160]="\\_";ESCAPE_SEQUENCES[8232]="\\L";ESCAPE_SEQUENCES[8233]="\\P";DEPRECATED_BOOLEANS_SYNTAX=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],DEPRECATED_BASE60_SYNTAX=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;dump_1=dump$1,dumper={dump:dump_1};Type=type,Schema=schema,FAILSAFE_SCHEMA=failsafe,JSON_SCHEMA=json,CORE_SCHEMA=core,DEFAULT_SCHEMA=_default,load2=loader.load,loadAll=loader.loadAll,dump=dumper.dump,YAMLException=exception,types3={binary,float,map,null:_null,pairs,set,timestamp,bool,int,merge,omap,seq,str},safeLoad=renamed("safeLoad","load"),safeLoadAll=renamed("safeLoadAll","loadAll"),safeDump=renamed("safeDump","dump"),jsYaml={Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load:load2,loadAll,dump,YAMLException,types:types3,safeLoad,safeLoadAll,safeDump}});var exports_frontmatter={};__export(exports_frontmatter,{parseFrontmatter:()=>parseFrontmatter,AgentFrontmatterSchema:()=>AgentFrontmatterSchema});function extractRawYaml(content){let match=content.match(/^---\n([\s\S]*?)\n---/);if(!match)return null;try{let parsed=load2(match[1]);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function warnUnknownFields(raw){for(let key of Object.keys(raw))if(!knownKeys.has(key))console.warn(`[frontmatter] Unknown field "${key}" \u2014 ignored.`)}function validateFieldByField(raw){let out={};for(let key of knownKeys){let fieldResult=AgentFrontmatterSchema.shape[key].safeParse(raw[key]);if(fieldResult.success){if(fieldResult.data!==void 0)out[key]=fieldResult.data}else if(raw[key]!==void 0)console.warn(`[frontmatter] Invalid value for "${key}": ${JSON.stringify(raw[key])} \u2014 using default.`)}return out}function parseFrontmatter(content){let raw=extractRawYaml(content);if(!raw)return{};warnUnknownFields(raw);let result2=AgentFrontmatterSchema.safeParse(raw);if(result2.success)return result2.data;return validateFieldByField(raw)}var promptModeValues,providerValues,AgentFrontmatterSchema,knownKeys;var init_frontmatter=__esm(()=>{init_js_yaml();init_zod();promptModeValues=["system","append"],providerValues=["claude","codex","claude-sdk"],AgentFrontmatterSchema=exports_external.object({name:exports_external.string().optional(),description:exports_external.string().optional(),model:exports_external.string().optional(),color:exports_external.string().optional(),promptMode:exports_external.enum(promptModeValues).optional(),provider:exports_external.enum(providerValues).optional(),tools:exports_external.array(exports_external.string()).optional(),permissionMode:exports_external.string().optional(),sdk:exports_external.record(exports_external.unknown()).optional()}),knownKeys=new Set(Object.keys(AgentFrontmatterSchema.shape))});import{existsSync as existsSync16,readFileSync as readFileSync10,readdirSync as readdirSync4,realpathSync}from"fs";import{dirname as dirname3,join as join18,resolve as resolve2}from"path";function resolvePackageRoot(){let scriptPath=realpathSync(process.argv[1]||""),candidates=[resolve2(dirname3(scriptPath),".."),resolve2(dirname3(scriptPath),"..",".."),resolve2(dirname3(import.meta.dir??__dirname),"..",".."),resolve2(dirname3(import.meta.dir??__dirname),"..")];for(let candidate of candidates)if(existsSync16(join18(candidate,"plugins","genie","agents")))return candidate;return candidates[0]}function scanAgents(agentsDir){if(!existsSync16(agentsDir))return[];let agents=[],entries;try{entries=readdirSync4(agentsDir,{withFileTypes:!0})}catch{return[]}for(let entry of entries){if(!entry.isDirectory())continue;let agentsPath=join18(agentsDir,entry.name,"AGENTS.md");if(!existsSync16(agentsPath))continue;let content=readFileSync10(agentsPath,"utf-8"),fm=parseFrontmatter(content),name=fm.name||entry.name,isCouncil=name.startsWith("council");agents.push({name,description:fm.description||"",agentPath:agentsPath,model:normalizeValue(fm.model),promptMode:fm.promptMode||void 0,category:isCouncil?"council":"role",color:fm.color})}return agents}function getBuiltin(name){return ALL_BUILTINS.find((a)=>a.name===name)??null}function resolveBuiltinAgentPath(name){return getBuiltin(name)?.agentPath??null}var __dirname="/home/runner/_work/genie/genie/src/lib",AGENTS_DIR,_allAgents,BUILTIN_ROLES,BUILTIN_COUNCIL_MEMBERS,ALL_BUILTINS;var init_builtin_agents=__esm(()=>{init_defaults();init_frontmatter();AGENTS_DIR=join18(resolvePackageRoot(),"plugins","genie","agents"),_allAgents=scanAgents(AGENTS_DIR),BUILTIN_ROLES=_allAgents.filter((a)=>a.category==="role"),BUILTIN_COUNCIL_MEMBERS=_allAgents.filter((a)=>a.category==="council"),ALL_BUILTINS=_allAgents});function ts2(v){if(!v)return new Date().toISOString();return v instanceof Date?v.toISOString():v}function rowToExecutor(r){return{id:r.id,agentId:r.agent_id,provider:r.provider,transport:r.transport,pid:r.pid,tmuxSession:r.tmux_session,tmuxPaneId:r.tmux_pane_id,tmuxWindow:r.tmux_window,tmuxWindowId:r.tmux_window_id,claudeSessionId:r.claude_session_id,state:r.state,metadata:typeof r.metadata==="string"?JSON.parse(r.metadata):r.metadata??{},worktree:r.worktree,repoPath:r.repo_path,paneColor:r.pane_color,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,createdAt:ts2(r.created_at),updatedAt:ts2(r.updated_at)}}function rowToAssignment(r){return{id:r.id,executorId:r.executor_id,taskId:r.task_id,wishSlug:r.wish_slug,groupNumber:r.group_number,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,outcome:r.outcome,createdAt:ts2(r.created_at)}}var exports_executor_registry={};__export(exports_executor_registry,{updateExecutorState:()=>updateExecutorState,updateClaudeSessionId:()=>updateClaudeSessionId,terminateExecutor:()=>terminateExecutor,terminateActiveExecutor:()=>terminateActiveExecutor,relinkExecutorToAgent:()=>relinkExecutorToAgent,listExecutors:()=>listExecutors,getExecutor:()=>getExecutor,getCurrentExecutor:()=>getCurrentExecutor,findLatestByMetadata:()=>findLatestByMetadata,findExecutorBySession:()=>findExecutorBySession,findExecutorByPane:()=>findExecutorByPane,createExecutor:()=>createExecutor,createAndLinkExecutor:()=>createAndLinkExecutor});import{randomUUID as randomUUID3}from"crypto";async function createExecutor(agentId,provider,transport,opts={}){let sql=await getConnection(),id=opts.id??randomUUID3(),now=new Date().toISOString(),rows=await sql`
437
+ \r`,binary,_hasOwnProperty$3,_toString$2,omap,_toString$1,pairs,_hasOwnProperty$2,set,_default,_hasOwnProperty$1,CONTEXT_FLOW_IN=1,CONTEXT_FLOW_OUT=2,CONTEXT_BLOCK_IN=3,CONTEXT_BLOCK_OUT=4,CHOMPING_CLIP=1,CHOMPING_STRIP=2,CHOMPING_KEEP=3,PATTERN_NON_PRINTABLE,PATTERN_NON_ASCII_LINE_BREAKS,PATTERN_FLOW_INDICATORS,PATTERN_TAG_HANDLE,PATTERN_TAG_URI,simpleEscapeCheck,simpleEscapeMap,i,directiveHandlers,loadAll_1,load_1,loader,_toString,_hasOwnProperty,CHAR_BOM=65279,CHAR_TAB=9,CHAR_LINE_FEED=10,CHAR_CARRIAGE_RETURN=13,CHAR_SPACE=32,CHAR_EXCLAMATION=33,CHAR_DOUBLE_QUOTE=34,CHAR_SHARP=35,CHAR_PERCENT=37,CHAR_AMPERSAND=38,CHAR_SINGLE_QUOTE=39,CHAR_ASTERISK=42,CHAR_COMMA=44,CHAR_MINUS=45,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_GREATER_THAN=62,CHAR_QUESTION=63,CHAR_COMMERCIAL_AT=64,CHAR_LEFT_SQUARE_BRACKET=91,CHAR_RIGHT_SQUARE_BRACKET=93,CHAR_GRAVE_ACCENT=96,CHAR_LEFT_CURLY_BRACKET=123,CHAR_VERTICAL_LINE=124,CHAR_RIGHT_CURLY_BRACKET=125,ESCAPE_SEQUENCES,DEPRECATED_BOOLEANS_SYNTAX,DEPRECATED_BASE60_SYNTAX,QUOTING_TYPE_SINGLE=1,QUOTING_TYPE_DOUBLE=2,STYLE_PLAIN=1,STYLE_SINGLE=2,STYLE_LITERAL=3,STYLE_FOLDED=4,STYLE_DOUBLE=5,dump_1,dumper,Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load2,loadAll,dump,YAMLException,types3,safeLoad,safeLoadAll,safeDump,jsYaml;var init_js_yaml=__esm(()=>{/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */isNothing_1=isNothing,isObject_1=isObject,toArray_1=toArray,repeat_1=repeat,isNegativeZero_1=isNegativeZero,extend_1=extend,common2={isNothing:isNothing_1,isObject:isObject_1,toArray:toArray_1,repeat:repeat_1,isNegativeZero:isNegativeZero_1,extend:extend_1};YAMLException$1.prototype=Object.create(Error.prototype);YAMLException$1.prototype.constructor=YAMLException$1;YAMLException$1.prototype.toString=function(compact){return this.name+": "+formatError(this,compact)};exception=YAMLException$1;snippet=makeSnippet,TYPE_CONSTRUCTOR_OPTIONS=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],YAML_NODE_KINDS=["scalar","sequence","mapping"];type=Type$1;Schema$1.prototype.extend=function(definition){var implicit=[],explicit=[];if(definition instanceof type)explicit.push(definition);else if(Array.isArray(definition))explicit=explicit.concat(definition);else if(definition&&(Array.isArray(definition.implicit)||Array.isArray(definition.explicit))){if(definition.implicit)implicit=implicit.concat(definition.implicit);if(definition.explicit)explicit=explicit.concat(definition.explicit)}else throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");implicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(type$1.loadKind&&type$1.loadKind!=="scalar")throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(type$1.multi)throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),explicit.forEach(function(type$1){if(!(type$1 instanceof type))throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var result2=Object.create(Schema$1.prototype);return result2.implicit=(this.implicit||[]).concat(implicit),result2.explicit=(this.explicit||[]).concat(explicit),result2.compiledImplicit=compileList(result2,"implicit"),result2.compiledExplicit=compileList(result2,"explicit"),result2.compiledTypeMap=compileMap(result2.compiledImplicit,result2.compiledExplicit),result2};schema=Schema$1,str=new type("tag:yaml.org,2002:str",{kind:"scalar",construct:function(data){return data!==null?data:""}}),seq=new type("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(data){return data!==null?data:[]}}),map=new type("tag:yaml.org,2002:map",{kind:"mapping",construct:function(data){return data!==null?data:{}}}),failsafe=new schema({explicit:[str,seq,map]});_null=new type("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});bool=new type("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:function(object){return object?"true":"false"},uppercase:function(object){return object?"TRUE":"FALSE"},camelcase:function(object){return object?"True":"False"}},defaultStyle:"lowercase"});int=new type("tag:yaml.org,2002:int",{kind:"scalar",resolve:resolveYamlInteger,construct:constructYamlInteger,predicate:isInteger,represent:{binary:function(obj){return obj>=0?"0b"+obj.toString(2):"-0b"+obj.toString(2).slice(1)},octal:function(obj){return obj>=0?"0o"+obj.toString(8):"-0o"+obj.toString(8).slice(1)},decimal:function(obj){return obj.toString(10)},hexadecimal:function(obj){return obj>=0?"0x"+obj.toString(16).toUpperCase():"-0x"+obj.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),YAML_FLOAT_PATTERN=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");SCIENTIFIC_WITHOUT_DOT=/^[-+]?[0-9]+e/;float=new type("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat,represent:representYamlFloat,defaultStyle:"lowercase"}),json=failsafe.extend({implicit:[_null,bool,int,float]}),core=json,YAML_DATE_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),YAML_TIMESTAMP_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");timestamp=new type("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:resolveYamlTimestamp,construct:constructYamlTimestamp,instanceOf:Date,represent:representYamlTimestamp});merge=new type("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge});binary=new type("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary}),_hasOwnProperty$3=Object.prototype.hasOwnProperty,_toString$2=Object.prototype.toString;omap=new type("tag:yaml.org,2002:omap",{kind:"sequence",resolve:resolveYamlOmap,construct:constructYamlOmap}),_toString$1=Object.prototype.toString;pairs=new type("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:resolveYamlPairs,construct:constructYamlPairs}),_hasOwnProperty$2=Object.prototype.hasOwnProperty;set=new type("tag:yaml.org,2002:set",{kind:"mapping",resolve:resolveYamlSet,construct:constructYamlSet}),_default=core.extend({implicit:[timestamp,merge],explicit:[binary,omap,pairs,set]}),_hasOwnProperty$1=Object.prototype.hasOwnProperty,PATTERN_NON_PRINTABLE=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,PATTERN_NON_ASCII_LINE_BREAKS=/[\x85\u2028\u2029]/,PATTERN_FLOW_INDICATORS=/[,\[\]\{\}]/,PATTERN_TAG_HANDLE=/^(?:!|!!|![a-z\-]+!)$/i,PATTERN_TAG_URI=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;simpleEscapeCheck=Array(256),simpleEscapeMap=Array(256);for(i=0;i<256;i++)simpleEscapeCheck[i]=simpleEscapeSequence(i)?1:0,simpleEscapeMap[i]=simpleEscapeSequence(i);directiveHandlers={YAML:function(state,name,args){var match,major,minor;if(state.version!==null)throwError(state,"duplication of %YAML directive");if(args.length!==1)throwError(state,"YAML directive accepts exactly one argument");if(match=/^([0-9]+)\.([0-9]+)$/.exec(args[0]),match===null)throwError(state,"ill-formed argument of the YAML directive");if(major=parseInt(match[1],10),minor=parseInt(match[2],10),major!==1)throwError(state,"unacceptable YAML version of the document");if(state.version=args[0],state.checkLineBreaks=minor<2,minor!==1&&minor!==2)throwWarning(state,"unsupported YAML version of the document")},TAG:function(state,name,args){var handle,prefix;if(args.length!==2)throwError(state,"TAG directive accepts exactly two arguments");if(handle=args[0],prefix=args[1],!PATTERN_TAG_HANDLE.test(handle))throwError(state,"ill-formed tag handle (first argument) of the TAG directive");if(_hasOwnProperty$1.call(state.tagMap,handle))throwError(state,'there is a previously declared suffix for "'+handle+'" tag handle');if(!PATTERN_TAG_URI.test(prefix))throwError(state,"ill-formed tag prefix (second argument) of the TAG directive");try{prefix=decodeURIComponent(prefix)}catch(err){throwError(state,"tag prefix is malformed: "+prefix)}state.tagMap[handle]=prefix}};loadAll_1=loadAll$1,load_1=load$1,loader={loadAll:loadAll_1,load:load_1},_toString=Object.prototype.toString,_hasOwnProperty=Object.prototype.hasOwnProperty,ESCAPE_SEQUENCES={};ESCAPE_SEQUENCES[0]="\\0";ESCAPE_SEQUENCES[7]="\\a";ESCAPE_SEQUENCES[8]="\\b";ESCAPE_SEQUENCES[9]="\\t";ESCAPE_SEQUENCES[10]="\\n";ESCAPE_SEQUENCES[11]="\\v";ESCAPE_SEQUENCES[12]="\\f";ESCAPE_SEQUENCES[13]="\\r";ESCAPE_SEQUENCES[27]="\\e";ESCAPE_SEQUENCES[34]="\\\"";ESCAPE_SEQUENCES[92]="\\\\";ESCAPE_SEQUENCES[133]="\\N";ESCAPE_SEQUENCES[160]="\\_";ESCAPE_SEQUENCES[8232]="\\L";ESCAPE_SEQUENCES[8233]="\\P";DEPRECATED_BOOLEANS_SYNTAX=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],DEPRECATED_BASE60_SYNTAX=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;dump_1=dump$1,dumper={dump:dump_1};Type=type,Schema=schema,FAILSAFE_SCHEMA=failsafe,JSON_SCHEMA=json,CORE_SCHEMA=core,DEFAULT_SCHEMA=_default,load2=loader.load,loadAll=loader.loadAll,dump=dumper.dump,YAMLException=exception,types3={binary,float,map,null:_null,pairs,set,timestamp,bool,int,merge,omap,seq,str},safeLoad=renamed("safeLoad","load"),safeLoadAll=renamed("safeLoadAll","loadAll"),safeDump=renamed("safeDump","dump"),jsYaml={Type,Schema,FAILSAFE_SCHEMA,JSON_SCHEMA,CORE_SCHEMA,DEFAULT_SCHEMA,load:load2,loadAll,dump,YAMLException,types:types3,safeLoad,safeLoadAll,safeDump}});var exports_frontmatter={};__export(exports_frontmatter,{parseFrontmatter:()=>parseFrontmatter,AgentFrontmatterSchema:()=>AgentFrontmatterSchema});function extractRawYaml(content){let match=content.match(/^---\n([\s\S]*?)\n---/);if(!match)return null;try{let parsed=load2(match[1]);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function warnUnknownFields(raw){for(let key of Object.keys(raw))if(!knownKeys.has(key))console.warn(`[frontmatter] Unknown field "${key}" \u2014 ignored.`)}function validateFieldByField(raw){let out={};for(let key of knownKeys){let fieldResult=AgentFrontmatterSchema.shape[key].safeParse(raw[key]);if(fieldResult.success){if(fieldResult.data!==void 0)out[key]=fieldResult.data}else if(raw[key]!==void 0)console.warn(`[frontmatter] Invalid value for "${key}": ${JSON.stringify(raw[key])} \u2014 using default.`)}return out}function parseFrontmatter(content){let raw=extractRawYaml(content);if(!raw)return{};warnUnknownFields(raw);let result2=AgentFrontmatterSchema.safeParse(raw);if(result2.success)return result2.data;return validateFieldByField(raw)}var promptModeValues,providerValues,AgentFrontmatterSchema,knownKeys;var init_frontmatter=__esm(()=>{init_js_yaml();init_zod();promptModeValues=["system","append"],providerValues=["claude","codex","claude-sdk"],AgentFrontmatterSchema=exports_external.object({name:exports_external.string().optional(),description:exports_external.string().optional(),model:exports_external.string().optional(),color:exports_external.string().optional(),promptMode:exports_external.enum(promptModeValues).optional(),provider:exports_external.enum(providerValues).optional(),tools:exports_external.array(exports_external.string()).optional(),permissionMode:exports_external.string().optional(),disallowedTools:exports_external.array(exports_external.string()).optional(),permissions:exports_external.object({allow:exports_external.array(exports_external.string()).optional(),deny:exports_external.array(exports_external.string()).optional()}).optional(),omniScopes:exports_external.array(exports_external.string()).optional(),hooks:exports_external.record(exports_external.unknown()).optional(),sdk:exports_external.record(exports_external.unknown()).optional()}),knownKeys=new Set(Object.keys(AgentFrontmatterSchema.shape))});import{existsSync as existsSync16,readFileSync as readFileSync10,readdirSync as readdirSync4,realpathSync}from"fs";import{dirname as dirname3,join as join18,resolve as resolve2}from"path";function resolvePackageRoot(){let scriptPath=realpathSync(process.argv[1]||""),candidates=[resolve2(dirname3(scriptPath),".."),resolve2(dirname3(scriptPath),"..",".."),resolve2(dirname3(import.meta.dir??__dirname),"..",".."),resolve2(dirname3(import.meta.dir??__dirname),"..")];for(let candidate of candidates)if(existsSync16(join18(candidate,"plugins","genie","agents")))return candidate;return candidates[0]}function scanAgents(agentsDir){if(!existsSync16(agentsDir))return[];let agents=[],entries;try{entries=readdirSync4(agentsDir,{withFileTypes:!0})}catch{return[]}for(let entry of entries){if(!entry.isDirectory())continue;let agentsPath=join18(agentsDir,entry.name,"AGENTS.md");if(!existsSync16(agentsPath))continue;let content=readFileSync10(agentsPath,"utf-8"),fm=parseFrontmatter(content),name=fm.name||entry.name,isCouncil=name.startsWith("council");agents.push({name,description:fm.description||"",agentPath:agentsPath,model:normalizeValue(fm.model),promptMode:fm.promptMode||void 0,category:isCouncil?"council":"role",color:fm.color})}return agents}function getBuiltin(name){return ALL_BUILTINS.find((a)=>a.name===name)??null}function resolveBuiltinAgentPath(name){return getBuiltin(name)?.agentPath??null}var __dirname="/home/runner/_work/genie/genie/src/lib",AGENTS_DIR,_allAgents,BUILTIN_ROLES,BUILTIN_COUNCIL_MEMBERS,ALL_BUILTINS;var init_builtin_agents=__esm(()=>{init_defaults();init_frontmatter();AGENTS_DIR=join18(resolvePackageRoot(),"plugins","genie","agents"),_allAgents=scanAgents(AGENTS_DIR),BUILTIN_ROLES=_allAgents.filter((a)=>a.category==="role"),BUILTIN_COUNCIL_MEMBERS=_allAgents.filter((a)=>a.category==="council"),ALL_BUILTINS=_allAgents});function ts2(v){if(!v)return new Date().toISOString();return v instanceof Date?v.toISOString():v}function rowToExecutor(r){return{id:r.id,agentId:r.agent_id,provider:r.provider,transport:r.transport,pid:r.pid,tmuxSession:r.tmux_session,tmuxPaneId:r.tmux_pane_id,tmuxWindow:r.tmux_window,tmuxWindowId:r.tmux_window_id,claudeSessionId:r.claude_session_id,state:r.state,metadata:typeof r.metadata==="string"?JSON.parse(r.metadata):r.metadata??{},worktree:r.worktree,repoPath:r.repo_path,paneColor:r.pane_color,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,createdAt:ts2(r.created_at),updatedAt:ts2(r.updated_at)}}function rowToAssignment(r){return{id:r.id,executorId:r.executor_id,taskId:r.task_id,wishSlug:r.wish_slug,groupNumber:r.group_number,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,outcome:r.outcome,createdAt:ts2(r.created_at)}}var exports_executor_registry={};__export(exports_executor_registry,{updateExecutorState:()=>updateExecutorState,updateClaudeSessionId:()=>updateClaudeSessionId,terminateExecutor:()=>terminateExecutor,terminateActiveExecutor:()=>terminateActiveExecutor,relinkExecutorToAgent:()=>relinkExecutorToAgent,listExecutors:()=>listExecutors,getExecutor:()=>getExecutor,getCurrentExecutor:()=>getCurrentExecutor,findLatestByMetadata:()=>findLatestByMetadata,findExecutorBySession:()=>findExecutorBySession,findExecutorByPane:()=>findExecutorByPane,createExecutor:()=>createExecutor,createAndLinkExecutor:()=>createAndLinkExecutor});import{randomUUID as randomUUID3}from"crypto";async function createExecutor(agentId,provider,transport,opts={}){let sql=await getConnection(),id=opts.id??randomUUID3(),now=new Date().toISOString(),rows=await sql`
438
438
  INSERT INTO executors (
439
439
  id, agent_id, provider, transport, pid,
440
440
  tmux_session, tmux_pane_id, tmux_window, tmux_window_id,
@@ -573,7 +573,7 @@ ${body}`;writeFileSync9(filePath,output,"utf-8")}function serializeSdkConfig(sdk
573
573
  UPDATE agents
574
574
  SET metadata = metadata || ${sql.json(metadataPatch)}
575
575
  WHERE role = ${name}
576
- `}catch{}return updated}function loadIdentity(entry){if(!entry.dir)return null;let agentsPath=join20(entry.dir,"AGENTS.md");if(existsSync18(agentsPath))return agentsPath;return null}function builtinToEntry(agent){return{name:agent.name,dir:"",promptMode:agent.promptMode??"append",model:agent.model,roles:[],registeredAt:"(built-in)"}}function roleToEntry(role,team,metadata){if(!(metadata&&Object.keys(metadata).length>0)){let builtin=[...BUILTIN_ROLES,...BUILTIN_COUNCIL_MEMBERS].find((b2)=>b2.name===role);if(builtin)return builtinToEntry(builtin)}return{name:role,dir:metadata?.dir||"",promptMode:metadata?.promptMode||"append",model:metadata?.model,roles:[],registeredAt:new Date().toISOString(),description:metadata?.description,color:metadata?.color,provider:metadata?.provider,permissions:metadata?.permissions,sdk:metadata?.sdk,...metadata?.repo?{repo:metadata.repo}:team?{repo:team}:{}}}function buildMetadata(entry){let meta={};if(entry.dir)meta.dir=entry.dir;if(entry.repo)meta.repo=entry.repo;if(entry.model)meta.model=entry.model;if(entry.promptMode&&entry.promptMode!=="append")meta.promptMode=entry.promptMode;if(entry.description)meta.description=entry.description;if(entry.color)meta.color=entry.color;if(entry.provider)meta.provider=entry.provider;if(entry.permissions)meta.permissions=entry.permissions;if(entry.sdk)meta.sdk=entry.sdk;return meta}function parseMetadata(raw){if(!raw)return{};if(typeof raw==="object"&&!Array.isArray(raw))return raw;if(typeof raw==="string")try{return JSON.parse(raw)}catch{return{}}return{}}function syncFrontmatterToDisk(entry,updates){try{if(!entry.dir)return;let agentsPath=join20(entry.dir,"AGENTS.md");if(!existsSync18(agentsPath))return;if(!Object.keys(updates).some((k)=>FRONTMATTER_KEYS.has(k)))return;let fmUpdates={};if(updates.model!==void 0)fmUpdates.model=updates.model;if(updates.description!==void 0)fmUpdates.description=updates.description;if(updates.color!==void 0)fmUpdates.color=updates.color;if(updates.promptMode!==void 0)fmUpdates.promptMode=updates.promptMode;if(updates.provider!==void 0)fmUpdates.provider=updates.provider;if(updates.sdk!==void 0)fmUpdates.sdk=serializeSdkConfig(updates.sdk);if(Object.keys(fmUpdates).length===0)return;writeFrontmatter(agentsPath,fmUpdates)}catch{}}var FRONTMATTER_KEYS;var init_agent_directory=__esm(()=>{init_builtin_agents();init_frontmatter_writer();FRONTMATTER_KEYS=new Set(["name","description","model","color","promptMode","provider","sdk"])});var exports_runtime_events={};__export(exports_runtime_events,{waitForRuntimeEvent:()=>waitForRuntimeEvent,publishSubjectEvent:()=>publishSubjectEvent,publishRuntimeEvent:()=>publishRuntimeEvent,listRuntimeEvents:()=>listRuntimeEvents,getLatestRuntimeEventId:()=>getLatestRuntimeEventId,getEventMetrics:()=>getEventMetrics,followRuntimeEvents:()=>followRuntimeEvents});class EventCircuitBreaker{failures=0;lastFailure=0;loggedOpen=!1;threshold=5;cooldown=30000;isOpen(){if(this.failures<this.threshold)return!1;if(Date.now()-this.lastFailure>this.cooldown)return this.failures=0,!1;return!0}recordSuccess(){if(this.failures>=this.threshold)console.warn("[runtime-events] circuit breaker closed \u2014 PG writes resumed");this.failures=0,this.loggedOpen=!1}recordFailure(){if(this.failures++,this.lastFailure=Date.now(),this.failures>=this.threshold&&!this.loggedOpen)console.warn(`[runtime-events] circuit breaker open \u2014 skipping PG writes for ${this.cooldown/1000}s after ${this.threshold} consecutive failures`),this.loggedOpen=!0}get state(){if(this.failures<this.threshold)return"closed";if(Date.now()-this.lastFailure>this.cooldown)return"half-open";return"open"}}function getEventMetrics(){return{eventsEmitted,eventsFailed,lastEmitDuration,circuitState:circuitBreaker.state}}function logFollowDrainError(context,error2,active){if(!active)return;let message=error2 instanceof Error?error2.message:String(error2);console.error(`[runtime-events] ${context} drain failed: ${message}`)}function rowToRuntimeEvent(row){return{id:Number(row.id),repoPath:row.repo_path,timestamp:row.created_at instanceof Date?row.created_at.toISOString():String(row.created_at),kind:row.kind,agent:row.agent,team:row.team??void 0,direction:row.direction??void 0,peer:row.peer??void 0,text:row.text,data:row.data??void 0,source:row.source,subject:row.subject??void 0,threadId:row.thread_id??void 0,traceId:row.trace_id??void 0,parentEventId:row.parent_event_id!=null?Number(row.parent_event_id):void 0}}function nextParam(values2,value){return values2.push(value),`$${values2.length}`}function buildScopeClause(query,values2){let scopeClauses=[];if(query.agentIds&&query.agentIds.length>0)scopeClauses.push(`agent = ANY(${nextParam(values2,query.agentIds)})`);if(query.team)scopeClauses.push(`team = ${nextParam(values2,query.team)}`);if(query.teamPrefix)scopeClauses.push(`team LIKE ${nextParam(values2,`${query.teamPrefix}%`)}`);if(scopeClauses.length===0)return null;if(scopeClauses.length===1)return scopeClauses[0];if(query.scopeMode==="any")return`(${scopeClauses.join(" OR ")})`;return`(${scopeClauses.join(" AND ")})`}function buildWhere(query){let values2=[],clauses=[];if(query.afterId!=null)clauses.push(`id > ${nextParam(values2,query.afterId)}`);if(query.repoPath)clauses.push(`repo_path = ${nextParam(values2,query.repoPath)}`);if(query.subject)clauses.push(`subject = ${nextParam(values2,query.subject)}`);if(query.kinds&&query.kinds.length>0)clauses.push(`kind = ANY(${nextParam(values2,query.kinds)})`);if(query.since)clauses.push(`created_at >= ${nextParam(values2,query.since)}`);if(query.threadId)clauses.push(`thread_id = ${nextParam(values2,query.threadId)}`);if(query.traceId)clauses.push(`trace_id = ${nextParam(values2,query.traceId)}`);let scopeClause=buildScopeClause(query,values2);if(scopeClause)clauses.push(scopeClause);return{clause:clauses.length>0?`WHERE ${clauses.join(" AND ")}`:"",values:values2}}async function publishRuntimeEvent(input){if(circuitBreaker.isOpen())throw eventsFailed++,Error("circuit breaker open \u2014 PG event write skipped");let start=Date.now();try{let sql=await getConnection(),threadId=input.threadId??`agent:${input.agent}`,rows=await sql`
576
+ `}catch{}return updated}function loadIdentity(entry){if(!entry.dir)return null;let agentsPath=join20(entry.dir,"AGENTS.md");if(existsSync18(agentsPath))return agentsPath;return null}function builtinToEntry(agent){return{name:agent.name,dir:"",promptMode:agent.promptMode??"append",model:agent.model,roles:[],registeredAt:"(built-in)"}}function roleToEntry(role,team,metadata){if(!(metadata&&Object.keys(metadata).length>0)){let builtin=[...BUILTIN_ROLES,...BUILTIN_COUNCIL_MEMBERS].find((b2)=>b2.name===role);if(builtin)return builtinToEntry(builtin)}return{name:role,dir:metadata?.dir||"",promptMode:metadata?.promptMode||"append",model:metadata?.model,roles:[],registeredAt:new Date().toISOString(),description:metadata?.description,color:metadata?.color,provider:metadata?.provider,permissions:metadata?.permissions,disallowedTools:metadata?.disallowedTools,omniScopes:metadata?.omniScopes,hooks:metadata?.hooks,sdk:metadata?.sdk,...metadata?.repo?{repo:metadata.repo}:team?{repo:team}:{}}}function buildMetadata(entry){let meta={};if(entry.dir)meta.dir=entry.dir;if(entry.repo)meta.repo=entry.repo;if(entry.model)meta.model=entry.model;if(entry.promptMode&&entry.promptMode!=="append")meta.promptMode=entry.promptMode;if(entry.description)meta.description=entry.description;if(entry.color)meta.color=entry.color;if(entry.provider)meta.provider=entry.provider;if(entry.permissions)meta.permissions=entry.permissions;if(entry.disallowedTools)meta.disallowedTools=entry.disallowedTools;if(entry.omniScopes)meta.omniScopes=entry.omniScopes;if(entry.hooks)meta.hooks=entry.hooks;if(entry.sdk)meta.sdk=entry.sdk;return meta}function parseMetadata(raw){if(!raw)return{};if(typeof raw==="object"&&!Array.isArray(raw))return raw;if(typeof raw==="string")try{return JSON.parse(raw)}catch{return{}}return{}}function syncFrontmatterToDisk(entry,updates){try{if(!entry.dir)return;let agentsPath=join20(entry.dir,"AGENTS.md");if(!existsSync18(agentsPath))return;if(!Object.keys(updates).some((k)=>FRONTMATTER_KEYS.has(k)))return;let fmUpdates={};if(updates.model!==void 0)fmUpdates.model=updates.model;if(updates.description!==void 0)fmUpdates.description=updates.description;if(updates.color!==void 0)fmUpdates.color=updates.color;if(updates.promptMode!==void 0)fmUpdates.promptMode=updates.promptMode;if(updates.provider!==void 0)fmUpdates.provider=updates.provider;if(updates.sdk!==void 0)fmUpdates.sdk=serializeSdkConfig(updates.sdk);if(Object.keys(fmUpdates).length===0)return;writeFrontmatter(agentsPath,fmUpdates)}catch{}}var FRONTMATTER_KEYS;var init_agent_directory=__esm(()=>{init_builtin_agents();init_frontmatter_writer();FRONTMATTER_KEYS=new Set(["name","description","model","color","promptMode","provider","sdk"])});var exports_runtime_events={};__export(exports_runtime_events,{waitForRuntimeEvent:()=>waitForRuntimeEvent,publishSubjectEvent:()=>publishSubjectEvent,publishRuntimeEvent:()=>publishRuntimeEvent,listRuntimeEvents:()=>listRuntimeEvents,getLatestRuntimeEventId:()=>getLatestRuntimeEventId,getEventMetrics:()=>getEventMetrics,followRuntimeEvents:()=>followRuntimeEvents});class EventCircuitBreaker{failures=0;lastFailure=0;loggedOpen=!1;threshold=5;cooldown=30000;isOpen(){if(this.failures<this.threshold)return!1;if(Date.now()-this.lastFailure>this.cooldown)return this.failures=0,!1;return!0}recordSuccess(){if(this.failures>=this.threshold)console.warn("[runtime-events] circuit breaker closed \u2014 PG writes resumed");this.failures=0,this.loggedOpen=!1}recordFailure(){if(this.failures++,this.lastFailure=Date.now(),this.failures>=this.threshold&&!this.loggedOpen)console.warn(`[runtime-events] circuit breaker open \u2014 skipping PG writes for ${this.cooldown/1000}s after ${this.threshold} consecutive failures`),this.loggedOpen=!0}get state(){if(this.failures<this.threshold)return"closed";if(Date.now()-this.lastFailure>this.cooldown)return"half-open";return"open"}}function getEventMetrics(){return{eventsEmitted,eventsFailed,lastEmitDuration,circuitState:circuitBreaker.state}}function logFollowDrainError(context,error2,active){if(!active)return;let message=error2 instanceof Error?error2.message:String(error2);console.error(`[runtime-events] ${context} drain failed: ${message}`)}function rowToRuntimeEvent(row){return{id:Number(row.id),repoPath:row.repo_path,timestamp:row.created_at instanceof Date?row.created_at.toISOString():String(row.created_at),kind:row.kind,agent:row.agent,team:row.team??void 0,direction:row.direction??void 0,peer:row.peer??void 0,text:row.text,data:row.data??void 0,source:row.source,subject:row.subject??void 0,threadId:row.thread_id??void 0,traceId:row.trace_id??void 0,parentEventId:row.parent_event_id!=null?Number(row.parent_event_id):void 0}}function nextParam(values2,value){return values2.push(value),`$${values2.length}`}function buildScopeClause(query,values2){let scopeClauses=[];if(query.agentIds&&query.agentIds.length>0)scopeClauses.push(`agent = ANY(${nextParam(values2,query.agentIds)})`);if(query.team)scopeClauses.push(`team = ${nextParam(values2,query.team)}`);if(query.teamPrefix)scopeClauses.push(`team LIKE ${nextParam(values2,`${query.teamPrefix}%`)}`);if(scopeClauses.length===0)return null;if(scopeClauses.length===1)return scopeClauses[0];if(query.scopeMode==="any")return`(${scopeClauses.join(" OR ")})`;return`(${scopeClauses.join(" AND ")})`}function buildWhere(query){let values2=[],clauses=[];if(query.afterId!=null)clauses.push(`id > ${nextParam(values2,query.afterId)}`);if(query.repoPath)clauses.push(`repo_path = ${nextParam(values2,query.repoPath)}`);if(query.subject)clauses.push(`subject = ${nextParam(values2,query.subject)}`);if(query.kinds&&query.kinds.length>0)clauses.push(`kind = ANY(${nextParam(values2,query.kinds)})`);if(query.since)clauses.push(`created_at >= ${nextParam(values2,query.since)}`);if(query.threadId)clauses.push(`thread_id = ${nextParam(values2,query.threadId)}`);if(query.traceId)clauses.push(`trace_id = ${nextParam(values2,query.traceId)}`);let scopeClause=buildScopeClause(query,values2);if(scopeClause)clauses.push(scopeClause);return{clause:clauses.length>0?`WHERE ${clauses.join(" AND ")}`:"",values:values2}}async function publishRuntimeEvent(input){if(circuitBreaker.isOpen())throw eventsFailed++,Error("circuit breaker open \u2014 PG event write skipped");let start=Date.now();try{let sql=await getConnection(),threadId=input.threadId??`agent:${input.agent}`,rows=await sql`
577
577
  INSERT INTO genie_runtime_events (
578
578
  repo_path, subject, kind, source, agent, team, direction, peer, text, data, thread_id, trace_id, parent_event_id, created_at
579
579
  )
@@ -705,7 +705,7 @@ Run 'genie agent list' to list agents.`)}async function resolveTarget(target,opt
705
705
  LIMIT 100
706
706
  `).map((r)=>({id:r.id,requestType:r.request_type,senderId:r.sender_id,body:r.body,createdAt:r.created_at instanceof Date?r.created_at.toISOString():String(r.created_at)}))}async function generateBrief(options){let teamConfig=await getTeam(options.team);if(!teamConfig)throw Error(`Team not found: ${options.team}`);let since=await resolveSince(options),repoPath=options.repoPath??teamConfig.repo,agentName=options.agent??teamConfig.leader??null,agentIdentifiers=agentName?[agentName]:[],[unreadMessages,taskMessages,recentEvents,pendingRequests,teamRoster]=await Promise.all([agentIdentifiers.length>0?getUnread(repoPath,agentIdentifiers):Promise.resolve([]),getTaskMessages(options.team,since),listRuntimeEvents({team:options.team,since,limit:100}),getPendingRequestMessages(options.team),getTeamRoster(options.team)]);return{team:options.team,agent:agentName,since,unreadMessages,taskMessages,recentEvents,pendingRequests,teamRoster}}function truncate(text,max){return text.length>max?`${text.slice(0,max)}...`:text}function formatUnreadSection(messages2){if(messages2.length===0)return[];let lines=[`## Unread Messages (${messages2.length})`];for(let msg of messages2)lines.push(`- **${msg.from}**: ${truncate(msg.body,120)}`);return lines.push(""),lines}function formatTaskMessagesSection(messages2){if(messages2.length===0)return[];let lines=[`## Task Updates (${messages2.length})`],byTask=new Map;for(let msg of messages2){let existing=byTask.get(msg.taskId)??[];existing.push(msg),byTask.set(msg.taskId,existing)}for(let[taskId,msgs]of byTask){lines.push(`### ${taskId}: ${msgs[0].taskTitle}`);for(let msg of msgs)lines.push(`- [${msg.senderType}:${msg.senderId}] ${truncate(msg.body,100)}`)}return lines.push(""),lines}function formatRequestsSection(requests){if(requests.length===0)return[];let lines=[`## Pending Requests (${requests.length})`];for(let req of requests)lines.push(`- [${req.requestType}] ${req.senderId}: ${truncate(req.body,80)}`);return lines.push(""),lines}function formatRosterSection(roster){if(roster.length===0)return[];let lines=[`## Team Roster (${roster.length})`];for(let member of roster){let state=member.executorState??"offline",icon=STATE_ICONS[state]??"\u25CC";lines.push(`- ${icon} **${member.agentId}** (${member.role??"unassigned"}): ${state}`)}return lines.push(""),lines}function formatEventsSection(events){if(events.length===0)return[];let lines=[`## Recent Events (${events.length})`],tail=events.slice(-10);for(let evt of tail){let ts3=evt.timestamp.slice(11,16);lines.push(`- ${ts3} [${evt.kind}] ${evt.agent}: ${truncate(evt.text,80)}`)}if(events.length>10)lines.push(` _(${events.length-10} more events)_`);return lines.push(""),lines}function formatBrief(brief){let lines=[`# BRIEF \u2014 ${brief.team}${brief.agent?` ${brief.agent}`:""}`,`Since: ${brief.since}`,"",...formatUnreadSection(brief.unreadMessages),...formatTaskMessagesSection(brief.taskMessages),...formatRequestsSection(brief.pendingRequests),...formatRosterSection(brief.teamRoster),...formatEventsSection(brief.recentEvents)];if(!(brief.unreadMessages.length+brief.taskMessages.length+brief.pendingRequests.length+brief.recentEvents.length>0))lines.push("_No activity since last session._","");return lines.join(`
707
707
  `)}var STATE_ICONS;var init_brief=__esm(()=>{init_db();init_mailbox();init_runtime_events();init_team_manager();STATE_ICONS={working:"\u25CF",idle:"\u25CB",error:"\u2718"}});var exports_agent_sync={};__export(exports_agent_sync,{watchAgentDirectory:()=>watchAgentDirectory,syncAgentDirectory:()=>syncAgentDirectory,printSyncResult:()=>printSyncResult,healAgentFile:()=>healAgentFile});import{execSync as execSync6}from"child_process";import{existsSync as existsSync22,watch as fsWatch,readFileSync as readFileSync14,readdirSync as readdirSync6,realpathSync as realpathSync3,writeFileSync as writeFileSync11}from"fs";import{join as join24}from"path";function getGitRemoteUrl(dir){try{return execSync6(`git -C "${dir}" config --get remote.origin.url`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function extractOrgRepo(remoteUrl){let sshMatch=remoteUrl.match(/[^/:]+\/[^/]+?(?:\.git)?$/);if(sshMatch)return sshMatch[0].replace(/\.git$/,"");return null}function getRepoPathForAgent(agentDir){let reposLink=join24(agentDir,"repos");try{if(!existsSync22(reposLink))return null;let target=realpathSync3(reposLink);if(!existsSync22(target))return null;return target}catch{return null}}function discoverAgents(workspaceRoot){let agentsDir=join24(workspaceRoot,"agents");if(!existsSync22(agentsDir))return[];let agents=[];try{let entries=readdirSync6(agentsDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isDirectory())continue;let agentDir=join24(agentsDir,entry.name);if(!existsSync22(join24(agentDir,"AGENTS.md")))continue;agents.push({name:entry.name,dir:agentDir,repoUrl:getGitRemoteUrl(agentDir),productRepo:getRepoPathForAgent(agentDir)}),discoverSubAgents(agentDir,entry.name,agents)}}catch{}return agents}function discoverSubAgents(parentDir,parentName,agents){let subAgentsDir=join24(parentDir,".genie","agents");if(!existsSync22(subAgentsDir))return;try{let entries=readdirSync6(subAgentsDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isDirectory())continue;let subDir=join24(subAgentsDir,entry.name);if(!existsSync22(join24(subDir,"AGENTS.md")))continue;agents.push({name:`${parentName}/${entry.name}`,dir:subDir,repoUrl:getGitRemoteUrl(parentDir),productRepo:getRepoPathForAgent(parentDir)})}}catch{}}function discoverSingleAgent(workspaceRoot,agentName){let agentDir=join24(workspaceRoot,"agents",agentName);if(!existsSync22(join24(agentDir,"AGENTS.md")))return null;return{name:agentName,dir:agentDir,repoUrl:getGitRemoteUrl(agentDir),productRepo:getRepoPathForAgent(agentDir)}}function healAgentFile(agentsMdPath,agentName,healResult){let content=readFileSync14(agentsMdPath,"utf-8"),fmMatch=content.match(/^(---\n)([\s\S]*?)(\n---)/);if(!fmMatch)return!1;let prefix=fmMatch[1],fmBlock=fmMatch[2],suffix=fmMatch[3],rest=content.slice(fmMatch[0].length),modified=!1,healedBlock=fmBlock;for(let{field,value}of INVALID_LITERALS)if(new RegExp(`^${field}:\\s*${value}\\s*$`,"m").test(healedBlock))healedBlock=healedBlock.replace(new RegExp(`${field}:\\s*${value}\\s*\\n?`,"m"),""),healResult.healed.push({agent:agentName,field,value}),modified=!0;if(!modified)return!1;let newContent=prefix+healedBlock+suffix+rest,tmpPath=`${agentsMdPath}.tmp.${Date.now()}`;writeFileSync11(tmpPath,newContent,"utf-8");let{renameSync:renameSync2}=__require("fs");return renameSync2(tmpPath,agentsMdPath),!0}function buildResolveContext(workspaceRoot,agentName){let workspaceDefaults;try{workspaceDefaults=getWorkspaceConfig(workspaceRoot).agents?.defaults}catch{}let parent;if(agentName.includes("/")){let parentName=agentName.split("/")[0],parentAgentsMd=join24(workspaceRoot,"agents",parentName,"AGENTS.md");if(existsSync22(parentAgentsMd)){let parentContent=readFileSync14(parentAgentsMd,"utf-8"),parentFm=parseFrontmatter(parentContent);parent={name:parentName,fields:parentFm}}}return{workspaceDefaults,parent}}function computeResolvedMetadata(fm,ctx){let declared={},resolved={};for(let field of Object.keys(BUILTIN_DEFAULTS)){let fmValue=fm[field];if(fmValue!==void 0&&fmValue!==null&&fmValue!==""&&fmValue!=="inherit")declared[field]=fmValue;let result2=resolveFieldWithSource(fm,field,ctx);resolved[field]={value:result2.value,source:result2.source}}return{declared,resolved}}async function syncAgentDirectory(workspaceRoot){let result2={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],healed:[],errors:[]},agents=discoverAgents(workspaceRoot),discoveredNames=new Set(agents.map((a)=>a.name)),healResult={healed:[]};for(let agent of agents){let agentsMdPath=join24(agent.dir,"AGENTS.md");try{healAgentFile(agentsMdPath,agent.name,healResult)}catch{}}result2.healed=healResult.healed;for(let h of healResult.healed)console.log(`[sync] healed ${h.agent}/AGENTS.md: removed invalid '${h.field}: ${h.value}' line`);for(let agent of agents)try{await syncSingleAgent(agent,result2,workspaceRoot)}catch(err){result2.errors.push({name:agent.name,error:err instanceof Error?err.message:String(err)})}return await removeMissingAgents(discoveredNames,result2),result2}function printSyncResult(result2){if(result2.healed.length>0)console.log(` Healed: ${result2.healed.length} invalid literal(s) removed`);if(result2.registered.length>0)console.log(` Registered: ${result2.registered.join(", ")}`);if(result2.updated.length>0)console.log(` Updated: ${result2.updated.join(", ")}`);if(result2.reactivated.length>0)console.log(` Reactivated: ${result2.reactivated.join(", ")}`);if(result2.archived.length>0)console.log(` Removed: ${result2.archived.join(", ")}`);if(result2.unchanged.length>0)console.log(` Unchanged: ${result2.unchanged.join(", ")}`);for(let err of result2.errors)console.error(` Error (${err.name}): ${err.error}`);let total=result2.registered.length+result2.updated.length+result2.unchanged.length+result2.reactivated.length;console.log(`
708
- Sync complete: ${total} active agent(s), ${result2.archived.length} removed.`)}async function removeMissingAgents(discoveredNames,result2){try{let entries=await ls();for(let entry of entries){if(discoveredNames.has(entry.name))continue;if(entry.scope==="built-in")continue;if(!entry.dir||!entry.dir.includes("/agents/"))continue;if(await rm3(entry.name))result2.archived.push(entry.name)}}catch{}}async function syncSingleAgent(agent,result2,workspaceRoot){let repoPath=(agent.repoUrl?extractOrgRepo(agent.repoUrl):null)??agent.repoUrl??agent.dir,agentsMdPath=join24(agent.dir,"AGENTS.md"),content=readFileSync14(agentsMdPath,"utf-8"),fm=parseFrontmatter(content),_resolvedMeta;if(workspaceRoot){let ctx=buildResolveContext(workspaceRoot,agent.name);_resolvedMeta=computeResolvedMetadata(fm,ctx)}let resolved=await resolve3(agent.name),existing=resolved&&!resolved.builtin?resolved.entry:null,sdkConfig=fm.sdk;if(!existing){await add({name:agent.name,dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,sdk:sdkConfig}),result2.registered.push(agent.name);return}let identityUpdate={dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,sdk:sdkConfig};if(JSON.stringify(existing.sdk)!==JSON.stringify(sdkConfig)||existing.repo!==repoPath||existing.dir!==agent.dir||existing.promptMode!==(fm.promptMode??"append")||existing.model!==fm.model||existing.description!==fm.description||existing.color!==fm.color||existing.provider!==fm.provider)await edit(agent.name,identityUpdate),result2.updated.push(agent.name);else result2.unchanged.push(agent.name)}async function syncSingleAgentByName(workspaceRoot,agentName){let agent=discoverSingleAgent(workspaceRoot,agentName);if(!agent)return"not-found";let result2={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],healed:[],errors:[]};if(await syncSingleAgent(agent,result2,workspaceRoot),result2.registered.length>0)return"registered";if(result2.updated.length>0)return"updated";return"unchanged"}function watchAgentDirectory(workspaceRoot,options){let agentsDir=join24(workspaceRoot,"agents");if(!existsSync22(agentsDir))return null;let debounceTimer=null,pendingChanges=new Set,processChanges=async()=>{let names=[...pendingChanges];pendingChanges.clear();for(let name of names)try{let action=await processWatchedAgent(workspaceRoot,agentsDir,name);if(action)options?.onSync?.(name,action)}catch{}},watcher=fsWatch(agentsDir,{persistent:!1},(_event,filename)=>{if(!filename)return;let name=filename.split("/")[0];if(!name||name.startsWith("."))return;if(pendingChanges.add(name),debounceTimer)clearTimeout(debounceTimer);debounceTimer=setTimeout(processChanges,2000)});return{close:()=>{if(debounceTimer)clearTimeout(debounceTimer);watcher.close()}}}async function processWatchedAgent(workspaceRoot,agentsDir,name){let agentDir=join24(agentsDir,name);if(existsSync22(agentDir)&&existsSync22(join24(agentDir,"AGENTS.md"))){let action=await syncSingleAgentByName(workspaceRoot,name);return action!=="unchanged"&&action!=="not-found"?action:null}if(!existsSync22(agentDir)){if(await rm3(name))return"removed"}return null}var INVALID_LITERALS;var init_agent_sync=__esm(()=>{init_agent_directory();init_defaults();init_frontmatter();init_workspace();INVALID_LITERALS=[{field:"model",value:"inherit"}]});var exports_term_format={};__export(exports_term_format,{truncate:()=>truncate2,stripAnsi:()=>stripAnsi2,padRight:()=>padRight,formatTimestamp:()=>formatTimestamp,formatTime:()=>formatTime,formatRelativeTimestamp:()=>formatRelativeTimestamp,formatDate:()=>formatDate,color:()=>color});function padRight(str2,len){return str2.length>=len?str2:str2+" ".repeat(len-str2.length)}function truncate2(str2,len){return str2.length<=len?str2:`${str2.slice(0,len-1)}\u2026`}function formatDate(iso){if(!iso)return"-";return new Date(iso).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function formatRelativeTimestamp(ts3){let d=new Date(ts3),diffMs=Date.now()-d.getTime();if(diffMs<60000)return`${Math.floor(diffMs/1000)}s ago`;if(diffMs<3600000)return`${Math.floor(diffMs/60000)}m ago`;if(diffMs<86400000)return`${Math.floor(diffMs/3600000)}h ago`;return d.toISOString().replace("T"," ").slice(0,19)}function formatTimestamp(iso,opts){if(!iso)return opts?.fallback??"-";let d=iso instanceof Date?iso:new Date(iso),fmt={month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1};if(opts?.seconds)fmt.second="2-digit";return d.toLocaleString("en-US",fmt)}function formatTime(iso,opts){try{let date=new Date(iso),fmt={hour:"2-digit",minute:"2-digit",hour12:!1};if(opts?.seconds)fmt.second="2-digit";return date.toLocaleTimeString("en-US",fmt)}catch{return opts?.fallback??"??:??"}}function color(name,text){return isTTY?`${ANSI[name]}${text}${ANSI.reset}`:text}function stripAnsi2(str2){return str2.replace(ANSI_REGEX,"")}var ANSI,isTTY,ANSI_REGEX;var init_term_format=__esm(()=>{ANSI={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightCyan:"\x1B[96m"},isTTY=process.stdout.isTTY&&!process.env.NO_COLOR;ANSI_REGEX=/\x1b\[[0-9;]*m/g});var exports_task_service={};__export(exports_task_service,{updateTask:()=>updateTask,updateMessage:()=>updateMessage,untagTask:()=>untagTask,unblockTask:()=>unblockTask,unarchiveTask:()=>unarchiveTask,unarchiveProject:()=>unarchiveProject,tagTask:()=>tagTask,setRelease:()=>setRelease,setPreference:()=>setPreference,sendMessage:()=>sendMessage,resolveTaskId:()=>resolveTaskId,resolveChannels:()=>resolveChannels,removeMember:()=>removeMember,removeDependency:()=>removeDependency,removeActor:()=>removeActor,releaseTask:()=>releaseTask,moveTask:()=>moveTask,markDone:()=>markDone,listTypes:()=>listTypes,listTasksForActor:()=>listTasksForActor,listTasks:()=>listTasks,listTags:()=>listTags,listReleases:()=>listReleases,listProjectsFiltered:()=>listProjectsFiltered,listProjects:()=>listProjects,listConversations:()=>listConversations,linkTask:()=>linkTask,getType:()=>getType,getTaskTags:()=>getTaskTags,getTaskActors:()=>getTaskActors,getTask:()=>getTask,getStageLog:()=>getStageLog,getProjectByRepoPath:()=>getProjectByRepoPath,getProjectByName:()=>getProjectByName,getPreferences:()=>getPreferences,getMessages:()=>getMessages,getMessage:()=>getMessage,getMembers:()=>getMembers,getDependents:()=>getDependents,getConversation:()=>getConversation,getCheckoutOwner:()=>getCheckoutOwner,getBlockingDependencies:()=>getBlockingDependencies,getBlockers:()=>getBlockers,forceUnlockTask:()=>forceUnlockTask,findOrCreateConversation:()=>findOrCreateConversation,expireStaleCheckouts:()=>expireStaleCheckouts,ensureProject:()=>ensureProject,deletePreference:()=>deletePreference,createType:()=>createType,createTask:()=>createTask,createTag:()=>createTag,createProject:()=>createProject,commentOnTask:()=>commentOnTask,checkoutTask:()=>checkoutTask,blockTask:()=>blockTask,assignTask:()=>assignTask,archiveTask:()=>archiveTask,archiveProject:()=>archiveProject,archiveBoard:()=>archiveBoard,addMember:()=>addMember,addDependency:()=>addDependency});import{execSync as execSync7}from"child_process";function str2(v){return v!=null?String(v):null}function strOrDefault(v,def){return v!=null?String(v):def}function mapTask(row){return{id:row.id,seq:row.seq,parentId:str2(row.parent_id),repoPath:row.repo_path,projectId:str2(row.project_id),genieOsFolderId:str2(row.genie_os_folder_id),wishFile:str2(row.wish_file),groupName:str2(row.group_name),title:row.title,description:str2(row.description),acceptanceCriteria:str2(row.acceptance_criteria),typeId:row.type_id,stage:row.stage,status:row.status,priority:row.priority,startDate:str2(row.start_date),dueDate:str2(row.due_date),estimatedEffort:str2(row.estimated_effort),startedAt:str2(row.started_at),endedAt:str2(row.ended_at),blockedReason:str2(row.blocked_reason),releaseId:str2(row.release_id),checkoutRunId:str2(row.checkout_run_id),executionLockedAt:str2(row.execution_locked_at),checkoutTimeoutMs:row.checkout_timeout_ms??600000,sessionId:str2(row.session_id),paneId:str2(row.pane_id),traceId:str2(row.trace_id),boardId:str2(row.board_id),columnId:str2(row.column_id),externalId:str2(row.external_id),externalUrl:str2(row.external_url),archivedAt:str2(row.archived_at),metadata:row.metadata??{},createdAt:strOrDefault(row.created_at,""),updatedAt:strOrDefault(row.updated_at,"")}}function mapConversation(row){return{id:row.id,parentMessageId:row.parent_message_id!=null?Number(row.parent_message_id):null,name:row.name??null,type:row.type,linkedEntity:row.linked_entity??null,linkedEntityId:row.linked_entity_id??null,createdByType:row.created_by_type??null,createdById:row.created_by_id??null,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapMessage(row){return{id:Number(row.id),conversationId:row.conversation_id,replyToId:row.reply_to_id!=null?Number(row.reply_to_id):null,senderType:row.sender_type,senderId:row.sender_id,body:row.body,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapTaskActor(row){return{taskId:row.task_id,actorType:row.actor_type,actorId:row.actor_id,role:row.role,permissions:row.permissions??{},createdAt:String(row.created_at)}}function mapDependency(row){return{taskId:row.task_id,dependsOnId:row.depends_on_id,depType:row.dep_type,createdAt:String(row.created_at)}}function mapTag(row){return{id:row.id,name:row.name,color:row.color??"#9ca3af",typeId:row.type_id??null,createdAt:String(row.created_at)}}function mapTaskType(row){return{id:row.id,name:row.name,description:row.description??null,icon:row.icon??null,stages:row.stages,isBuiltin:row.is_builtin,createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapNotificationPref(row){return{actorType:row.actor_type,actorId:row.actor_id,channel:row.channel,priorityThreshold:row.priority_threshold,isDefault:row.is_default,enabled:row.enabled,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapStageLog(row){return{id:Number(row.id),taskId:row.task_id,fromStage:row.from_stage??null,toStage:row.to_stage,actorType:row.actor_type??null,actorId:row.actor_id??null,runId:row.run_id??null,gateType:row.gate_type??null,createdAt:String(row.created_at)}}function mapConversationMember(row){return{conversationId:row.conversation_id,actorType:row.actor_type,actorId:row.actor_id,role:row.role,joinedAt:String(row.joined_at)}}function mapProject(row){return{id:row.id,name:row.name,repoPath:str2(row.repo_path),description:str2(row.description),leaderAgent:str2(row.leader_agent),tmuxSession:str2(row.tmux_session),status:strOrDefault(row.status,"active"),archivedAt:str2(row.archived_at),createdAt:String(row.created_at)}}function getRepoPath(){try{return execSync7("git rev-parse --show-toplevel",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return process.cwd()}}async function resolveTaskId(idOrSeq,repoPath){let sql=await getConnection(),repo=repoPath??getRepoPath(),projectSeqMatch=idOrSeq.match(/^([^#]+)#(\d+)$/);if(projectSeqMatch&&!idOrSeq.startsWith("#")){let[,projectName,seqStr]=projectSeqMatch,seq2=Number.parseInt(seqStr,10);if(Number.isNaN(seq2))return null;let rows2=await sql`
708
+ Sync complete: ${total} active agent(s), ${result2.archived.length} removed.`)}async function removeMissingAgents(discoveredNames,result2){try{let entries=await ls();for(let entry of entries){if(discoveredNames.has(entry.name))continue;if(entry.scope==="built-in")continue;if(!entry.dir||!entry.dir.includes("/agents/"))continue;if(await rm3(entry.name))result2.archived.push(entry.name)}}catch{}}async function syncSingleAgent(agent,result2,workspaceRoot){let repoPath=(agent.repoUrl?extractOrgRepo(agent.repoUrl):null)??agent.repoUrl??agent.dir,agentsMdPath=join24(agent.dir,"AGENTS.md"),content=readFileSync14(agentsMdPath,"utf-8"),fm=parseFrontmatter(content),_resolvedMeta;if(workspaceRoot){let ctx=buildResolveContext(workspaceRoot,agent.name);_resolvedMeta=computeResolvedMetadata(fm,ctx)}let resolved=await resolve3(agent.name),existing=resolved&&!resolved.builtin?resolved.entry:null,sdkConfig=fm.sdk,permissions=fm.permissions,disallowedTools=fm.disallowedTools,omniScopes=fm.omniScopes,hooks=fm.hooks;if(!existing){await add({name:agent.name,dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,permissions,disallowedTools,omniScopes,hooks,sdk:sdkConfig}),result2.registered.push(agent.name);return}let identityUpdate={dir:agent.dir,repo:repoPath,promptMode:fm.promptMode??"append",model:fm.model,description:fm.description,color:fm.color,provider:fm.provider,permissions,disallowedTools,omniScopes,hooks,sdk:sdkConfig},sdkChanged=JSON.stringify(existing.sdk)!==JSON.stringify(sdkConfig),permissionsChanged=JSON.stringify(existing.permissions)!==JSON.stringify(permissions),disallowedToolsChanged=JSON.stringify(existing.disallowedTools)!==JSON.stringify(disallowedTools),omniScopesChanged=JSON.stringify(existing.omniScopes)!==JSON.stringify(omniScopes),hooksChanged=JSON.stringify(existing.hooks)!==JSON.stringify(hooks);if(sdkChanged||permissionsChanged||disallowedToolsChanged||omniScopesChanged||hooksChanged||existing.repo!==repoPath||existing.dir!==agent.dir||existing.promptMode!==(fm.promptMode??"append")||existing.model!==fm.model||existing.description!==fm.description||existing.color!==fm.color||existing.provider!==fm.provider)await edit(agent.name,identityUpdate),result2.updated.push(agent.name);else result2.unchanged.push(agent.name)}async function syncSingleAgentByName(workspaceRoot,agentName){let agent=discoverSingleAgent(workspaceRoot,agentName);if(!agent)return"not-found";let result2={registered:[],updated:[],unchanged:[],archived:[],reactivated:[],healed:[],errors:[]};if(await syncSingleAgent(agent,result2,workspaceRoot),result2.registered.length>0)return"registered";if(result2.updated.length>0)return"updated";return"unchanged"}function watchAgentDirectory(workspaceRoot,options){let agentsDir=join24(workspaceRoot,"agents");if(!existsSync22(agentsDir))return null;let debounceTimer=null,pendingChanges=new Set,processChanges=async()=>{let names=[...pendingChanges];pendingChanges.clear();for(let name of names)try{let action=await processWatchedAgent(workspaceRoot,agentsDir,name);if(action)options?.onSync?.(name,action)}catch{}},watcher=fsWatch(agentsDir,{persistent:!1},(_event,filename)=>{if(!filename)return;let name=filename.split("/")[0];if(!name||name.startsWith("."))return;if(pendingChanges.add(name),debounceTimer)clearTimeout(debounceTimer);debounceTimer=setTimeout(processChanges,2000)});return{close:()=>{if(debounceTimer)clearTimeout(debounceTimer);watcher.close()}}}async function processWatchedAgent(workspaceRoot,agentsDir,name){let agentDir=join24(agentsDir,name);if(existsSync22(agentDir)&&existsSync22(join24(agentDir,"AGENTS.md"))){let action=await syncSingleAgentByName(workspaceRoot,name);return action!=="unchanged"&&action!=="not-found"?action:null}if(!existsSync22(agentDir)){if(await rm3(name))return"removed"}return null}var INVALID_LITERALS;var init_agent_sync=__esm(()=>{init_agent_directory();init_defaults();init_frontmatter();init_workspace();INVALID_LITERALS=[{field:"model",value:"inherit"}]});var exports_term_format={};__export(exports_term_format,{truncate:()=>truncate2,stripAnsi:()=>stripAnsi2,padRight:()=>padRight,formatTimestamp:()=>formatTimestamp,formatTime:()=>formatTime,formatRelativeTimestamp:()=>formatRelativeTimestamp,formatDate:()=>formatDate,color:()=>color});function padRight(str2,len){return str2.length>=len?str2:str2+" ".repeat(len-str2.length)}function truncate2(str2,len){return str2.length<=len?str2:`${str2.slice(0,len-1)}\u2026`}function formatDate(iso){if(!iso)return"-";return new Date(iso).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function formatRelativeTimestamp(ts3){let d=new Date(ts3),diffMs=Date.now()-d.getTime();if(diffMs<60000)return`${Math.floor(diffMs/1000)}s ago`;if(diffMs<3600000)return`${Math.floor(diffMs/60000)}m ago`;if(diffMs<86400000)return`${Math.floor(diffMs/3600000)}h ago`;return d.toISOString().replace("T"," ").slice(0,19)}function formatTimestamp(iso,opts){if(!iso)return opts?.fallback??"-";let d=iso instanceof Date?iso:new Date(iso),fmt={month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1};if(opts?.seconds)fmt.second="2-digit";return d.toLocaleString("en-US",fmt)}function formatTime(iso,opts){try{let date=new Date(iso),fmt={hour:"2-digit",minute:"2-digit",hour12:!1};if(opts?.seconds)fmt.second="2-digit";return date.toLocaleTimeString("en-US",fmt)}catch{return opts?.fallback??"??:??"}}function color(name,text){return isTTY?`${ANSI[name]}${text}${ANSI.reset}`:text}function stripAnsi2(str2){return str2.replace(ANSI_REGEX,"")}var ANSI,isTTY,ANSI_REGEX;var init_term_format=__esm(()=>{ANSI={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightCyan:"\x1B[96m"},isTTY=process.stdout.isTTY&&!process.env.NO_COLOR;ANSI_REGEX=/\x1b\[[0-9;]*m/g});var exports_task_service={};__export(exports_task_service,{updateTask:()=>updateTask,updateMessage:()=>updateMessage,untagTask:()=>untagTask,unblockTask:()=>unblockTask,unarchiveTask:()=>unarchiveTask,unarchiveProject:()=>unarchiveProject,tagTask:()=>tagTask,setRelease:()=>setRelease,setPreference:()=>setPreference,sendMessage:()=>sendMessage,resolveTaskId:()=>resolveTaskId,resolveChannels:()=>resolveChannels,removeMember:()=>removeMember,removeDependency:()=>removeDependency,removeActor:()=>removeActor,releaseTask:()=>releaseTask,moveTask:()=>moveTask,markDone:()=>markDone,listTypes:()=>listTypes,listTasksForActor:()=>listTasksForActor,listTasks:()=>listTasks,listTags:()=>listTags,listReleases:()=>listReleases,listProjectsFiltered:()=>listProjectsFiltered,listProjects:()=>listProjects,listConversations:()=>listConversations,linkTask:()=>linkTask,getType:()=>getType,getTaskTags:()=>getTaskTags,getTaskActors:()=>getTaskActors,getTask:()=>getTask,getStageLog:()=>getStageLog,getProjectByRepoPath:()=>getProjectByRepoPath,getProjectByName:()=>getProjectByName,getPreferences:()=>getPreferences,getMessages:()=>getMessages,getMessage:()=>getMessage,getMembers:()=>getMembers,getDependents:()=>getDependents,getConversation:()=>getConversation,getCheckoutOwner:()=>getCheckoutOwner,getBlockingDependencies:()=>getBlockingDependencies,getBlockers:()=>getBlockers,forceUnlockTask:()=>forceUnlockTask,findOrCreateConversation:()=>findOrCreateConversation,expireStaleCheckouts:()=>expireStaleCheckouts,ensureProject:()=>ensureProject,deletePreference:()=>deletePreference,createType:()=>createType,createTask:()=>createTask,createTag:()=>createTag,createProject:()=>createProject,commentOnTask:()=>commentOnTask,checkoutTask:()=>checkoutTask,blockTask:()=>blockTask,assignTask:()=>assignTask,archiveTask:()=>archiveTask,archiveProject:()=>archiveProject,archiveBoard:()=>archiveBoard,addMember:()=>addMember,addDependency:()=>addDependency});import{execSync as execSync7}from"child_process";function str2(v){return v!=null?String(v):null}function strOrDefault(v,def){return v!=null?String(v):def}function mapTask(row){return{id:row.id,seq:row.seq,parentId:str2(row.parent_id),repoPath:row.repo_path,projectId:str2(row.project_id),genieOsFolderId:str2(row.genie_os_folder_id),wishFile:str2(row.wish_file),groupName:str2(row.group_name),title:row.title,description:str2(row.description),acceptanceCriteria:str2(row.acceptance_criteria),typeId:row.type_id,stage:row.stage,status:row.status,priority:row.priority,startDate:str2(row.start_date),dueDate:str2(row.due_date),estimatedEffort:str2(row.estimated_effort),startedAt:str2(row.started_at),endedAt:str2(row.ended_at),blockedReason:str2(row.blocked_reason),releaseId:str2(row.release_id),checkoutRunId:str2(row.checkout_run_id),executionLockedAt:str2(row.execution_locked_at),checkoutTimeoutMs:row.checkout_timeout_ms??600000,sessionId:str2(row.session_id),paneId:str2(row.pane_id),traceId:str2(row.trace_id),boardId:str2(row.board_id),columnId:str2(row.column_id),externalId:str2(row.external_id),externalUrl:str2(row.external_url),archivedAt:str2(row.archived_at),metadata:row.metadata??{},createdAt:strOrDefault(row.created_at,""),updatedAt:strOrDefault(row.updated_at,"")}}function mapConversation(row){return{id:row.id,parentMessageId:row.parent_message_id!=null?Number(row.parent_message_id):null,name:row.name??null,type:row.type,linkedEntity:row.linked_entity??null,linkedEntityId:row.linked_entity_id??null,createdByType:row.created_by_type??null,createdById:row.created_by_id??null,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapMessage(row){return{id:Number(row.id),conversationId:row.conversation_id,replyToId:row.reply_to_id!=null?Number(row.reply_to_id):null,senderType:row.sender_type,senderId:row.sender_id,body:row.body,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapTaskActor(row){return{taskId:row.task_id,actorType:row.actor_type,actorId:row.actor_id,role:row.role,permissions:row.permissions??{},createdAt:String(row.created_at)}}function mapDependency(row){return{taskId:row.task_id,dependsOnId:row.depends_on_id,depType:row.dep_type,createdAt:String(row.created_at)}}function mapTag(row){return{id:row.id,name:row.name,color:row.color??"#9ca3af",typeId:row.type_id??null,createdAt:String(row.created_at)}}function mapTaskType(row){return{id:row.id,name:row.name,description:row.description??null,icon:row.icon??null,stages:row.stages,isBuiltin:row.is_builtin,createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapNotificationPref(row){return{actorType:row.actor_type,actorId:row.actor_id,channel:row.channel,priorityThreshold:row.priority_threshold,isDefault:row.is_default,enabled:row.enabled,metadata:row.metadata??{},createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function mapStageLog(row){return{id:Number(row.id),taskId:row.task_id,fromStage:row.from_stage??null,toStage:row.to_stage,actorType:row.actor_type??null,actorId:row.actor_id??null,runId:row.run_id??null,gateType:row.gate_type??null,createdAt:String(row.created_at)}}function mapConversationMember(row){return{conversationId:row.conversation_id,actorType:row.actor_type,actorId:row.actor_id,role:row.role,joinedAt:String(row.joined_at)}}function mapProject(row){return{id:row.id,name:row.name,repoPath:str2(row.repo_path),description:str2(row.description),leaderAgent:str2(row.leader_agent),tmuxSession:str2(row.tmux_session),status:strOrDefault(row.status,"active"),archivedAt:str2(row.archived_at),createdAt:String(row.created_at)}}function getRepoPath(){try{return execSync7("git rev-parse --show-toplevel",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return process.cwd()}}async function resolveTaskId(idOrSeq,repoPath){let sql=await getConnection(),repo=repoPath??getRepoPath(),projectSeqMatch=idOrSeq.match(/^([^#]+)#(\d+)$/);if(projectSeqMatch&&!idOrSeq.startsWith("#")){let[,projectName,seqStr]=projectSeqMatch,seq2=Number.parseInt(seqStr,10);if(Number.isNaN(seq2))return null;let rows2=await sql`
709
709
  SELECT t.id FROM tasks t
710
710
  JOIN projects p ON t.project_id = p.id
711
711
  WHERE p.name = ${projectName} AND t.seq = ${seq2}
@@ -1127,7 +1127,7 @@ Stopping inbox watcher...`),stopInboxWatcher2(handle),process.exit(0)};process.o
1127
1127
  JOIN agents a ON e.agent_id = a.id
1128
1128
  WHERE e.id = ${executorId}
1129
1129
  LIMIT 1
1130
- `;if(rows.length===0)return;let{custom_name:agentName,team:teamName}=rows[0];if(!agentName||!teamName)return;let{writeNativeInbox:writeNativeInbox2}=await Promise.resolve().then(() => (init_claude_native_teams(),exports_claude_native_teams));await writeNativeInbox2(teamName,agentName,{from:"system",text:message.text,summary:message.text.slice(0,120),timestamp:new Date().toISOString(),color:"red",read:!1})}}function spawnContextToParams2(ctx){return{provider:"claude",team:ctx.team,role:ctx.role,skill:ctx.skill,agentId:ctx.agentId,executorId:ctx.executorId,extraArgs:ctx.extraArgs,model:ctx.model,sessionId:ctx.sessionId,systemPromptFile:ctx.systemPromptFile,systemPrompt:ctx.systemPrompt,promptMode:ctx.promptMode,initialPrompt:ctx.initialPrompt,name:ctx.name,nativeTeam:ctx.nativeTeam,otelPort:ctx.otelPort,otelLogPrompts:ctx.otelLogPrompts,otelWishSlug:ctx.otelWishSlug}}function resumeContextToParams2(ctx){return{provider:"claude",team:ctx.team,role:ctx.role,agentId:ctx.agentId,executorId:ctx.executorId,extraArgs:ctx.extraArgs,model:ctx.model,resume:ctx.claudeSessionId,nativeTeam:ctx.nativeTeam,otelPort:ctx.otelPort,otelLogPrompts:ctx.otelLogPrompts,otelWishSlug:ctx.otelWishSlug}}async function findSessionLogPath(sessionId,projectPath){let{access:access2,readdir:readdir4}=await import("fs/promises"),{join:join30}=await import("path"),claudeDir=join30(process.env.HOME||"",".claude","projects");try{await access2(claudeDir)}catch{return null}let jsonlName=`${sessionId}.jsonl`;if(projectPath){let{projectPathToHash:projectPathToHash2}=await Promise.resolve().then(() => (init_claude_logs(),exports_claude_logs)),hash=projectPathToHash2(projectPath),candidate=join30(claudeDir,hash,jsonlName);try{return await access2(candidate),candidate}catch{}}try{let dirs=await readdir4(claudeDir);for(let dir of dirs){let candidate=join30(claudeDir,dir,jsonlName);try{return await access2(candidate),candidate}catch{}}}catch{}return null}function mapDetectedState(detectedType){switch(detectedType){case"idle":return"idle";case"working":case"tool_use":return"working";case"permission":return"permission";case"question":return"question";case"error":return"error";case"complete":return"done";case"unknown":return"running"}}var init_claude_code=__esm(()=>{init_provider_adapters()});function getEventType(msg){if(msg.type==="result"){let sub=msg.subtype??"";return RESULT_SUBTYPE_MAP[sub]??"sdk.result.error"}if(msg.type==="system"){let sub=msg.subtype??"";return SYSTEM_SUBTYPE_MAP[sub]??null}return TOP_LEVEL_MAP[msg.type]??null}function truncate3(s,max=200){return s.slice(0,max)}function assistantDetails(msg){let details={},content=msg.message?.content;if(Array.isArray(content)){let textBlock=content.find((b2)=>b2.type==="text");if(textBlock?.text)details.textPreview=truncate3(textBlock.text);let toolBlocks=content.filter((b2)=>b2.type==="tool_use");if(toolBlocks.length>0)details.toolCalls=toolBlocks.map((t)=>{let call={name:t.name};if(t.name==="Bash"&&t.input&&typeof t.input.command==="string")call.command=truncate3(t.input.command,150);if(t.name==="Read"&&t.input&&typeof t.input.file_path==="string")call.path=t.input.file_path;return call})}if(msg.error)details.error=msg.error;if(msg.parent_tool_use_id)details.parentToolUseId=msg.parent_tool_use_id;return details}function resultDetails(msg){let details={subtype:msg.subtype,isError:msg.is_error,durationMs:msg.duration_ms,durationApiMs:msg.duration_api_ms,numTurns:msg.num_turns,totalCostUsd:msg.total_cost_usd};if(msg.usage)details.usage=msg.usage;if(msg.subtype==="success"&&typeof msg.result==="string")details.resultPreview=truncate3(msg.result);if(Array.isArray(msg.errors)&&msg.errors.length>0)details.errors=msg.errors;return details}function systemDetails(msg){let details={subtype:msg.subtype},subtype=msg.subtype;return{init:()=>{if(details.model=msg.model,details.cwd=msg.cwd,details.version=msg.claude_code_version,details.tools=Array.isArray(msg.tools)?msg.tools.length:0,msg.session_id)details.sessionId=msg.session_id},api_retry:()=>{details.attempt=msg.attempt,details.maxRetries=msg.max_retries,details.retryDelayMs=msg.retry_delay_ms,details.errorStatus=msg.error_status,details.error=msg.error},compact_boundary:()=>{let meta=msg.compact_metadata;if(meta)details.trigger=meta.trigger,details.preTokens=meta.pre_tokens},hook_started:()=>assignHookDetails(msg,details),hook_progress:()=>assignHookDetails(msg,details),hook_response:()=>{assignHookDetails(msg,details),details.outcome=msg.outcome,details.exitCode=msg.exit_code},task_notification:()=>{if(details.taskId=msg.task_id,details.status=msg.status,details.summary=typeof msg.summary==="string"?truncate3(msg.summary):void 0,msg.usage)details.usage=msg.usage},task_started:()=>{details.taskId=msg.task_id,details.description=typeof msg.description==="string"?truncate3(msg.description):void 0,details.taskType=msg.task_type},task_progress:()=>{if(details.taskId=msg.task_id,details.description=typeof msg.description==="string"?truncate3(msg.description):void 0,details.lastToolName=msg.last_tool_name,msg.usage)details.usage=msg.usage},session_state_changed:()=>{details.state=msg.state},status:()=>{details.status=msg.status},files_persisted:()=>{let files=msg.files;details.fileCount=Array.isArray(files)?files.length:0;let failed=msg.failed;details.failedCount=Array.isArray(failed)?failed.length:0},elicitation_complete:()=>{details.mcpServerName=msg.mcp_server_name,details.elicitationId=msg.elicitation_id},local_command_output:()=>{details.contentPreview=typeof msg.content==="string"?truncate3(msg.content):void 0}}[subtype]?.(),details}function assignHookDetails(msg,details){details.hookId=msg.hook_id,details.hookName=msg.hook_name,details.hookEvent=msg.hook_event}function buildEventDetails(msg){let base={sdkType:msg.type},extra=DETAIL_BUILDERS[msg.type]?.(msg)??{};return{...base,...extra}}async function routeSdkMessage(msg,executorId,agentId){let eventType=getEventType(msg);if(!eventType)return null;if(eventType==="sdk.stream.partial")return eventType;let details=buildEventDetails(msg);return details.executorId=executorId,await recordAuditEvent("sdk_message",executorId,eventType,agentId,details),eventType}var SYSTEM_SUBTYPE_MAP,RESULT_SUBTYPE_MAP,TOP_LEVEL_MAP,DETAIL_BUILDERS;var init_claude_sdk_events=__esm(()=>{init_audit();SYSTEM_SUBTYPE_MAP={init:"sdk.system",api_retry:"sdk.api.retry",compact_boundary:"sdk.context.compacted",elicitation_complete:"sdk.elicitation.complete",files_persisted:"sdk.files.persisted",hook_progress:"sdk.hook.progress",hook_response:"sdk.hook.response",hook_started:"sdk.hook.started",local_command_output:"sdk.command.output",session_state_changed:"sdk.session.state",status:"sdk.status",task_notification:"sdk.task.notification",task_progress:"sdk.task.progress",task_started:"sdk.task.started"},RESULT_SUBTYPE_MAP={success:"sdk.result.success",error_max_turns:"sdk.result.max_turns",error_max_budget_usd:"sdk.result.max_budget"},TOP_LEVEL_MAP={assistant:"sdk.assistant.message",stream_event:"sdk.stream.partial",tool_progress:"sdk.tool.progress",tool_use_summary:"sdk.tool.summary",rate_limit_event:"sdk.rate_limit",auth_status:"sdk.auth.status",prompt_suggestion:"sdk.prompt.suggestion",user:"sdk.user.message"};DETAIL_BUILDERS={assistant:(msg)=>assistantDetails(msg),result:(msg)=>resultDetails(msg),system:(msg)=>systemDetails(msg),stream_event:(msg)=>msg.parent_tool_use_id?{parentToolUseId:msg.parent_tool_use_id}:{},tool_progress:(msg)=>{let d={toolName:msg.tool_name,toolUseId:msg.tool_use_id,elapsedSeconds:msg.elapsed_time_seconds};if(msg.task_id)d.taskId=msg.task_id;return d},tool_use_summary:(msg)=>({summaryPreview:truncate3(msg.summary),toolUseIds:msg.preceding_tool_use_ids}),rate_limit_event:(msg)=>{let d={status:msg.rate_limit_info.status};if(msg.rate_limit_info.resetsAt)d.resetsAt=msg.rate_limit_info.resetsAt;if(msg.rate_limit_info.utilization!=null)d.utilization=msg.rate_limit_info.utilization;return d},auth_status:(msg)=>{let d={isAuthenticating:msg.isAuthenticating};if(msg.error)d.error=msg.error;return d},prompt_suggestion:(msg)=>({suggestion:truncate3(msg.suggestion)}),user:(msg)=>{let d={isReplay:msg.isReplay===!0,isSynthetic:msg.isSynthetic===!0};if(msg.parent_tool_use_id)d.parentToolUseId=msg.parent_tool_use_id;let content=msg.message?.content;if(typeof content==="string")d.textPreview=truncate3(content);else if(Array.isArray(content)){let textBlock=content.find((b2)=>b2.type==="text");if(textBlock?.text)d.textPreview=truncate3(textBlock.text)}return d}}});function normalizeCommand(command){let normalized=command.trim().replace(/\s+/g," ");if(normalized==="")return"";return normalized=normalized.replace(/^\/[\w./-]*\/(\w)/,"$1"),normalized}function hasShellMetacharacters(command){return/(&&|\||;|`|\$\()/.test(command)}var ToolName,RepoConfigSchema,DefaultsConfigSchema,AutoApproveConfigSchema;var init_auto_approve=__esm(()=>{init_js_yaml();init_zod();ToolName=exports_external.string(),RepoConfigSchema=exports_external.object({inherit:exports_external.enum(["global","none"]).optional(),allow:exports_external.array(ToolName).default([]),deny:exports_external.array(ToolName).default([]),bash_allow_patterns:exports_external.array(exports_external.string()).optional(),bash_deny_patterns:exports_external.array(exports_external.string()).optional()}),DefaultsConfigSchema=exports_external.object({allow:exports_external.array(ToolName).default([]),deny:exports_external.array(ToolName).default([]),bash_allow_patterns:exports_external.array(exports_external.string()).optional(),bash_deny_patterns:exports_external.array(exports_external.string()).optional()}),AutoApproveConfigSchema=exports_external.object({defaults:DefaultsConfigSchema.default({}),repos:exports_external.record(exports_external.string(),RepoConfigSchema).optional()})});var exports_claude_sdk_permissions={};__export(exports_claude_sdk_permissions,{resolvePreset:()=>resolvePreset,resolvePermissionConfig:()=>resolvePermissionConfig,createPermissionGate:()=>createPermissionGate,PRESET_READ_ONLY:()=>PRESET_READ_ONLY,PRESET_FULL:()=>PRESET_FULL,PRESET_CHAT_ONLY:()=>PRESET_CHAT_ONLY});function resolvePreset(name){let preset=PRESETS[name];if(!preset)throw Error(`Unknown permission preset "${name}". Valid: ${Object.keys(PRESETS).join(", ")}`);return preset}function resolvePermissionConfig(permissions){if(permissions?.preset)return resolvePreset(permissions.preset);if(permissions?.allow)return{allow:permissions.allow,bashAllowPatterns:permissions.bashAllowPatterns};return PRESET_FULL}function matchesCompoundPattern(normalized,patterns2){for(let pattern of patterns2)try{let match=normalized.match(new RegExp(pattern));if(match&&match[0]===normalized)return!0}catch{}return!1}function matchesSimplePattern(normalized,patterns2){for(let pattern of patterns2)try{if(new RegExp(pattern).test(normalized))return!0}catch{if(normalized.includes(pattern))return!0}return!1}function matchesBashAllow(command,patterns2){let normalized=normalizeCommand(command);if(hasShellMetacharacters(normalized))return matchesCompoundPattern(normalized,patterns2);return matchesSimplePattern(normalized,patterns2)}function createPermissionGate(config){let{allow,bashAllowPatterns=[]}=config,allowAll=allow.includes("*"),allowSet=new Set(allow);return async(input)=>{let hookInput=input,toolName=hookInput.tool_name;if(!allowAll&&!allowSet.has(toolName))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Tool "${toolName}" is not allowed. Allowed: ${allow.join(", ")}`}};if(toolName==="Bash"&&bashAllowPatterns.length>0){let toolInput=hookInput.tool_input??{},command=typeof toolInput.command==="string"?toolInput.command:"";if(!command||!matchesBashAllow(command,bashAllowPatterns))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Bash command not in allow patterns: ${command||"(empty)"}`}}}return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}var PRESET_FULL,PRESET_READ_ONLY,PRESET_CHAT_ONLY,PRESETS;var init_claude_sdk_permissions=__esm(()=>{init_auto_approve();PRESET_FULL={allow:["*"]},PRESET_READ_ONLY={allow:["Read","Glob","Grep","WebFetch"]},PRESET_CHAT_ONLY={allow:["SendMessage","Read"]},PRESETS={full:PRESET_FULL,"read-only":PRESET_READ_ONLY,"chat-only":PRESET_CHAT_ONLY}});function pruneRecentSends(){let cutoff=Date.now()-BATCH_WINDOW_MS;while(recentOmniSends.length>0&&recentOmniSends[0]<cutoff)recentOmniSends.shift()}function formatApprovalMessage(approvalId,agentName,toolName,preview){let shortPreview=preview.length>200?`${preview.slice(0,197)}...`:preview;return["\uD83D\uDD14 *Approval Required*","",`Agent: *${agentName}*`,`Tool: \`${toolName}\``,`Preview: ${shortPreview}`,"","Reply *y* to approve or *n* to deny","Or react \uD83D\uDC4D / \uD83D\uDC4E","",`_ID: ${approvalId}_`].join(`
1130
+ `;if(rows.length===0)return;let{custom_name:agentName,team:teamName}=rows[0];if(!agentName||!teamName)return;let{writeNativeInbox:writeNativeInbox2}=await Promise.resolve().then(() => (init_claude_native_teams(),exports_claude_native_teams));await writeNativeInbox2(teamName,agentName,{from:"system",text:message.text,summary:message.text.slice(0,120),timestamp:new Date().toISOString(),color:"red",read:!1})}}function spawnContextToParams2(ctx){return{provider:"claude",team:ctx.team,role:ctx.role,skill:ctx.skill,agentId:ctx.agentId,executorId:ctx.executorId,extraArgs:ctx.extraArgs,model:ctx.model,sessionId:ctx.sessionId,systemPromptFile:ctx.systemPromptFile,systemPrompt:ctx.systemPrompt,promptMode:ctx.promptMode,initialPrompt:ctx.initialPrompt,name:ctx.name,nativeTeam:ctx.nativeTeam,otelPort:ctx.otelPort,otelLogPrompts:ctx.otelLogPrompts,otelWishSlug:ctx.otelWishSlug}}function resumeContextToParams2(ctx){return{provider:"claude",team:ctx.team,role:ctx.role,agentId:ctx.agentId,executorId:ctx.executorId,extraArgs:ctx.extraArgs,model:ctx.model,resume:ctx.claudeSessionId,nativeTeam:ctx.nativeTeam,otelPort:ctx.otelPort,otelLogPrompts:ctx.otelLogPrompts,otelWishSlug:ctx.otelWishSlug}}async function findSessionLogPath(sessionId,projectPath){let{access:access2,readdir:readdir4}=await import("fs/promises"),{join:join30}=await import("path"),claudeDir=join30(process.env.HOME||"",".claude","projects");try{await access2(claudeDir)}catch{return null}let jsonlName=`${sessionId}.jsonl`;if(projectPath){let{projectPathToHash:projectPathToHash2}=await Promise.resolve().then(() => (init_claude_logs(),exports_claude_logs)),hash=projectPathToHash2(projectPath),candidate=join30(claudeDir,hash,jsonlName);try{return await access2(candidate),candidate}catch{}}try{let dirs=await readdir4(claudeDir);for(let dir of dirs){let candidate=join30(claudeDir,dir,jsonlName);try{return await access2(candidate),candidate}catch{}}}catch{}return null}function mapDetectedState(detectedType){switch(detectedType){case"idle":return"idle";case"working":case"tool_use":return"working";case"permission":return"permission";case"question":return"question";case"error":return"error";case"complete":return"done";case"unknown":return"running"}}var init_claude_code=__esm(()=>{init_provider_adapters()});function getEventType(msg){if(msg.type==="result"){let sub=msg.subtype??"";return RESULT_SUBTYPE_MAP[sub]??"sdk.result.error"}if(msg.type==="system"){let sub=msg.subtype??"";return SYSTEM_SUBTYPE_MAP[sub]??null}return TOP_LEVEL_MAP[msg.type]??null}function truncate3(s,max=200){return s.slice(0,max)}function assistantDetails(msg){let details={},content=msg.message?.content;if(Array.isArray(content)){let textBlock=content.find((b2)=>b2.type==="text");if(textBlock?.text)details.textPreview=truncate3(textBlock.text);let toolBlocks=content.filter((b2)=>b2.type==="tool_use");if(toolBlocks.length>0)details.toolCalls=toolBlocks.map((t)=>{let call={name:t.name};if(t.name==="Bash"&&t.input&&typeof t.input.command==="string")call.command=truncate3(t.input.command,150);if(t.name==="Read"&&t.input&&typeof t.input.file_path==="string")call.path=t.input.file_path;return call})}if(msg.error)details.error=msg.error;if(msg.parent_tool_use_id)details.parentToolUseId=msg.parent_tool_use_id;return details}function resultDetails(msg){let details={subtype:msg.subtype,isError:msg.is_error,durationMs:msg.duration_ms,durationApiMs:msg.duration_api_ms,numTurns:msg.num_turns,totalCostUsd:msg.total_cost_usd};if(msg.usage)details.usage=msg.usage;if(msg.subtype==="success"&&typeof msg.result==="string")details.resultPreview=truncate3(msg.result);if(Array.isArray(msg.errors)&&msg.errors.length>0)details.errors=msg.errors;return details}function systemDetails(msg){let details={subtype:msg.subtype},subtype=msg.subtype;return{init:()=>{if(details.model=msg.model,details.cwd=msg.cwd,details.version=msg.claude_code_version,details.tools=Array.isArray(msg.tools)?msg.tools.length:0,msg.session_id)details.sessionId=msg.session_id},api_retry:()=>{details.attempt=msg.attempt,details.maxRetries=msg.max_retries,details.retryDelayMs=msg.retry_delay_ms,details.errorStatus=msg.error_status,details.error=msg.error},compact_boundary:()=>{let meta=msg.compact_metadata;if(meta)details.trigger=meta.trigger,details.preTokens=meta.pre_tokens},hook_started:()=>assignHookDetails(msg,details),hook_progress:()=>assignHookDetails(msg,details),hook_response:()=>{assignHookDetails(msg,details),details.outcome=msg.outcome,details.exitCode=msg.exit_code},task_notification:()=>{if(details.taskId=msg.task_id,details.status=msg.status,details.summary=typeof msg.summary==="string"?truncate3(msg.summary):void 0,msg.usage)details.usage=msg.usage},task_started:()=>{details.taskId=msg.task_id,details.description=typeof msg.description==="string"?truncate3(msg.description):void 0,details.taskType=msg.task_type},task_progress:()=>{if(details.taskId=msg.task_id,details.description=typeof msg.description==="string"?truncate3(msg.description):void 0,details.lastToolName=msg.last_tool_name,msg.usage)details.usage=msg.usage},session_state_changed:()=>{details.state=msg.state},status:()=>{details.status=msg.status},files_persisted:()=>{let files=msg.files;details.fileCount=Array.isArray(files)?files.length:0;let failed=msg.failed;details.failedCount=Array.isArray(failed)?failed.length:0},elicitation_complete:()=>{details.mcpServerName=msg.mcp_server_name,details.elicitationId=msg.elicitation_id},local_command_output:()=>{details.contentPreview=typeof msg.content==="string"?truncate3(msg.content):void 0}}[subtype]?.(),details}function assignHookDetails(msg,details){details.hookId=msg.hook_id,details.hookName=msg.hook_name,details.hookEvent=msg.hook_event}function buildEventDetails(msg){let base={sdkType:msg.type},extra=DETAIL_BUILDERS[msg.type]?.(msg)??{};return{...base,...extra}}async function routeSdkMessage(msg,executorId,agentId){let eventType=getEventType(msg);if(!eventType)return null;if(eventType==="sdk.stream.partial")return eventType;let details=buildEventDetails(msg);return details.executorId=executorId,await recordAuditEvent("sdk_message",executorId,eventType,agentId,details),eventType}var SYSTEM_SUBTYPE_MAP,RESULT_SUBTYPE_MAP,TOP_LEVEL_MAP,DETAIL_BUILDERS;var init_claude_sdk_events=__esm(()=>{init_audit();SYSTEM_SUBTYPE_MAP={init:"sdk.system",api_retry:"sdk.api.retry",compact_boundary:"sdk.context.compacted",elicitation_complete:"sdk.elicitation.complete",files_persisted:"sdk.files.persisted",hook_progress:"sdk.hook.progress",hook_response:"sdk.hook.response",hook_started:"sdk.hook.started",local_command_output:"sdk.command.output",session_state_changed:"sdk.session.state",status:"sdk.status",task_notification:"sdk.task.notification",task_progress:"sdk.task.progress",task_started:"sdk.task.started"},RESULT_SUBTYPE_MAP={success:"sdk.result.success",error_max_turns:"sdk.result.max_turns",error_max_budget_usd:"sdk.result.max_budget"},TOP_LEVEL_MAP={assistant:"sdk.assistant.message",stream_event:"sdk.stream.partial",tool_progress:"sdk.tool.progress",tool_use_summary:"sdk.tool.summary",rate_limit_event:"sdk.rate_limit",auth_status:"sdk.auth.status",prompt_suggestion:"sdk.prompt.suggestion",user:"sdk.user.message"};DETAIL_BUILDERS={assistant:(msg)=>assistantDetails(msg),result:(msg)=>resultDetails(msg),system:(msg)=>systemDetails(msg),stream_event:(msg)=>msg.parent_tool_use_id?{parentToolUseId:msg.parent_tool_use_id}:{},tool_progress:(msg)=>{let d={toolName:msg.tool_name,toolUseId:msg.tool_use_id,elapsedSeconds:msg.elapsed_time_seconds};if(msg.task_id)d.taskId=msg.task_id;return d},tool_use_summary:(msg)=>({summaryPreview:truncate3(msg.summary),toolUseIds:msg.preceding_tool_use_ids}),rate_limit_event:(msg)=>{let d={status:msg.rate_limit_info.status};if(msg.rate_limit_info.resetsAt)d.resetsAt=msg.rate_limit_info.resetsAt;if(msg.rate_limit_info.utilization!=null)d.utilization=msg.rate_limit_info.utilization;return d},auth_status:(msg)=>{let d={isAuthenticating:msg.isAuthenticating};if(msg.error)d.error=msg.error;return d},prompt_suggestion:(msg)=>({suggestion:truncate3(msg.suggestion)}),user:(msg)=>{let d={isReplay:msg.isReplay===!0,isSynthetic:msg.isSynthetic===!0};if(msg.parent_tool_use_id)d.parentToolUseId=msg.parent_tool_use_id;let content=msg.message?.content;if(typeof content==="string")d.textPreview=truncate3(content);else if(Array.isArray(content)){let textBlock=content.find((b2)=>b2.type==="text");if(textBlock?.text)d.textPreview=truncate3(textBlock.text)}return d}}});function normalizeCommand(command){let normalized=command.trim().replace(/\s+/g," ");if(normalized==="")return"";return normalized=normalized.replace(/^\/[\w./-]*\/(\w)/,"$1"),normalized}function hasShellMetacharacters(command){return/(&&|\||;|`|\$\()/.test(command)}var ToolName,RepoConfigSchema,DefaultsConfigSchema,AutoApproveConfigSchema;var init_auto_approve=__esm(()=>{init_js_yaml();init_zod();ToolName=exports_external.string(),RepoConfigSchema=exports_external.object({inherit:exports_external.enum(["global","none"]).optional(),allow:exports_external.array(ToolName).default([]),deny:exports_external.array(ToolName).default([]),bash_allow_patterns:exports_external.array(exports_external.string()).optional(),bash_deny_patterns:exports_external.array(exports_external.string()).optional()}),DefaultsConfigSchema=exports_external.object({allow:exports_external.array(ToolName).default([]),deny:exports_external.array(ToolName).default([]),bash_allow_patterns:exports_external.array(exports_external.string()).optional(),bash_deny_patterns:exports_external.array(exports_external.string()).optional()}),AutoApproveConfigSchema=exports_external.object({defaults:DefaultsConfigSchema.default({}),repos:exports_external.record(exports_external.string(),RepoConfigSchema).optional()})});var exports_claude_sdk_permissions={};__export(exports_claude_sdk_permissions,{translateClaudeCodePermissions:()=>translateClaudeCodePermissions,resolvePreset:()=>resolvePreset,resolvePermissionConfig:()=>resolvePermissionConfig,createPermissionGate:()=>createPermissionGate,PRESET_READ_ONLY:()=>PRESET_READ_ONLY,PRESET_FULL:()=>PRESET_FULL,PRESET_CHAT_ONLY:()=>PRESET_CHAT_ONLY});function resolvePreset(name){let preset=PRESETS[name];if(!preset)throw Error(`Unknown permission preset "${name}". Valid: ${Object.keys(PRESETS).join(", ")}`);return preset}function translateClaudeCodePermissions(ccPerms){let toolAllow=[],bashPatterns=[];for(let entry of ccPerms.allow??[]){let bashMatch=entry.match(/^Bash\((.+)\)$/);if(bashMatch){let regex=`^${bashMatch[1].replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;if(bashPatterns.push(regex),!toolAllow.includes("Bash"))toolAllow.push("Bash")}else toolAllow.push(entry)}return{allow:toolAllow.length>0?toolAllow:["*"],bashAllowPatterns:bashPatterns.length>0?bashPatterns:void 0}}function isClaudeCodeFormat(permissions){if(Array.isArray(permissions.allow))return permissions.allow.some((entry)=>typeof entry==="string"&&/^Bash\(.+\)$/.test(entry));return"deny"in permissions&&!("preset"in permissions)&&!("bashAllowPatterns"in permissions)}function resolvePermissionConfig(permissions){if(permissions?.preset)return resolvePreset(permissions.preset);if(permissions&&isClaudeCodeFormat(permissions))return translateClaudeCodePermissions(permissions);if(permissions?.allow)return{allow:permissions.allow,bashAllowPatterns:permissions.bashAllowPatterns};return PRESET_FULL}function matchesCompoundPattern(normalized,patterns2){for(let pattern of patterns2)try{let match=normalized.match(new RegExp(pattern));if(match&&match[0]===normalized)return!0}catch{}return!1}function matchesSimplePattern(normalized,patterns2){for(let pattern of patterns2)try{if(new RegExp(pattern).test(normalized))return!0}catch{if(normalized.includes(pattern))return!0}return!1}function matchesBashAllow(command,patterns2){let normalized=normalizeCommand(command);if(hasShellMetacharacters(normalized))return matchesCompoundPattern(normalized,patterns2);return matchesSimplePattern(normalized,patterns2)}function createPermissionGate(config){let{allow,bashAllowPatterns=[]}=config,allowAll=allow.includes("*"),allowSet=new Set(allow);return async(input)=>{let hookInput=input,toolName=hookInput.tool_name;if(!allowAll&&!allowSet.has(toolName))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Tool "${toolName}" is not allowed. Allowed: ${allow.join(", ")}`}};if(toolName==="Bash"&&bashAllowPatterns.length>0){let toolInput=hookInput.tool_input??{},command=typeof toolInput.command==="string"?toolInput.command:"";if(!command||!matchesBashAllow(command,bashAllowPatterns))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Bash command not in allow patterns: ${command||"(empty)"}`}}}return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}var PRESET_FULL,PRESET_READ_ONLY,PRESET_CHAT_ONLY,PRESETS;var init_claude_sdk_permissions=__esm(()=>{init_auto_approve();PRESET_FULL={allow:["*"]},PRESET_READ_ONLY={allow:["Read","Glob","Grep","WebFetch"]},PRESET_CHAT_ONLY={allow:["SendMessage","Read"]},PRESETS={full:PRESET_FULL,"read-only":PRESET_READ_ONLY,"chat-only":PRESET_CHAT_ONLY}});function pruneRecentSends(){let cutoff=Date.now()-BATCH_WINDOW_MS;while(recentOmniSends.length>0&&recentOmniSends[0]<cutoff)recentOmniSends.shift()}function formatApprovalMessage(approvalId,agentName,toolName,preview){let shortPreview=preview.length>200?`${preview.slice(0,197)}...`:preview;return["\uD83D\uDD14 *Approval Required*","",`Agent: *${agentName}*`,`Tool: \`${toolName}\``,`Preview: ${shortPreview}`,"","Reply *y* to approve or *n* to deny","Or react \uD83D\uDC4D / \uD83D\uDC4E","",`_ID: ${approvalId}_`].join(`
1131
1131
  `)}function formatBatchMessage(pendingCount){return[`\uD83D\uDD14 *${pendingCount} Approvals Pending*`,"","Multiple tool approvals are queued.","Reply *y* to approve next or *n* to deny.","Use `genie approval list` for details."].join(`
1132
1132
  `)}async function updateOmniMessageId(approvalId,omniMessageId){try{await(await getConnection())`UPDATE approvals SET omni_message_id = ${omniMessageId} WHERE id = ${approvalId}`}catch{}}async function sendApprovalToOmni(approvalId,agentName,toolName,preview,permissions){let{omniChat,omniInstance}=permissions;if(!omniChat||!omniInstance)return;pruneRecentSends();let text;if(recentOmniSends.length>=BATCH_THRESHOLD){let sql=await getConnection(),[row]=await sql`SELECT count(*)::int AS count FROM approvals WHERE decision = 'pending'`;text=formatBatchMessage(row.count)}else text=formatApprovalMessage(approvalId,agentName,toolName,preview);recentOmniSends.push(Date.now());try{let proc=Bun.spawn(["omni","send","--instance",omniInstance,"--to",omniChat,"--text",text,"--json"],{stdout:"pipe",stderr:"ignore"}),stdout=await new Response(proc.stdout).text();await proc.exited;try{let result2=JSON.parse(stdout),messageId=result2.messageId??result2.message_id??result2.id;if(messageId)await updateOmniMessageId(approvalId,String(messageId))}catch{}}catch(err){console.warn(`[remote-approval] Omni notification failed: ${err instanceof Error?err.message:String(err)}`)}}async function insertApproval(executorId,agentName,toolName,toolInputPreview,timeoutAt){let sql=await getConnection(),[row]=await sql`
1133
1133
  INSERT INTO approvals (executor_id, agent_name, tool_name, tool_input_preview, timeout_at)
@@ -2104,40 +2104,48 @@ ${answer}
2104
2104
  AND table_name NOT LIKE '_genie_%'
2105
2105
  ORDER BY table_name
2106
2106
  `).map((r)=>r.table_name)}async function filterAvailableTables(sql,requested){let existing=new Set(await getAvailableTables(sql)),available=[],skipped=[];for(let table of requested)if(existing.has(table))available.push(table);else skipped.push(table);return{available,skipped}}var require_ignore=__commonJS((exports,module)=>{function makeArray(subject){return Array.isArray(subject)?subject:[subject]}var UNDEFINED=void 0,EMPTY="",SPACE=" ",ESCAPE="\\",REGEX_TEST_BLANK_LINE=/^\s+$/,REGEX_INVALID_TRAILING_BACKSLASH=/(?:[^\\]|^)\\$/,REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION=/^\\!/,REGEX_REPLACE_LEADING_EXCAPED_HASH=/^\\#/,REGEX_SPLITALL_CRLF=/\r?\n/g,REGEX_TEST_INVALID_PATH=/^\.{0,2}\/|^\.{1,2}$/,REGEX_TEST_TRAILING_SLASH=/\/$/,SLASH="/",TMP_KEY_IGNORE="node-ignore";if(typeof Symbol<"u")TMP_KEY_IGNORE=Symbol.for("node-ignore");var KEY_IGNORE=TMP_KEY_IGNORE,define2=(object,key,value)=>{return Object.defineProperty(object,key,{value}),value},REGEX_REGEXP_RANGE=/([0-z])-([0-z])/g,RETURN_FALSE=()=>!1,sanitizeRange=(range)=>range.replace(REGEX_REGEXP_RANGE,(match,from,to)=>from.charCodeAt(0)<=to.charCodeAt(0)?match:EMPTY),cleanRangeBackSlash=(slashes)=>{let{length}=slashes;return slashes.slice(0,length-length%2)},REPLACERS=[[/^\uFEFF/,()=>EMPTY],[/((?:\\\\)*?)(\\?\s+)$/,(_,m1,m2)=>m1+(m2.indexOf("\\")===0?SPACE:EMPTY)],[/(\\+?)\s/g,(_,m1)=>{let{length}=m1;return m1.slice(0,length-length%2)+SPACE}],[/[\\$.|*+(){^]/g,(match)=>`\\${match}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return!/\/(?!$)/.test(this)?"(?:^|\\/)":"^"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(_,index,str5)=>index+6<str5.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(_,p1,p2)=>{let unescaped=p2.replace(/\\\*/g,"[^\\/]*");return p1+unescaped}],[/\\\\\\(?=[$.|*+(){^])/g,()=>ESCAPE],[/\\\\/g,()=>ESCAPE],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(match,leadEscape,range,endEscape,close)=>leadEscape===ESCAPE?`\\[${range}${cleanRangeBackSlash(endEscape)}${close}`:close==="]"?endEscape.length%2===0?`[${sanitizeRange(range)}${endEscape}]`:"[]":"[]"],[/(?:[^*])$/,(match)=>/\/$/.test(match)?`${match}$`:`${match}(?=$|\\/$)`]],REGEX_REPLACE_TRAILING_WILDCARD=/(^|\\\/)?\\\*$/,MODE_IGNORE="regex",MODE_CHECK_IGNORE="checkRegex",UNDERSCORE="_",TRAILING_WILD_CARD_REPLACERS={[MODE_IGNORE](_,p1){return`${p1?`${p1}[^/]+`:"[^/]*"}(?=$|\\/$)`},[MODE_CHECK_IGNORE](_,p1){return`${p1?`${p1}[^/]*`:"[^/]*"}(?=$|\\/$)`}},makeRegexPrefix=(pattern)=>REPLACERS.reduce((prev,[matcher,replacer])=>prev.replace(matcher,replacer.bind(pattern)),pattern),isString=(subject)=>typeof subject==="string",checkPattern=(pattern)=>pattern&&isString(pattern)&&!REGEX_TEST_BLANK_LINE.test(pattern)&&!REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)&&pattern.indexOf("#")!==0,splitPattern=(pattern)=>pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);class IgnoreRule{constructor(pattern,mark,body,ignoreCase,negative,prefix){this.pattern=pattern,this.mark=mark,this.negative=negative,define2(this,"body",body),define2(this,"ignoreCase",ignoreCase),define2(this,"regexPrefix",prefix)}get regex(){let key=UNDERSCORE+MODE_IGNORE;if(this[key])return this[key];return this._make(MODE_IGNORE,key)}get checkRegex(){let key=UNDERSCORE+MODE_CHECK_IGNORE;if(this[key])return this[key];return this._make(MODE_CHECK_IGNORE,key)}_make(mode,key){let str5=this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,TRAILING_WILD_CARD_REPLACERS[mode]),regex=this.ignoreCase?new RegExp(str5,"i"):new RegExp(str5);return define2(this,key,regex)}}var createRule=({pattern,mark},ignoreCase)=>{let negative=!1,body=pattern;if(body.indexOf("!")===0)negative=!0,body=body.substr(1);body=body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION,"!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH,"#");let regexPrefix=makeRegexPrefix(body);return new IgnoreRule(pattern,mark,body,ignoreCase,negative,regexPrefix)};class RuleManager{constructor(ignoreCase){this._ignoreCase=ignoreCase,this._rules=[]}_add(pattern){if(pattern&&pattern[KEY_IGNORE]){this._rules=this._rules.concat(pattern._rules._rules),this._added=!0;return}if(isString(pattern))pattern={pattern};if(checkPattern(pattern.pattern)){let rule=createRule(pattern,this._ignoreCase);this._added=!0,this._rules.push(rule)}}add(pattern){return this._added=!1,makeArray(isString(pattern)?splitPattern(pattern):pattern).forEach(this._add,this),this._added}test(path3,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule;this._rules.forEach((rule)=>{let{negative}=rule;if(unignored===negative&&ignored!==unignored||negative&&!ignored&&!unignored&&!checkUnignored)return;if(!rule[mode].test(path3))return;ignored=!negative,unignored=negative,matchedRule=negative?UNDEFINED:rule});let ret={ignored,unignored};if(matchedRule)ret.rule=matchedRule;return ret}}var throwError2=(message,Ctor)=>{throw new Ctor(message)},checkPath=(path3,originalPath,doThrow)=>{if(!isString(path3))return doThrow(`path must be a string, but got \`${originalPath}\``,TypeError);if(!path3)return doThrow("path must not be empty",TypeError);if(checkPath.isNotRelative(path3))return doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`,RangeError);return!0},isNotRelative=(path3)=>REGEX_TEST_INVALID_PATH.test(path3);checkPath.isNotRelative=isNotRelative;checkPath.convert=(p)=>p;class Ignore{constructor({ignorecase=!0,ignoreCase=ignorecase,allowRelativePaths=!1}={}){define2(this,KEY_IGNORE,!0),this._rules=new RuleManager(ignoreCase),this._strictPathCheck=!allowRelativePaths,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(pattern){if(this._rules.add(pattern))this._initCache();return this}addPattern(pattern){return this.add(pattern)}_test(originalPath,cache,checkUnignored,slices){let path3=originalPath&&checkPath.convert(originalPath);return checkPath(path3,originalPath,this._strictPathCheck?throwError2:RETURN_FALSE),this._t(path3,cache,checkUnignored,slices)}checkIgnore(path3){if(!REGEX_TEST_TRAILING_SLASH.test(path3))return this.test(path3);let slices=path3.split(SLASH).filter(Boolean);if(slices.pop(),slices.length){let parent=this._t(slices.join(SLASH)+SLASH,this._testCache,!0,slices);if(parent.ignored)return parent}return this._rules.test(path3,!1,MODE_CHECK_IGNORE)}_t(path3,cache,checkUnignored,slices){if(path3 in cache)return cache[path3];if(!slices)slices=path3.split(SLASH).filter(Boolean);if(slices.pop(),!slices.length)return cache[path3]=this._rules.test(path3,checkUnignored,MODE_IGNORE);let parent=this._t(slices.join(SLASH)+SLASH,cache,checkUnignored,slices);return cache[path3]=parent.ignored?parent:this._rules.test(path3,checkUnignored,MODE_IGNORE)}ignores(path3){return this._test(path3,this._ignoreCache,!1).ignored}createFilter(){return(path3)=>!this.ignores(path3)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path3){return this._test(path3,this._testCache,!0)}}var factory=(options)=>new Ignore(options),isPathValid=(path3)=>checkPath(path3&&checkPath.convert(path3),path3,RETURN_FALSE),setupWindows=()=>{let makePosix=(str5)=>/^\\\\\?\\/.test(str5)||/["<>|\u0000-\u001F]+/u.test(str5)?str5:str5.replace(/\\/g,"/");checkPath.convert=makePosix;let REGEX_TEST_WINDOWS_PATH_ABSOLUTE=/^[a-z]:\//i;checkPath.isNotRelative=(path3)=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path3)||isNotRelative(path3)};if(typeof process<"u"&&process.platform==="win32")setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define2(module.exports,Symbol.for("setupWindows"),setupWindows)});function isValid2(value){return typeof value==="string"&&VALID.has(value)}function resolveExecutorType(override){if(isValid2(override))return override;let env=process.env.GENIE_EXECUTOR;if(isValid2(env))return env;try{let persisted=loadGenieConfigSync().omni?.executor;if(isValid2(persisted))return persisted}catch{}return"tmux"}var VALID;var init_executor_config=__esm(()=>{init_genie_config2();VALID=new Set(["tmux","sdk"])});function buildTurnBasedPrompt(senderName,instanceId,chatId){return`
2107
- # WhatsApp Turn-Based Conversation
2107
+ [WhatsApp Turn \u2014 reply to ${senderName}]
2108
2108
 
2109
- You are responding to a WhatsApp message from ${senderName}.
2110
- Your context is pre-set (instance: ${instanceId}, chat: ${chatId}) \u2014 do NOT use \`omni use\` or \`omni open\`.
2109
+ You received a WhatsApp message. Read it, reply, then close the turn.
2110
+ Context is pre-set (instance: ${instanceId}, chat: ${chatId}) \u2014 do NOT run \`omni use\` or \`omni open\`.
2111
2111
 
2112
- ## Reply Channels
2112
+ Reply with omni verbs:
2113
+ - \`omni say "your reply"\` \u2014 send a text message
2114
+ - \`omni speak "text" --voice Kore\` \u2014 send a voice note
2115
+ - \`omni imagine "prompt"\` \u2014 generate and send an image
2116
+ - \`omni react "\uD83D\uDC4D"\` \u2014 react to the trigger message
2117
+ - \`omni done\` \u2014 close the turn (ALWAYS your last action)
2113
2118
 
2114
- You have two equivalent ways to send a reply to the user:
2119
+ Flow: 1) \`omni say "..."\` to reply \u2192 2) \`omni done\` to close.
2120
+ Bare text output goes nowhere \u2014 you MUST use omni verbs to reach the user.
2115
2121
 
2116
- 1. **SendMessage** (preferred): \`SendMessage(recipient: "omni", message: "your reply")\` \u2014
2117
- intercepted by the omni bridge and delivered as a WhatsApp text message.
2118
- You may call SendMessage multiple times in one turn for multi-message replies.
2119
- 2. **omni done text='...'** \u2014 closes the turn AND sends a final text in one call.
2122
+ The user's message:
2123
+ `.trim()}import{randomUUID as randomUUID9}from"crypto";import{homedir as homedir28}from"os";import{join as join52}from"path";function safeName(raw,maxLen=30){return raw.replace(/[^a-zA-Z0-9._-]/g,"").slice(0,maxLen)||"unknown"}function sanitizeWindowName2(chatId,chatName){let whatsappDm=chatId.match(/^(\d+)@s\.whatsapp\.net$/);if(whatsappDm)return`wa-${whatsappDm[1]}`;let whatsappGroup=chatId.match(/^(\d+)@g\.us$/);if(whatsappGroup)return`grp-${chatName?safeName(chatName):whatsappGroup[1]}`;let lid=chatId.match(/^(\d+)@lid$/);if(lid)return chatName?`wa-${safeName(chatName)}`:`lid-${lid[1]}`;return`chat-${safeName(chatId)}`}async function lookupChatName(chatId,_instanceId){try{let configPath2=join52(homedir28(),".omni","config.json"),{readFileSync:readFileSync27}=await import("fs"),config=JSON.parse(readFileSync27(configPath2,"utf-8")),apiUrl=config.apiUrl||"http://localhost:8882",apiKey=config.apiKey||"";if(!apiKey)return null;let url=`${apiUrl}/api/v2/chats?externalId=${encodeURIComponent(chatId)}`,res=await fetch(url,{headers:{Authorization:`Bearer ${apiKey}`},signal:AbortSignal.timeout(3000)});if(!res.ok)return null;let body=await res.json();return(body.items?.find((c)=>c.externalId===chatId)??body.items?.[0])?.name||null}catch{return null}}function buildOmniSpawnParams(agentName,chatId,entry,env,initialMessage){let instanceId=env.OMNI_INSTANCE??"",senderName=env.OMNI_SENDER_NAME??"whatsapp-user",turnContext=buildTurnBasedPrompt(senderName,instanceId,chatId),fullInitialPrompt=initialMessage?`${turnContext}
2120
2124
 
2121
- ## Available Tools
2125
+ ---
2126
+
2127
+ ${initialMessage}`:turnContext;return{provider:entry.provider??"claude",team:agentName,role:agentName,sessionId:randomUUID9(),model:entry.model,promptMode:entry.promptMode,systemPromptFile:join52(entry.dir,"AGENTS.md"),initialPrompt:fullInitialPrompt,nativeTeam:{enabled:!0,agentName,color:entry.color??void 0}}}class ClaudeCodeOmniExecutor{sessions=new Map;safePgCall=null;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(_fn){}async injectNudge(session,text){let paneId=session.tmux?.paneId;if(!paneId)return;let nudgeText=`[system] ${text}`;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(nudgeText)} Enter`)}async spawn(agentName,chatId,env,initialMessage){let resolved=await resolve3(agentName);if(!resolved)throw Error(`Agent "${agentName}" not found in genie directory`);let entry=resolved.entry,tmuxSession=agentName,chatName=await lookupChatName(chatId,env.OMNI_INSTANCE??""),windowName=sanitizeWindowName2(chatId,chatName??void 0),{paneId,created}=await ensureTeamWindow(tmuxSession,windowName,entry.dir);if(created){let omniEnv={...env,GENIE_OMNI_CHAT_ID:chatId,GENIE_OMNI_AGENT:agentName},params=buildOmniSpawnParams(agentName,chatId,entry,omniEnv,initialMessage),launch=buildLaunchCommand(params),allEnv={...omniEnv,...launch.env},envPrefix=Object.entries(allEnv).map(([k,v])=>`${k}=${shellQuote(v)}`).join(" "),cmd=envPrefix?`${envPrefix} ${launch.command}`:launch.command;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(cmd)} Enter`)}let sessionKey2=`${agentName}:${chatId}`,registration=await this.registerInWorldA(agentName,chatId,env.OMNI_INSTANCE??"",tmuxSession,windowName,paneId,entry.dir);if(this.sessions.set(sessionKey2,{executorId:registration?.executorId??null,agentId:registration?.agentId??null,repoPath:entry.dir}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionKey2,agentName,chatId,executorType:"tmux",createdAt:now,lastActivityAt:now,tmux:{session:tmuxSession,window:windowName,paneId}}}async registerInWorldA(agentName,chatId,instanceId,tmuxSession,tmuxWindow,tmuxPaneId,repoPath){if(!this.safePgCall)return null;let agent=await this.safePgCall("tmux-find-or-create-agent",()=>findOrCreateAgent(agentName,"omni","omni"),null,{chatId});if(!agent)return null;await this.safePgCall("tmux-update-agent-pane",async()=>{await(await Promise.resolve().then(() => (init_db(),exports_db)).then((m)=>m.getConnection()))`
2128
+ UPDATE agents
2129
+ SET pane_id = ${tmuxPaneId},
2130
+ session = ${tmuxSession},
2131
+ repo_path = ${repoPath},
2132
+ window_name = ${tmuxWindow},
2133
+ state = 'idle',
2134
+ last_state_change = now()
2135
+ WHERE id = ${agent.id}
2136
+ `},void 0,{chatId});let executor=await this.safePgCall("tmux-create-executor",()=>createAndLinkExecutor(agent.id,"claude","tmux",{tmuxSession,tmuxWindow,tmuxPaneId,tmuxWindowId:null,metadata:{source:"omni",chat_id:chatId,instance_id:instanceId}}),null,{chatId});return executor?{executorId:executor.id,agentId:agent.id}:null}async updateState(executorId,state,chatId){if(!this.safePgCall)return;await this.safePgCall("tmux-update-executor-state",()=>updateExecutorState(executorId,state),void 0,{executorId,chatId})}async deliver(session,message){let state=this.sessions.get(session.id);if(state?.executorId)await this.updateState(state.executorId,"working",session.chatId);let senderName=message.sender||"whatsapp-user",body=`${buildTurnBasedPrompt(senderName,message.instanceId,session.chatId)}
2122
2137
 
2123
- - SendMessage(recipient: "omni", message: '...') \u2014 send a text reply (repeatable)
2124
- - omni done text='...' \u2014 send final text + close turn (use as the LAST action)
2125
- - omni done react='emoji' \u2014 react instead of replying, then close turn
2126
- - omni done media='/path' caption='...' \u2014 send media + close turn
2127
- - omni done skip=true \u2014 close turn silently
2138
+ ---
2128
2139
 
2129
- ## Rules
2140
+ [${senderName}]: ${message.content}`,agentId=state?.agentId,repoPath=state?.repoPath;if(agentId&&repoPath)try{await send(repoPath,`omni:${senderName}`,agentId,body)}catch(err){console.error(`[claude-code] mailbox.send failed for ${session.id}:`,err instanceof Error?err.message:err)}else console.error(`[claude-code] deliver: no agentId/repoPath for session ${session.id}, message lost`);if(session.lastActivityAt=Date.now(),state?.executorId)await this.updateState(state.executorId,"idle",session.chatId)}async shutdown(session){let state=this.sessions.get(session.id);try{if(session.tmux)await killWindow(session.tmux.session,session.tmux.window)}finally{if(state?.executorId&&this.safePgCall)await this.safePgCall("tmux-terminate-executor",()=>terminateExecutor(state.executorId),void 0,{executorId:state.executorId,chatId:session.chatId});if(state?.agentId&&this.safePgCall)await this.safePgCall("tmux-unregister-agent",()=>unregister(state.agentId),void 0,{chatId:session.chatId});this.sessions.delete(session.id)}}async isAlive(session){let paneId=session.tmux?.paneId;if(!paneId)return!1;try{if(!await isPaneAlive(paneId))return!1;return await isPaneProcessRunning(paneId,"claude")}catch{return!1}}}var init_claude_code2=__esm(()=>{init_agent_directory();init_agent_registry();init_executor_registry();init_mailbox();init_provider_adapters();init_team_lead_command();init_tmux()});async function recordAuditEvent2(safePgCall,type2,attrs){let entityType=attrs.entity_type??"executor",entityId=attrs.entity_id??attrs.executor_id??"",actor=attrs.actor??attrs.agent_id??null,{entity_type:_et,entity_id:_eid,actor:_a,...details}=attrs;await safePgCall(`audit:${type2}`,(sql)=>sql`INSERT INTO audit_events (entity_type, entity_id, event_type, actor, details)
2141
+ VALUES (${entityType}, ${entityId}, ${type2}, ${actor}, ${JSON.stringify(details)})`,void 0,{executorId:entityId,chatId:attrs.chat_id??""})}async function loadSystemPrompt(entry){let identityPath=loadIdentity(entry);if(!identityPath)return;let{readFileSync:readFileSync27}=await import("fs");try{return readFileSync27(identityPath,"utf-8")}catch{return}}async function resolveSystemPrompt(entry,state){let prompt2=await loadSystemPrompt(entry),isTurnBased=Boolean(state.env.OMNI_INSTANCE);return{prompt:prompt2,isTurnBased}}function buildTurnContextPrefix(state,message,chatId){if(!state.env.OMNI_INSTANCE)return"";return buildTurnBasedPrompt(message.sender,state.env.OMNI_INSTANCE,state.env.OMNI_CHAT??chatId)}function extractTextFromAssistant(msg){if(!msg.message)return[];return msg.message.content.filter((b2)=>b2.type==="text"&&b2.text).map((b2)=>b2.text)}async function collectQueryResult(queryMessages){let textParts=[],sessionId;try{for await(let msg of queryMessages){if(msg.type==="assistant")textParts.push(...extractTextFromAssistant(msg));if(msg.type==="result"&&msg.subtype==="success")sessionId=msg.session_id}}catch(err){if(err.name==="AbortError")return{text:""};throw err}return{text:textParts.join(`
2142
+ `).trim(),sessionId}}function buildReplyPayload(agent,chatId,instanceId,extra={}){return JSON.stringify({content:"",agent,chat_id:chatId,instance_id:instanceId,timestamp:new Date().toISOString(),...extra})}function resolveAction(params,env){if(params.skip)return{type:"skip",extra:{reason:params.reason},label:"Turn closed (skip)."};if(params.react)return{type:"react",extra:{react:String(params.react),message_id:env.OMNI_MESSAGE??""},label:`Reacted ${params.react} + turn closed.`};if(params.media)return{type:"media",extra:{content:params.caption?String(params.caption):params.text?String(params.text):"",media:String(params.media)},label:"Media sent + turn closed."};if(params.text)return{type:"text",extra:{content:String(params.text)},label:"Turn closed. Message delivered."};return{type:"skip",extra:{},label:"Turn closed (skip)."}}function handleDoneTool(params,env,natsPublish){let instanceId=env.OMNI_INSTANCE??"",chatId=env.OMNI_CHAT??"",agent=env.OMNI_AGENT??"",action=resolveAction(params,env);if(action.type==="skip"){if(natsPublish&&instanceId&&chatId)natsPublish(`omni.turn.done.${instanceId}.${chatId}`,JSON.stringify({action:"skip",...action.extra}));return action.label}if(!natsPublish||!instanceId||!chatId)return console.warn("[claude-sdk] No NATS publish available \u2014 reply dropped"),"Turn close attempted but NATS publish not available.";return natsPublish(`omni.reply.${instanceId}.${chatId}`,buildReplyPayload(agent,chatId,instanceId,action.extra)),action.label}function parseSendMessageInput(input){if(!input||typeof input!=="object")return{};let obj=input,recipient=typeof obj.recipient==="string"?obj.recipient:typeof obj.to==="string"?obj.to:void 0,body=typeof obj.message==="string"?obj.message:typeof obj.content==="string"?obj.content:void 0;return{recipient,body}}function createSendMessageOmniHook(env,natsPublish){return async(input)=>{let hookInput=input;if(hookInput.tool_name!=="SendMessage")return{};let{recipient,body}=parseSendMessageInput(hookInput.tool_input);if(recipient!=="omni")return{};let instanceId=env.OMNI_INSTANCE??"",chatId=env.OMNI_CHAT??"",agent=env.OMNI_AGENT??"";if(!instanceId||!chatId)return{};if(!body||body.trim()==="")return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'SendMessage(recipient: "omni") requires a non-empty `message` field. Retry with the reply text.'}};if(!natsPublish)return console.warn("[claude-sdk] SendMessage(to: omni) intercepted but NATS publish unavailable \u2014 message dropped"),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Omni bridge unavailable \u2014 message could not be delivered."}};return natsPublish(`omni.reply.${instanceId}.${chatId}`,buildReplyPayload(agent,chatId,instanceId,{content:body})),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Message delivered to user via omni bridge."}}}}async function createDoneMcpServer(env,natsPublish){let{createSdkMcpServer,tool}=await import("@anthropic-ai/claude-agent-sdk");return createSdkMcpServer({name:"genie-omni-tools",tools:[tool("done","Close this turn. REQUIRED after processing the user message. Sends a final response, reacts, or skips. Call exactly once per turn.",{text:exports_external.string().optional().describe("Final message to the user"),media:exports_external.string().optional().describe("File path for media attachment"),caption:exports_external.string().optional().describe("Caption for media"),react:exports_external.string().optional().describe("Emoji reaction (instead of text)"),skip:exports_external.boolean().optional().describe("Close turn without sending anything"),reason:exports_external.string().optional().describe("Internal reason for skipping")},async(args)=>{return{content:[{type:"text",text:handleDoneTool(args,env,natsPublish)}]}})]})}class ClaudeSdkOmniExecutor{sessions=new Map;safePgCall=null;natsPublish=null;deliveryQueues=new Map;pendingNudges=new Map;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(fn){this.natsPublish=fn}async injectNudge(session,text){if(!this.sessions.has(session.id))return;this.pendingNudges.set(session.id,text)}async spawn(agentName,chatId,env,_initialMessage){if(!await resolve3(agentName))throw Error(`Agent "${agentName}" not found in genie directory`);let provider=new ClaudeSdkProvider,abortController=new AbortController,sessionId=`${agentName}:${chatId}`,registration=await this.registerInWorldA(agentName,chatId,env.OMNI_INSTANCE??"");if(this.sessions.set(sessionId,{abortController,running:!0,provider,executorId:registration?.executorId??null,claudeSessionId:registration?.claudeSessionId,dbSessionId:null,turnIndex:0,env}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionId,agentName,chatId,executorType:"sdk",createdAt:now,lastActivityAt:now,sdk:{claudeSessionId:registration?.claudeSessionId,executorId:registration?.executorId}}}async registerInWorldA(agentName,chatId,instanceId){if(!this.safePgCall)return null;let agent=await this.safePgCall("sdk-find-or-create-agent",()=>findOrCreateAgent(agentName,"omni","omni"),null,{chatId});if(!agent)return null;let existing=await this.safePgCall("sdk-find-existing-executor",()=>findLatestByMetadata({agentId:agent.id,source:"omni",chatId}),null,{chatId});if(existing)return await this.safePgCall("sdk-relink-executor",()=>relinkExecutorToAgent(existing.id,agent.id),void 0,{executorId:existing.id,chatId}),await recordAuditEvent2(this.safePgCall,"session.resumed",{executor_id:existing.id,agent_id:agentName,chat_id:chatId,claude_session_id:existing.claudeSessionId}),{executorId:existing.id,claudeSessionId:existing.claudeSessionId??void 0};let executor=await this.safePgCall("sdk-create-executor",()=>createAndLinkExecutor(agent.id,"claude","api",{claudeSessionId:void 0,metadata:{source:"omni",chat_id:chatId,instance_id:instanceId}}),null,{chatId});if(executor)await recordAuditEvent2(this.safePgCall,"session.created_fresh",{executor_id:executor.id,agent_id:agentName,chat_id:chatId});return executor?{executorId:executor.id}:null}async updateState(executorId,state,chatId){if(!this.safePgCall)return;await this.safePgCall("sdk-update-executor-state",()=>updateExecutorState(executorId,state),void 0,{executorId,chatId})}async deliver(session,message){let state=this.sessions.get(session.id);if(!state)throw Error(`No SDK session found for ${session.id}`);let current=(this.deliveryQueues.get(session.id)??Promise.resolve()).then(()=>this._processDelivery(session,state,message));this.deliveryQueues.set(session.id,current.catch(()=>{}))}async _processDelivery(session,state,message){let resolved=await resolve3(session.agentName);if(!resolved)throw Error(`Agent "${session.agentName}" not found in genie directory`);let entry=resolved.entry,permissionConfig=resolvePermissionConfig(entry.permissions),{prompt:systemPrompt,isTurnBased}=await resolveSystemPrompt(entry,state);if(state.executorId)await this.updateState(state.executorId,"working",session.chatId);if(this.safePgCall)await recordAuditEvent2(this.safePgCall,"deliver.start",{executor_id:state.executorId??session.id,agent_id:session.agentName,chat_id:message.chatId,instance_id:message.instanceId});let doneMcp=await createDoneMcpServer(state.env,this.natsPublish),sendMessageHooks=isTurnBased?{PreToolUse:[{matcher:"SendMessage",hooks:[createSendMessageOmniHook(state.env,this.natsPublish)]}]}:void 0,extraOptions={abortController:state.abortController,mcpServers:{"genie-omni-tools":doneMcp},...sendMessageHooks&&{hooks:sendMessageHooks}};if(state.claudeSessionId)extraOptions.resume=state.claudeSessionId;let turnPrefix=buildTurnContextPrefix(state,message,session.chatId),queryContent=message.content,pendingNudge=this.pendingNudges.get(session.id);if(pendingNudge)queryContent=`[system] ${pendingNudge}
2130
2143
 
2131
- 1. Use \`SendMessage(recipient: "omni", ...)\` for normal text replies.
2132
- 2. ALWAYS call \`omni done\` as your LAST action to close the turn \u2014 even if you already sent SendMessage replies, call \`omni done skip=true\`.
2133
- 3. Do NOT generate bare text as your reply \u2014 it will go nowhere. Use SendMessage or omni done.
2134
- `.trim()}import{randomUUID as randomUUID9}from"crypto";import{mkdirSync as mkdirSync20,writeFileSync as writeFileSync23}from"fs";import{homedir as homedir28}from"os";import{dirname as dirname10,join as join52}from"path";function sanitizeWindowName2(chatId){let whatsappDm=chatId.match(/^(\d+)@s\.whatsapp\.net$/);if(whatsappDm)return`wa-${whatsappDm[1]}`;let whatsappGroup=chatId.match(/^(\d+)@g\.us$/);if(whatsappGroup)return`group-${whatsappGroup[1]}`;let lid=chatId.match(/^(\d+)@lid$/);if(lid)return`lid-${lid[1]}`;return`chat-${chatId.replace(/[^a-zA-Z0-9._-]/g,"").slice(0,30)||"unknown"}`}function buildOmniSpawnParams(agentName,chatId,entry,env,initialMessage){let instanceId=env.OMNI_INSTANCE??"",senderName=env.OMNI_SENDER_NAME??"whatsapp-user",turnPrompt=buildTurnBasedPrompt(senderName,instanceId,chatId);return{provider:entry.provider??"claude",team:agentName,role:agentName,sessionId:randomUUID9(),model:entry.model,promptMode:entry.promptMode,systemPromptFile:join52(entry.dir,"AGENTS.md"),systemPrompt:turnPrompt,initialPrompt:initialMessage,nativeTeam:{enabled:!0,agentName,color:entry.color??void 0}}}class ClaudeCodeOmniExecutor{sessions=new Map;safePgCall=null;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(_fn){}async injectNudge(session,text){let paneId=session.tmux?.paneId;if(!paneId)return;let nudgeText=`[system] ${text}`;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(nudgeText)} Enter`)}async spawn(agentName,chatId,env){let resolved=await resolve3(agentName);if(!resolved)throw Error(`Agent "${agentName}" not found in genie directory`);let entry=resolved.entry,tmuxSession=agentName,windowName=sanitizeWindowName2(chatId),{paneId,created}=await ensureTeamWindow(tmuxSession,windowName,entry.dir);if(created){let omniEnv={...env,GENIE_OMNI_CHAT_ID:chatId,GENIE_OMNI_AGENT:agentName},params=buildOmniSpawnParams(agentName,chatId,entry,omniEnv),launch=buildLaunchCommand(params),allEnv={...omniEnv,...launch.env},envPrefix=Object.entries(allEnv).map(([k,v])=>`${k}=${shellQuote(v)}`).join(" "),cmd=envPrefix?`${envPrefix} ${launch.command}`:launch.command;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(cmd)} Enter`)}let sessionKey2=`${agentName}:${chatId}`,executorId=await this.registerInWorldA(agentName,chatId,env.OMNI_INSTANCE??"",tmuxSession,windowName,paneId);if(this.sessions.set(sessionKey2,{executorId}),executorId)await this.updateState(executorId,"running",chatId);let now=Date.now();return{id:sessionKey2,agentName,chatId,executorType:"tmux",createdAt:now,lastActivityAt:now,tmux:{session:tmuxSession,window:windowName,paneId}}}async registerInWorldA(agentName,chatId,instanceId,tmuxSession,tmuxWindow,tmuxPaneId){if(!this.safePgCall)return null;let agent=await this.safePgCall("tmux-find-or-create-agent",()=>findOrCreateAgent(agentName,"omni","omni"),null,{chatId});if(!agent)return null;return(await this.safePgCall("tmux-create-executor",()=>createAndLinkExecutor(agent.id,"claude","tmux",{tmuxSession,tmuxWindow,tmuxPaneId,tmuxWindowId:null,metadata:{source:"omni",chat_id:chatId,instance_id:instanceId}}),null,{chatId}))?.id??null}async updateState(executorId,state,chatId){if(!this.safePgCall)return;await this.safePgCall("tmux-update-executor-state",()=>updateExecutorState(executorId,state),void 0,{executorId,chatId})}async deliver(session,message){let state=this.sessions.get(session.id);if(state?.executorId)await this.updateState(state.executorId,"working",session.chatId);let tmuxSessionName=session.tmux?.session??session.agentName,inboxDir=join52(process.env.CLAUDE_CONFIG_DIR??join52(homedir28(),".claude"),"teams",tmuxSessionName,"inboxes"),inboxFile=join52(inboxDir,`${sanitizeWindowName2(session.chatId)}.json`);mkdirSync20(dirname10(inboxFile),{recursive:!0});let messages2=[];try{let{readFileSync:readFileSync27}=await import("fs");messages2=JSON.parse(readFileSync27(inboxFile,"utf-8"))}catch{}if(messages2.push({from:message.sender||"whatsapp-user",text:message.content,summary:message.content.slice(0,120),timestamp:message.timestamp||new Date().toISOString(),read:!1}),writeFileSync23(inboxFile,JSON.stringify(messages2,null,2)),session.lastActivityAt=Date.now(),state?.executorId)await this.updateState(state.executorId,"idle",session.chatId)}async shutdown(session){let state=this.sessions.get(session.id);try{if(session.tmux)await killWindow(session.tmux.session,session.tmux.window)}finally{if(state?.executorId&&this.safePgCall)await this.safePgCall("tmux-terminate-executor",()=>terminateExecutor(state.executorId),void 0,{executorId:state.executorId,chatId:session.chatId});this.sessions.delete(session.id)}}async isAlive(session){let paneId=session.tmux?.paneId;if(!paneId)return!1;try{if(!await isPaneAlive(paneId))return!1;return await isPaneProcessRunning(paneId,"claude")}catch{return!1}}}var init_claude_code2=__esm(()=>{init_agent_directory();init_agent_registry();init_executor_registry();init_provider_adapters();init_team_lead_command();init_tmux()});async function recordAuditEvent2(safePgCall,type2,attrs){let entityType=attrs.entity_type??"executor",entityId=attrs.entity_id??attrs.executor_id??"",actor=attrs.actor??attrs.agent_id??null,{entity_type:_et,entity_id:_eid,actor:_a,...details}=attrs;await safePgCall(`audit:${type2}`,(sql)=>sql`INSERT INTO audit_events (entity_type, entity_id, event_type, actor, details)
2135
- VALUES (${entityType}, ${entityId}, ${type2}, ${actor}, ${JSON.stringify(details)})`,void 0,{executorId:entityId,chatId:attrs.chat_id??""})}async function loadSystemPrompt(entry){let identityPath=loadIdentity(entry);if(!identityPath)return;let{readFileSync:readFileSync27}=await import("fs");try{return readFileSync27(identityPath,"utf-8")}catch{return}}async function resolveSystemPrompt(entry,state,message,chatId){let prompt2=await loadSystemPrompt(entry),isTurnBased=Boolean(state.env.OMNI_INSTANCE);if(isTurnBased){let turnPrompt=buildTurnBasedPrompt(message.sender,state.env.OMNI_INSTANCE,state.env.OMNI_CHAT??chatId);prompt2=prompt2?`${turnPrompt}
2144
+ ${message.content}`,this.pendingNudges.delete(session.id);if(turnPrefix)queryContent=`${turnPrefix}
2136
2145
 
2137
- ${prompt2}`:turnPrompt}return{prompt:prompt2,isTurnBased}}function extractTextFromAssistant(msg){if(!msg.message)return[];return msg.message.content.filter((b2)=>b2.type==="text"&&b2.text).map((b2)=>b2.text)}async function collectQueryResult(queryMessages){let textParts=[],sessionId;try{for await(let msg of queryMessages){if(msg.type==="assistant")textParts.push(...extractTextFromAssistant(msg));if(msg.type==="result"&&msg.subtype==="success")sessionId=msg.session_id}}catch(err){if(err.name==="AbortError")return{text:""};throw err}return{text:textParts.join(`
2138
- `).trim(),sessionId}}function buildReplyPayload(agent,chatId,instanceId,extra={}){return JSON.stringify({content:"",agent,chat_id:chatId,instance_id:instanceId,timestamp:new Date().toISOString(),...extra})}function resolveAction(params,env){if(params.skip)return{type:"skip",extra:{reason:params.reason},label:"Turn closed (skip)."};if(params.react)return{type:"react",extra:{react:String(params.react),message_id:env.OMNI_MESSAGE??""},label:`Reacted ${params.react} + turn closed.`};if(params.media)return{type:"media",extra:{content:params.caption?String(params.caption):params.text?String(params.text):"",media:String(params.media)},label:"Media sent + turn closed."};if(params.text)return{type:"text",extra:{content:String(params.text)},label:"Turn closed. Message delivered."};return{type:"skip",extra:{},label:"Turn closed (skip)."}}function handleDoneTool(params,env,natsPublish){let instanceId=env.OMNI_INSTANCE??"",chatId=env.OMNI_CHAT??"",agent=env.OMNI_AGENT??"",action=resolveAction(params,env);if(action.type==="skip"){if(natsPublish&&instanceId&&chatId)natsPublish(`omni.turn.done.${instanceId}.${chatId}`,JSON.stringify({action:"skip",...action.extra}));return action.label}if(!natsPublish||!instanceId||!chatId)return console.warn("[claude-sdk] No NATS publish available \u2014 reply dropped"),"Turn close attempted but NATS publish not available.";return natsPublish(`omni.reply.${instanceId}.${chatId}`,buildReplyPayload(agent,chatId,instanceId,action.extra)),action.label}function parseSendMessageInput(input){if(!input||typeof input!=="object")return{};let obj=input,recipient=typeof obj.recipient==="string"?obj.recipient:typeof obj.to==="string"?obj.to:void 0,body=typeof obj.message==="string"?obj.message:typeof obj.content==="string"?obj.content:void 0;return{recipient,body}}function createSendMessageOmniHook(env,natsPublish){return async(input)=>{let hookInput=input;if(hookInput.tool_name!=="SendMessage")return{};let{recipient,body}=parseSendMessageInput(hookInput.tool_input);if(recipient!=="omni")return{};let instanceId=env.OMNI_INSTANCE??"",chatId=env.OMNI_CHAT??"",agent=env.OMNI_AGENT??"";if(!instanceId||!chatId)return{};if(!body||body.trim()==="")return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'SendMessage(recipient: "omni") requires a non-empty `message` field. Retry with the reply text.'}};if(!natsPublish)return console.warn("[claude-sdk] SendMessage(to: omni) intercepted but NATS publish unavailable \u2014 message dropped"),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Omni bridge unavailable \u2014 message could not be delivered."}};return natsPublish(`omni.reply.${instanceId}.${chatId}`,buildReplyPayload(agent,chatId,instanceId,{content:body})),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Message delivered to user via omni bridge."}}}}async function createDoneMcpServer(env,natsPublish){let{createSdkMcpServer,tool}=await import("@anthropic-ai/claude-agent-sdk");return createSdkMcpServer({name:"genie-omni-tools",tools:[tool("done","Close this turn. REQUIRED after processing the user message. Sends a final response, reacts, or skips. Call exactly once per turn.",{text:exports_external.string().optional().describe("Final message to the user"),media:exports_external.string().optional().describe("File path for media attachment"),caption:exports_external.string().optional().describe("Caption for media"),react:exports_external.string().optional().describe("Emoji reaction (instead of text)"),skip:exports_external.boolean().optional().describe("Close turn without sending anything"),reason:exports_external.string().optional().describe("Internal reason for skipping")},async(args)=>{return{content:[{type:"text",text:handleDoneTool(args,env,natsPublish)}]}})]})}class ClaudeSdkOmniExecutor{sessions=new Map;safePgCall=null;natsPublish=null;deliveryQueues=new Map;pendingNudges=new Map;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(fn){this.natsPublish=fn}async injectNudge(session,text){if(!this.sessions.has(session.id))return;this.pendingNudges.set(session.id,text)}async spawn(agentName,chatId,env){if(!await resolve3(agentName))throw Error(`Agent "${agentName}" not found in genie directory`);let provider=new ClaudeSdkProvider,abortController=new AbortController,sessionId=`${agentName}:${chatId}`,registration=await this.registerInWorldA(agentName,chatId,env.OMNI_INSTANCE??"");if(this.sessions.set(sessionId,{abortController,running:!0,provider,executorId:registration?.executorId??null,claudeSessionId:registration?.claudeSessionId,dbSessionId:null,turnIndex:0,env}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionId,agentName,chatId,executorType:"sdk",createdAt:now,lastActivityAt:now,sdk:{claudeSessionId:registration?.claudeSessionId,executorId:registration?.executorId}}}async registerInWorldA(agentName,chatId,instanceId){if(!this.safePgCall)return null;let agent=await this.safePgCall("sdk-find-or-create-agent",()=>findOrCreateAgent(agentName,"omni","omni"),null,{chatId});if(!agent)return null;let existing=await this.safePgCall("sdk-find-existing-executor",()=>findLatestByMetadata({agentId:agent.id,source:"omni",chatId}),null,{chatId});if(existing)return await this.safePgCall("sdk-relink-executor",()=>relinkExecutorToAgent(existing.id,agent.id),void 0,{executorId:existing.id,chatId}),await recordAuditEvent2(this.safePgCall,"session.resumed",{executor_id:existing.id,agent_id:agentName,chat_id:chatId,claude_session_id:existing.claudeSessionId}),{executorId:existing.id,claudeSessionId:existing.claudeSessionId??void 0};let executor=await this.safePgCall("sdk-create-executor",()=>createAndLinkExecutor(agent.id,"claude","api",{claudeSessionId:void 0,metadata:{source:"omni",chat_id:chatId,instance_id:instanceId}}),null,{chatId});if(executor)await recordAuditEvent2(this.safePgCall,"session.created_fresh",{executor_id:executor.id,agent_id:agentName,chat_id:chatId});return executor?{executorId:executor.id}:null}async updateState(executorId,state,chatId){if(!this.safePgCall)return;await this.safePgCall("sdk-update-executor-state",()=>updateExecutorState(executorId,state),void 0,{executorId,chatId})}async deliver(session,message){let state=this.sessions.get(session.id);if(!state)throw Error(`No SDK session found for ${session.id}`);let current=(this.deliveryQueues.get(session.id)??Promise.resolve()).then(()=>this._processDelivery(session,state,message));this.deliveryQueues.set(session.id,current.catch(()=>{}))}async _processDelivery(session,state,message){let resolved=await resolve3(session.agentName);if(!resolved)throw Error(`Agent "${session.agentName}" not found in genie directory`);let entry=resolved.entry,permissionConfig=resolvePermissionConfig(entry.permissions),{prompt:systemPrompt,isTurnBased}=await resolveSystemPrompt(entry,state,message,session.chatId);if(state.executorId)await this.updateState(state.executorId,"working",session.chatId);if(this.safePgCall)await recordAuditEvent2(this.safePgCall,"deliver.start",{executor_id:state.executorId??session.id,agent_id:session.agentName,chat_id:message.chatId,instance_id:message.instanceId});let doneMcp=await createDoneMcpServer(state.env,this.natsPublish),sendMessageHooks=isTurnBased?{PreToolUse:[{matcher:"SendMessage",hooks:[createSendMessageOmniHook(state.env,this.natsPublish)]}]}:void 0,extraOptions={abortController:state.abortController,mcpServers:{"genie-omni-tools":doneMcp},...sendMessageHooks&&{hooks:sendMessageHooks}};if(state.claudeSessionId)extraOptions.resume=state.claudeSessionId;let queryContent=message.content,pendingNudge=this.pendingNudges.get(session.id);if(pendingNudge)queryContent=`[system] ${pendingNudge}
2146
+ ---
2139
2147
 
2140
- ${message.content}`,this.pendingNudges.delete(session.id);let{messages:queryMessages}=state.provider.runQuery({agentId:session.agentName,executorId:session.id,team:"",role:session.agentName,cwd:entry.dir||process.cwd(),model:entry.model,systemPrompt:state.claudeSessionId&&!isTurnBased?void 0:systemPrompt},queryContent,permissionConfig,extraOptions,entry.sdk);await this.captureUserTurn(state,session.agentName,session.id,message.content);let result2=await collectQueryResult(queryMessages);if(result2.sessionId)await this.reconcileSessionId(state,session,result2.sessionId);if(await this.captureAssistantTurn(state,session.id,result2.sessionId,session.agentName,result2.text),session.lastActivityAt=Date.now(),this.safePgCall)await recordAuditEvent2(this.safePgCall,"deliver.end",{executor_id:state.executorId??session.id,agent_id:session.agentName,chat_id:message.chatId,instance_id:message.instanceId,turn_count:state.turnIndex});if(state.executorId)await this.updateState(state.executorId,"idle",session.chatId)}async reconcileSessionId(state,session,returnedSessionId){if(state.claudeSessionId&&returnedSessionId!==state.claudeSessionId&&this.safePgCall)await recordAuditEvent2(this.safePgCall,"session.resume_rejected",{executor_id:state.executorId??session.id,agent_id:session.agentName,chat_id:session.chatId,old_session_id:state.claudeSessionId,new_session_id:returnedSessionId});let execId=state.executorId;if(execId&&this.safePgCall&&returnedSessionId!==state.claudeSessionId)await this.safePgCall("sdk-update-claude-session",()=>updateClaudeSessionId(execId,returnedSessionId),void 0,{executorId:execId,chatId:session.chatId});state.claudeSessionId=returnedSessionId}async captureUserTurn(state,agentName,_sessionKey,content){if(!this.safePgCall)return;if(!state.dbSessionId&&state.executorId)state.dbSessionId=await startSession(this.safePgCall,state.executorId,state.claudeSessionId,agentName);if(state.dbSessionId)await recordTurn(this.safePgCall,state.dbSessionId,state.turnIndex++,"user",content)}async captureAssistantTurn(state,sessionKey2,claudeSessionId,agentName,replyText){if(!this.safePgCall)return;if(claudeSessionId&&state.dbSessionId?.startsWith("sdk-")){let newId=await startSession(this.safePgCall,state.executorId??sessionKey2,claudeSessionId,agentName);if(newId)state.dbSessionId=newId}if(state.dbSessionId&&replyText)await recordTurn(this.safePgCall,state.dbSessionId,state.turnIndex++,"assistant",replyText),await updateTurnCount(this.safePgCall,state.dbSessionId,state.turnIndex)}async waitForDeliveries(sessionId){if(sessionId)await this.deliveryQueues.get(sessionId);else await Promise.all([...this.deliveryQueues.values()])}async shutdown(session){let state=this.sessions.get(session.id);if(!state)return;if(state.abortController.abort(),state.running=!1,state.dbSessionId&&this.safePgCall)await endSession(this.safePgCall,state.dbSessionId,"completed");if(state.executorId&&this.safePgCall)await this.safePgCall("sdk-terminate-executor",()=>terminateExecutor(state.executorId),void 0,{executorId:state.executorId,chatId:session.chatId});this.sessions.delete(session.id),this.deliveryQueues.delete(session.id)}async isAlive(session){let state=this.sessions.get(session.id);if(!state)return!1;return state.running&&!state.abortController.signal.aborted}}var init_claude_sdk2=__esm(()=>{init_zod();init_agent_directory();init_agent_registry();init_executor_registry();init_claude_sdk_permissions();init_claude_sdk()});class OmniQueue{sql;handler;pollTimer=null;processing=0;stopped=!1;maxPerMinute;pollIntervalMs;maxConcurrent;staleTimeoutMs;constructor(sql,handler,config={}){this.sql=sql;this.handler=handler;this.maxPerMinute=config.maxPerMinute??60,this.pollIntervalMs=config.pollIntervalMs??1000,this.maxConcurrent=config.maxConcurrent??5,this.staleTimeoutMs=config.staleTimeoutMs??300000}async enqueue(message,env={}){let envJson=JSON.stringify(env);return(await this.sql`
2148
+ ${queryContent}`;let{messages:queryMessages}=state.provider.runQuery({agentId:session.agentName,executorId:session.id,team:"",role:session.agentName,cwd:entry.dir||process.cwd(),model:entry.model,systemPrompt:state.claudeSessionId&&!isTurnBased?void 0:systemPrompt},queryContent,permissionConfig,extraOptions,entry.sdk);await this.captureUserTurn(state,session.agentName,session.id,message.content);let result2=await collectQueryResult(queryMessages);if(result2.sessionId)await this.reconcileSessionId(state,session,result2.sessionId);if(await this.captureAssistantTurn(state,session.id,result2.sessionId,session.agentName,result2.text),session.lastActivityAt=Date.now(),this.safePgCall)await recordAuditEvent2(this.safePgCall,"deliver.end",{executor_id:state.executorId??session.id,agent_id:session.agentName,chat_id:message.chatId,instance_id:message.instanceId,turn_count:state.turnIndex});if(state.executorId)await this.updateState(state.executorId,"idle",session.chatId)}async reconcileSessionId(state,session,returnedSessionId){if(state.claudeSessionId&&returnedSessionId!==state.claudeSessionId&&this.safePgCall)await recordAuditEvent2(this.safePgCall,"session.resume_rejected",{executor_id:state.executorId??session.id,agent_id:session.agentName,chat_id:session.chatId,old_session_id:state.claudeSessionId,new_session_id:returnedSessionId});let execId=state.executorId;if(execId&&this.safePgCall&&returnedSessionId!==state.claudeSessionId)await this.safePgCall("sdk-update-claude-session",()=>updateClaudeSessionId(execId,returnedSessionId),void 0,{executorId:execId,chatId:session.chatId});state.claudeSessionId=returnedSessionId}async captureUserTurn(state,agentName,_sessionKey,content){if(!this.safePgCall)return;if(!state.dbSessionId&&state.executorId)state.dbSessionId=await startSession(this.safePgCall,state.executorId,state.claudeSessionId,agentName);if(state.dbSessionId)await recordTurn(this.safePgCall,state.dbSessionId,state.turnIndex++,"user",content)}async captureAssistantTurn(state,sessionKey2,claudeSessionId,agentName,replyText){if(!this.safePgCall)return;if(claudeSessionId&&state.dbSessionId?.startsWith("sdk-")){let newId=await startSession(this.safePgCall,state.executorId??sessionKey2,claudeSessionId,agentName);if(newId)state.dbSessionId=newId}if(state.dbSessionId&&replyText)await recordTurn(this.safePgCall,state.dbSessionId,state.turnIndex++,"assistant",replyText),await updateTurnCount(this.safePgCall,state.dbSessionId,state.turnIndex)}async waitForDeliveries(sessionId){if(sessionId)await this.deliveryQueues.get(sessionId);else await Promise.all([...this.deliveryQueues.values()])}async shutdown(session){let state=this.sessions.get(session.id);if(!state)return;if(state.abortController.abort(),state.running=!1,state.dbSessionId&&this.safePgCall)await endSession(this.safePgCall,state.dbSessionId,"completed");if(state.executorId&&this.safePgCall)await this.safePgCall("sdk-terminate-executor",()=>terminateExecutor(state.executorId),void 0,{executorId:state.executorId,chatId:session.chatId});this.sessions.delete(session.id),this.deliveryQueues.delete(session.id)}async isAlive(session){let state=this.sessions.get(session.id);if(!state)return!1;return state.running&&!state.abortController.signal.aborted}}var init_claude_sdk2=__esm(()=>{init_zod();init_agent_directory();init_agent_registry();init_executor_registry();init_claude_sdk_permissions();init_claude_sdk()});class OmniQueue{sql;handler;pollTimer=null;processing=0;stopped=!1;maxPerMinute;pollIntervalMs;maxConcurrent;staleTimeoutMs;constructor(sql,handler,config={}){this.sql=sql;this.handler=handler;this.maxPerMinute=config.maxPerMinute??60,this.pollIntervalMs=config.pollIntervalMs??1000,this.maxConcurrent=config.maxConcurrent??5,this.staleTimeoutMs=config.staleTimeoutMs??300000}async enqueue(message,env={}){let envJson=JSON.stringify(env);return(await this.sql`
2141
2149
  INSERT INTO omni_requests (agent, chat_id, instance_id, content, sender, env)
2142
2150
  VALUES (${message.agent}, ${message.chatId}, ${message.instanceId}, ${message.content}, ${message.sender}, ${envJson}::jsonb)
2143
2151
  RETURNING id
@@ -2183,13 +2191,13 @@ ${message.content}`,this.pendingNudges.delete(session.id);let{messages:queryMess
2183
2191
  `}}class TurnTracker{turns=new Map;open(sessionKey2,turnId,messageId){this.turns.set(sessionKey2,{turnId,sessionKey:sessionKey2,messageId,startedAt:Date.now(),closed:!1})}close(sessionKey2,action){let turn=this.turns.get(sessionKey2);if(turn&&!turn.closed)turn.closed=!0,turn.closedAction=action}isOpen(sessionKey2){let turn=this.turns.get(sessionKey2);return turn!==void 0&&!turn.closed}getTurnId(sessionKey2){return this.turns.get(sessionKey2)?.turnId}getByTurnId(turnId){for(let turn of this.turns.values())if(turn.turnId===turnId)return turn;return}delete(sessionKey2){this.turns.delete(sessionKey2)}}var exports_omni_bridge={};__export(exports_omni_bridge,{getBridge:()=>getBridge,OmniBridge:()=>OmniBridge});function getBridge(){return bridgeInstance}function withTimeout(p,ms,label){return new Promise((resolve9,reject)=>{let timer2=setTimeout(()=>reject(Error(`${label} timed out after ${ms}ms`)),ms);timer2.unref?.(),p.then((v)=>{clearTimeout(timer2),resolve9(v)},(err)=>{clearTimeout(timer2),reject(err)})})}function isPgConnectionError(err){if(!err||typeof err!=="object")return!1;let e=err,code=e.code??"";if(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EPIPE","EHOSTUNREACH"].includes(code))return!0;let msg=e.message??String(err);return/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EPIPE|connection terminated|connection closed|server closed the connection|the database system is shutting down/i.test(msg)}class OmniBridge{nc=null;sub=null;executor;turnTracker=new TurnTracker;sessions=new Map;messageQueue=[];idleCheckTimer=null;sc=import_nats4.StringCodec();sql=null;pgAvailable=!1;pgProvider;natsConnectFn;queueConfig;queue=null;natsUrl;idleTimeoutMs;maxConcurrent;executorType;constructor(config={}){if(this.natsUrl=config.natsUrl??process.env.GENIE_NATS_URL??DEFAULT_NATS_URL,this.idleTimeoutMs=config.idleTimeoutMs??(process.env.GENIE_IDLE_TIMEOUT_MS?Number(process.env.GENIE_IDLE_TIMEOUT_MS):DEFAULT_IDLE_TIMEOUT_MS2),this.maxConcurrent=config.maxConcurrent??(process.env.GENIE_MAX_CONCURRENT?Number(process.env.GENIE_MAX_CONCURRENT):DEFAULT_MAX_CONCURRENT),this.pgProvider=config.pgProvider??(async()=>{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return await getConnection2()}),this.natsConnectFn=config.natsConnectFn??import_nats4.connect,this.queueConfig=config.queue??{},this.executorType=resolveExecutorType(config.executorType),this.executorType==="sdk")this.executor=new ClaudeSdkOmniExecutor;else this.executor=new ClaudeCodeOmniExecutor}async start(){if(this.nc){console.log("[omni-bridge] Already running");return}if(console.log(`[omni-bridge] Connecting to NATS at ${this.natsUrl}...`),this.nc=await this.natsConnectFn({servers:this.natsUrl,name:"genie-omni-bridge",reconnect:!0,maxReconnectAttempts:-1,reconnectTimeWait:2000}),console.log("[omni-bridge] Connected to NATS"),await this.probePg(),this.executorType==="sdk"&&this.pgAvailable&&this.sql)this.queue=new OmniQueue(this.sql,(_req,msg)=>this.routeMessage(msg),this.queueConfig),await this.queue.recoverStale(),this.queue.start();this.executor.setSafePgCall(this.safePgCall.bind(this));let sc3=this.sc,nc2=this.nc;this.executor.setNatsPublish((topic,payload)=>{nc2.publish(topic,sc3.encode(payload))}),this.sub=this.nc.subscribe("omni.message.>"),this.processSubscription();let turnSubs=["omni.turn.open.>","omni.turn.done.>","omni.turn.nudge.>","omni.turn.timeout.>"];for(let topic of turnSubs){let sub=this.nc.subscribe(topic);this.processTurnEvents(sub)}let sessionResetSub=this.nc.subscribe("omni.session.reset.>");this.processSessionResetEvents(sessionResetSub),this.idleCheckTimer=setInterval(()=>this.checkIdleSessions(),IDLE_CHECK_INTERVAL_MS),bridgeInstance=this,console.log(`[omni-bridge] Listening on omni.message.> (max_concurrent=${this.maxConcurrent}, idle_timeout=${this.idleTimeoutMs}ms)`)}async stop(){if(!this.nc){console.log("[omni-bridge] Not running");return}if(console.log("[omni-bridge] Shutting down..."),this.queue)this.queue.stop(),this.queue=null;if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null;for(let[key,entry]of this.sessions){if(entry.idleTimer)clearTimeout(entry.idleTimer);if(!entry.spawning&&entry.session)try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down session ${key}:`,err)}}if(this.sessions.clear(),this.sub)this.sub.unsubscribe(),this.sub=null;try{await this.nc.drain()}catch{}this.nc=null,this.sql=null,this.pgAvailable=!1,bridgeInstance=null,console.log("[omni-bridge] Stopped")}async status(){let now=Date.now(),activeFromPg=null,executorIds=[];if(this.pgAvailable&&this.sql){let rows=await this.safePgCall("status_active_count",async(sql)=>sql`
2184
2192
  SELECT id FROM executors
2185
2193
  WHERE ended_at IS NULL AND metadata->>'source' = 'omni'
2186
- `,null);if(rows)activeFromPg=rows.length,executorIds=rows.map((r)=>r.id)}let pgQueue=null;if(this.queue)pgQueue=await this.safePgCall("status_queue_stats",(_sql)=>this.queue?.stats()??Promise.resolve(null),null);return{connected:this.nc!==null,natsUrl:this.natsUrl,pgAvailable:this.pgAvailable,activeSessions:activeFromPg??this.sessions.size,maxConcurrent:this.maxConcurrent,idleTimeoutMs:this.idleTimeoutMs,queueDepth:pgQueue?pgQueue.pending+pgQueue.processing:this.messageQueue.length,executorType:this.executorType,executorIds,pgQueue,sessions:Array.from(this.sessions.entries()).map(([key,entry])=>({id:key,agentName:entry.session.agentName,chatId:entry.session.chatId,instanceId:entry.instanceId,executorType:entry.session.executorType,spawning:entry.spawning,idleMs:now-entry.session.lastActivityAt,bufferSize:entry.buffer.length}))}}async probePg(){try{let sql=await withTimeout(this.pgProvider(),PG_STARTUP_PROBE_TIMEOUT_MS,"PG provider startup");await withTimeout(Promise.resolve(sql`SELECT 1`),PG_STARTUP_PROBE_TIMEOUT_MS,"PG SELECT 1 probe"),this.sql=sql,this.pgAvailable=!0,console.log("[omni-bridge] PG reachable \u2014 session recovery enabled")}catch(err){this.sql=null,this.pgAvailable=!1;let msg=err instanceof Error?err.message:String(err);if(isPgConnectionError(err)){console.warn(`[omni-bridge] PG unavailable \u2014 session recovery disabled (${msg})`);return}throw Error(`[omni-bridge] PG schema mismatch or setup error: ${msg}. ${"Run `bun run migrate` (or the equivalent migration command) and retry."}`)}}async safePgCall(op,fn,fallback,ctx){if(!this.pgAvailable||!this.sql)return fallback;let sql=this.sql;try{return await withTimeout(fn(sql),PG_RUNTIME_QUERY_TIMEOUT_MS,`safePgCall(${op})`)}catch(err){let msg=err instanceof Error?err.message:String(err),execPart=ctx?.executorId?` executor_id=${ctx.executorId}`:"",chatPart=ctx?.chatId?` chat_id=${ctx.chatId}`:"";if(console.warn(`[omni-bridge] safePgCall(${op}) failed${execPart}${chatPart}: ${msg}`),isPgConnectionError(err))this.pgAvailable=!1,this.sql=null,console.warn("[omni-bridge] PG connection lost \u2014 switching to degraded mode");return fallback}}async processSubscription(){if(!this.sub)return;for await(let msg of this.sub)try{let data=this.sc.decode(msg.data),parsed=JSON.parse(data),parts=msg.subject.split(".");if(parts.length>=4)parsed.instanceId=parsed.instanceId||parts[2],parsed.chatId=parsed.chatId||parts[3];if(!parsed.chatId||!parsed.agent){console.warn("[omni-bridge] Dropping message: missing chatId or agent",msg.subject);continue}if(this.queue){let env=parsed.env??{};await this.queue.enqueue(parsed,env)}else await this.routeMessage(parsed)}catch(err){console.error("[omni-bridge] Error processing message:",err)}}async processTurnEvents(sub){for await(let msg of sub)try{let payload=JSON.parse(this.sc.decode(msg.data)),parts=msg.subject.split("."),eventType=parts[2],instanceId=parts[3],chatId=parts.slice(4).join("."),sessionKey2=this.findSessionKey(instanceId,chatId);if(sessionKey2)await this.routeTurnEvent(eventType,sessionKey2,payload)}catch(err){console.warn("[omni-bridge] Error processing turn event:",err)}}async routeTurnEvent(eventType,sessionKey2,payload){switch(eventType){case"open":this.turnTracker.open(sessionKey2,payload.turnId,payload.messageId);break;case"done":this.turnTracker.close(sessionKey2,payload.action);break;case"nudge":await this.handleTurnNudge(sessionKey2,payload.message);break;case"timeout":await this.handleTurnTimeout(sessionKey2);break}}findSessionKey(instanceId,chatId){for(let[key,entry]of this.sessions){if(entry.instanceId!==instanceId)continue;if(entry.session?.chatId===chatId)return key;if(entry.spawning&&key.endsWith(`:${chatId}`))return key}return}async handleTurnNudge(sessionKey2,nudgeText){let entry=this.sessions.get(sessionKey2);if(!entry?.session)return;try{await this.executor.injectNudge(entry.session,nudgeText)}catch(err){console.warn(`[omni-bridge] Failed to inject nudge for ${sessionKey2}:`,err)}}async processSessionResetEvents(sub){for await(let msg of sub)try{let parts=msg.subject.split(".");if(parts.length<5){console.warn(`[omni-bridge] Malformed session-reset subject: ${msg.subject}`);continue}let instanceId=parts[3],chatId=parts.slice(4).join("."),action;try{action=JSON.parse(this.sc.decode(msg.data)).action}catch{}await this.handleSessionReset(instanceId,chatId,action)}catch(err){console.warn("[omni-bridge] Error processing session reset event:",err)}}async handleSessionReset(instanceId,chatId,action){let sessionKey2=this.findSessionKey(instanceId,chatId);if(!sessionKey2){console.log(`[omni-bridge] Session reset for cold chat ${instanceId}/${chatId} \u2014 no-op`);return}let entry=this.sessions.get(sessionKey2);if(!entry)return;let actionTag=action?` (action=${action})`:"";if(entry.spawning){console.log(`[omni-bridge] Session reset for spawning ${sessionKey2}${actionTag}, marking cancelled`),entry.cancelled=!0,entry.buffer=[],this.turnTracker.close(sessionKey2,"reset"),this.removeSession(sessionKey2),await this.drainQueue();return}if(!entry.session)return;console.log(`[omni-bridge] Session reset for ${sessionKey2}${actionTag}, evicting`),this.turnTracker.close(sessionKey2,"reset");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down reset session ${sessionKey2}:`,err)}this.removeSession(sessionKey2),await this.drainQueue()}async handleTurnTimeout(sessionKey2){let entry=this.sessions.get(sessionKey2);if(!entry?.session)return;console.warn(`[omni-bridge] Turn timed out for ${sessionKey2}, evicting session`),this.turnTracker.close(sessionKey2,"timeout");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down timed-out session ${sessionKey2}:`,err)}this.sessions.delete(sessionKey2)}async routeMessage(message){let key=`${message.agent}:${message.chatId}`,entry=this.sessions.get(key);if(entry){if(entry.spawning){if(entry.buffer.length<MAX_BUFFER_PER_CHAT)entry.buffer.push(message);else console.warn(`[omni-bridge] Buffer full (${MAX_BUFFER_PER_CHAT}) for ${key}, dropping message from ${message.sender}`),await this.publishBufferFullReply(message);return}if(await this.executor.isAlive(entry.session)){await this.executor.deliver(entry.session,message),this.resetIdleTimer(key);return}this.removeSession(key)}await this.spawnSession(message)}async spawnSession(message){let key=`${message.agent}:${message.chatId}`;if(this.sessions.size>=this.maxConcurrent){this.messageQueue.push(message),await this.publishAutoReply(message),console.log(`[omni-bridge] Max concurrent (${this.maxConcurrent}) reached, queued message for ${key}`);return}let placeholder={session:null,instanceId:message.instanceId,spawning:!0,buffer:[message],idleTimer:null};this.sessions.set(key,placeholder);try{let raw=message,payloadEnv=raw.env,spawnEnv={OMNI_API_KEY:payloadEnv?.OMNI_API_KEY??process.env.OMNI_API_KEY??"",OMNI_INSTANCE:payloadEnv?.OMNI_INSTANCE??message.instanceId,OMNI_CHAT:payloadEnv?.OMNI_CHAT??message.chatId,OMNI_MESSAGE:payloadEnv?.OMNI_MESSAGE??raw.messageId??"",OMNI_TURN_ID:payloadEnv?.OMNI_TURN_ID??""};console.log(`[omni-bridge] Spawning session for ${key}...`);let session=await this.executor.spawn(message.agent,message.chatId,spawnEnv);if(placeholder.cancelled){console.log(`[omni-bridge] Spawn for ${key} completed but was cancelled by reset, shutting down`);try{await this.executor.shutdown(session)}catch(err){console.warn(`[omni-bridge] Error shutting down cancelled spawn for ${key}:`,err)}return}placeholder.session=session,placeholder.spawning=!1;for(let buffered of placeholder.buffer)await this.executor.deliver(session,buffered);placeholder.buffer=[],this.resetIdleTimer(key);let sessionTag=session.executorType==="tmux"?`(tmux pane=${session.tmux?.paneId})`:"(executor=sdk)";console.log(`[omni-bridge] Session active: ${key} ${sessionTag}`)}catch(err){console.error(`[omni-bridge] Failed to spawn session for ${key}:`,err);let lostMessages=placeholder.buffer;if(lostMessages.length>0)console.warn(`[omni-bridge] Re-queuing ${lostMessages.length} buffered message(s) from failed spawn for ${key}`),this.messageQueue.push(...lostMessages);this.sessions.delete(key)}}resetIdleTimer(key){let entry=this.sessions.get(key);if(!entry)return;if(entry.idleTimer)clearTimeout(entry.idleTimer);entry.idleTimer=setTimeout(async()=>{console.log(`[omni-bridge] Idle timeout for ${key}, shutting down...`);try{await this.executor.shutdown(entry.session)}catch{}this.removeSession(key),await this.drainQueue()},this.idleTimeoutMs)}async checkIdleSessions(){let now=Date.now();for(let[key,entry]of this.sessions){if(entry.spawning)continue;if(!await this.executor.isAlive(entry.session)){console.log(`[omni-bridge] Dead session detected: ${key}`),this.removeSession(key);continue}let idleMs=now-entry.session.lastActivityAt;if(idleMs>this.idleTimeoutMs){console.log(`[omni-bridge] Forcing idle shutdown: ${key} (idle ${Math.round(idleMs/1000)}s)`);try{await this.executor.shutdown(entry.session)}catch{}this.removeSession(key)}}}removeSession(key){let entry=this.sessions.get(key);if(entry?.idleTimer)clearTimeout(entry.idleTimer);this.sessions.delete(key)}async drainQueue(){while(this.messageQueue.length>0){if(this.sessions.size>=this.maxConcurrent)break;let message=this.messageQueue.shift();if(message)await this.spawnSession(message)}}async publishBufferFullReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply2={content:"Fila de mensagens cheia, por favor aguarde e tente novamente.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply2)))}async publishAutoReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply2={content:"Aguarde um momento, estou atendendo outros clientes.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply2)))}}var import_nats4,DEFAULT_NATS_URL="localhost:4222",DEFAULT_IDLE_TIMEOUT_MS2=900000,DEFAULT_MAX_CONCURRENT=20,MAX_BUFFER_PER_CHAT=50,IDLE_CHECK_INTERVAL_MS=30000,PG_STARTUP_PROBE_TIMEOUT_MS=5000,PG_RUNTIME_QUERY_TIMEOUT_MS=2000,bridgeInstance=null;var init_omni_bridge=__esm(()=>{init_executor_config();init_claude_code2();init_claude_sdk2();import_nats4=__toESM(require_mod4(),1)});var exports_task_close_merged={};__export(exports_task_close_merged,{parseSinceDate:()=>parseSinceDate,matchPRsToSlugs:()=>matchPRsToSlugs,fetchMergedPRs:()=>fetchMergedPRs,extractWishSlug:()=>extractWishSlug,extractSlugFromBranch:()=>extractSlugFromBranch,extractSlugFromBody:()=>extractSlugFromBody,closeMergedTasks:()=>closeMergedTasks});import{execSync as execSync15}from"child_process";function extractSlugFromBody(body){if(!body)return null;let match=body.match(/(?:wish|slug):\s*(\S+)/i);return match?match[1]:null}function extractSlugFromBranch(branch){if(!branch)return null;let match=branch.match(/^(?:feat|fix|chore|docs|refactor|test|dream)\/(.+)$/);return match?match[1]:null}function extractWishSlug(pr){return extractSlugFromBody(pr.body)??extractSlugFromBranch(pr.headRefName)}function parseSinceDate(since){let match=since.match(/^(\d+)([hd])$/);if(!match)throw Error(`Invalid --since format: "${since}". Use e.g. "24h" or "7d".`);let amount=Number.parseInt(match[1],10),unit=match[2],now=new Date;if(unit==="h")now.setHours(now.getHours()-amount);else now.setDate(now.getDate()-amount);return now.toISOString()}function fetchMergedPRs(since,repo){let sinceDate=parseSinceDate(since),cmd=`gh pr list --state merged --json number,title,body,headRefName,mergedAt --limit 100 ${repo?`--repo ${repo}`:""}`.trim(),output;try{output=execSync15(cmd,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(err){let message=err instanceof Error?err.message:String(err);throw Error(`Failed to fetch merged PRs: ${message}`)}return JSON.parse(output).filter((pr)=>new Date(pr.mergedAt)>=new Date(sinceDate))}function matchPRsToSlugs(prs){let matches=[];for(let pr of prs){let slug=extractWishSlug(pr);if(slug)matches.push({prNumber:pr.number,slug,mergedAt:pr.mergedAt})}return matches}async function closeMergedTasks(options={}){let{since="24h",dryRun=!1,repo,repoPath}=options,ts3=await Promise.resolve().then(() => (init_task_service(),exports_task_service)),prs=fetchMergedPRs(since,repo),slugMatches=matchPRsToSlugs(prs),result2={closed:0,alreadyShipped:0,prsScanned:prs.length,details:[]};if(slugMatches.length===0)return result2;let actor={actorType:"local",actorId:process.env.GENIE_AGENT_NAME??"cli"},processedTaskIds=new Set;for(let{prNumber,slug}of slugMatches){let tasks=await findTasksByWishSlug(slug,repoPath);for(let task of tasks){if(processedTaskIds.has(task.id))continue;if(processedTaskIds.add(task.id),task.stage==="ship"){result2.alreadyShipped++;continue}if(!dryRun)await ts3.moveTask(task.id,"ship",actor,void 0,task.repoPath),await ts3.commentOnTask(task.id,actor,`Auto-closed: PR #${prNumber} merged to dev`,task.repoPath);result2.closed++,result2.details.push({taskSeq:task.seq,taskTitle:task.title,prNumber,slug})}}return result2}async function findTasksByWishSlug(slug,repoPath){let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),sql=await getConnection2(),repo=repoPath??resolveRepoPath(),pattern=`%${slug}%`;return(await sql`
2194
+ `,null);if(rows)activeFromPg=rows.length,executorIds=rows.map((r)=>r.id)}let pgQueue=null;if(this.queue)pgQueue=await this.safePgCall("status_queue_stats",(_sql)=>this.queue?.stats()??Promise.resolve(null),null);return{connected:this.nc!==null,natsUrl:this.natsUrl,pgAvailable:this.pgAvailable,activeSessions:activeFromPg??this.sessions.size,maxConcurrent:this.maxConcurrent,idleTimeoutMs:this.idleTimeoutMs,queueDepth:pgQueue?pgQueue.pending+pgQueue.processing:this.messageQueue.length,executorType:this.executorType,executorIds,pgQueue,sessions:Array.from(this.sessions.entries()).map(([key,entry])=>({id:key,agentName:entry.session.agentName,chatId:entry.session.chatId,instanceId:entry.instanceId,executorType:entry.session.executorType,spawning:entry.spawning,idleMs:now-entry.session.lastActivityAt,bufferSize:entry.buffer.length}))}}async probePg(){try{let sql=await withTimeout(this.pgProvider(),PG_STARTUP_PROBE_TIMEOUT_MS,"PG provider startup");await withTimeout(Promise.resolve(sql`SELECT 1`),PG_STARTUP_PROBE_TIMEOUT_MS,"PG SELECT 1 probe"),this.sql=sql,this.pgAvailable=!0,console.log("[omni-bridge] PG reachable \u2014 session recovery enabled")}catch(err){this.sql=null,this.pgAvailable=!1;let msg=err instanceof Error?err.message:String(err);if(isPgConnectionError(err)){console.warn(`[omni-bridge] PG unavailable \u2014 session recovery disabled (${msg})`);return}throw Error(`[omni-bridge] PG schema mismatch or setup error: ${msg}. ${"Run `bun run migrate` (or the equivalent migration command) and retry."}`)}}async safePgCall(op,fn,fallback,ctx){if(!this.pgAvailable||!this.sql)return fallback;let sql=this.sql;try{return await withTimeout(fn(sql),PG_RUNTIME_QUERY_TIMEOUT_MS,`safePgCall(${op})`)}catch(err){let msg=err instanceof Error?err.message:String(err),execPart=ctx?.executorId?` executor_id=${ctx.executorId}`:"",chatPart=ctx?.chatId?` chat_id=${ctx.chatId}`:"";if(console.warn(`[omni-bridge] safePgCall(${op}) failed${execPart}${chatPart}: ${msg}`),isPgConnectionError(err))this.pgAvailable=!1,this.sql=null,console.warn("[omni-bridge] PG connection lost \u2014 switching to degraded mode");return fallback}}async processSubscription(){if(!this.sub)return;for await(let msg of this.sub)try{let data=this.sc.decode(msg.data),parsed=JSON.parse(data),parts=msg.subject.split(".");if(parts.length>=4)parsed.instanceId=parsed.instanceId||parts[2],parsed.chatId=parsed.chatId||parts[3];if(console.log(`[omni-bridge] NATS message received: ${msg.subject} agent=${parsed.agent} chat=${parsed.chatId}`),!parsed.chatId||!parsed.agent){console.warn("[omni-bridge] Dropping message: missing chatId or agent",msg.subject);continue}if(this.queue){let env=parsed.env??{};await this.queue.enqueue(parsed,env)}else{let key=`${parsed.agent}:${parsed.chatId}`,hasSession=this.sessions.has(key);console.log(`[omni-bridge] Routing message for ${key} (hasSession=${hasSession}, queue=${!!this.queue})`),await this.routeMessage(parsed),console.log(`[omni-bridge] routeMessage done for ${key}`)}}catch(err){console.error("[omni-bridge] Error processing message:",err)}}async processTurnEvents(sub){for await(let msg of sub)try{let payload=JSON.parse(this.sc.decode(msg.data)),parts=msg.subject.split("."),eventType=parts[2],instanceId=parts[3],chatId=parts.slice(4).join(".");console.log(`[omni-bridge] Turn event: ${eventType} instance=${instanceId} chat=${chatId}`);let sessionKey2=this.findSessionKey(instanceId,chatId);if(!sessionKey2&&payload.turnId){if(sessionKey2=this.findSessionKeyByTurnId(payload.turnId),sessionKey2)console.log(`[omni-bridge] Matched session via turnId fallback: ${sessionKey2}`)}if(sessionKey2)await this.routeTurnEvent(eventType,sessionKey2,payload);else console.log(`[omni-bridge] No session found for turn.${eventType} (instance=${instanceId}, chat=${chatId})`)}catch(err){console.warn("[omni-bridge] Error processing turn event:",err)}}async routeTurnEvent(eventType,sessionKey2,payload){switch(eventType){case"open":this.turnTracker.open(sessionKey2,payload.turnId,payload.messageId);break;case"done":this.turnTracker.close(sessionKey2,payload.action),await this.handleTurnDone(sessionKey2);break;case"nudge":await this.handleTurnNudge(sessionKey2,payload.message);break;case"timeout":await this.handleTurnTimeout(sessionKey2);break}}findSessionKeyByTurnId(turnId){for(let[key]of this.sessions)if(this.turnTracker.getTurnId(key)===turnId)return key;return}chatIdMap=new Map;findSessionKey(instanceId,chatId){let resolvedChatId=this.chatIdMap.get(chatId);for(let[key,entry]of this.sessions){if(entry.instanceId!==instanceId)continue;if(entry.session?.chatId===chatId)return key;if(resolvedChatId&&entry.session?.chatId===resolvedChatId)return key;if(entry.spawning&&key.endsWith(`:${chatId}`))return key;if(resolvedChatId&&entry.spawning&&key.endsWith(`:${resolvedChatId}`))return key}return}async handleTurnNudge(sessionKey2,nudgeText){let entry=this.sessions.get(sessionKey2);if(!entry?.session)return;try{await this.executor.injectNudge(entry.session,nudgeText)}catch(err){console.warn(`[omni-bridge] Failed to inject nudge for ${sessionKey2}:`,err)}}async processSessionResetEvents(sub){for await(let msg of sub)try{let parts=msg.subject.split(".");if(parts.length<5){console.warn(`[omni-bridge] Malformed session-reset subject: ${msg.subject}`);continue}let instanceId=parts[3],chatId=parts.slice(4).join("."),action;try{action=JSON.parse(this.sc.decode(msg.data)).action}catch{}await this.handleSessionReset(instanceId,chatId,action)}catch(err){console.warn("[omni-bridge] Error processing session reset event:",err)}}async handleSessionReset(instanceId,chatId,action){let sessionKey2=this.findSessionKey(instanceId,chatId);if(!sessionKey2){console.log(`[omni-bridge] Session reset for cold chat ${instanceId}/${chatId} \u2014 no-op`);return}let entry=this.sessions.get(sessionKey2);if(!entry)return;let actionTag=action?` (action=${action})`:"";if(entry.spawning){console.log(`[omni-bridge] Session reset for spawning ${sessionKey2}${actionTag}, marking cancelled`),entry.cancelled=!0,entry.buffer=[],this.turnTracker.close(sessionKey2,"reset"),this.removeSession(sessionKey2),await this.drainQueue();return}if(!entry.session)return;console.log(`[omni-bridge] Session reset for ${sessionKey2}${actionTag}, evicting`),this.turnTracker.close(sessionKey2,"reset");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down reset session ${sessionKey2}:`,err)}this.removeSession(sessionKey2),await this.drainQueue()}async handleTurnDone(sessionKey2){if(!this.sessions.get(sessionKey2)?.session)return;console.log(`[omni-bridge] Turn done for ${sessionKey2}, session stays alive for next message`),this.resetIdleTimer(sessionKey2)}async handleTurnTimeout(sessionKey2){let entry=this.sessions.get(sessionKey2);if(!entry?.session)return;console.warn(`[omni-bridge] Turn timed out for ${sessionKey2}, evicting session`),this.turnTracker.close(sessionKey2,"timeout");try{await this.executor.shutdown(entry.session)}catch(err){console.warn(`[omni-bridge] Error shutting down timed-out session ${sessionKey2}:`,err)}this.sessions.delete(sessionKey2)}async routeMessage(message){let key=`${message.agent}:${message.chatId}`,entry=this.sessions.get(key);if(entry){if(entry.spawning){if(entry.buffer.length<MAX_BUFFER_PER_CHAT)entry.buffer.push(message);else console.warn(`[omni-bridge] Buffer full (${MAX_BUFFER_PER_CHAT}) for ${key}, dropping message from ${message.sender}`),await this.publishBufferFullReply(message);return}if(await this.executor.isAlive(entry.session)){await this.executor.deliver(entry.session,message),this.resetIdleTimer(key);return}this.removeSession(key)}await this.spawnSession(message)}async spawnSession(message){let key=`${message.agent}:${message.chatId}`,existing=this.sessions.get(key);if(existing){if(existing.buffer.length<MAX_BUFFER_PER_CHAT)existing.buffer.push(message),console.log(`[omni-bridge] Buffered message for existing session ${key} (buffer=${existing.buffer.length})`);return}if(this.sessions.size>=this.maxConcurrent){this.messageQueue.push(message),await this.publishAutoReply(message),console.log(`[omni-bridge] Max concurrent (${this.maxConcurrent}) reached, queued message for ${key}`);return}let placeholder={session:null,instanceId:message.instanceId,spawning:!0,buffer:[message],idleTimer:null};this.sessions.set(key,placeholder);try{let raw=message,payloadEnv=raw.env,spawnEnv={OMNI_API_KEY:payloadEnv?.OMNI_API_KEY??process.env.OMNI_API_KEY??"",OMNI_INSTANCE:payloadEnv?.OMNI_INSTANCE??message.instanceId,OMNI_CHAT:payloadEnv?.OMNI_CHAT??message.chatId,OMNI_MESSAGE:payloadEnv?.OMNI_MESSAGE??raw.messageId??"",OMNI_TURN_ID:payloadEnv?.OMNI_TURN_ID??"",OMNI_SENDER_NAME:payloadEnv?.OMNI_SENDER_NAME??message.sender??""};console.log(`[omni-bridge] Spawning session for ${key}...`);let session=await this.executor.spawn(message.agent,message.chatId,spawnEnv,message.content);if(placeholder.cancelled){console.log(`[omni-bridge] Spawn for ${key} completed but was cancelled by reset, shutting down`);try{await this.executor.shutdown(session)}catch(err){console.warn(`[omni-bridge] Error shutting down cancelled spawn for ${key}:`,err)}return}placeholder.session=session,placeholder.spawning=!1;for(let buffered of placeholder.buffer)await this.executor.deliver(session,buffered);placeholder.buffer=[],this.resetIdleTimer(key);let sessionTag=session.executorType==="tmux"?`(tmux pane=${session.tmux?.paneId})`:"(executor=sdk)";console.log(`[omni-bridge] Session active: ${key} ${sessionTag}`)}catch(err){console.error(`[omni-bridge] Failed to spawn session for ${key}:`,err);let lostMessages=placeholder.buffer;if(lostMessages.length>0)console.warn(`[omni-bridge] Re-queuing ${lostMessages.length} buffered message(s) from failed spawn for ${key}`),this.messageQueue.push(...lostMessages);this.sessions.delete(key)}}resetIdleTimer(key){let entry=this.sessions.get(key);if(!entry)return;if(entry.idleTimer)clearTimeout(entry.idleTimer);entry.idleTimer=setTimeout(async()=>{console.log(`[omni-bridge] Idle timeout for ${key}, shutting down...`);try{await this.executor.shutdown(entry.session)}catch{}this.removeSession(key),await this.drainQueue()},this.idleTimeoutMs)}async checkIdleSessions(){let now=Date.now();for(let[key,entry]of this.sessions){if(entry.spawning)continue;if(!await this.executor.isAlive(entry.session)){console.log(`[omni-bridge] Dead session detected: ${key}`),this.removeSession(key);continue}let idleMs=now-entry.session.lastActivityAt;if(idleMs>this.idleTimeoutMs){console.log(`[omni-bridge] Forcing idle shutdown: ${key} (idle ${Math.round(idleMs/1000)}s)`);try{await this.executor.shutdown(entry.session)}catch{}this.removeSession(key)}}}removeSession(key){let entry=this.sessions.get(key);if(entry?.idleTimer)clearTimeout(entry.idleTimer);this.sessions.delete(key)}async drainQueue(){while(this.messageQueue.length>0){if(this.sessions.size>=this.maxConcurrent)break;let message=this.messageQueue.shift();if(message)await this.spawnSession(message)}}async publishBufferFullReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply2={content:"Fila de mensagens cheia, por favor aguarde e tente novamente.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply2)))}async publishAutoReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply2={content:"Aguarde um momento, estou atendendo outros clientes.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply2)))}}var import_nats4,DEFAULT_NATS_URL="localhost:4222",DEFAULT_IDLE_TIMEOUT_MS2=900000,DEFAULT_MAX_CONCURRENT=20,MAX_BUFFER_PER_CHAT=50,IDLE_CHECK_INTERVAL_MS=30000,PG_STARTUP_PROBE_TIMEOUT_MS=5000,PG_RUNTIME_QUERY_TIMEOUT_MS=2000,bridgeInstance=null;var init_omni_bridge=__esm(()=>{init_executor_config();init_claude_code2();init_claude_sdk2();import_nats4=__toESM(require_mod4(),1)});var exports_task_close_merged={};__export(exports_task_close_merged,{parseSinceDate:()=>parseSinceDate,matchPRsToSlugs:()=>matchPRsToSlugs,fetchMergedPRs:()=>fetchMergedPRs,extractWishSlug:()=>extractWishSlug,extractSlugFromBranch:()=>extractSlugFromBranch,extractSlugFromBody:()=>extractSlugFromBody,closeMergedTasks:()=>closeMergedTasks});import{execSync as execSync15}from"child_process";function extractSlugFromBody(body){if(!body)return null;let match=body.match(/(?:wish|slug):\s*(\S+)/i);return match?match[1]:null}function extractSlugFromBranch(branch){if(!branch)return null;let match=branch.match(/^(?:feat|fix|chore|docs|refactor|test|dream)\/(.+)$/);return match?match[1]:null}function extractWishSlug(pr){return extractSlugFromBody(pr.body)??extractSlugFromBranch(pr.headRefName)}function parseSinceDate(since){let match=since.match(/^(\d+)([hd])$/);if(!match)throw Error(`Invalid --since format: "${since}". Use e.g. "24h" or "7d".`);let amount=Number.parseInt(match[1],10),unit=match[2],now=new Date;if(unit==="h")now.setHours(now.getHours()-amount);else now.setDate(now.getDate()-amount);return now.toISOString()}function fetchMergedPRs(since,repo){let sinceDate=parseSinceDate(since),cmd=`gh pr list --state merged --json number,title,body,headRefName,mergedAt --limit 100 ${repo?`--repo ${repo}`:""}`.trim(),output;try{output=execSync15(cmd,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(err){let message=err instanceof Error?err.message:String(err);throw Error(`Failed to fetch merged PRs: ${message}`)}return JSON.parse(output).filter((pr)=>new Date(pr.mergedAt)>=new Date(sinceDate))}function matchPRsToSlugs(prs){let matches=[];for(let pr of prs){let slug=extractWishSlug(pr);if(slug)matches.push({prNumber:pr.number,slug,mergedAt:pr.mergedAt})}return matches}async function closeMergedTasks(options={}){let{since="24h",dryRun=!1,repo,repoPath}=options,ts3=await Promise.resolve().then(() => (init_task_service(),exports_task_service)),prs=fetchMergedPRs(since,repo),slugMatches=matchPRsToSlugs(prs),result2={closed:0,alreadyShipped:0,prsScanned:prs.length,details:[]};if(slugMatches.length===0)return result2;let actor={actorType:"local",actorId:process.env.GENIE_AGENT_NAME??"cli"},processedTaskIds=new Set;for(let{prNumber,slug}of slugMatches){let tasks=await findTasksByWishSlug(slug,repoPath);for(let task of tasks){if(processedTaskIds.has(task.id))continue;if(processedTaskIds.add(task.id),task.stage==="ship"){result2.alreadyShipped++;continue}if(!dryRun)await ts3.moveTask(task.id,"ship",actor,void 0,task.repoPath),await ts3.commentOnTask(task.id,actor,`Auto-closed: PR #${prNumber} merged to dev`,task.repoPath);result2.closed++,result2.details.push({taskSeq:task.seq,taskTitle:task.title,prNumber,slug})}}return result2}async function findTasksByWishSlug(slug,repoPath){let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),sql=await getConnection2(),repo=repoPath??resolveRepoPath(),pattern=`%${slug}%`;return(await sql`
2187
2195
  SELECT id, seq, title, stage, repo_path
2188
2196
  FROM tasks
2189
2197
  WHERE repo_path = ${repo}
2190
2198
  AND wish_file LIKE ${pattern}
2191
2199
  ORDER BY seq
2192
- `).map((r)=>({id:r.id,seq:r.seq,title:r.title,stage:r.stage,repoPath:r.repo_path}))}var init_task_close_merged=__esm(()=>{init_wish_state()});var highlights_default="./highlights-ghv9g403.scm";var init_highlights=()=>{};var tree_sitter_javascript_default="./tree-sitter-javascript-nd0q4pe9.wasm";var init_tree_sitter_javascript=()=>{};var highlights_default2="./highlights-eq9cgrbb.scm";var init_highlights2=()=>{};var tree_sitter_typescript_default="./tree-sitter-typescript-zxjzwt75.wasm";var init_tree_sitter_typescript=()=>{};var highlights_default3="./highlights-r812a2qc.scm";var init_highlights3=()=>{};var tree_sitter_markdown_default="./tree-sitter-markdown-411r6y9b.wasm";var init_tree_sitter_markdown=()=>{};var injections_default="./injections-73j83es3.scm";var init_injections=()=>{};var highlights_default4="./highlights-x6tmsnaa.scm";var init_highlights4=()=>{};var tree_sitter_markdown_inline_default="./tree-sitter-markdown_inline-j5349f42.wasm";var init_tree_sitter_markdown_inline=()=>{};var highlights_default5="./highlights-hk7bwhj4.scm";var init_highlights5=()=>{};var tree_sitter_zig_default="./tree-sitter-zig-e78zbjpm.wasm";var init_tree_sitter_zig=()=>{};import{EventEmitter}from"events";import{Buffer as Buffer2}from"buffer";import{Buffer as Buffer3}from"buffer";import{EventEmitter as EventEmitter2}from"events";import{resolve as resolve11,dirname as dirname12}from"path";import{fileURLToPath as fileURLToPath2}from"url";import{resolve as resolve22,isAbsolute,parse as parse2}from"path";import{existsSync as existsSync43}from"fs";import{basename as basename10,join as join56}from"path";import os3 from"os";import path3 from"path";import{EventEmitter as EventEmitter3}from"events";import path22 from"path";import{readFile as readFile22,writeFile as writeFile22,mkdir as mkdir22}from"fs/promises";import*as path4 from"path";import{mkdir as mkdir9,readFile as readFile13,writeFile as writeFile6}from"fs/promises";import*as path32 from"path";import{readdir as readdir7}from"fs/promises";import{dlopen,toArrayBuffer as toArrayBuffer4,JSCallback,ptr as ptr4}from"bun:ffi";import{existsSync as existsSync210,writeFileSync as writeFileSync24}from"fs";import{EventEmitter as EventEmitter4}from"events";import{toArrayBuffer,ptr}from"bun:ffi";import{ptr as ptr2,toArrayBuffer as toArrayBuffer2}from"bun:ffi";import{ptr as ptr3,toArrayBuffer as toArrayBuffer3}from"bun:ffi";import{EventEmitter as EventEmitter5}from"events";import util3 from"util";import{EventEmitter as EventEmitter7}from"events";import{Console}from"console";import fs2 from"fs";import path5 from"path";import util22 from"util";import{Writable}from"stream";import{EventEmitter as EventEmitter6}from"events";import{EventEmitter as EventEmitter8}from"events";function __exportSetter2(name,newValue){this[name]=__returnValue2.bind(null,newValue)}function wrapAssembly(lib){function patch(prototype,name,fn){let original=prototype[name];prototype[name]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return fn.call(this,original,...args)}}for(let fnName of["setPosition","setMargin","setFlexBasis","setWidth","setHeight","setMinWidth","setMinHeight","setMaxWidth","setMaxHeight","setPadding","setGap"]){let methods={[Unit.Point]:lib.Node.prototype[fnName],[Unit.Percent]:lib.Node.prototype[`${fnName}Percent`],[Unit.Auto]:lib.Node.prototype[`${fnName}Auto`]};patch(lib.Node.prototype,fnName,function(original){for(var _len2=arguments.length,args=Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];let value=args.pop(),unit,asNumber;if(value==="auto")unit=Unit.Auto,asNumber=void 0;else if(typeof value==="object")unit=value.unit,asNumber=value.valueOf();else if(unit=typeof value==="string"&&value.endsWith("%")?Unit.Percent:Unit.Point,asNumber=parseFloat(value),value!==void 0&&!Number.isNaN(value)&&Number.isNaN(asNumber))throw Error(`Invalid value ${value} for ${fnName}`);if(!methods[unit])throw Error(`Failed to execute "${fnName}": Unsupported unit '${value}'`);if(asNumber!==void 0)return methods[unit].call(this,...args,asNumber);else return methods[unit].call(this,...args)})}function wrapMeasureFunction(measureFunction){return lib.MeasureCallback.implement({measure:function(){let{width,height:height2}=measureFunction(...arguments);return{width:width??NaN,height:height2??NaN}}})}patch(lib.Node.prototype,"setMeasureFunc",function(original,measureFunc){if(measureFunc)return original.call(this,wrapMeasureFunction(measureFunc));else return this.unsetMeasureFunc()});function wrapDirtiedFunc(dirtiedFunction){return lib.DirtiedCallback.implement({dirtied:dirtiedFunction})}return patch(lib.Node.prototype,"setDirtiedFunc",function(original,dirtiedFunc){original.call(this,wrapDirtiedFunc(dirtiedFunc))}),patch(lib.Config.prototype,"free",function(){lib.Config.destroy(this)}),patch(lib.Node,"create",(_,config)=>{return config?lib.Node.createWithConfig(config):lib.Node.createDefault()}),patch(lib.Node.prototype,"free",function(){lib.Node.destroy(this)}),patch(lib.Node.prototype,"freeRecursive",function(){for(let t=0,T=this.getChildCount();t<T;++t)this.getChild(0).freeRecursive();this.free()}),patch(lib.Node.prototype,"calculateLayout",function(original){let width=arguments.length>1&&arguments[1]!==void 0?arguments[1]:NaN,height2=arguments.length>2&&arguments[2]!==void 0?arguments[2]:NaN,direction=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Direction.LTR;return original.call(this,width,height2,direction)}),{Config:lib.Config,Node:lib.Node,...YGEnums_default}}function isValidBorderStyle(value){return typeof value==="string"&&VALID_BORDER_STYLES.includes(value)}function parseBorderStyle(value,fallback="single"){if(isValidBorderStyle(value))return value;if(value!==void 0&&value!==null)console.warn(`Invalid borderStyle "${value}", falling back to "${fallback}". Valid values are: ${VALID_BORDER_STYLES.join(", ")}`);return fallback}function getBorderFromSides(sides){let result2=[];if(sides.top)result2.push("top");if(sides.right)result2.push("right");if(sides.bottom)result2.push("bottom");if(sides.left)result2.push("left");return result2.length>0?result2:!1}function getBorderSides(border){return border===!0?{top:!0,right:!0,bottom:!0,left:!0}:Array.isArray(border)?{top:border.includes("top"),right:border.includes("right"),bottom:border.includes("bottom"),left:border.includes("left")}:{top:!1,right:!1,bottom:!1,left:!1}}function borderCharsToArray(chars){let array=new Uint32Array(11);return array[0]=chars.topLeft.codePointAt(0),array[1]=chars.topRight.codePointAt(0),array[2]=chars.bottomLeft.codePointAt(0),array[3]=chars.bottomRight.codePointAt(0),array[4]=chars.horizontal.codePointAt(0),array[5]=chars.vertical.codePointAt(0),array[6]=chars.topT.codePointAt(0),array[7]=chars.bottomT.codePointAt(0),array[8]=chars.leftT.codePointAt(0),array[9]=chars.rightT.codePointAt(0),array[10]=chars.cross.codePointAt(0),array}class KeyEvent{name;ctrl;meta;shift;option;sequence;number;raw;eventType;source;code;super;hyper;capsLock;numLock;baseCode;repeated;_defaultPrevented=!1;_propagationStopped=!1;constructor(key){this.name=key.name,this.ctrl=key.ctrl,this.meta=key.meta,this.shift=key.shift,this.option=key.option,this.sequence=key.sequence,this.number=key.number,this.raw=key.raw,this.eventType=key.eventType,this.source=key.source,this.code=key.code,this.super=key.super,this.hyper=key.hyper,this.capsLock=key.capsLock,this.numLock=key.numLock,this.baseCode=key.baseCode,this.repeated=key.repeated}get defaultPrevented(){return this._defaultPrevented}get propagationStopped(){return this._propagationStopped}preventDefault(){this._defaultPrevented=!0}stopPropagation(){this._propagationStopped=!0}}class PasteEvent{type="paste";bytes;metadata;_defaultPrevented=!1;_propagationStopped=!1;constructor(bytes,metadata){this.bytes=bytes,this.metadata=metadata}get defaultPrevented(){return this._defaultPrevented}get propagationStopped(){return this._propagationStopped}preventDefault(){this._defaultPrevented=!0}stopPropagation(){this._propagationStopped=!0}}class RGBA{buffer;constructor(buffer2){this.buffer=buffer2}static fromArray(array){return new RGBA(array)}static fromValues(r,g,b2,a=1){return new RGBA(new Float32Array([r,g,b2,a]))}static fromInts(r,g,b2,a=255){return new RGBA(new Float32Array([r/255,g/255,b2/255,a/255]))}static fromHex(hex){return hexToRgb(hex)}toInts(){return[Math.round(this.r*255),Math.round(this.g*255),Math.round(this.b*255),Math.round(this.a*255)]}get r(){return this.buffer[0]}set r(value){this.buffer[0]=value}get g(){return this.buffer[1]}set g(value){this.buffer[1]=value}get b(){return this.buffer[2]}set b(value){this.buffer[2]=value}get a(){return this.buffer[3]}set a(value){this.buffer[3]=value}map(fn){return[fn(this.r),fn(this.g),fn(this.b),fn(this.a)]}toString(){return`rgba(${this.r.toFixed(2)}, ${this.g.toFixed(2)}, ${this.b.toFixed(2)}, ${this.a.toFixed(2)})`}equals(other){if(!other)return!1;return this.r===other.r&&this.g===other.g&&this.b===other.b&&this.a===other.a}}function hexToRgb(hex){if(hex=hex.replace(/^#/,""),hex.length===3)hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];else if(hex.length===4)hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]+hex[3]+hex[3];if(!/^[0-9A-Fa-f]{6}$/.test(hex)&&!/^[0-9A-Fa-f]{8}$/.test(hex))return console.warn(`Invalid hex color: ${hex}, defaulting to magenta`),RGBA.fromValues(1,0,1,1);let r=parseInt(hex.substring(0,2),16)/255,g=parseInt(hex.substring(2,4),16)/255,b2=parseInt(hex.substring(4,6),16)/255,a=hex.length===8?parseInt(hex.substring(6,8),16)/255:1;return RGBA.fromValues(r,g,b2,a)}function rgbToHex(rgb){return"#"+(rgb.a===1?[rgb.r,rgb.g,rgb.b]:[rgb.r,rgb.g,rgb.b,rgb.a]).map((x)=>{let hex=Math.floor(Math.max(0,Math.min(1,x)*255)).toString(16);return hex.length===1?"0"+hex:hex}).join("")}function hsvToRgb(h,s2,v){let r=0,g=0,b2=0,i2=Math.floor(h/60)%6,f=h/60-Math.floor(h/60),p=v*(1-s2),q=v*(1-f*s2),t=v*(1-(1-f)*s2);switch(i2){case 0:r=v,g=t,b2=p;break;case 1:r=q,g=v,b2=p;break;case 2:r=p,g=v,b2=t;break;case 3:r=p,g=q,b2=v;break;case 4:r=t,g=p,b2=v;break;case 5:r=v,g=p,b2=q;break}return RGBA.fromValues(r,g,b2,1)}function parseColor(color2){if(typeof color2==="string"){let lowerColor=color2.toLowerCase();if(lowerColor==="transparent")return RGBA.fromValues(0,0,0,0);if(CSS_COLOR_NAMES[lowerColor])return hexToRgb(CSS_COLOR_NAMES[lowerColor]);return hexToRgb(color2)}return color2}function parseColorTags(text){let segments=[],currentIndex=0,colorTagRegex=/<c(\d+)>(.*?)<\/c\d+>/g,lastIndex=0,match;while((match=colorTagRegex.exec(text))!==null){if(match.index>lastIndex){let plainText=text.slice(lastIndex,match.index);if(plainText)segments.push({text:plainText,colorIndex:0})}let colorIndex=parseInt(match[1])-1,taggedText=match[2];segments.push({text:taggedText,colorIndex:Math.max(0,colorIndex)}),lastIndex=match.index+match[0].length}if(lastIndex<text.length){let remainingText=text.slice(lastIndex);if(remainingText)segments.push({text:remainingText,colorIndex:0})}return segments}function getParsedFont(fontKey){if(!parsedFonts[fontKey]){let fontDef=fonts[fontKey],parsedChars={};for(let[char,lines]of Object.entries(fontDef.chars))parsedChars[char]=lines.map((line)=>parseColorTags(line));parsedFonts[fontKey]={...fontDef,colors:fontDef.colors||1,chars:parsedChars}}return parsedFonts[fontKey]}function measureText({text,font="tiny"}){let fontDef=getParsedFont(font);if(!fontDef)return console.warn(`Font '${font}' not found`),{width:0,height:0};let currentX=0;for(let i2=0;i2<text.length;i2++){let char=text[i2].toUpperCase(),charDef=fontDef.chars[char];if(!charDef){let spaceChar=fontDef.chars[" "];if(spaceChar&&spaceChar[0]){let spaceWidth=0;for(let segment of spaceChar[0])spaceWidth+=segment.text.length;currentX+=spaceWidth}else currentX+=1;continue}let charWidth=0;if(charDef[0])for(let segment of charDef[0])charWidth+=segment.text.length;if(currentX+=charWidth,i2<text.length-1)currentX+=fontDef.letterspace_size}return{width:currentX,height:fontDef.lines}}function getCharacterPositions(text,font="tiny"){let fontDef=getParsedFont(font);if(!fontDef)return[0];let positions=[0],currentX=0;for(let i2=0;i2<text.length;i2++){let char=text[i2].toUpperCase(),charDef=fontDef.chars[char],charWidth=0;if(!charDef){let spaceChar=fontDef.chars[" "];if(spaceChar&&spaceChar[0])for(let segment of spaceChar[0])charWidth+=segment.text.length;else charWidth=1}else if(charDef[0])for(let segment of charDef[0])charWidth+=segment.text.length;if(currentX+=charWidth,i2<text.length-1)currentX+=fontDef.letterspace_size;positions.push(currentX)}return positions}function coordinateToCharacterIndex(x,text,font="tiny"){let positions=getCharacterPositions(text,font);if(x<0)return 0;for(let i2=0;i2<positions.length-1;i2++){let currentPos=positions[i2],nextPos=positions[i2+1];if(x>=currentPos&&x<nextPos){let charMidpoint=currentPos+(nextPos-currentPos)/2;return x<charMidpoint?i2:i2+1}}if(positions.length>0&&x>=positions[positions.length-1])return text.length;return 0}function renderFontToFrameBuffer(buffer2,{text,x=0,y=0,color:color2=[RGBA.fromInts(255,255,255,255)],backgroundColor=RGBA.fromInts(0,0,0,255),font="tiny"}){let{width,height:height2}=buffer2,fontDef=getParsedFont(font);if(!fontDef)return console.warn(`Font '${font}' not found`),{width:0,height:0};let colors8=Array.isArray(color2)?color2:[color2];if(y<0||y+fontDef.lines>height2)return{width:0,height:fontDef.lines};let currentX=x,startX=x;for(let i2=0;i2<text.length;i2++){let char=text[i2].toUpperCase(),charDef=fontDef.chars[char];if(!charDef){let spaceChar=fontDef.chars[" "];if(spaceChar&&spaceChar[0]){let spaceWidth=0;for(let segment of spaceChar[0])spaceWidth+=segment.text.length;currentX+=spaceWidth}else currentX+=1;continue}let charWidth=0;if(charDef[0])for(let segment of charDef[0])charWidth+=segment.text.length;if(currentX>=width)break;if(currentX+charWidth<0){currentX+=charWidth+fontDef.letterspace_size;continue}for(let lineIdx=0;lineIdx<fontDef.lines&&lineIdx<charDef.length;lineIdx++){let segments=charDef[lineIdx],renderY=y+lineIdx;if(renderY>=0&&renderY<height2){let segmentX=currentX;for(let segment of segments){let segmentColor=colors8[segment.colorIndex]||colors8[0];for(let charIdx=0;charIdx<segment.text.length;charIdx++){let renderX=segmentX+charIdx;if(renderX>=0&&renderX<width){let fontChar=segment.text[charIdx];if(fontChar!==" ")buffer2.setCellWithAlphaBlending(renderX,renderY,fontChar,parseColor(segmentColor),parseColor(backgroundColor))}}segmentX+=segment.text.length}}}if(currentX+=charWidth,i2<text.length-1)currentX+=fontDef.letterspace_size}return{width:currentX-startX,height:fontDef.lines}}function getBaseAttributes(attr){return attr&ATTRIBUTE_BASE_MASK}function createTextAttributes({bold=!1,italic=!1,underline=!1,dim=!1,blink=!1,inverse=!1,hidden=!1,strikethrough=!1}={}){let attributes=TextAttributes.NONE;if(bold)attributes|=TextAttributes.BOLD;if(italic)attributes|=TextAttributes.ITALIC;if(underline)attributes|=TextAttributes.UNDERLINE;if(dim)attributes|=TextAttributes.DIM;if(blink)attributes|=TextAttributes.BLINK;if(inverse)attributes|=TextAttributes.INVERSE;if(hidden)attributes|=TextAttributes.HIDDEN;if(strikethrough)attributes|=TextAttributes.STRIKETHROUGH;return attributes}function attributesWithLink(baseAttributes,linkId){let base=baseAttributes&ATTRIBUTE_BASE_MASK2,linkBits=(linkId&LINK_ID_PAYLOAD_MASK)<<LINK_ID_SHIFT;return base|linkBits}function getLinkId(attributes){return attributes>>>LINK_ID_SHIFT&LINK_ID_PAYLOAD_MASK}function visualizeRenderableTree(renderable,maxDepth=10){function buildTreeLines(node,prefix="",parentPrefix="",isLastChild=!0,depth=0){if(depth>=maxDepth)return[`${prefix}${node.id} ... (max depth reached)`];let lines=[],children=node.getChildren();if(lines.push(`${prefix}${node.id}`),children.length>0){let lastChildIndex=children.length-1;children.forEach((child,index)=>{let childIsLast=index===lastChildIndex,connector=childIsLast?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",childPrefix=parentPrefix+(isLastChild?" ":"\u2502 "),childLines=buildTreeLines(child,childPrefix+connector,childPrefix,childIsLast,depth+1);lines.push(...childLines)})}return lines}let treeLines=buildTreeLines(renderable);console.log(`Renderable Tree:
2200
+ `).map((r)=>({id:r.id,seq:r.seq,title:r.title,stage:r.stage,repoPath:r.repo_path}))}var init_task_close_merged=__esm(()=>{init_wish_state()});var highlights_default="./highlights-ghv9g403.scm";var init_highlights=()=>{};var tree_sitter_javascript_default="./tree-sitter-javascript-nd0q4pe9.wasm";var init_tree_sitter_javascript=()=>{};var highlights_default2="./highlights-eq9cgrbb.scm";var init_highlights2=()=>{};var tree_sitter_typescript_default="./tree-sitter-typescript-zxjzwt75.wasm";var init_tree_sitter_typescript=()=>{};var highlights_default3="./highlights-r812a2qc.scm";var init_highlights3=()=>{};var tree_sitter_markdown_default="./tree-sitter-markdown-411r6y9b.wasm";var init_tree_sitter_markdown=()=>{};var injections_default="./injections-73j83es3.scm";var init_injections=()=>{};var highlights_default4="./highlights-x6tmsnaa.scm";var init_highlights4=()=>{};var tree_sitter_markdown_inline_default="./tree-sitter-markdown_inline-j5349f42.wasm";var init_tree_sitter_markdown_inline=()=>{};var highlights_default5="./highlights-hk7bwhj4.scm";var init_highlights5=()=>{};var tree_sitter_zig_default="./tree-sitter-zig-e78zbjpm.wasm";var init_tree_sitter_zig=()=>{};import{EventEmitter}from"events";import{Buffer as Buffer2}from"buffer";import{Buffer as Buffer3}from"buffer";import{EventEmitter as EventEmitter2}from"events";import{resolve as resolve11,dirname as dirname11}from"path";import{fileURLToPath as fileURLToPath2}from"url";import{resolve as resolve22,isAbsolute,parse as parse2}from"path";import{existsSync as existsSync43}from"fs";import{basename as basename10,join as join56}from"path";import os3 from"os";import path3 from"path";import{EventEmitter as EventEmitter3}from"events";import path22 from"path";import{readFile as readFile22,writeFile as writeFile22,mkdir as mkdir22}from"fs/promises";import*as path4 from"path";import{mkdir as mkdir9,readFile as readFile13,writeFile as writeFile6}from"fs/promises";import*as path32 from"path";import{readdir as readdir7}from"fs/promises";import{dlopen,toArrayBuffer as toArrayBuffer4,JSCallback,ptr as ptr4}from"bun:ffi";import{existsSync as existsSync210,writeFileSync as writeFileSync23}from"fs";import{EventEmitter as EventEmitter4}from"events";import{toArrayBuffer,ptr}from"bun:ffi";import{ptr as ptr2,toArrayBuffer as toArrayBuffer2}from"bun:ffi";import{ptr as ptr3,toArrayBuffer as toArrayBuffer3}from"bun:ffi";import{EventEmitter as EventEmitter5}from"events";import util3 from"util";import{EventEmitter as EventEmitter7}from"events";import{Console}from"console";import fs2 from"fs";import path5 from"path";import util22 from"util";import{Writable}from"stream";import{EventEmitter as EventEmitter6}from"events";import{EventEmitter as EventEmitter8}from"events";function __exportSetter2(name,newValue){this[name]=__returnValue2.bind(null,newValue)}function wrapAssembly(lib){function patch(prototype,name,fn){let original=prototype[name];prototype[name]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return fn.call(this,original,...args)}}for(let fnName of["setPosition","setMargin","setFlexBasis","setWidth","setHeight","setMinWidth","setMinHeight","setMaxWidth","setMaxHeight","setPadding","setGap"]){let methods={[Unit.Point]:lib.Node.prototype[fnName],[Unit.Percent]:lib.Node.prototype[`${fnName}Percent`],[Unit.Auto]:lib.Node.prototype[`${fnName}Auto`]};patch(lib.Node.prototype,fnName,function(original){for(var _len2=arguments.length,args=Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];let value=args.pop(),unit,asNumber;if(value==="auto")unit=Unit.Auto,asNumber=void 0;else if(typeof value==="object")unit=value.unit,asNumber=value.valueOf();else if(unit=typeof value==="string"&&value.endsWith("%")?Unit.Percent:Unit.Point,asNumber=parseFloat(value),value!==void 0&&!Number.isNaN(value)&&Number.isNaN(asNumber))throw Error(`Invalid value ${value} for ${fnName}`);if(!methods[unit])throw Error(`Failed to execute "${fnName}": Unsupported unit '${value}'`);if(asNumber!==void 0)return methods[unit].call(this,...args,asNumber);else return methods[unit].call(this,...args)})}function wrapMeasureFunction(measureFunction){return lib.MeasureCallback.implement({measure:function(){let{width,height:height2}=measureFunction(...arguments);return{width:width??NaN,height:height2??NaN}}})}patch(lib.Node.prototype,"setMeasureFunc",function(original,measureFunc){if(measureFunc)return original.call(this,wrapMeasureFunction(measureFunc));else return this.unsetMeasureFunc()});function wrapDirtiedFunc(dirtiedFunction){return lib.DirtiedCallback.implement({dirtied:dirtiedFunction})}return patch(lib.Node.prototype,"setDirtiedFunc",function(original,dirtiedFunc){original.call(this,wrapDirtiedFunc(dirtiedFunc))}),patch(lib.Config.prototype,"free",function(){lib.Config.destroy(this)}),patch(lib.Node,"create",(_,config)=>{return config?lib.Node.createWithConfig(config):lib.Node.createDefault()}),patch(lib.Node.prototype,"free",function(){lib.Node.destroy(this)}),patch(lib.Node.prototype,"freeRecursive",function(){for(let t=0,T=this.getChildCount();t<T;++t)this.getChild(0).freeRecursive();this.free()}),patch(lib.Node.prototype,"calculateLayout",function(original){let width=arguments.length>1&&arguments[1]!==void 0?arguments[1]:NaN,height2=arguments.length>2&&arguments[2]!==void 0?arguments[2]:NaN,direction=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Direction.LTR;return original.call(this,width,height2,direction)}),{Config:lib.Config,Node:lib.Node,...YGEnums_default}}function isValidBorderStyle(value){return typeof value==="string"&&VALID_BORDER_STYLES.includes(value)}function parseBorderStyle(value,fallback="single"){if(isValidBorderStyle(value))return value;if(value!==void 0&&value!==null)console.warn(`Invalid borderStyle "${value}", falling back to "${fallback}". Valid values are: ${VALID_BORDER_STYLES.join(", ")}`);return fallback}function getBorderFromSides(sides){let result2=[];if(sides.top)result2.push("top");if(sides.right)result2.push("right");if(sides.bottom)result2.push("bottom");if(sides.left)result2.push("left");return result2.length>0?result2:!1}function getBorderSides(border){return border===!0?{top:!0,right:!0,bottom:!0,left:!0}:Array.isArray(border)?{top:border.includes("top"),right:border.includes("right"),bottom:border.includes("bottom"),left:border.includes("left")}:{top:!1,right:!1,bottom:!1,left:!1}}function borderCharsToArray(chars){let array=new Uint32Array(11);return array[0]=chars.topLeft.codePointAt(0),array[1]=chars.topRight.codePointAt(0),array[2]=chars.bottomLeft.codePointAt(0),array[3]=chars.bottomRight.codePointAt(0),array[4]=chars.horizontal.codePointAt(0),array[5]=chars.vertical.codePointAt(0),array[6]=chars.topT.codePointAt(0),array[7]=chars.bottomT.codePointAt(0),array[8]=chars.leftT.codePointAt(0),array[9]=chars.rightT.codePointAt(0),array[10]=chars.cross.codePointAt(0),array}class KeyEvent{name;ctrl;meta;shift;option;sequence;number;raw;eventType;source;code;super;hyper;capsLock;numLock;baseCode;repeated;_defaultPrevented=!1;_propagationStopped=!1;constructor(key){this.name=key.name,this.ctrl=key.ctrl,this.meta=key.meta,this.shift=key.shift,this.option=key.option,this.sequence=key.sequence,this.number=key.number,this.raw=key.raw,this.eventType=key.eventType,this.source=key.source,this.code=key.code,this.super=key.super,this.hyper=key.hyper,this.capsLock=key.capsLock,this.numLock=key.numLock,this.baseCode=key.baseCode,this.repeated=key.repeated}get defaultPrevented(){return this._defaultPrevented}get propagationStopped(){return this._propagationStopped}preventDefault(){this._defaultPrevented=!0}stopPropagation(){this._propagationStopped=!0}}class PasteEvent{type="paste";bytes;metadata;_defaultPrevented=!1;_propagationStopped=!1;constructor(bytes,metadata){this.bytes=bytes,this.metadata=metadata}get defaultPrevented(){return this._defaultPrevented}get propagationStopped(){return this._propagationStopped}preventDefault(){this._defaultPrevented=!0}stopPropagation(){this._propagationStopped=!0}}class RGBA{buffer;constructor(buffer2){this.buffer=buffer2}static fromArray(array){return new RGBA(array)}static fromValues(r,g,b2,a=1){return new RGBA(new Float32Array([r,g,b2,a]))}static fromInts(r,g,b2,a=255){return new RGBA(new Float32Array([r/255,g/255,b2/255,a/255]))}static fromHex(hex){return hexToRgb(hex)}toInts(){return[Math.round(this.r*255),Math.round(this.g*255),Math.round(this.b*255),Math.round(this.a*255)]}get r(){return this.buffer[0]}set r(value){this.buffer[0]=value}get g(){return this.buffer[1]}set g(value){this.buffer[1]=value}get b(){return this.buffer[2]}set b(value){this.buffer[2]=value}get a(){return this.buffer[3]}set a(value){this.buffer[3]=value}map(fn){return[fn(this.r),fn(this.g),fn(this.b),fn(this.a)]}toString(){return`rgba(${this.r.toFixed(2)}, ${this.g.toFixed(2)}, ${this.b.toFixed(2)}, ${this.a.toFixed(2)})`}equals(other){if(!other)return!1;return this.r===other.r&&this.g===other.g&&this.b===other.b&&this.a===other.a}}function hexToRgb(hex){if(hex=hex.replace(/^#/,""),hex.length===3)hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];else if(hex.length===4)hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]+hex[3]+hex[3];if(!/^[0-9A-Fa-f]{6}$/.test(hex)&&!/^[0-9A-Fa-f]{8}$/.test(hex))return console.warn(`Invalid hex color: ${hex}, defaulting to magenta`),RGBA.fromValues(1,0,1,1);let r=parseInt(hex.substring(0,2),16)/255,g=parseInt(hex.substring(2,4),16)/255,b2=parseInt(hex.substring(4,6),16)/255,a=hex.length===8?parseInt(hex.substring(6,8),16)/255:1;return RGBA.fromValues(r,g,b2,a)}function rgbToHex(rgb){return"#"+(rgb.a===1?[rgb.r,rgb.g,rgb.b]:[rgb.r,rgb.g,rgb.b,rgb.a]).map((x)=>{let hex=Math.floor(Math.max(0,Math.min(1,x)*255)).toString(16);return hex.length===1?"0"+hex:hex}).join("")}function hsvToRgb(h,s2,v){let r=0,g=0,b2=0,i2=Math.floor(h/60)%6,f=h/60-Math.floor(h/60),p=v*(1-s2),q=v*(1-f*s2),t=v*(1-(1-f)*s2);switch(i2){case 0:r=v,g=t,b2=p;break;case 1:r=q,g=v,b2=p;break;case 2:r=p,g=v,b2=t;break;case 3:r=p,g=q,b2=v;break;case 4:r=t,g=p,b2=v;break;case 5:r=v,g=p,b2=q;break}return RGBA.fromValues(r,g,b2,1)}function parseColor(color2){if(typeof color2==="string"){let lowerColor=color2.toLowerCase();if(lowerColor==="transparent")return RGBA.fromValues(0,0,0,0);if(CSS_COLOR_NAMES[lowerColor])return hexToRgb(CSS_COLOR_NAMES[lowerColor]);return hexToRgb(color2)}return color2}function parseColorTags(text){let segments=[],currentIndex=0,colorTagRegex=/<c(\d+)>(.*?)<\/c\d+>/g,lastIndex=0,match;while((match=colorTagRegex.exec(text))!==null){if(match.index>lastIndex){let plainText=text.slice(lastIndex,match.index);if(plainText)segments.push({text:plainText,colorIndex:0})}let colorIndex=parseInt(match[1])-1,taggedText=match[2];segments.push({text:taggedText,colorIndex:Math.max(0,colorIndex)}),lastIndex=match.index+match[0].length}if(lastIndex<text.length){let remainingText=text.slice(lastIndex);if(remainingText)segments.push({text:remainingText,colorIndex:0})}return segments}function getParsedFont(fontKey){if(!parsedFonts[fontKey]){let fontDef=fonts[fontKey],parsedChars={};for(let[char,lines]of Object.entries(fontDef.chars))parsedChars[char]=lines.map((line)=>parseColorTags(line));parsedFonts[fontKey]={...fontDef,colors:fontDef.colors||1,chars:parsedChars}}return parsedFonts[fontKey]}function measureText({text,font="tiny"}){let fontDef=getParsedFont(font);if(!fontDef)return console.warn(`Font '${font}' not found`),{width:0,height:0};let currentX=0;for(let i2=0;i2<text.length;i2++){let char=text[i2].toUpperCase(),charDef=fontDef.chars[char];if(!charDef){let spaceChar=fontDef.chars[" "];if(spaceChar&&spaceChar[0]){let spaceWidth=0;for(let segment of spaceChar[0])spaceWidth+=segment.text.length;currentX+=spaceWidth}else currentX+=1;continue}let charWidth=0;if(charDef[0])for(let segment of charDef[0])charWidth+=segment.text.length;if(currentX+=charWidth,i2<text.length-1)currentX+=fontDef.letterspace_size}return{width:currentX,height:fontDef.lines}}function getCharacterPositions(text,font="tiny"){let fontDef=getParsedFont(font);if(!fontDef)return[0];let positions=[0],currentX=0;for(let i2=0;i2<text.length;i2++){let char=text[i2].toUpperCase(),charDef=fontDef.chars[char],charWidth=0;if(!charDef){let spaceChar=fontDef.chars[" "];if(spaceChar&&spaceChar[0])for(let segment of spaceChar[0])charWidth+=segment.text.length;else charWidth=1}else if(charDef[0])for(let segment of charDef[0])charWidth+=segment.text.length;if(currentX+=charWidth,i2<text.length-1)currentX+=fontDef.letterspace_size;positions.push(currentX)}return positions}function coordinateToCharacterIndex(x,text,font="tiny"){let positions=getCharacterPositions(text,font);if(x<0)return 0;for(let i2=0;i2<positions.length-1;i2++){let currentPos=positions[i2],nextPos=positions[i2+1];if(x>=currentPos&&x<nextPos){let charMidpoint=currentPos+(nextPos-currentPos)/2;return x<charMidpoint?i2:i2+1}}if(positions.length>0&&x>=positions[positions.length-1])return text.length;return 0}function renderFontToFrameBuffer(buffer2,{text,x=0,y=0,color:color2=[RGBA.fromInts(255,255,255,255)],backgroundColor=RGBA.fromInts(0,0,0,255),font="tiny"}){let{width,height:height2}=buffer2,fontDef=getParsedFont(font);if(!fontDef)return console.warn(`Font '${font}' not found`),{width:0,height:0};let colors8=Array.isArray(color2)?color2:[color2];if(y<0||y+fontDef.lines>height2)return{width:0,height:fontDef.lines};let currentX=x,startX=x;for(let i2=0;i2<text.length;i2++){let char=text[i2].toUpperCase(),charDef=fontDef.chars[char];if(!charDef){let spaceChar=fontDef.chars[" "];if(spaceChar&&spaceChar[0]){let spaceWidth=0;for(let segment of spaceChar[0])spaceWidth+=segment.text.length;currentX+=spaceWidth}else currentX+=1;continue}let charWidth=0;if(charDef[0])for(let segment of charDef[0])charWidth+=segment.text.length;if(currentX>=width)break;if(currentX+charWidth<0){currentX+=charWidth+fontDef.letterspace_size;continue}for(let lineIdx=0;lineIdx<fontDef.lines&&lineIdx<charDef.length;lineIdx++){let segments=charDef[lineIdx],renderY=y+lineIdx;if(renderY>=0&&renderY<height2){let segmentX=currentX;for(let segment of segments){let segmentColor=colors8[segment.colorIndex]||colors8[0];for(let charIdx=0;charIdx<segment.text.length;charIdx++){let renderX=segmentX+charIdx;if(renderX>=0&&renderX<width){let fontChar=segment.text[charIdx];if(fontChar!==" ")buffer2.setCellWithAlphaBlending(renderX,renderY,fontChar,parseColor(segmentColor),parseColor(backgroundColor))}}segmentX+=segment.text.length}}}if(currentX+=charWidth,i2<text.length-1)currentX+=fontDef.letterspace_size}return{width:currentX-startX,height:fontDef.lines}}function getBaseAttributes(attr){return attr&ATTRIBUTE_BASE_MASK}function createTextAttributes({bold=!1,italic=!1,underline=!1,dim=!1,blink=!1,inverse=!1,hidden=!1,strikethrough=!1}={}){let attributes=TextAttributes.NONE;if(bold)attributes|=TextAttributes.BOLD;if(italic)attributes|=TextAttributes.ITALIC;if(underline)attributes|=TextAttributes.UNDERLINE;if(dim)attributes|=TextAttributes.DIM;if(blink)attributes|=TextAttributes.BLINK;if(inverse)attributes|=TextAttributes.INVERSE;if(hidden)attributes|=TextAttributes.HIDDEN;if(strikethrough)attributes|=TextAttributes.STRIKETHROUGH;return attributes}function attributesWithLink(baseAttributes,linkId){let base=baseAttributes&ATTRIBUTE_BASE_MASK2,linkBits=(linkId&LINK_ID_PAYLOAD_MASK)<<LINK_ID_SHIFT;return base|linkBits}function getLinkId(attributes){return attributes>>>LINK_ID_SHIFT&LINK_ID_PAYLOAD_MASK}function visualizeRenderableTree(renderable,maxDepth=10){function buildTreeLines(node,prefix="",parentPrefix="",isLastChild=!0,depth=0){if(depth>=maxDepth)return[`${prefix}${node.id} ... (max depth reached)`];let lines=[],children=node.getChildren();if(lines.push(`${prefix}${node.id}`),children.length>0){let lastChildIndex=children.length-1;children.forEach((child,index)=>{let childIsLast=index===lastChildIndex,connector=childIsLast?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",childPrefix=parentPrefix+(isLastChild?" ":"\u2502 "),childLines=buildTreeLines(child,childPrefix+connector,childPrefix,childIsLast,depth+1);lines.push(...childLines)})}return lines}let treeLines=buildTreeLines(renderable);console.log(`Renderable Tree:
2193
2201
  `+treeLines.join(`
2194
2202
  `))}function isStyledText(obj){return obj&&obj[BrandedStyledText]}function stringToStyledText(content){return new StyledText([{__isChunk:!0,text:content}])}function applyStyle(input,style){if(typeof input==="object"&&"__isChunk"in input){let existingChunk=input,fg=style.fg?parseColor(style.fg):existingChunk.fg,bg=style.bg?parseColor(style.bg):existingChunk.bg,newAttrs=createTextAttributes(style),mergedAttrs=existingChunk.attributes?existingChunk.attributes|newAttrs:newAttrs;return{__isChunk:!0,text:existingChunk.text,fg,bg,attributes:mergedAttrs,link:existingChunk.link}}else{let plainTextStr=String(input),fg=style.fg?parseColor(style.fg):void 0,bg=style.bg?parseColor(style.bg):void 0,attributes=createTextAttributes(style);return{__isChunk:!0,text:plainTextStr,fg,bg,attributes}}}function t(strings,...values2){let chunks=[];for(let i2=0;i2<strings.length;i2++){let raw=strings[i2];if(raw)chunks.push({__isChunk:!0,text:raw,attributes:0});let val=values2[i2];if(typeof val==="object"&&"__isChunk"in val)chunks.push(val);else if(val!==void 0){let plainTextStr=String(val);chunks.push({__isChunk:!0,text:plainTextStr,attributes:0})}}return new StyledText(chunks)}function hastToTextChunks(node,syntaxStyle,parentStyles=[]){let chunks=[];if(node.type==="text"){let stylesToMerge=parentStyles.length>0?parentStyles:["default"],mergedStyle=syntaxStyle.mergeStyles(...stylesToMerge);chunks.push({__isChunk:!0,text:node.value,fg:mergedStyle.fg,bg:mergedStyle.bg,attributes:mergedStyle.attributes})}else if(node.type==="element"){let currentStyles=[...parentStyles];if(node.properties?.className){let classes=node.properties.className.split(" ");for(let cls of classes)currentStyles.push(cls)}for(let child of node.children)chunks.push(...hastToTextChunks(child,syntaxStyle,currentStyles))}return chunks}function hastToStyledText(hast,syntaxStyle){let chunks=hastToTextChunks(hast,syntaxStyle);return new StyledText(chunks)}class SystemClock{now(){if(!globalThis.performance||typeof globalThis.performance.now!=="function")throw Error("SystemClock requires globalThis.performance.now()");return globalThis.performance.now()}setTimeout(fn,delayMs){return globalThis.setTimeout(fn,delayMs)}clearTimeout(handle){globalThis.clearTimeout(handle)}setInterval(fn,delayMs){return globalThis.setInterval(fn,delayMs)}clearInterval(handle){globalThis.clearInterval(handle)}}function fromKittyMods(mod){return{shift:!!(mod&1),alt:!!(mod&2),ctrl:!!(mod&4),super:!!(mod&8),hyper:!!(mod&16),meta:!!(mod&32),capsLock:!!(mod&64),numLock:!!(mod&128)}}function parseKittySpecialKey(sequence){let match=/^\x1b\[(\d+);(\d+):(\d+)([A-Z~])$/.exec(sequence);if(!match)return null;let keyNumOrOne=match[1],modifierStr=match[2],eventTypeStr=match[3],terminator=match[4],keyName;if(terminator==="~")keyName=tildeKeyMap[keyNumOrOne];else{if(keyNumOrOne!=="1")return null;keyName=functionalKeyMap[terminator]}if(!keyName)return null;let key={name:keyName,ctrl:!1,meta:!1,shift:!1,option:!1,number:!1,sequence,raw:sequence,eventType:"press",source:"kitty",super:!1,hyper:!1,capsLock:!1,numLock:!1};if(modifierStr){let modifierMask=parseInt(modifierStr,10);if(!isNaN(modifierMask)&&modifierMask>1){let mods=fromKittyMods(modifierMask-1);key.shift=mods.shift,key.ctrl=mods.ctrl,key.meta=mods.alt||mods.meta,key.option=mods.alt,key.super=mods.super,key.hyper=mods.hyper,key.capsLock=mods.capsLock,key.numLock=mods.numLock}}if(eventTypeStr==="1"||!eventTypeStr)key.eventType="press";else if(eventTypeStr==="2")key.eventType="press",key.repeated=!0;else if(eventTypeStr==="3")key.eventType="release";return key}function parseKittyKeyboard(sequence){let specialResult=parseKittySpecialKey(sequence);if(specialResult)return specialResult;let match=/^\x1b\[([^\x1b]+)u$/.exec(sequence);if(!match)return null;let fields=match[1].split(";");if(fields.length<1)return null;let key={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,number:!1,sequence,raw:sequence,eventType:"press",source:"kitty",super:!1,hyper:!1,capsLock:!1,numLock:!1},text="",field1=fields[0]?.split(":")||[],codepointStr=field1[0];if(!codepointStr)return null;let codepoint=parseInt(codepointStr,10);if(isNaN(codepoint))return null;let shiftedCodepoint,baseCodepoint;if(field1[1]){let shifted=parseInt(field1[1],10);if(!isNaN(shifted)&&shifted>0&&shifted<=1114111)shiftedCodepoint=shifted}if(field1[2]){let base=parseInt(field1[2],10);if(!isNaN(base)&&base>0&&base<=1114111)baseCodepoint=base}let knownKey=kittyKeyMap[codepoint];if(knownKey)key.name=knownKey,key.code=`[${codepoint}u`;else if(codepoint===0)key.name="";else if(codepoint>0&&codepoint<=1114111){let char=String.fromCodePoint(codepoint);if(key.name=char,baseCodepoint)key.baseCode=baseCodepoint}else return null;if(fields[1]){let field2=fields[1].split(":"),modifierStr=field2[0],eventTypeStr=field2[1];if(modifierStr){let modifierMask=parseInt(modifierStr,10);if(!isNaN(modifierMask)&&modifierMask>1){let mods=fromKittyMods(modifierMask-1);key.shift=mods.shift,key.ctrl=mods.ctrl,key.meta=mods.alt||mods.meta,key.option=mods.alt,key.super=mods.super,key.hyper=mods.hyper,key.capsLock=mods.capsLock,key.numLock=mods.numLock}}if(eventTypeStr==="1"||!eventTypeStr)key.eventType="press";else if(eventTypeStr==="2")key.eventType="press",key.repeated=!0;else if(eventTypeStr==="3")key.eventType="release";else key.eventType="press"}if(fields[2]){let codepoints=fields[2].split(":");for(let cpStr of codepoints){let cp3=parseInt(cpStr,10);if(!isNaN(cp3)&&cp3>0&&cp3<=1114111)text+=String.fromCodePoint(cp3)}}if(text===""){if(key.name.length>0&&!kittyKeyMap[codepoint])if(key.shift&&shiftedCodepoint)text=String.fromCodePoint(shiftedCodepoint);else if(key.shift&&key.name.length===1)text=key.name.toLocaleUpperCase();else text=key.name}if(key.name===" "&&key.shift&&!key.ctrl&&!key.meta)text=" ";if(text){if(codepoint===0)key.name=text;key.sequence=text}if(codepoint===0&&text==="")return null;return key}class LinearScrollAccel{tick(_now){return 1}reset(){}}class MacOSScrollAccel{opts;lastTickTime=0;velocityHistory=[];historySize=3;streakTimeout=150;minTickInterval=6;constructor(opts={}){this.opts=opts}tick(now=Date.now()){let A=this.opts.A??0.8,tau=this.opts.tau??3,maxMultiplier=this.opts.maxMultiplier??6,dt=this.lastTickTime?now-this.lastTickTime:1/0;if(dt===1/0||dt>this.streakTimeout)return this.lastTickTime=now,this.velocityHistory=[],1;if(dt<this.minTickInterval)return 1;if(this.lastTickTime=now,this.velocityHistory.push(dt),this.velocityHistory.length>this.historySize)this.velocityHistory.shift();let x=100/(this.velocityHistory.reduce((a,b2)=>a+b2,0)/this.velocityHistory.length)/tau,multiplier=1+A*(Math.exp(x)-1);return Math.min(multiplier,maxMultiplier)}reset(){this.lastTickTime=0,this.velocityHistory=[]}}function parseAlign(value){if(value==null)return Align.Auto;switch(value.toLowerCase()){case"auto":return Align.Auto;case"flex-start":return Align.FlexStart;case"center":return Align.Center;case"flex-end":return Align.FlexEnd;case"stretch":return Align.Stretch;case"baseline":return Align.Baseline;case"space-between":return Align.SpaceBetween;case"space-around":return Align.SpaceAround;case"space-evenly":return Align.SpaceEvenly;default:return Align.Auto}}function parseAlignItems(value){if(value==null)return Align.Stretch;switch(value.toLowerCase()){case"auto":return Align.Auto;case"flex-start":return Align.FlexStart;case"center":return Align.Center;case"flex-end":return Align.FlexEnd;case"stretch":return Align.Stretch;case"baseline":return Align.Baseline;case"space-between":return Align.SpaceBetween;case"space-around":return Align.SpaceAround;case"space-evenly":return Align.SpaceEvenly;default:return Align.Stretch}}function parseBoxSizing(value){if(value==null)return BoxSizing.BorderBox;switch(value.toLowerCase()){case"border-box":return BoxSizing.BorderBox;case"content-box":return BoxSizing.ContentBox;default:return BoxSizing.BorderBox}}function parseDimension(value){if(value==null)return Dimension.Width;switch(value.toLowerCase()){case"width":return Dimension.Width;case"height":return Dimension.Height;default:return Dimension.Width}}function parseDirection(value){if(value==null)return Direction.LTR;switch(value.toLowerCase()){case"inherit":return Direction.Inherit;case"ltr":return Direction.LTR;case"rtl":return Direction.RTL;default:return Direction.LTR}}function parseDisplay(value){if(value==null)return Display.Flex;switch(value.toLowerCase()){case"flex":return Display.Flex;case"none":return Display.None;case"contents":return Display.Contents;default:return Display.Flex}}function parseEdge(value){if(value==null)return Edge.All;switch(value.toLowerCase()){case"left":return Edge.Left;case"top":return Edge.Top;case"right":return Edge.Right;case"bottom":return Edge.Bottom;case"start":return Edge.Start;case"end":return Edge.End;case"horizontal":return Edge.Horizontal;case"vertical":return Edge.Vertical;case"all":return Edge.All;default:return Edge.All}}function parseFlexDirection(value){if(value==null)return FlexDirection.Column;switch(value.toLowerCase()){case"column":return FlexDirection.Column;case"column-reverse":return FlexDirection.ColumnReverse;case"row":return FlexDirection.Row;case"row-reverse":return FlexDirection.RowReverse;default:return FlexDirection.Column}}function parseGutter(value){if(value==null)return Gutter.All;switch(value.toLowerCase()){case"column":return Gutter.Column;case"row":return Gutter.Row;case"all":return Gutter.All;default:return Gutter.All}}function parseJustify(value){if(value==null)return Justify.FlexStart;switch(value.toLowerCase()){case"flex-start":return Justify.FlexStart;case"center":return Justify.Center;case"flex-end":return Justify.FlexEnd;case"space-between":return Justify.SpaceBetween;case"space-around":return Justify.SpaceAround;case"space-evenly":return Justify.SpaceEvenly;default:return Justify.FlexStart}}function parseLogLevel(value){if(value==null)return LogLevel.Info;switch(value.toLowerCase()){case"error":return LogLevel.Error;case"warn":return LogLevel.Warn;case"info":return LogLevel.Info;case"debug":return LogLevel.Debug;case"verbose":return LogLevel.Verbose;case"fatal":return LogLevel.Fatal;default:return LogLevel.Info}}function parseMeasureMode(value){if(value==null)return MeasureMode.Undefined;switch(value.toLowerCase()){case"undefined":return MeasureMode.Undefined;case"exactly":return MeasureMode.Exactly;case"at-most":return MeasureMode.AtMost;default:return MeasureMode.Undefined}}function parseOverflow(value){if(value==null)return Overflow.Visible;switch(value.toLowerCase()){case"visible":return Overflow.Visible;case"hidden":return Overflow.Hidden;case"scroll":return Overflow.Scroll;default:return Overflow.Visible}}function parsePositionType(value){if(value==null)return PositionType.Relative;switch(value.toLowerCase()){case"static":return PositionType.Static;case"relative":return PositionType.Relative;case"absolute":return PositionType.Absolute;default:return PositionType.Static}}function parseUnit(value){if(value==null)return Unit.Point;switch(value.toLowerCase()){case"undefined":return Unit.Undefined;case"point":return Unit.Point;case"percent":return Unit.Percent;case"auto":return Unit.Auto;default:return Unit.Point}}function parseWrap(value){if(value==null)return Wrap.NoWrap;switch(value.toLowerCase()){case"no-wrap":return Wrap.NoWrap;case"wrap":return Wrap.Wrap;case"wrap-reverse":return Wrap.WrapReverse;default:return Wrap.NoWrap}}class SelectionAnchor{renderable;relativeX;relativeY;constructor(renderable,absoluteX,absoluteY){this.renderable=renderable,this.relativeX=absoluteX-this.renderable.x,this.relativeY=absoluteY-this.renderable.y}get x(){return this.renderable.x+this.relativeX}get y(){return this.renderable.y+this.relativeY}}class Selection{_anchor;_focus;_selectedRenderables=[];_touchedRenderables=[];_isActive=!0;_isDragging=!0;_isStart=!1;constructor(anchorRenderable,anchor,focus){this._anchor=new SelectionAnchor(anchorRenderable,anchor.x,anchor.y),this._focus={...focus}}get isStart(){return this._isStart}set isStart(value){this._isStart=value}get anchor(){return{x:this._anchor.x,y:this._anchor.y}}get focus(){return{...this._focus}}set focus(value){this._focus={...value}}get isActive(){return this._isActive}set isActive(value){this._isActive=value}get isDragging(){return this._isDragging}set isDragging(value){this._isDragging=value}get bounds(){let minX=Math.min(this._anchor.x,this._focus.x),maxX=Math.max(this._anchor.x,this._focus.x),minY=Math.min(this._anchor.y,this._focus.y),maxY=Math.max(this._anchor.y,this._focus.y),width=maxX-minX+1,height2=maxY-minY+1;return{x:minX,y:minY,width,height:height2}}updateSelectedRenderables(selectedRenderables){this._selectedRenderables=selectedRenderables}get selectedRenderables(){return this._selectedRenderables}updateTouchedRenderables(touchedRenderables){this._touchedRenderables=touchedRenderables}get touchedRenderables(){return this._touchedRenderables}getSelectedText(){return this._selectedRenderables.sort((a,b2)=>{let aY=a.y,bY=b2.y;if(aY!==bY)return aY-bY;return a.x-b2.x}).filter((renderable)=>!renderable.isDestroyed).map((renderable)=>renderable.getSelectedText()).filter((text)=>text).join(`
2195
2203
  `)}}function convertGlobalToLocalSelection(globalSelection,localX,localY){if(!globalSelection?.isActive)return null;return{anchorX:globalSelection.anchor.x-localX,anchorY:globalSelection.anchor.y-localY,focusX:globalSelection.focus.x-localX,focusY:globalSelection.focus.y-localY,isActive:!0}}class ASCIIFontSelectionHelper{getText;getFont;localSelection=null;constructor(getText,getFont){this.getText=getText,this.getFont=getFont}hasSelection(){return this.localSelection!==null}getSelection(){return this.localSelection}shouldStartSelection(localX,localY,width,height2){if(localX<0||localX>=width||localY<0||localY>=height2)return!1;let text=this.getText(),font=this.getFont(),charIndex=coordinateToCharacterIndex(localX,text,font);return charIndex>=0&&charIndex<=text.length}onLocalSelectionChanged(localSelection,width,height2){let previousSelection=this.localSelection;if(!localSelection?.isActive)return this.localSelection=null,previousSelection!==null;let text=this.getText(),font=this.getFont(),selStart={x:localSelection.anchorX,y:localSelection.anchorY},selEnd={x:localSelection.focusX,y:localSelection.focusY};if(height2-1<selStart.y||0>selEnd.y)return this.localSelection=null,previousSelection!==null;let startCharIndex=0,endCharIndex=text.length;if(selStart.y>height2-1)return this.localSelection=null,previousSelection!==null;else if(selStart.y>=0&&selStart.y<=height2-1){if(selStart.x>0)startCharIndex=coordinateToCharacterIndex(selStart.x,text,font)}if(selEnd.y<0)return this.localSelection=null,previousSelection!==null;else if(selEnd.y>=0&&selEnd.y<=height2-1)if(selEnd.x>=0)endCharIndex=coordinateToCharacterIndex(selEnd.x,text,font);else endCharIndex=0;if(startCharIndex<endCharIndex&&startCharIndex>=0&&endCharIndex<=text.length)this.localSelection={start:startCharIndex,end:endCharIndex};else this.localSelection=null;return previousSelection?.start!==this.localSelection?.start||previousSelection?.end!==this.localSelection?.end}}function singleton(key,factory){let bag=globalThis[singletonCacheSymbol]??={};if(!(key in bag))bag[key]=factory();return bag[key]}function destroySingleton(key){let bag=globalThis[singletonCacheSymbol];if(bag&&key in bag)delete bag[key]}function hasSingleton(key){let bag=globalThis[singletonCacheSymbol];return bag&&key in bag}function registerEnvVar(config){let existing=envRegistry[config.name];if(existing){if(existing.description!==config.description||existing.type!==config.type||existing.default!==config.default)throw Error(`Environment variable "${config.name}" is already registered with different configuration. Existing: ${JSON.stringify(existing)}, New: ${JSON.stringify(config)}`);return}envRegistry[config.name]=config}function normalizeBoolean(value){let lowerValue=value.toLowerCase();return["true","1","on","yes"].includes(lowerValue)}function parseEnvValue(config){let envValue=process.env[config.name];if(envValue===void 0&&config.default!==void 0)return config.default;if(envValue===void 0)throw Error(`Required environment variable ${config.name} is not set. ${config.description}`);switch(config.type){case"boolean":return typeof envValue==="boolean"?envValue:normalizeBoolean(envValue);case"number":let numValue=Number(envValue);if(isNaN(numValue))throw Error(`Environment variable ${config.name} must be a valid number, got: ${envValue}`);return numValue;case"string":default:return envValue}}class EnvStore{parsedValues=new Map;get(key){if(this.parsedValues.has(key))return this.parsedValues.get(key);if(!(key in envRegistry))throw Error(`Environment variable ${key} is not registered.`);try{let value=parseEnvValue(envRegistry[key]);return this.parsedValues.set(key,value),value}catch(error2){throw Error(`Failed to parse env var ${key}: ${error2 instanceof Error?error2.message:String(error2)}`)}}has(key){return key in envRegistry}clearCache(){this.parsedValues.clear()}}function clearEnvCache(){envStore.clearCache()}function generateEnvMarkdown(){let configs=Object.values(envRegistry);if(configs.length===0)return`# Environment Variables
@@ -2217,7 +2225,7 @@ No environment variables registered.
2217
2225
  `}else output+=`\x1B[32mDefault:\x1B[0m \x1B[31mRequired\x1B[0m
2218
2226
  `;output+=`
2219
2227
  `}return output}class ByteQueue{buf;start=0;end=0;constructor(capacity=INITIAL_PENDING_CAPACITY){this.buf=new Uint8Array(capacity)}get length(){return this.end-this.start}get capacity(){return this.buf.length}view(){return this.buf.subarray(this.start,this.end)}take(){let chunk=this.view();return this.start=0,this.end=0,chunk}append(chunk){if(chunk.length===0)return;this.ensureCapacity(this.length+chunk.length),this.buf.set(chunk,this.end),this.end+=chunk.length}consume(count){if(count<=0)return;if(count>=this.length){this.start=0,this.end=0;return}if(this.start+=count,this.start>=this.buf.length/2)this.buf.copyWithin(0,this.start,this.end),this.end-=this.start,this.start=0}clear(){this.start=0,this.end=0}reset(capacity=INITIAL_PENDING_CAPACITY){this.buf=new Uint8Array(capacity),this.start=0,this.end=0}ensureCapacity(requiredLength){let currentLength=this.length;if(requiredLength<=this.buf.length){if(this.buf.length-this.end>=requiredLength-currentLength)return;if(this.buf.copyWithin(0,this.start,this.end),this.end=currentLength,this.start=0,requiredLength<=this.buf.length)return}let nextCapacity=this.buf.length;while(nextCapacity<requiredLength)nextCapacity*=2;let next=new Uint8Array(nextCapacity);next.set(this.view(),0),this.buf=next,this.start=0,this.end=currentLength}}function normalizePositiveOption(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<=0)return fallback;return Math.floor(value)}function utf8SequenceLength(first){if(first<128)return 1;if(first>=194&&first<=223)return 2;if(first>=224&&first<=239)return 3;if(first>=240&&first<=244)return 4;return 0}function bytesEqual(left,right){if(left.length!==right.length)return!1;for(let index=0;index<left.length;index+=1)if(left[index]!==right[index])return!1;return!0}function isMouseSgrSequence(sequence){if(sequence.length<7)return!1;if(sequence[0]!==ESC||sequence[1]!==91||sequence[2]!==60)return!1;let final=sequence[sequence.length-1];if(final!==77&&final!==109)return!1;let part=0,hasDigit=!1;for(let index=3;index<sequence.length-1;index+=1){let byte=sequence[index];if(byte>=48&&byte<=57){hasDigit=!0;continue}if(byte===59&&hasDigit&&part<2){part+=1,hasDigit=!1;continue}return!1}return part===2&&hasDigit}function isAsciiDigit(byte){return byte>=48&&byte<=57}function parsePositiveDecimalPrefix(sequence,start2,endExclusive){if(start2>=endExclusive)return null;let value=0,sawDigit=!1;for(let index=start2;index<endExclusive;index+=1){let byte=sequence[index];if(!isAsciiDigit(byte))return null;sawDigit=!0,value=value*10+(byte-48)}return sawDigit?value:null}function canStillBeKittyU(state){return state.semicolons>=1}function canStillBeKittySpecial(state){return state.semicolons===1&&state.segments>1}function canStillBeExplicitWidthCpr(state){return state.firstParamValue===1&&state.semicolons===1}function canStillBePixelResolution(state){return state.firstParamValue===4&&state.semicolons===2}function canDeferParametricCsi(state,context){return context.kittyKeyboardEnabled&&(canStillBeKittyU(state)||canStillBeKittySpecial(state))||context.explicitWidthCprActive&&canStillBeExplicitWidthCpr(state)||context.pixelResolutionQueryActive&&canStillBePixelResolution(state)}function canCompleteDeferredParametricCsi(state,byte,context){if(context.kittyKeyboardEnabled){if(state.hasDigit&&byte===117)return!0;if(state.hasDigit&&state.semicolons===1&&state.segments>1&&(byte===126||byte>=65&&byte<=90))return!0}if(context.explicitWidthCprActive&&state.hasDigit&&state.firstParamValue===1&&state.semicolons===1&&byte===82)return!0;if(context.pixelResolutionQueryActive&&state.hasDigit&&state.firstParamValue===4&&state.semicolons===2&&byte===116)return!0;return!1}function canDeferPrivateReplyCsi(context){return context.privateCapabilityRepliesActive}function canCompleteDeferredPrivateReplyCsi(state,byte,context){if(!context.privateCapabilityRepliesActive)return!1;if(state.sawDollar)return state.hasDigit&&byte===121;if(byte===99)return state.hasDigit||state.semicolons>0;return state.hasDigit&&byte===117}function concatBytes(left,right){if(left.length===0)return right;if(right.length===0)return left;let combined=new Uint8Array(left.length+right.length);return combined.set(left,0),combined.set(right,left.length),combined}function indexOfBytes(haystack,needle){if(needle.length===0)return 0;let limit=haystack.length-needle.length;for(let offset=0;offset<=limit;offset+=1){let matched=!0;for(let index=0;index<needle.length;index+=1)if(haystack[offset+index]!==needle[index]){matched=!1;break}if(matched)return offset}return-1}function decodeLatin1(bytes){return Buffer3.from(bytes.buffer,bytes.byteOffset,bytes.byteLength).toString("latin1")}function decodeUtf8(bytes){return KEY_DECODER.decode(bytes)}function createPasteCollector(){return{tail:EMPTY_BYTES,parts:[],totalLength:0}}function joinPasteBytes(parts,totalLength){if(totalLength===0)return EMPTY_BYTES;if(parts.length===1)return parts[0];let bytes=new Uint8Array(totalLength),offset=0;for(let part of parts)bytes.set(part,offset),offset+=part.length;return bytes}class StdinParser{pending=new ByteQueue(INITIAL_PENDING_CAPACITY);events=[];timeoutMs;maxPendingBytes;armTimeouts;onTimeoutFlush;useKittyKeyboard;mouseParser=new MouseParser;clock;protocolContext;timeoutId=null;destroyed=!1;pendingSinceMs=null;forceFlush=!1;justFlushedEsc=!1;state={tag:"ground"};cursor=0;unitStart=0;paste=null;constructor(options={}){this.timeoutMs=normalizePositiveOption(options.timeoutMs,DEFAULT_TIMEOUT_MS),this.maxPendingBytes=normalizePositiveOption(options.maxPendingBytes,DEFAULT_MAX_PENDING_BYTES),this.armTimeouts=options.armTimeouts??!0,this.onTimeoutFlush=options.onTimeoutFlush??null,this.useKittyKeyboard=options.useKittyKeyboard??!0,this.clock=options.clock??SYSTEM_CLOCK,this.protocolContext={...DEFAULT_PROTOCOL_CONTEXT,kittyKeyboardEnabled:options.protocolContext?.kittyKeyboardEnabled??!1,privateCapabilityRepliesActive:options.protocolContext?.privateCapabilityRepliesActive??!1,pixelResolutionQueryActive:options.protocolContext?.pixelResolutionQueryActive??!1,explicitWidthCprActive:options.protocolContext?.explicitWidthCprActive??!1}}get bufferCapacity(){return this.pending.capacity}updateProtocolContext(patch){this.ensureAlive(),this.protocolContext={...this.protocolContext,...patch},this.reconcileDeferredStateWithProtocolContext(),this.reconcileTimeoutState()}push(data){if(this.ensureAlive(),data.length===0){this.emitKeyOrResponse("unknown","");return}let remainder=data;while(remainder.length>0){if(this.paste){remainder=this.consumePasteBytes(remainder);continue}let immediatePasteStartIndex=this.state.tag==="ground"&&this.pending.length===0?indexOfBytes(remainder,BRACKETED_PASTE_START):-1,appendEnd=immediatePasteStartIndex===-1?remainder.length:immediatePasteStartIndex+BRACKETED_PASTE_START.length;if(this.pending.append(remainder.subarray(0,appendEnd)),remainder=remainder.subarray(appendEnd),this.scanPending(),this.paste&&this.pending.length>0){remainder=this.consumePasteBytes(this.takePendingBytes());continue}if(!this.paste&&this.pending.length>this.maxPendingBytes){if(this.flushPendingOverflow(),this.scanPending(),this.paste&&this.pending.length>0)remainder=this.consumePasteBytes(this.takePendingBytes())}}this.reconcileTimeoutState()}read(){if(this.ensureAlive(),this.events.length===0&&this.forceFlush)this.scanPending(),this.reconcileTimeoutState();return this.events.shift()??null}drain(onEvent){this.ensureAlive();while(!0){if(this.destroyed)return;let event=this.read();if(!event)return;onEvent(event)}}flushTimeout(nowMsValue=this.clock.now()){if(this.ensureAlive(),this.paste||this.pendingSinceMs===null||this.pending.length===0)return;if(nowMsValue<this.pendingSinceMs||nowMsValue-this.pendingSinceMs<this.timeoutMs)return;this.forceFlush=!0}reset(){if(this.destroyed)return;this.clearTimeout(),this.resetState()}resetMouseState(){this.ensureAlive(),this.mouseParser.reset()}destroy(){if(this.destroyed)return;this.clearTimeout(),this.destroyed=!0,this.resetState()}ensureAlive(){if(this.destroyed)throw Error("StdinParser has been destroyed")}scanPending(){while(!this.paste){let bytes=this.pending.view();if(this.state.tag==="ground"&&this.cursor>=bytes.length){this.pending.clear(),this.cursor=0,this.unitStart=0,this.pendingSinceMs=null,this.forceFlush=!1;return}let byte=this.cursor<bytes.length?bytes[this.cursor]:-1;switch(this.state.tag){case"ground":{if(this.unitStart=this.cursor,this.justFlushedEsc){if(byte===91){this.justFlushedEsc=!1,this.cursor+=1,this.state={tag:"esc_recovery"};continue}this.justFlushedEsc=!1}if(byte===ESC){this.cursor+=1,this.state={tag:"esc"};continue}if(byte<128){this.emitKeyOrResponse("unknown",decodeUtf8(bytes.subarray(this.cursor,this.cursor+1))),this.consumePrefix(this.cursor+1);continue}let expected=utf8SequenceLength(byte);if(expected===0){if(!this.forceFlush&&this.cursor+1===bytes.length){this.markPending();return}this.emitLegacyHighByte(byte),this.consumePrefix(this.cursor+1);continue}this.cursor+=1,this.state={tag:"utf8",expected,seen:1};continue}case"utf8":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitLegacyHighByte(bytes[this.unitStart]),this.state={tag:"ground"},this.consumePrefix(this.unitStart+1);continue}if((byte&192)!==128){this.emitLegacyHighByte(bytes[this.unitStart]),this.state={tag:"ground"},this.consumePrefix(this.unitStart+1);continue}let nextSeen=this.state.seen+1;if(this.cursor+=1,nextSeen<this.state.expected){this.state={tag:"utf8",expected:this.state.expected,seen:nextSeen};continue}this.emitKeyOrResponse("unknown",decodeUtf8(bytes.subarray(this.unitStart,this.cursor))),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}case"esc":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}let flushedLoneEsc=this.cursor===this.unitStart+1&&bytes[this.unitStart]===ESC;this.emitKeyOrResponse("unknown",decodeUtf8(bytes.subarray(this.unitStart,this.cursor))),this.justFlushedEsc=flushedLoneEsc,this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}switch(byte){case 91:this.cursor+=1,this.state={tag:"csi"};continue;case 79:this.cursor+=1,this.state={tag:"ss3"};continue;case 93:this.cursor+=1,this.state={tag:"osc",sawEsc:!1};continue;case 80:this.cursor+=1,this.state={tag:"dcs",sawEsc:!1};continue;case 95:this.cursor+=1,this.state={tag:"apc",sawEsc:!1};continue;case ESC:this.cursor+=1;continue;default:this.cursor+=1,this.emitKeyOrResponse("unknown",decodeUtf8(bytes.subarray(this.unitStart,this.cursor))),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}}case"ss3":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}this.cursor+=1,this.emitKeyOrResponse("unknown",decodeUtf8(bytes.subarray(this.unitStart,this.cursor))),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}case"esc_recovery":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitKeyOrResponse("unknown",decodeUtf8(bytes.subarray(this.unitStart,this.cursor))),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(byte===60){this.cursor+=1,this.state={tag:"esc_less_mouse"};continue}if(byte===77){this.cursor+=1,this.state={tag:"esc_less_x10_mouse"};continue}this.emitKeyOrResponse("unknown",decodeUtf8(bytes.subarray(this.unitStart,this.unitStart+1))),this.state={tag:"ground"},this.consumePrefix(this.unitStart+1);continue}case"csi":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(byte===77&&this.cursor===this.unitStart+2){let end=this.cursor+4;if(bytes.length<end){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,bytes.length)),this.state={tag:"ground"},this.consumePrefix(bytes.length);continue}this.emitMouse(bytes.subarray(this.unitStart,end),"x10"),this.state={tag:"ground"},this.consumePrefix(end);continue}if(byte===36){let candidateEnd=this.cursor+1,candidate=decodeUtf8(bytes.subarray(this.unitStart,candidateEnd));if(RXVT_DOLLAR_CSI_RE.test(candidate)){this.emitKeyOrResponse("csi",candidate),this.state={tag:"ground"},this.consumePrefix(candidateEnd);continue}if(!this.forceFlush&&candidateEnd>=bytes.length){this.markPending();return}}if(byte===60&&this.cursor===this.unitStart+2){this.cursor+=1,this.state={tag:"csi_sgr_mouse",part:0,hasDigit:!1};continue}if(byte===91&&this.cursor===this.unitStart+2){this.cursor+=1;continue}if(byte===63&&this.cursor===this.unitStart+2){this.cursor+=1,this.state={tag:"csi_private_reply",semicolons:0,hasDigit:!1,sawDollar:!1};continue}if(byte===59){let firstParamValue=parsePositiveDecimalPrefix(bytes,this.unitStart+2,this.cursor);if(firstParamValue!==null){this.cursor+=1,this.state={tag:"csi_parametric",semicolons:1,segments:1,hasDigit:!1,firstParamValue};continue}}if(byte>=64&&byte<=126){let end=this.cursor+1,rawBytes=bytes.subarray(this.unitStart,end);if(bytesEqual(rawBytes,BRACKETED_PASTE_START)){this.state={tag:"ground"},this.consumePrefix(end),this.paste=createPasteCollector();continue}if(isMouseSgrSequence(rawBytes)){this.emitMouse(rawBytes,"sgr"),this.state={tag:"ground"},this.consumePrefix(end);continue}this.emitKeyOrResponse("csi",decodeUtf8(rawBytes)),this.state={tag:"ground"},this.consumePrefix(end);continue}this.cursor+=1;continue}case"csi_sgr_mouse":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.state={tag:"csi_sgr_mouse_deferred",part:this.state.part,hasDigit:this.state.hasDigit},this.pendingSinceMs=null,this.forceFlush=!1;return}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(isAsciiDigit(byte)){this.cursor+=1,this.state={tag:"csi_sgr_mouse",part:this.state.part,hasDigit:!0};continue}if(byte===59&&this.state.hasDigit&&this.state.part<2){this.cursor+=1,this.state={tag:"csi_sgr_mouse",part:this.state.part+1,hasDigit:!1};continue}if(byte>=64&&byte<=126){let end=this.cursor+1,rawBytes=bytes.subarray(this.unitStart,end);if(isMouseSgrSequence(rawBytes))this.emitMouse(rawBytes,"sgr");else this.emitKeyOrResponse("csi",decodeUtf8(rawBytes));this.state={tag:"ground"},this.consumePrefix(end);continue}this.state={tag:"csi"};continue}case"csi_sgr_mouse_deferred":{if(this.cursor>=bytes.length){this.pendingSinceMs=null,this.forceFlush=!1;return}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(isAsciiDigit(byte)||byte===59||byte===77||byte===109){this.state={tag:"csi_sgr_mouse",part:this.state.part,hasDigit:this.state.hasDigit};continue}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}case"csi_parametric":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}if(canDeferParametricCsi(this.state,this.protocolContext)){this.state={tag:"csi_parametric_deferred",semicolons:this.state.semicolons,segments:this.state.segments,hasDigit:this.state.hasDigit,firstParamValue:this.state.firstParamValue},this.pendingSinceMs=null,this.forceFlush=!1;return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(isAsciiDigit(byte)){this.cursor+=1,this.state={tag:"csi_parametric",semicolons:this.state.semicolons,segments:this.state.segments,hasDigit:!0,firstParamValue:this.state.firstParamValue};continue}if(byte===58&&this.state.hasDigit&&this.state.segments<3){this.cursor+=1,this.state={tag:"csi_parametric",semicolons:this.state.semicolons,segments:this.state.segments+1,hasDigit:!1,firstParamValue:this.state.firstParamValue};continue}if(byte===59&&this.state.semicolons<2){this.cursor+=1,this.state={tag:"csi_parametric",semicolons:this.state.semicolons+1,segments:1,hasDigit:!1,firstParamValue:this.state.firstParamValue};continue}if(byte>=64&&byte<=126){let end=this.cursor+1;this.emitKeyOrResponse("csi",decodeUtf8(bytes.subarray(this.unitStart,end))),this.state={tag:"ground"},this.consumePrefix(end);continue}this.state={tag:"csi"};continue}case"csi_parametric_deferred":{if(this.cursor>=bytes.length){this.pendingSinceMs=null,this.forceFlush=!1;return}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(isAsciiDigit(byte)||byte===58||byte===59){this.state={tag:"csi_parametric",semicolons:this.state.semicolons,segments:this.state.segments,hasDigit:this.state.hasDigit,firstParamValue:this.state.firstParamValue};continue}if(canCompleteDeferredParametricCsi(this.state,byte,this.protocolContext)){this.state={tag:"csi_parametric",semicolons:this.state.semicolons,segments:this.state.segments,hasDigit:this.state.hasDigit,firstParamValue:this.state.firstParamValue};continue}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}case"csi_private_reply":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}if(canDeferPrivateReplyCsi(this.protocolContext)){this.state={tag:"csi_private_reply_deferred",semicolons:this.state.semicolons,hasDigit:this.state.hasDigit,sawDollar:this.state.sawDollar},this.pendingSinceMs=null,this.forceFlush=!1;return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(isAsciiDigit(byte)){this.cursor+=1,this.state={tag:"csi_private_reply",semicolons:this.state.semicolons,hasDigit:!0,sawDollar:this.state.sawDollar};continue}if(byte===59){this.cursor+=1,this.state={tag:"csi_private_reply",semicolons:this.state.semicolons+1,hasDigit:!1,sawDollar:!1};continue}if(byte===36&&this.state.hasDigit&&!this.state.sawDollar){this.cursor+=1,this.state={tag:"csi_private_reply",semicolons:this.state.semicolons,hasDigit:!0,sawDollar:!0};continue}if(byte>=64&&byte<=126){let end=this.cursor+1;this.emitKeyOrResponse("csi",decodeUtf8(bytes.subarray(this.unitStart,end))),this.state={tag:"ground"},this.consumePrefix(end);continue}this.state={tag:"csi"};continue}case"csi_private_reply_deferred":{if(this.cursor>=bytes.length){this.pendingSinceMs=null,this.forceFlush=!1;return}if(byte===ESC){this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(isAsciiDigit(byte)||byte===59||byte===36){this.state={tag:"csi_private_reply",semicolons:this.state.semicolons,hasDigit:this.state.hasDigit,sawDollar:this.state.sawDollar};continue}if(canCompleteDeferredPrivateReplyCsi(this.state,byte,this.protocolContext)){this.state={tag:"csi_private_reply",semicolons:this.state.semicolons,hasDigit:this.state.hasDigit,sawDollar:this.state.sawDollar};continue}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}case"osc":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(this.state.sawEsc){if(byte===92){let end=this.cursor+1;this.emitOpaqueResponse("osc",bytes.subarray(this.unitStart,end)),this.state={tag:"ground"},this.consumePrefix(end);continue}this.state={tag:"osc",sawEsc:!1};continue}if(byte===BEL){let end=this.cursor+1;this.emitOpaqueResponse("osc",bytes.subarray(this.unitStart,end)),this.state={tag:"ground"},this.consumePrefix(end);continue}if(byte===ESC){this.cursor+=1,this.state={tag:"osc",sawEsc:!0};continue}this.cursor+=1;continue}case"dcs":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(this.state.sawEsc){if(byte===92){let end=this.cursor+1;this.emitOpaqueResponse("dcs",bytes.subarray(this.unitStart,end)),this.state={tag:"ground"},this.consumePrefix(end);continue}this.state={tag:"dcs",sawEsc:!1};continue}if(byte===ESC){this.cursor+=1,this.state={tag:"dcs",sawEsc:!0};continue}this.cursor+=1;continue}case"apc":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(this.state.sawEsc){if(byte===92){let end=this.cursor+1;this.emitOpaqueResponse("apc",bytes.subarray(this.unitStart,end)),this.state={tag:"ground"},this.consumePrefix(end);continue}this.state={tag:"apc",sawEsc:!1};continue}if(byte===ESC){this.cursor+=1,this.state={tag:"apc",sawEsc:!0};continue}this.cursor+=1;continue}case"esc_less_mouse":{if(this.cursor>=bytes.length){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}if(byte>=48&&byte<=57||byte===59){this.cursor+=1;continue}if(byte===77||byte===109){let end=this.cursor+1;this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,end)),this.state={tag:"ground"},this.consumePrefix(end);continue}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);continue}case"esc_less_x10_mouse":{let end=this.unitStart+5;if(bytes.length<end){if(!this.forceFlush){this.markPending();return}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,bytes.length)),this.state={tag:"ground"},this.consumePrefix(bytes.length);continue}this.emitOpaqueResponse("unknown",bytes.subarray(this.unitStart,end)),this.state={tag:"ground"},this.consumePrefix(end);continue}}}}emitKeyOrResponse(protocol,raw){let parsed=parseKeypress(raw,{useKittyKeyboard:this.useKittyKeyboard});if(parsed){this.events.push({type:"key",raw:parsed.raw,key:parsed});return}this.events.push({type:"response",protocol,sequence:raw})}emitMouse(rawBytes,encoding){let event=this.mouseParser.parseMouseEvent(rawBytes);if(!event){this.emitOpaqueResponse("unknown",rawBytes);return}this.events.push({type:"mouse",raw:decodeLatin1(rawBytes),encoding,event})}emitLegacyHighByte(byte){let parsed=parseKeypress(Buffer3.from([byte]),{useKittyKeyboard:this.useKittyKeyboard});if(parsed){this.events.push({type:"key",raw:parsed.raw,key:parsed});return}this.events.push({type:"response",protocol:"unknown",sequence:String.fromCharCode(byte)})}emitOpaqueResponse(protocol,rawBytes){this.events.push({type:"response",protocol,sequence:decodeLatin1(rawBytes)})}consumePrefix(endExclusive){this.pending.consume(endExclusive),this.cursor=0,this.unitStart=0,this.pendingSinceMs=null,this.forceFlush=!1}takePendingBytes(){let buffered=this.pending.take();return this.cursor=0,this.unitStart=0,this.pendingSinceMs=null,this.forceFlush=!1,buffered}flushPendingOverflow(){if(this.pending.length===0)return;this.emitOpaqueResponse("unknown",this.pending.view()),this.pending.clear(),this.cursor=0,this.unitStart=0,this.pendingSinceMs=null,this.forceFlush=!1,this.state={tag:"ground"}}markPending(){this.pendingSinceMs=this.clock.now()}consumePasteBytes(chunk){let paste=this.paste,combined=concatBytes(paste.tail,chunk),endIndex=indexOfBytes(combined,BRACKETED_PASTE_END);if(endIndex!==-1)return this.pushPasteBytes(combined.subarray(0,endIndex)),this.events.push({type:"paste",bytes:joinPasteBytes(paste.parts,paste.totalLength)}),this.paste=null,combined.subarray(endIndex+BRACKETED_PASTE_END.length);let keep=Math.min(BRACKETED_PASTE_END.length-1,combined.length),stableLength=combined.length-keep;if(stableLength>0)this.pushPasteBytes(combined.subarray(0,stableLength));return paste.tail=Uint8Array.from(combined.subarray(stableLength)),EMPTY_BYTES}pushPasteBytes(bytes){if(bytes.length===0)return;this.paste.parts.push(Uint8Array.from(bytes)),this.paste.totalLength+=bytes.length}reconcileDeferredStateWithProtocolContext(){switch(this.state.tag){case"csi_parametric_deferred":if(!canDeferParametricCsi(this.state,this.protocolContext))this.emitOpaqueResponse("unknown",this.pending.view().subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);return;case"csi_private_reply_deferred":if(!canDeferPrivateReplyCsi(this.protocolContext))this.emitOpaqueResponse("unknown",this.pending.view().subarray(this.unitStart,this.cursor)),this.state={tag:"ground"},this.consumePrefix(this.cursor);return}}reconcileTimeoutState(){if(!this.armTimeouts)return;if(this.paste||this.pendingSinceMs===null||this.pending.length===0){this.clearTimeout();return}this.clearTimeout(),this.timeoutId=this.clock.setTimeout(()=>{if(this.timeoutId=null,this.destroyed)return;try{this.flushTimeout(this.clock.now()),this.onTimeoutFlush?.()}catch(error2){console.error("stdin parser timeout flush failed",error2)}},this.timeoutMs)}clearTimeout(){if(!this.timeoutId)return;this.clock.clearTimeout(this.timeoutId),this.timeoutId=null}resetState(){this.pending.reset(INITIAL_PENDING_CAPACITY),this.events.length=0,this.pendingSinceMs=null,this.forceFlush=!1,this.justFlushedEsc=!1,this.state={tag:"ground"},this.cursor=0,this.unitStart=0,this.paste=null,this.mouseParser.reset()}}function getSpecificity(group){return group.split(".").length}function shouldSuppressInInjection(group,meta){if(meta?.isInjection)return!1;return group==="markup.raw.block"}function treeSitterToTextChunks(content,highlights,syntaxStyle,options){let chunks=[],defaultStyle=syntaxStyle.getStyle("default"),concealEnabled=options?.enabled??!0,injectionContainerRanges=[],boundaries=[];for(let i2=0;i2<highlights.length;i2++){let[start2,end,,meta]=highlights[i2];if(start2===end)continue;if(meta?.containsInjection)injectionContainerRanges.push({start:start2,end});boundaries.push({offset:start2,type:"start",highlightIndex:i2}),boundaries.push({offset:end,type:"end",highlightIndex:i2})}boundaries.sort((a,b2)=>{if(a.offset!==b2.offset)return a.offset-b2.offset;if(a.type==="end"&&b2.type==="start")return-1;if(a.type==="start"&&b2.type==="end")return 1;return 0});let activeHighlights=new Set,currentOffset=0;for(let i2=0;i2<boundaries.length;i2++){let boundary=boundaries[i2];if(currentOffset<boundary.offset&&activeHighlights.size>0){let segmentText=content.slice(currentOffset,boundary.offset),activeGroups=[];for(let idx of activeHighlights){let[,,group,meta]=highlights[idx];activeGroups.push({group,meta,index:idx})}let concealHighlight=concealEnabled?activeGroups.find((h)=>h.meta?.conceal!==void 0||h.group==="conceal"||h.group.startsWith("conceal.")):void 0;if(concealHighlight){let replacementText="";if(concealHighlight.meta?.conceal!==void 0)replacementText=concealHighlight.meta.conceal;else if(concealHighlight.group==="conceal.with.space")replacementText=" ";if(replacementText)chunks.push({__isChunk:!0,text:replacementText,fg:defaultStyle?.fg,bg:defaultStyle?.bg,attributes:defaultStyle?createTextAttributes({bold:defaultStyle.bold,italic:defaultStyle.italic,underline:defaultStyle.underline,dim:defaultStyle.dim}):0})}else{let insideInjectionContainer=injectionContainerRanges.some((range)=>currentOffset>=range.start&&currentOffset<range.end),sortedGroups=activeGroups.filter((h)=>{if(insideInjectionContainer&&shouldSuppressInInjection(h.group,h.meta))return!1;return!0}).sort((a,b2)=>{let aSpec=getSpecificity(a.group),bSpec=getSpecificity(b2.group);if(aSpec!==bSpec)return aSpec-bSpec;return a.index-b2.index}),mergedStyle={};for(let{group}of sortedGroups){let styleForGroup=syntaxStyle.getStyle(group);if(!styleForGroup&&group.includes(".")){let baseName=group.split(".")[0];styleForGroup=syntaxStyle.getStyle(baseName)}if(styleForGroup){if(styleForGroup.fg!==void 0)mergedStyle.fg=styleForGroup.fg;if(styleForGroup.bg!==void 0)mergedStyle.bg=styleForGroup.bg;if(styleForGroup.bold!==void 0)mergedStyle.bold=styleForGroup.bold;if(styleForGroup.italic!==void 0)mergedStyle.italic=styleForGroup.italic;if(styleForGroup.underline!==void 0)mergedStyle.underline=styleForGroup.underline;if(styleForGroup.dim!==void 0)mergedStyle.dim=styleForGroup.dim}else if(group.includes(".")){let baseName=group.split(".")[0];if(env.OTUI_TS_STYLE_WARN)console.warn(`Syntax style not found for group "${group}" or base scope "${baseName}", using default style`)}else if(env.OTUI_TS_STYLE_WARN)console.warn(`Syntax style not found for group "${group}", using default style`)}let finalStyle=Object.keys(mergedStyle).length>0?mergedStyle:defaultStyle;chunks.push({__isChunk:!0,text:segmentText,fg:finalStyle?.fg,bg:finalStyle?.bg,attributes:finalStyle?createTextAttributes({bold:finalStyle.bold,italic:finalStyle.italic,underline:finalStyle.underline,dim:finalStyle.dim}):0})}}else if(currentOffset<boundary.offset){let text=content.slice(currentOffset,boundary.offset);chunks.push({__isChunk:!0,text,fg:defaultStyle?.fg,bg:defaultStyle?.bg,attributes:defaultStyle?createTextAttributes({bold:defaultStyle.bold,italic:defaultStyle.italic,underline:defaultStyle.underline,dim:defaultStyle.dim}):0})}if(boundary.type==="start")activeHighlights.add(boundary.highlightIndex);else if(activeHighlights.delete(boundary.highlightIndex),concealEnabled){let[,,group,meta]=highlights[boundary.highlightIndex];if(meta?.concealLines!==void 0){if(boundary.offset<content.length&&content[boundary.offset]===`
2220
- `){currentOffset=boundary.offset+1;continue}}if(meta?.conceal!==void 0){if(meta.conceal===" "){if(boundary.offset<content.length&&content[boundary.offset]===" "){currentOffset=boundary.offset+1;continue}}else if(meta.conceal===""&&group==="conceal"&&!meta.isInjection){if(boundary.offset<content.length&&content[boundary.offset]===" "){currentOffset=boundary.offset+1;continue}}}}currentOffset=boundary.offset}if(currentOffset<content.length){let text=content.slice(currentOffset);chunks.push({__isChunk:!0,text,fg:defaultStyle?.fg,bg:defaultStyle?.bg,attributes:defaultStyle?createTextAttributes({bold:defaultStyle.bold,italic:defaultStyle.italic,underline:defaultStyle.underline,dim:defaultStyle.dim}):0})}return chunks}async function treeSitterToStyledText(content,filetype,syntaxStyle,client,options){let result2=await client.highlightOnce(content,filetype);if(result2.highlights&&result2.highlights.length>0){let chunks=treeSitterToTextChunks(content,result2.highlights,syntaxStyle,options?.conceal);return new StyledText(chunks)}else{let defaultStyle=syntaxStyle.mergeStyles("default"),chunks=[{__isChunk:!0,text:content,fg:defaultStyle.fg,bg:defaultStyle.bg,attributes:defaultStyle.attributes}];return new StyledText(chunks)}}class DebounceController{scopeId;constructor(scopeId){if(this.scopeId=scopeId,!TIMERS_MAP.has(this.scopeId))TIMERS_MAP.set(this.scopeId,new Map)}debounce(id,ms,fn){let scopeMap=TIMERS_MAP.get(this.scopeId);return new Promise((resolve13,reject)=>{if(scopeMap.has(id))clearTimeout(scopeMap.get(id));let timerId=setTimeout(()=>{try{resolve13(fn())}catch(error2){reject(error2)}scopeMap.delete(id)},ms);scopeMap.set(id,timerId)})}clearDebounce(id){let scopeMap=TIMERS_MAP.get(this.scopeId);if(scopeMap&&scopeMap.has(id))clearTimeout(scopeMap.get(id)),scopeMap.delete(id)}clear(){let scopeMap=TIMERS_MAP.get(this.scopeId);if(scopeMap)scopeMap.forEach((timerId)=>clearTimeout(timerId)),scopeMap.clear()}}function createDebounce(scopeId){return new DebounceController(scopeId)}function clearDebounceScope(scopeId){let scopeMap=TIMERS_MAP.get(scopeId);if(scopeMap)scopeMap.forEach((timerId)=>clearTimeout(timerId)),scopeMap.clear()}class ProcessQueue{processor;queue=[];processing=!1;autoProcess=!0;constructor(processor,autoProcess=!0){this.processor=processor,this.autoProcess=autoProcess}enqueue(item){if(this.queue.push(item),!this.processing&&this.autoProcess)this.processQueue()}processQueue(){if(this.queue.length===0)return;this.processing=!0,queueMicrotask(async()=>{if(this.queue.length===0){this.processing=!1;return}let item=this.queue.shift();try{await this.processor(item)}catch(error2){console.error("Error processing queue item:",error2)}if(this.queue.length>0)this.processQueue();else this.processing=!1})}clear(){this.queue=[]}isProcessing(){return this.processing}size(){return this.queue.length}}function getParsers(){if(!_cachedParsers)_cachedParsers=[{filetype:"javascript",aliases:["javascriptreact"],queries:{highlights:[resolve11(dirname12(fileURLToPath2(import.meta.url)),highlights_default)]},wasm:resolve11(dirname12(fileURLToPath2(import.meta.url)),tree_sitter_javascript_default)},{filetype:"typescript",aliases:["typescriptreact"],queries:{highlights:[resolve11(dirname12(fileURLToPath2(import.meta.url)),highlights_default2)]},wasm:resolve11(dirname12(fileURLToPath2(import.meta.url)),tree_sitter_typescript_default)},{filetype:"markdown",queries:{highlights:[resolve11(dirname12(fileURLToPath2(import.meta.url)),highlights_default3)],injections:[resolve11(dirname12(fileURLToPath2(import.meta.url)),injections_default)]},wasm:resolve11(dirname12(fileURLToPath2(import.meta.url)),tree_sitter_markdown_default),injectionMapping:{nodeTypes:{inline:"markdown_inline",pipe_table_cell:"markdown_inline"},infoStringMap:{javascript:"javascript",js:"javascript",jsx:"javascriptreact",javascriptreact:"javascriptreact",typescript:"typescript",ts:"typescript",tsx:"typescriptreact",typescriptreact:"typescriptreact",markdown:"markdown",md:"markdown"}}},{filetype:"markdown_inline",queries:{highlights:[resolve11(dirname12(fileURLToPath2(import.meta.url)),highlights_default4)]},wasm:resolve11(dirname12(fileURLToPath2(import.meta.url)),tree_sitter_markdown_inline_default)},{filetype:"zig",queries:{highlights:[resolve11(dirname12(fileURLToPath2(import.meta.url)),highlights_default5)]},wasm:resolve11(dirname12(fileURLToPath2(import.meta.url)),tree_sitter_zig_default)}];return _cachedParsers}function isBunfsPath(path6){return path6.includes("$bunfs")||/^B:[\\/]~BUN/i.test(path6)}function getBunfsRootPath(){return process.platform==="win32"?"B:\\~BUN\\root":"/$bunfs/root"}function normalizeBunfsPath(fileName){return join56(getBunfsRootPath(),basename10(fileName))}function addDefaultParsers(parsers2){for(let parser of parsers2)DEFAULT_PARSERS=[...DEFAULT_PARSERS.filter((existingParser)=>existingParser.filetype!==parser.filetype),parser]}function isValidDirectoryName(name){if(!name||typeof name!=="string")return!1;if(name.trim().length===0)return!1;if(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"].includes(name.toUpperCase()))return!1;if(/[<>:"|?*/\\\x00-\x1f]/.test(name))return!1;if(name.endsWith(".")||name.endsWith(" "))return!1;if(name==="."||name==="..")return!1;return!0}function getDataPaths(){return singleton("data-paths-opentui",()=>new DataPathsManager)}function normalizeFiletypeToken(value){return value.trim().replace(/^\./,"").toLowerCase()||void 0}function getBasename(value){let normalizedValue=value.trim().replaceAll("\\","/");if(!normalizedValue)return;return path22.posix.basename(normalizedValue).toLowerCase()||void 0}function extToFiletype(extension){let normalizedExtension=normalizeFiletypeToken(extension);if(!normalizedExtension)return;return extensionToFiletype.get(normalizedExtension)}function pathToFiletype(path33){if(typeof path33!=="string")return;let basename22=getBasename(path33);if(!basename22)return;let basenameFiletype=basenameToFiletype.get(basename22);if(basenameFiletype)return basenameFiletype;let lastDot=basename22.lastIndexOf(".");if(lastDot===-1||lastDot===basename22.length-1)return;let extension=basename22.substring(lastDot+1);return extToFiletype(extension)}function infoStringToFiletype(infoString){if(typeof infoString!=="string")return;let token=infoString.trim().split(/\s+/,1)[0],directBasenameMatch=basenameToFiletype.get(token.toLowerCase());if(directBasenameMatch)return directBasenameMatch;let normalizedToken=normalizeFiletypeToken(token);if(!normalizedToken)return;return basenameToFiletype.get(normalizedToken)??pathToFiletype(normalizedToken)??extToFiletype(normalizedToken)??normalizedToken}class DownloadUtils{static hashUrl(url){let hash=0;for(let i2=0;i2<url.length;i2++){let char=url.charCodeAt(i2);hash=(hash<<5)-hash+char,hash=hash&hash}return Math.abs(hash).toString(16)}static async downloadOrLoad(source,cacheDir,cacheSubdir,fileExtension,useHashForCache=!0,filetype){if(source.startsWith("http://")||source.startsWith("https://")){let cacheFileName;if(useHashForCache){let hash=this.hashUrl(source);cacheFileName=filetype?`${filetype}-${hash}${fileExtension}`:`${hash}${fileExtension}`}else cacheFileName=path32.basename(source);let cacheFile=path32.join(cacheDir,cacheSubdir,cacheFileName);await mkdir9(path32.dirname(cacheFile),{recursive:!0});try{let cachedContent=await readFile13(cacheFile);if(cachedContent.byteLength>0)return console.log(`Loaded from cache: ${cacheFile} (${source})`),{content:cachedContent,filePath:cacheFile}}catch(error2){}try{console.log(`Downloading from URL: ${source}`);let response=await fetch(source);if(!response.ok)return{error:`Failed to fetch from ${source}: ${response.statusText}`};let content=Buffer.from(await response.arrayBuffer());try{await writeFile6(cacheFile,Buffer.from(content)),console.log(`Cached: ${source}`)}catch(cacheError){console.warn(`Failed to cache: ${cacheError}`)}return{content,filePath:cacheFile}}catch(error2){return{error:`Error downloading from ${source}: ${error2}`}}}else try{return console.log(`Loading from local path: ${source}`),{content:await readFile13(source),filePath:source}}catch(error2){return{error:`Error loading from local path ${source}: ${error2}`}}}static async downloadToPath(source,targetPath){let isUrl2=source.startsWith("http://")||source.startsWith("https://");if(await mkdir9(path32.dirname(targetPath),{recursive:!0}),isUrl2)try{console.log(`Downloading from URL: ${source}`);let response=await fetch(source);if(!response.ok)return{error:`Failed to fetch from ${source}: ${response.statusText}`};let content=Buffer.from(await response.arrayBuffer());return await writeFile6(targetPath,Buffer.from(content)),console.log(`Downloaded: ${source} -> ${targetPath}`),{content,filePath:targetPath}}catch(error2){return{error:`Error downloading from ${source}: ${error2}`}}else try{console.log(`Copying from local path: ${source}`);let content=await readFile13(source);return await writeFile6(targetPath,Buffer.from(content)),{content,filePath:targetPath}}catch(error2){return{error:`Error copying from local path ${source}: ${error2}`}}}static async fetchHighlightQueries(sources,cacheDir,filetype){let queryPromises=sources.map((source)=>this.fetchHighlightQuery(source,cacheDir,filetype));return(await Promise.all(queryPromises)).filter((query2)=>query2.trim().length>0).join(`
2228
+ `){currentOffset=boundary.offset+1;continue}}if(meta?.conceal!==void 0){if(meta.conceal===" "){if(boundary.offset<content.length&&content[boundary.offset]===" "){currentOffset=boundary.offset+1;continue}}else if(meta.conceal===""&&group==="conceal"&&!meta.isInjection){if(boundary.offset<content.length&&content[boundary.offset]===" "){currentOffset=boundary.offset+1;continue}}}}currentOffset=boundary.offset}if(currentOffset<content.length){let text=content.slice(currentOffset);chunks.push({__isChunk:!0,text,fg:defaultStyle?.fg,bg:defaultStyle?.bg,attributes:defaultStyle?createTextAttributes({bold:defaultStyle.bold,italic:defaultStyle.italic,underline:defaultStyle.underline,dim:defaultStyle.dim}):0})}return chunks}async function treeSitterToStyledText(content,filetype,syntaxStyle,client,options){let result2=await client.highlightOnce(content,filetype);if(result2.highlights&&result2.highlights.length>0){let chunks=treeSitterToTextChunks(content,result2.highlights,syntaxStyle,options?.conceal);return new StyledText(chunks)}else{let defaultStyle=syntaxStyle.mergeStyles("default"),chunks=[{__isChunk:!0,text:content,fg:defaultStyle.fg,bg:defaultStyle.bg,attributes:defaultStyle.attributes}];return new StyledText(chunks)}}class DebounceController{scopeId;constructor(scopeId){if(this.scopeId=scopeId,!TIMERS_MAP.has(this.scopeId))TIMERS_MAP.set(this.scopeId,new Map)}debounce(id,ms,fn){let scopeMap=TIMERS_MAP.get(this.scopeId);return new Promise((resolve13,reject)=>{if(scopeMap.has(id))clearTimeout(scopeMap.get(id));let timerId=setTimeout(()=>{try{resolve13(fn())}catch(error2){reject(error2)}scopeMap.delete(id)},ms);scopeMap.set(id,timerId)})}clearDebounce(id){let scopeMap=TIMERS_MAP.get(this.scopeId);if(scopeMap&&scopeMap.has(id))clearTimeout(scopeMap.get(id)),scopeMap.delete(id)}clear(){let scopeMap=TIMERS_MAP.get(this.scopeId);if(scopeMap)scopeMap.forEach((timerId)=>clearTimeout(timerId)),scopeMap.clear()}}function createDebounce(scopeId){return new DebounceController(scopeId)}function clearDebounceScope(scopeId){let scopeMap=TIMERS_MAP.get(scopeId);if(scopeMap)scopeMap.forEach((timerId)=>clearTimeout(timerId)),scopeMap.clear()}class ProcessQueue{processor;queue=[];processing=!1;autoProcess=!0;constructor(processor,autoProcess=!0){this.processor=processor,this.autoProcess=autoProcess}enqueue(item){if(this.queue.push(item),!this.processing&&this.autoProcess)this.processQueue()}processQueue(){if(this.queue.length===0)return;this.processing=!0,queueMicrotask(async()=>{if(this.queue.length===0){this.processing=!1;return}let item=this.queue.shift();try{await this.processor(item)}catch(error2){console.error("Error processing queue item:",error2)}if(this.queue.length>0)this.processQueue();else this.processing=!1})}clear(){this.queue=[]}isProcessing(){return this.processing}size(){return this.queue.length}}function getParsers(){if(!_cachedParsers)_cachedParsers=[{filetype:"javascript",aliases:["javascriptreact"],queries:{highlights:[resolve11(dirname11(fileURLToPath2(import.meta.url)),highlights_default)]},wasm:resolve11(dirname11(fileURLToPath2(import.meta.url)),tree_sitter_javascript_default)},{filetype:"typescript",aliases:["typescriptreact"],queries:{highlights:[resolve11(dirname11(fileURLToPath2(import.meta.url)),highlights_default2)]},wasm:resolve11(dirname11(fileURLToPath2(import.meta.url)),tree_sitter_typescript_default)},{filetype:"markdown",queries:{highlights:[resolve11(dirname11(fileURLToPath2(import.meta.url)),highlights_default3)],injections:[resolve11(dirname11(fileURLToPath2(import.meta.url)),injections_default)]},wasm:resolve11(dirname11(fileURLToPath2(import.meta.url)),tree_sitter_markdown_default),injectionMapping:{nodeTypes:{inline:"markdown_inline",pipe_table_cell:"markdown_inline"},infoStringMap:{javascript:"javascript",js:"javascript",jsx:"javascriptreact",javascriptreact:"javascriptreact",typescript:"typescript",ts:"typescript",tsx:"typescriptreact",typescriptreact:"typescriptreact",markdown:"markdown",md:"markdown"}}},{filetype:"markdown_inline",queries:{highlights:[resolve11(dirname11(fileURLToPath2(import.meta.url)),highlights_default4)]},wasm:resolve11(dirname11(fileURLToPath2(import.meta.url)),tree_sitter_markdown_inline_default)},{filetype:"zig",queries:{highlights:[resolve11(dirname11(fileURLToPath2(import.meta.url)),highlights_default5)]},wasm:resolve11(dirname11(fileURLToPath2(import.meta.url)),tree_sitter_zig_default)}];return _cachedParsers}function isBunfsPath(path6){return path6.includes("$bunfs")||/^B:[\\/]~BUN/i.test(path6)}function getBunfsRootPath(){return process.platform==="win32"?"B:\\~BUN\\root":"/$bunfs/root"}function normalizeBunfsPath(fileName){return join56(getBunfsRootPath(),basename10(fileName))}function addDefaultParsers(parsers2){for(let parser of parsers2)DEFAULT_PARSERS=[...DEFAULT_PARSERS.filter((existingParser)=>existingParser.filetype!==parser.filetype),parser]}function isValidDirectoryName(name){if(!name||typeof name!=="string")return!1;if(name.trim().length===0)return!1;if(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"].includes(name.toUpperCase()))return!1;if(/[<>:"|?*/\\\x00-\x1f]/.test(name))return!1;if(name.endsWith(".")||name.endsWith(" "))return!1;if(name==="."||name==="..")return!1;return!0}function getDataPaths(){return singleton("data-paths-opentui",()=>new DataPathsManager)}function normalizeFiletypeToken(value){return value.trim().replace(/^\./,"").toLowerCase()||void 0}function getBasename(value){let normalizedValue=value.trim().replaceAll("\\","/");if(!normalizedValue)return;return path22.posix.basename(normalizedValue).toLowerCase()||void 0}function extToFiletype(extension){let normalizedExtension=normalizeFiletypeToken(extension);if(!normalizedExtension)return;return extensionToFiletype.get(normalizedExtension)}function pathToFiletype(path33){if(typeof path33!=="string")return;let basename22=getBasename(path33);if(!basename22)return;let basenameFiletype=basenameToFiletype.get(basename22);if(basenameFiletype)return basenameFiletype;let lastDot=basename22.lastIndexOf(".");if(lastDot===-1||lastDot===basename22.length-1)return;let extension=basename22.substring(lastDot+1);return extToFiletype(extension)}function infoStringToFiletype(infoString){if(typeof infoString!=="string")return;let token=infoString.trim().split(/\s+/,1)[0],directBasenameMatch=basenameToFiletype.get(token.toLowerCase());if(directBasenameMatch)return directBasenameMatch;let normalizedToken=normalizeFiletypeToken(token);if(!normalizedToken)return;return basenameToFiletype.get(normalizedToken)??pathToFiletype(normalizedToken)??extToFiletype(normalizedToken)??normalizedToken}class DownloadUtils{static hashUrl(url){let hash=0;for(let i2=0;i2<url.length;i2++){let char=url.charCodeAt(i2);hash=(hash<<5)-hash+char,hash=hash&hash}return Math.abs(hash).toString(16)}static async downloadOrLoad(source,cacheDir,cacheSubdir,fileExtension,useHashForCache=!0,filetype){if(source.startsWith("http://")||source.startsWith("https://")){let cacheFileName;if(useHashForCache){let hash=this.hashUrl(source);cacheFileName=filetype?`${filetype}-${hash}${fileExtension}`:`${hash}${fileExtension}`}else cacheFileName=path32.basename(source);let cacheFile=path32.join(cacheDir,cacheSubdir,cacheFileName);await mkdir9(path32.dirname(cacheFile),{recursive:!0});try{let cachedContent=await readFile13(cacheFile);if(cachedContent.byteLength>0)return console.log(`Loaded from cache: ${cacheFile} (${source})`),{content:cachedContent,filePath:cacheFile}}catch(error2){}try{console.log(`Downloading from URL: ${source}`);let response=await fetch(source);if(!response.ok)return{error:`Failed to fetch from ${source}: ${response.statusText}`};let content=Buffer.from(await response.arrayBuffer());try{await writeFile6(cacheFile,Buffer.from(content)),console.log(`Cached: ${source}`)}catch(cacheError){console.warn(`Failed to cache: ${cacheError}`)}return{content,filePath:cacheFile}}catch(error2){return{error:`Error downloading from ${source}: ${error2}`}}}else try{return console.log(`Loading from local path: ${source}`),{content:await readFile13(source),filePath:source}}catch(error2){return{error:`Error loading from local path ${source}: ${error2}`}}}static async downloadToPath(source,targetPath){let isUrl2=source.startsWith("http://")||source.startsWith("https://");if(await mkdir9(path32.dirname(targetPath),{recursive:!0}),isUrl2)try{console.log(`Downloading from URL: ${source}`);let response=await fetch(source);if(!response.ok)return{error:`Failed to fetch from ${source}: ${response.statusText}`};let content=Buffer.from(await response.arrayBuffer());return await writeFile6(targetPath,Buffer.from(content)),console.log(`Downloaded: ${source} -> ${targetPath}`),{content,filePath:targetPath}}catch(error2){return{error:`Error downloading from ${source}: ${error2}`}}else try{console.log(`Copying from local path: ${source}`);let content=await readFile13(source);return await writeFile6(targetPath,Buffer.from(content)),{content,filePath:targetPath}}catch(error2){return{error:`Error copying from local path ${source}: ${error2}`}}}static async fetchHighlightQueries(sources,cacheDir,filetype){let queryPromises=sources.map((source)=>this.fetchHighlightQuery(source,cacheDir,filetype));return(await Promise.all(queryPromises)).filter((query2)=>query2.trim().length>0).join(`
2221
2229
  `)}static async fetchHighlightQuery(source,cacheDir,filetype){let result2=await this.downloadOrLoad(source,cacheDir,"queries",".scm",!0,filetype);if(result2.error)return console.error(`Error fetching highlight query from ${source}:`,result2.error),"";if(result2.content)return new TextDecoder().decode(result2.content);return""}}function getDefaultOptions(){return{configPath:path4.resolve(__dirname2,"../parsers-config"),assetsDir:path4.resolve(__dirname2),outputPath:path4.resolve(__dirname2,"../default-parsers.ts")}}async function loadConfig2(configPath2){let ext=path4.extname(configPath2),resolvedConfigPath=configPath2;if(ext===""){let file=(await readdir7(path4.dirname(configPath2))).find((file2)=>file2.startsWith(path4.basename(configPath2))&&(file2.endsWith(".json")||file2.endsWith(".ts")||file2.endsWith(".js")));if(!file)throw Error(`No config file found for ${configPath2}`);resolvedConfigPath=path4.join(path4.dirname(configPath2),file),ext=path4.extname(resolvedConfigPath)}if(ext===".json"){let configContent=await readFile22(resolvedConfigPath,"utf-8");return JSON.parse(configContent)}else if(ext===".ts"||ext===".js"){let{default:configContent}=await import(resolvedConfigPath);return configContent}throw Error(`Unsupported config file extension: ${ext}`)}async function downloadLanguage(filetype,languageUrl,assetsDir,outputPath){let languageDir=path4.join(assetsDir,filetype),languageFilename=path4.basename(languageUrl),languagePath=path4.join(languageDir,languageFilename),result2=await DownloadUtils.downloadToPath(languageUrl,languagePath);if(result2.error)throw Error(`Failed to download language for ${filetype}: ${result2.error}`);return"./"+path4.relative(path4.dirname(outputPath),languagePath)}async function downloadAndCombineQueries(filetype,queryUrls,assetsDir,outputPath,queryType,configPath2){let queriesDir=path4.join(assetsDir,filetype),queryPath=path4.join(queriesDir,`${queryType}.scm`),queryContents=[];for(let i2=0;i2<queryUrls.length;i2++){let queryUrl=queryUrls[i2];if(queryUrl.startsWith("./")){console.log(` Using local query ${i2+1}/${queryUrls.length}: ${queryUrl}`);try{let localPath=path4.resolve(path4.dirname(configPath2),queryUrl),content=await readFile22(localPath,"utf-8");if(content.trim())queryContents.push(content),console.log(` \u2713 Loaded ${content.split(`
2222
2230
  `).length} lines from local file`)}catch(error2){console.warn(`Failed to read local query from ${queryUrl}: ${error2}`);continue}}else{console.log(` Downloading query ${i2+1}/${queryUrls.length}: ${queryUrl}`);try{let response=await fetch(queryUrl);if(!response.ok){console.warn(`Failed to download query from ${queryUrl}: ${response.statusText}`);continue}let content=await response.text();if(content.trim())queryContents.push(`; Query from: ${queryUrl}
2223
2231
  ${content}`),console.log(` \u2713 Downloaded ${content.split(`
@@ -2261,7 +2269,7 @@ ${parserDefinitions},
2261
2269
  `){lineEnd=i2+1;break}let deleteLength=lineEnd-lineStart;this.originalDeleteLine(),this.adjustExtmarksAfterDeletion(lineStart,deleteLength)}}wrapInsertion(){this.editBuffer.insertText=(text)=>{if(this.destroyed){this.originalInsertText(text);return}this.saveSnapshot();let currentOffset=this.editorView.getVisualCursor().offset;this.originalInsertText(text),this.adjustExtmarksAfterInsertion(currentOffset,text.length)},this.editBuffer.insertChar=(char)=>{if(this.destroyed){this.originalInsertChar(char);return}this.saveSnapshot();let currentOffset=this.editorView.getVisualCursor().offset;this.originalInsertChar(char),this.adjustExtmarksAfterInsertion(currentOffset,1)},this.editBuffer.setText=(text)=>{if(this.destroyed){this.originalSetText(text);return}this.clear(),this.originalSetText(text)},this.editBuffer.replaceText=(text)=>{if(this.destroyed){this.originalReplaceText(text);return}this.saveSnapshot(),this.clear(),this.originalReplaceText(text)},this.editBuffer.clear=()=>{if(this.destroyed){this.originalClear();return}this.saveSnapshot(),this.clear(),this.originalClear()},this.editBuffer.newLine=()=>{if(this.destroyed){this.originalNewLine();return}this.saveSnapshot();let currentOffset=this.editorView.getVisualCursor().offset;this.originalNewLine(),this.adjustExtmarksAfterInsertion(currentOffset,1)}}wrapEditorViewDeleteSelectedText(){this.editorView.deleteSelectedText=()=>{if(this.destroyed){this.originalEditorViewDeleteSelectedText();return}this.saveSnapshot();let selection=this.editorView.getSelection();if(!selection){this.originalEditorViewDeleteSelectedText();return}let deleteOffset=Math.min(selection.start,selection.end),deleteLength=Math.abs(selection.end-selection.start);if(this.originalEditorViewDeleteSelectedText(),deleteLength>0)this.adjustExtmarksAfterDeletion(deleteOffset,deleteLength)}}setupContentChangeListener(){this.editBuffer.on("content-changed",()=>{if(this.destroyed)return;this.updateHighlights()})}deleteExtmarkById(id){let extmark=this.extmarks.get(id);if(extmark)this.extmarks.delete(id),this.extmarksByTypeId.get(extmark.typeId)?.delete(id),this.metadata.delete(id)}findVirtualExtmarkContaining(offset){for(let extmark of this.extmarks.values())if(extmark.virtual&&offset>=extmark.start&&offset<extmark.end)return extmark;return null}adjustExtmarksAfterInsertion(insertOffset,length){for(let extmark of this.extmarks.values())if(extmark.start>=insertOffset)extmark.start+=length,extmark.end+=length;else if(extmark.end>insertOffset)extmark.end+=length;this.updateHighlights()}adjustExtmarksAfterDeletion(deleteOffset,length){let toDelete=[];for(let extmark of this.extmarks.values()){if(extmark.end<=deleteOffset)continue;if(extmark.start>=deleteOffset+length)extmark.start-=length,extmark.end-=length;else if(extmark.start>=deleteOffset&&extmark.end<=deleteOffset+length)toDelete.push(extmark.id);else if(extmark.start<deleteOffset&&extmark.end>deleteOffset+length)extmark.end-=length;else if(extmark.start<deleteOffset&&extmark.end>deleteOffset)extmark.end-=Math.min(extmark.end,deleteOffset+length)-deleteOffset;else if(extmark.start<deleteOffset+length&&extmark.end>deleteOffset+length){let overlap=deleteOffset+length-extmark.start;extmark.start=deleteOffset,extmark.end-=length}}for(let id of toDelete)this.deleteExtmarkById(id);this.updateHighlights()}offsetToPosition(offset){let result2=this.editBuffer.offsetToPosition(offset);if(!result2)return{row:0,col:0};return result2}positionToOffset(row,col){return this.editBuffer.positionToOffset(row,col)}updateHighlights(){this.editBuffer.clearAllHighlights();for(let extmark of this.extmarks.values())if(extmark.styleId!==void 0){let startWithoutNewlines=this.offsetExcludingNewlines(extmark.start),endWithoutNewlines=this.offsetExcludingNewlines(extmark.end);this.editBuffer.addHighlightByCharRange({start:startWithoutNewlines,end:endWithoutNewlines,styleId:extmark.styleId,priority:extmark.priority??0,hlRef:extmark.id})}}offsetExcludingNewlines(offset){let text=this.editBuffer.getText(),displayWidthSoFar=0,newlineCount=0,i2=0;while(i2<text.length&&displayWidthSoFar<offset)if(text[i2]===`
2262
2270
  `)displayWidthSoFar++,newlineCount++,i2++;else{let j=i2;while(j<text.length&&text[j]!==`
2263
2271
  `)j++;let chunk=text.substring(i2,j),chunkWidth=Bun.stringWidth(chunk);if(displayWidthSoFar+chunkWidth<offset)displayWidthSoFar+=chunkWidth,i2=j;else{for(let k=i2;k<j&&displayWidthSoFar<offset;k++){let charWidth=Bun.stringWidth(text[k]);displayWidthSoFar+=charWidth}break}}return offset-newlineCount}create(options){if(this.destroyed)throw Error("ExtmarksController is destroyed");let id=this.nextId++,typeId=options.typeId??0,extmark={id,start:options.start,end:options.end,virtual:options.virtual??!1,styleId:options.styleId,priority:options.priority,data:options.data,typeId};if(this.extmarks.set(id,extmark),!this.extmarksByTypeId.has(typeId))this.extmarksByTypeId.set(typeId,new Set);if(this.extmarksByTypeId.get(typeId).add(id),options.metadata!==void 0)this.metadata.set(id,options.metadata);return this.updateHighlights(),id}delete(id){if(this.destroyed)throw Error("ExtmarksController is destroyed");if(!this.extmarks.get(id))return!1;return this.deleteExtmarkById(id),this.updateHighlights(),!0}get(id){if(this.destroyed)return null;return this.extmarks.get(id)??null}getAll(){if(this.destroyed)return[];return Array.from(this.extmarks.values())}getVirtual(){if(this.destroyed)return[];return Array.from(this.extmarks.values()).filter((e)=>e.virtual)}getAtOffset(offset){if(this.destroyed)return[];return Array.from(this.extmarks.values()).filter((e)=>offset>=e.start&&offset<e.end)}getAllForTypeId(typeId){if(this.destroyed)return[];let ids=this.extmarksByTypeId.get(typeId);if(!ids)return[];return Array.from(ids).map((id)=>this.extmarks.get(id)).filter((e)=>e!==void 0)}clear(){if(this.destroyed)return;this.extmarks.clear(),this.extmarksByTypeId.clear(),this.metadata.clear(),this.updateHighlights()}saveSnapshot(){this.history.saveSnapshot(this.extmarks,this.nextId)}restoreSnapshot(snapshot){this.extmarks=new Map(Array.from(snapshot.extmarks.entries()).map(([id,extmark])=>[id,{...extmark}])),this.nextId=snapshot.nextId,this.updateHighlights()}wrapUndoRedo(){this.editBuffer.undo=()=>{if(this.destroyed)return this.originalUndo();if(!this.history.canUndo())return this.originalUndo();let currentSnapshot={extmarks:new Map(Array.from(this.extmarks.entries()).map(([id,extmark])=>[id,{...extmark}])),nextId:this.nextId};this.history.pushRedo(currentSnapshot);let snapshot=this.history.undo();return this.restoreSnapshot(snapshot),this.originalUndo()},this.editBuffer.redo=()=>{if(this.destroyed)return this.originalRedo();if(!this.history.canRedo())return this.originalRedo();let currentSnapshot={extmarks:new Map(Array.from(this.extmarks.entries()).map(([id,extmark])=>[id,{...extmark}])),nextId:this.nextId};this.history.pushUndo(currentSnapshot);let snapshot=this.history.redo();return this.restoreSnapshot(snapshot),this.originalRedo()}}registerType(typeName){if(this.destroyed)throw Error("ExtmarksController is destroyed");let existing=this.typeNameToId.get(typeName);if(existing!==void 0)return existing;let typeId=this.nextTypeId++;return this.typeNameToId.set(typeName,typeId),this.typeIdToName.set(typeId,typeName),typeId}getTypeId(typeName){if(this.destroyed)return null;return this.typeNameToId.get(typeName)??null}getTypeName(typeId){if(this.destroyed)return null;return this.typeIdToName.get(typeId)??null}getMetadataFor(extmarkId){if(this.destroyed)return;return this.metadata.get(extmarkId)}destroy(){if(this.destroyed)return;this.editBuffer.moveCursorLeft=this.originalMoveCursorLeft,this.editBuffer.moveCursorRight=this.originalMoveCursorRight,this.editBuffer.setCursorByOffset=this.originalSetCursorByOffset,this.editorView.moveUpVisual=this.originalMoveUpVisual,this.editorView.moveDownVisual=this.originalMoveDownVisual,this.editBuffer.deleteCharBackward=this.originalDeleteCharBackward,this.editBuffer.deleteChar=this.originalDeleteChar,this.editBuffer.insertText=this.originalInsertText,this.editBuffer.insertChar=this.originalInsertChar,this.editBuffer.deleteRange=this.originalDeleteRange,this.editBuffer.setText=this.originalSetText,this.editBuffer.replaceText=this.originalReplaceText,this.editBuffer.clear=this.originalClear,this.editBuffer.newLine=this.originalNewLine,this.editBuffer.deleteLine=this.originalDeleteLine,this.editorView.deleteSelectedText=this.originalEditorViewDeleteSelectedText,this.editBuffer.undo=this.originalUndo,this.editBuffer.redo=this.originalRedo,this.extmarks.clear(),this.extmarksByTypeId.clear(),this.metadata.clear(),this.typeNameToId.clear(),this.typeIdToName.clear(),this.history.clear(),this.destroyed=!0}}function createExtmarksController(editBuffer,editorView){return new ExtmarksController(editBuffer,editorView)}function scaleComponent(comp){let val=parseInt(comp,16),maxIn=(1<<4*comp.length)-1;return Math.round(val/maxIn*255).toString(16).padStart(2,"0")}function toHex(r,g,b2,hex6){if(hex6)return`#${hex6.toLowerCase()}`;if(r&&g&&b2)return`#${scaleComponent(r)}${scaleComponent(g)}${scaleComponent(b2)}`;return"#000000"}function wrapForTmux(osc){return`\x1BPtmux;${osc.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`}class TerminalPalette{stdin;stdout;writeFn;activeQuerySessions=[];inLegacyTmux;oscSource;clock;constructor(stdin,stdout,writeFn,isLegacyTmux,oscSource,clock){this.stdin=stdin,this.stdout=stdout,this.writeFn=writeFn||((data)=>stdout.write(data)),this.inLegacyTmux=isLegacyTmux??!1,this.oscSource=oscSource,this.clock=clock??SYSTEM_CLOCK2}writeOsc(osc){let data=this.inLegacyTmux?wrapForTmux(osc):osc;return this.writeFn(data)}cleanup(){for(let cleanupSession of[...this.activeQuerySessions])cleanupSession();this.activeQuerySessions=[]}subscribeInput(handler){if(this.oscSource)return this.oscSource.subscribeOsc((sequence)=>{handler(sequence)});return this.stdin.on("data",handler),()=>{this.stdin.removeListener("data",handler)}}createQuerySession(){let timers=new Set,subscriptions=new Set,closed=!1,cleanup=()=>{if(closed)return;closed=!0;for(let timer2 of timers)this.clock.clearTimeout(timer2);timers.clear();for(let unsubscribe of subscriptions)unsubscribe();subscriptions.clear();let idx=this.activeQuerySessions.indexOf(cleanup);if(idx!==-1)this.activeQuerySessions.splice(idx,1)};return this.activeQuerySessions.push(cleanup),{setTimer:(fn,ms)=>{let timer2=this.clock.setTimeout(fn,ms);return timers.add(timer2),timer2},resetTimer:(existing,fn,ms)=>{if(existing)this.clock.clearTimeout(existing),timers.delete(existing);let timer2=this.clock.setTimeout(fn,ms);return timers.add(timer2),timer2},subscribeInput:(handler)=>{let unsubscribe=this.subscribeInput(handler);return subscriptions.add(unsubscribe),()=>{if(!subscriptions.has(unsubscribe))return;subscriptions.delete(unsubscribe),unsubscribe()}},cleanup}}async detectOSCSupport(timeoutMs=300){if(!this.stdout.isTTY||!this.stdin.isTTY)return!1;return new Promise((resolve42)=>{let session=this.createQuerySession(),buffer2="",settled=!1,finish=(supported)=>{if(settled)return;settled=!0,session.cleanup(),resolve42(supported)},onData=(chunk)=>{if(buffer2+=chunk.toString(),OSC4_RESPONSE.lastIndex=0,OSC4_RESPONSE.test(buffer2))finish(!0)};session.setTimer(()=>{finish(!1)},timeoutMs),session.subscribeInput(onData),this.writeOsc("\x1B]4;0;?\x07")})}async queryPalette(indices,timeoutMs=1200){let out=this.stdout,results=new Map;if(indices.forEach((i2)=>results.set(i2,null)),!out.isTTY||!this.stdin.isTTY)return results;return new Promise((resolve42)=>{let session=this.createQuerySession(),buffer2="",idleTimer=null,settled=!1,finish=()=>{if(settled)return;settled=!0,session.cleanup(),resolve42(results)},onData=(chunk)=>{buffer2+=chunk.toString();let m;OSC4_RESPONSE.lastIndex=0;while(m=OSC4_RESPONSE.exec(buffer2)){let idx=parseInt(m[1],10);if(results.has(idx))results.set(idx,toHex(m[2],m[3],m[4],m[5]))}if(buffer2.length>8192)buffer2=buffer2.slice(-4096);if([...results.values()].filter((v)=>v!==null).length===results.size){finish();return}idleTimer=session.resetTimer(idleTimer,finish,150)};session.setTimer(finish,timeoutMs),session.subscribeInput(onData),this.writeOsc(indices.map((i2)=>`\x1B]4;${i2};?\x07`).join(""))})}async querySpecialColors(timeoutMs=1200){let out=this.stdout,results={10:null,11:null,12:null,13:null,14:null,15:null,16:null,17:null,19:null};if(!out.isTTY||!this.stdin.isTTY)return results;return new Promise((resolve42)=>{let session=this.createQuerySession(),buffer2="",idleTimer=null,settled=!1,finish=()=>{if(settled)return;settled=!0,session.cleanup(),resolve42(results)},onData=(chunk)=>{buffer2+=chunk.toString();let updated=!1,m;OSC_SPECIAL_RESPONSE.lastIndex=0;while(m=OSC_SPECIAL_RESPONSE.exec(buffer2)){let idx=parseInt(m[1],10);if(idx in results)results[idx]=toHex(m[2],m[3],m[4],m[5]),updated=!0}if(buffer2.length>8192)buffer2=buffer2.slice(-4096);if(Object.values(results).filter((v)=>v!==null).length===Object.keys(results).length){finish();return}if(!updated)return;idleTimer=session.resetTimer(idleTimer,finish,150)};session.setTimer(finish,timeoutMs),session.subscribeInput(onData),this.writeOsc(["\x1B]10;?\x07","\x1B]11;?\x07","\x1B]12;?\x07","\x1B]13;?\x07","\x1B]14;?\x07","\x1B]15;?\x07","\x1B]16;?\x07","\x1B]17;?\x07","\x1B]19;?\x07"].join(""))})}async detect(options){let{timeout=5000,size=16}=options||{};if(!await this.detectOSCSupport())return{palette:Array(size).fill(null),defaultForeground:null,defaultBackground:null,cursorColor:null,mouseForeground:null,mouseBackground:null,tekForeground:null,tekBackground:null,highlightBackground:null,highlightForeground:null};let indicesToQuery=[...Array(size).keys()],[paletteResults,specialColors]=await Promise.all([this.queryPalette(indicesToQuery,timeout),this.querySpecialColors(timeout)]);return{palette:[...Array(size).keys()].map((i2)=>paletteResults.get(i2)??null),defaultForeground:specialColors[10],defaultBackground:specialColors[11],cursorColor:specialColors[12],mouseForeground:specialColors[13],mouseBackground:specialColors[14],tekForeground:specialColors[15],tekBackground:specialColors[16],highlightBackground:specialColors[17],highlightForeground:specialColors[19]}}}function createTerminalPalette(stdin,stdout,writeFn,isLegacyTmux,oscSource,clock){return new TerminalPalette(stdin,stdout,writeFn,isLegacyTmux,oscSource,clock)}function decodePasteBytes(bytes){return PASTE_TEXT_DECODER.decode(bytes)}function stripAnsiSequences(text){return Bun.stripANSI(text)}function detectLinks(chunks,context){let{content,highlights}=context,ranges=[];for(let i2=0;i2<highlights.length;i2++){let[start2,end,group]=highlights[i2];if(!URL_SCOPES.includes(group))continue;let url=content.slice(start2,end);ranges.push({start:start2,end,url});for(let j=i2-1;j>=0;j--){let[labelStart,labelEnd,prev]=highlights[j];if(prev==="markup.link.label"){ranges.push({start:labelStart,end:labelEnd,url});break}if(!prev.startsWith("markup.link"))break}}if(ranges.length===0)return chunks;let contentPos=0;for(let chunk of chunks){if(chunk.text.length<=1)continue;let idx=content.indexOf(chunk.text,contentPos);if(idx<0)continue;for(let range of ranges)if(idx<range.end&&idx+chunk.text.length>range.start){chunk.link={url:range.url};break}contentPos=idx+chunk.text.length}return chunks}function packDrawOptions(border2,shouldFill,titleAlignment){let packed=0;if(border2===!0)packed|=15;else if(Array.isArray(border2)){if(border2.includes("top"))packed|=8;if(border2.includes("right"))packed|=4;if(border2.includes("bottom"))packed|=2;if(border2.includes("left"))packed|=1}if(shouldFill)packed|=16;let alignment={left:0,center:1,right:2}[titleAlignment];return packed|=alignment<<5,packed}class OptimizedBuffer{static fbIdCounter=0;id;lib;bufferPtr;_width;_height;_widthMethod;respectAlpha=!1;_rawBuffers=null;_destroyed=!1;get ptr(){return this.bufferPtr}guard(){if(this._destroyed)throw Error(`Buffer ${this.id} is destroyed`)}get buffers(){if(this.guard(),this._rawBuffers===null){let size=this._width*this._height,charPtr=this.lib.bufferGetCharPtr(this.bufferPtr),fgPtr=this.lib.bufferGetFgPtr(this.bufferPtr),bgPtr=this.lib.bufferGetBgPtr(this.bufferPtr),attributesPtr=this.lib.bufferGetAttributesPtr(this.bufferPtr);this._rawBuffers={char:new Uint32Array(toArrayBuffer(charPtr,0,size*4)),fg:new Float32Array(toArrayBuffer(fgPtr,0,size*4*4)),bg:new Float32Array(toArrayBuffer(bgPtr,0,size*4*4)),attributes:new Uint32Array(toArrayBuffer(attributesPtr,0,size*4))}}return this._rawBuffers}constructor(lib,ptr22,width,height2,options){this.id=options.id||`fb_${OptimizedBuffer.fbIdCounter++}`,this.lib=lib,this.respectAlpha=options.respectAlpha||!1,this._width=width,this._height=height2,this._widthMethod=options.widthMethod||"unicode",this.bufferPtr=ptr22}static create(width,height2,widthMethod,options={}){let lib=resolveRenderLib(),respectAlpha=options.respectAlpha||!1,id=options.id&&options.id.trim()!==""?options.id:"unnamed buffer";return lib.createOptimizedBuffer(width,height2,widthMethod,respectAlpha,id)}get widthMethod(){return this._widthMethod}get width(){return this._width}get height(){return this._height}setRespectAlpha(respectAlpha){this.guard(),this.lib.bufferSetRespectAlpha(this.bufferPtr,respectAlpha),this.respectAlpha=respectAlpha}getNativeId(){return this.guard(),this.lib.bufferGetId(this.bufferPtr)}getRealCharBytes(addLineBreaks=!1){this.guard();let realSize=this.lib.bufferGetRealCharSize(this.bufferPtr),outputBuffer=new Uint8Array(realSize),bytesWritten=this.lib.bufferWriteResolvedChars(this.bufferPtr,outputBuffer,addLineBreaks);return outputBuffer.slice(0,bytesWritten)}getSpanLines(){this.guard();let{char,fg:fg2,bg:bg2,attributes}=this.buffers,lines=[],CHAR_FLAG_CONTINUATION=-1073741824,CHAR_FLAG_MASK=-1073741824,realTextBytes=this.getRealCharBytes(!0),realTextLines=new TextDecoder().decode(realTextBytes).split(`
2264
- `);for(let y=0;y<this._height;y++){let spans=[],currentSpan=null,lineChars=[...realTextLines[y]||""],charIdx=0;for(let x=0;x<this._width;x++){let i2=y*this._width+x,cp3=char[i2],cellFg=RGBA.fromValues(fg2[i2*4],fg2[i2*4+1],fg2[i2*4+2],fg2[i2*4+3]),cellBg=RGBA.fromValues(bg2[i2*4],bg2[i2*4+1],bg2[i2*4+2],bg2[i2*4+3]),cellAttrs=attributes[i2]&255,cellChar=(cp3&CHAR_FLAG_MASK)===CHAR_FLAG_CONTINUATION?"":lineChars[charIdx++]??" ";if(currentSpan&&currentSpan.fg.equals(cellFg)&&currentSpan.bg.equals(cellBg)&&currentSpan.attributes===cellAttrs)currentSpan.text+=cellChar,currentSpan.width+=1;else{if(currentSpan)spans.push(currentSpan);currentSpan={text:cellChar,fg:cellFg,bg:cellBg,attributes:cellAttrs,width:1}}}if(currentSpan)spans.push(currentSpan);lines.push({spans})}return lines}clear(bg2=RGBA.fromValues(0,0,0,1)){this.guard(),this.lib.bufferClear(this.bufferPtr,bg2)}setCell(x,y,char,fg2,bg2,attributes=0){this.guard(),this.lib.bufferSetCell(this.bufferPtr,x,y,char,fg2,bg2,attributes)}setCellWithAlphaBlending(x,y,char,fg2,bg2,attributes=0){this.guard(),this.lib.bufferSetCellWithAlphaBlending(this.bufferPtr,x,y,char,fg2,bg2,attributes)}drawText(text,x,y,fg2,bg2,attributes=0,selection2){if(this.guard(),!selection2){this.lib.bufferDrawText(this.bufferPtr,text,x,y,fg2,bg2,attributes);return}let{start:start2,end}=selection2,selectionBg,selectionFg;if(selection2.bgColor)selectionBg=selection2.bgColor,selectionFg=selection2.fgColor||fg2;else{let defaultBg=bg2||RGBA.fromValues(0,0,0,0);selectionFg=defaultBg.a>0?defaultBg:RGBA.fromValues(0,0,0,1),selectionBg=fg2}if(start2>0){let beforeText=text.slice(0,start2);this.lib.bufferDrawText(this.bufferPtr,beforeText,x,y,fg2,bg2,attributes)}if(end>start2){let selectedText=text.slice(start2,end);this.lib.bufferDrawText(this.bufferPtr,selectedText,x+start2,y,selectionFg,selectionBg,attributes)}if(end<text.length){let afterText=text.slice(end);this.lib.bufferDrawText(this.bufferPtr,afterText,x+end,y,fg2,bg2,attributes)}}fillRect(x,y,width,height2,bg2){this.lib.bufferFillRect(this.bufferPtr,x,y,width,height2,bg2)}colorMatrix(matrix,cellMask,strength=1,target=3){if(this.guard(),matrix.length!==16)throw RangeError(`colorMatrix matrix must have length 16, got ${matrix.length}`);let cellMaskCount=Math.floor(cellMask.length/3);this.lib.bufferColorMatrix(this.bufferPtr,ptr(matrix),ptr(cellMask),cellMaskCount,strength,target)}colorMatrixUniform(matrix,strength=1,target=3){if(this.guard(),matrix.length!==16)throw RangeError(`colorMatrixUniform matrix must have length 16, got ${matrix.length}`);if(strength===0)return;this.lib.bufferColorMatrixUniform(this.bufferPtr,ptr(matrix),strength,target)}drawFrameBuffer(destX,destY,frameBuffer,sourceX,sourceY,sourceWidth,sourceHeight){this.guard(),this.lib.drawFrameBuffer(this.bufferPtr,destX,destY,frameBuffer.ptr,sourceX,sourceY,sourceWidth,sourceHeight)}destroy(){if(this._destroyed)return;this._destroyed=!0,this.lib.destroyOptimizedBuffer(this.bufferPtr)}drawTextBuffer(textBufferView,x,y){this.guard(),this.lib.bufferDrawTextBufferView(this.bufferPtr,textBufferView.ptr,x,y)}drawEditorView(editorView,x,y){this.guard(),this.lib.bufferDrawEditorView(this.bufferPtr,editorView.ptr,x,y)}drawSuperSampleBuffer(x,y,pixelDataPtr,pixelDataLength,format,alignedBytesPerRow){this.guard(),this.lib.bufferDrawSuperSampleBuffer(this.bufferPtr,x,y,pixelDataPtr,pixelDataLength,format,alignedBytesPerRow)}drawPackedBuffer(dataPtr,dataLen,posX,posY,terminalWidthCells,terminalHeightCells){this.guard(),this.lib.bufferDrawPackedBuffer(this.bufferPtr,dataPtr,dataLen,posX,posY,terminalWidthCells,terminalHeightCells)}drawGrayscaleBuffer(posX,posY,intensities,srcWidth,srcHeight,fg2=null,bg2=null){this.guard(),this.lib.bufferDrawGrayscaleBuffer(this.bufferPtr,posX,posY,ptr(intensities),srcWidth,srcHeight,fg2,bg2)}drawGrayscaleBufferSupersampled(posX,posY,intensities,srcWidth,srcHeight,fg2=null,bg2=null){this.guard(),this.lib.bufferDrawGrayscaleBufferSupersampled(this.bufferPtr,posX,posY,ptr(intensities),srcWidth,srcHeight,fg2,bg2)}resize(width,height2){if(this.guard(),this._width===width&&this._height===height2)return;this._width=width,this._height=height2,this._rawBuffers=null,this.lib.bufferResize(this.bufferPtr,width,height2)}drawBox(options){this.guard();let style=parseBorderStyle(options.borderStyle,"single"),borderChars=options.customBorderChars??BorderCharArrays[style],packedOptions=packDrawOptions(options.border,options.shouldFill??!1,options.titleAlignment||"left");this.lib.bufferDrawBox(this.bufferPtr,options.x,options.y,options.width,options.height,borderChars,packedOptions,options.borderColor,options.backgroundColor,options.title??null)}pushScissorRect(x,y,width,height2){this.guard(),this.lib.bufferPushScissorRect(this.bufferPtr,x,y,width,height2)}popScissorRect(){this.guard(),this.lib.bufferPopScissorRect(this.bufferPtr)}clearScissorRects(){this.guard(),this.lib.bufferClearScissorRects(this.bufferPtr)}pushOpacity(opacity){this.guard(),this.lib.bufferPushOpacity(this.bufferPtr,Math.max(0,Math.min(1,opacity)))}popOpacity(){this.guard(),this.lib.bufferPopOpacity(this.bufferPtr)}getCurrentOpacity(){return this.guard(),this.lib.bufferGetCurrentOpacity(this.bufferPtr)}clearOpacity(){this.guard(),this.lib.bufferClearOpacity(this.bufferPtr)}encodeUnicode(text){return this.guard(),this.lib.encodeUnicode(text,this._widthMethod)}freeUnicode(encoded){this.guard(),this.lib.freeUnicode(encoded)}drawGrid(options){this.guard();let columnCount=Math.max(0,options.columnOffsets.length-1),rowCount=Math.max(0,options.rowOffsets.length-1);this.lib.bufferDrawGrid(this.bufferPtr,options.borderChars,options.borderFg,options.borderBg,options.columnOffsets,columnCount,options.rowOffsets,rowCount,{drawInner:options.drawInner,drawOuter:options.drawOuter})}drawChar(char,x,y,fg2,bg2,attributes=0){this.guard(),this.lib.bufferDrawChar(this.bufferPtr,char,x,y,fg2,bg2,attributes)}}function fatalError(...args){let message=args.join(" ");throw console.error("FATAL ERROR:",message),Error(message)}function isPrimitiveType(type2){return typeof type2==="string"&&primitiveKeys.includes(type2)}function isObjectPointerDef(type2){return typeof type2==="object"&&type2!==null&&type2.__type==="objectPointer"}function alignOffset(offset,align){return offset+(align-1)&~(align-1)}function enumTypeError(value){throw TypeError(`Invalid enum value: ${value}`)}function defineEnum(mapping,base="u32"){let reverse2=Object.fromEntries(Object.entries(mapping).map(([k,v])=>[v,k]));return{__type:"enum",type:base,to(value){return typeof value==="number"?value:mapping[value]??enumTypeError(String(value))},from(value){return reverse2[value]??enumTypeError(String(value))},enum:mapping}}function isEnum(type2){return typeof type2==="object"&&type2.__type==="enum"}function isStruct(type2){return typeof type2==="object"&&type2.__type==="struct"}function primitivePackers(type2){let pack,unpack;switch(type2){case"u8":pack=(view,off,val)=>view.setUint8(off,val),unpack=(view,off)=>view.getUint8(off);break;case"bool_u8":pack=(view,off,val)=>view.setUint8(off,val?1:0),unpack=(view,off)=>Boolean(view.getUint8(off));break;case"bool_u32":pack=(view,off,val)=>view.setUint32(off,val?1:0,!0),unpack=(view,off)=>Boolean(view.getUint32(off,!0));break;case"u16":pack=(view,off,val)=>view.setUint16(off,val,!0),unpack=(view,off)=>view.getUint16(off,!0);break;case"i16":pack=(view,off,val)=>view.setInt16(off,val,!0),unpack=(view,off)=>view.getInt16(off,!0);break;case"u32":pack=(view,off,val)=>view.setUint32(off,val,!0),unpack=(view,off)=>view.getUint32(off,!0);break;case"i32":pack=(view,off,val)=>view.setInt32(off,val,!0),unpack=(view,off)=>view.getInt32(off,!0);break;case"u64":pack=(view,off,val)=>view.setBigUint64(off,BigInt(val),!0),unpack=(view,off)=>view.getBigUint64(off,!0);break;case"f32":pack=(view,off,val)=>view.setFloat32(off,val,!0),unpack=(view,off)=>view.getFloat32(off,!0);break;case"f64":pack=(view,off,val)=>view.setFloat64(off,val,!0),unpack=(view,off)=>view.getFloat64(off,!0);break;case"pointer":pack=(view,off,val)=>{pointerSize===8?view.setBigUint64(off,val?BigInt(val):0n,!0):view.setUint32(off,val?Number(val):0,!0)},unpack=(view,off)=>{let bint=pointerSize===8?view.getBigUint64(off,!0):BigInt(view.getUint32(off,!0));return Number(bint)};break;default:fatalError(`Unsupported primitive type: ${type2}`)}return{pack,unpack}}function packObjectArray(val){let buffer2=new ArrayBuffer(val.length*pointerSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++){let ptrValue=val[i2]?.ptr??null;pointerPacker(bufferView,i2*pointerSize,ptrValue)}return bufferView}function defineStruct(fields,structDefOptions){let offset=0,maxAlign=1,layout=[],lengthOfFields={},lengthOfRequested=[],arrayFieldsMetadata={};for(let[name,typeOrStruct,options={}]of fields){if(options.condition&&!options.condition())continue;let size=0,align=0,pack,unpack,needsLengthOf=!1,lengthOfDef=null;if(isPrimitiveType(typeOrStruct))size=typeSizes[typeOrStruct],align=typeAlignments[typeOrStruct],{pack,unpack}=primitivePackers(typeOrStruct);else if(typeof typeOrStruct==="string"&&typeOrStruct==="cstring")size=pointerSize,align=pointerSize,pack=(view,off,val)=>{let bufPtr=val?ptr2(encoder.encode(val+"\x00")):null;pointerPacker(view,off,bufPtr)},unpack=(view,off)=>{return pointerUnpacker(view,off)};else if(typeof typeOrStruct==="string"&&typeOrStruct==="char*")size=pointerSize,align=pointerSize,pack=(view,off,val)=>{let bufPtr=val?ptr2(encoder.encode(val)):null;pointerPacker(view,off,bufPtr)},unpack=(view,off)=>{return pointerUnpacker(view,off)},needsLengthOf=!0;else if(isEnum(typeOrStruct)){let base=typeOrStruct.type;size=typeSizes[base],align=typeAlignments[base];let{pack:packEnum}=primitivePackers(base);pack=(view,off,val)=>{let num=typeOrStruct.to(val);packEnum(view,off,num)},unpack=(view,off)=>{let raw=typeGetters[base](view,off);return typeOrStruct.from(raw)}}else if(isStruct(typeOrStruct))if(options.asPointer===!0)size=pointerSize,align=pointerSize,pack=(view,off,val,obj,options2)=>{if(!val){pointerPacker(view,off,null);return}let nestedBuf=typeOrStruct.pack(val,options2);pointerPacker(view,off,ptr2(nestedBuf))},unpack=(view,off)=>{throw Error("Not implemented yet")};else size=typeOrStruct.size,align=typeOrStruct.align,pack=(view,off,val,obj,options2)=>{let nestedBuf=typeOrStruct.pack(val,options2),nestedView=new Uint8Array(nestedBuf);new Uint8Array(view.buffer).set(nestedView,off)},unpack=(view,off)=>{let slice=view.buffer.slice(off,off+size);return typeOrStruct.unpack(slice)};else if(isObjectPointerDef(typeOrStruct))size=pointerSize,align=pointerSize,pack=(view,off,value)=>{let ptrValue=value?.ptr??null;if(ptrValue===void 0)console.warn(`Field '${name}' expected object with '.ptr' property, but got undefined pointer value from:`,value),pointerPacker(view,off,null);else pointerPacker(view,off,ptrValue)},unpack=(view,off)=>{return pointerUnpacker(view,off)};else if(Array.isArray(typeOrStruct)&&typeOrStruct.length===1&&typeOrStruct[0]!==void 0){let[def]=typeOrStruct;size=pointerSize,align=pointerSize;let arrayElementSize;if(isEnum(def))arrayElementSize=typeSizes[def.type],pack=(view,off,val,obj)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let buffer2=new ArrayBuffer(val.length*arrayElementSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++){let num=def.to(val[i2]);bufferView.setUint32(i2*arrayElementSize,num,!0)}pointerPacker(view,off,ptr2(buffer2))},unpack=null,needsLengthOf=!0,lengthOfDef=def;else if(isStruct(def))arrayElementSize=def.size,pack=(view,off,val,obj,options2)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let buffer2=new ArrayBuffer(val.length*arrayElementSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++)def.packInto(val[i2],bufferView,i2*arrayElementSize,options2);pointerPacker(view,off,ptr2(buffer2))},unpack=(view,off)=>{throw Error("Not implemented yet")};else if(isPrimitiveType(def)){arrayElementSize=typeSizes[def];let{pack:primitivePack}=primitivePackers(def);pack=(view,off,val)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let buffer2=new ArrayBuffer(val.length*arrayElementSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++)primitivePack(bufferView,i2*arrayElementSize,val[i2]);pointerPacker(view,off,ptr2(buffer2))},unpack=null,needsLengthOf=!0,lengthOfDef=def}else if(isObjectPointerDef(def))arrayElementSize=pointerSize,pack=(view,off,val)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let packedView=packObjectArray(val);pointerPacker(view,off,ptr2(packedView.buffer))},unpack=()=>{throw Error("not implemented yet")};else throw Error(`Unsupported array element type for ${name}: ${JSON.stringify(def)}`);let lengthOfField=Object.values(lengthOfFields).find((f)=>f.lengthOf===name);if(lengthOfField&&isPrimitiveType(lengthOfField.type)){let{pack:lengthPack}=primitivePackers(lengthOfField.type);arrayFieldsMetadata[name]={elementSize:arrayElementSize,arrayOffset:offset,lengthOffset:lengthOfField.offset,lengthPack}}}else throw Error(`Unsupported field type for ${name}: ${JSON.stringify(typeOrStruct)}`);if(offset=alignOffset(offset,align),options.unpackTransform){let originalUnpack=unpack;unpack=(view,off)=>options.unpackTransform(originalUnpack(view,off))}if(options.packTransform){let originalPack=pack;pack=(view,off,val,obj,packOptions)=>originalPack(view,off,options.packTransform(val),obj,packOptions)}if(options.optional){let originalPack=pack;if(isStruct(typeOrStruct)&&!options.asPointer)pack=(view,off,val,obj,packOptions)=>{if(val||options.mapOptionalInline)originalPack(view,off,val,obj,packOptions)};else pack=(view,off,val,obj,packOptions)=>originalPack(view,off,val??0,obj,packOptions)}if(options.lengthOf){let originalPack=pack;pack=(view,off,val,obj,packOptions)=>{let targetValue=obj[options.lengthOf],length=0;if(targetValue)if(typeof targetValue==="string")length=Buffer.byteLength(targetValue);else length=targetValue.length;return originalPack(view,off,length,obj,packOptions)}}let validateFunctions;if(options.validate)validateFunctions=Array.isArray(options.validate)?options.validate:[options.validate];let layoutField={name,offset,size,align,validate:validateFunctions,optional:!!options.optional||!!options.lengthOf||options.default!==void 0,default:options.default,pack,unpack,type:typeOrStruct,lengthOf:options.lengthOf};if(layout.push(layoutField),options.lengthOf)lengthOfFields[options.lengthOf]=layoutField;if(needsLengthOf){let def=typeof typeOrStruct==="string"&&typeOrStruct==="char*"?"char*":lengthOfDef;if(!def)fatalError(`Internal error: needsLengthOf=true but def is null for ${name}`);lengthOfRequested.push({requester:layoutField,def})}offset+=size,maxAlign=Math.max(maxAlign,align)}for(let{requester,def}of lengthOfRequested){let lengthOfField=lengthOfFields[requester.name];if(!lengthOfField){if(def==="char*")continue;throw Error(`lengthOf field not found for array field ${requester.name}`)}if(def==="char*")requester.unpack=(view,off)=>{let ptrAddress=pointerUnpacker(view,off),length=lengthOfField.unpack(view,lengthOfField.offset);if(ptrAddress===0)return null;let byteLength=typeof length==="bigint"?Number(length):length;if(byteLength===0)return"";let buffer2=toArrayBuffer2(ptrAddress,0,byteLength);return decoder.decode(buffer2)};else if(isPrimitiveType(def)){let elemSize=typeSizes[def],{unpack:primitiveUnpack}=primitivePackers(def);requester.unpack=(view,off)=>{let result2=[],length=lengthOfField.unpack(view,lengthOfField.offset),ptrAddress=pointerUnpacker(view,off);if(ptrAddress===0n&&length>0)throw Error(`Array field ${requester.name} has null pointer but length ${length}.`);if(ptrAddress===0n||length===0)return[];let buffer2=toArrayBuffer2(ptrAddress,0,length*elemSize),bufferView=new DataView(buffer2);for(let i2=0;i2<length;i2++)result2.push(primitiveUnpack(bufferView,i2*elemSize));return result2}}else{let elemSize=def.type==="u32"?4:8;requester.unpack=(view,off)=>{let result2=[],length=lengthOfField.unpack(view,lengthOfField.offset),ptrAddress=pointerUnpacker(view,off);if(ptrAddress===0n&&length>0)throw Error(`Array field ${requester.name} has null pointer but length ${length}.`);if(ptrAddress===0n||length===0)return[];let buffer2=toArrayBuffer2(ptrAddress,0,length*elemSize),bufferView=new DataView(buffer2);for(let i2=0;i2<length;i2++)result2.push(def.from(bufferView.getUint32(i2*elemSize,!0)));return result2}}}let totalSize=alignOffset(offset,maxAlign),description=layout.map((f)=>({name:f.name,offset:f.offset,size:f.size,align:f.align,optional:f.optional,type:f.type,lengthOf:f.lengthOf})),layoutByName=new Map(description.map((f)=>[f.name,f])),arrayFields=new Map(Object.entries(arrayFieldsMetadata));return{__type:"struct",size:totalSize,align:maxAlign,hasMapValue:!!structDefOptions?.mapValue,layoutByName,arrayFields,pack(obj,options){let buf=new ArrayBuffer(totalSize),view=new DataView(buf),mappedObj=obj;if(structDefOptions?.mapValue)mappedObj=structDefOptions.mapValue(obj);for(let field of layout){let value=mappedObj[field.name]??field.default;if(!field.optional&&value===void 0)fatalError(`Packing non-optional field '${field.name}' but value is undefined (and no default provided)`);if(field.validate)for(let validateFn of field.validate)validateFn(value,field.name,{hints:options?.validationHints,input:mappedObj});field.pack(view,field.offset,value,mappedObj,options)}return view.buffer},packInto(obj,view,offset2,options){let mappedObj=obj;if(structDefOptions?.mapValue)mappedObj=structDefOptions.mapValue(obj);for(let field of layout){let value=mappedObj[field.name]??field.default;if(!field.optional&&value===void 0)console.warn(`packInto missing value for non-optional field '${field.name}' at offset ${offset2+field.offset}. Writing default or zero.`);if(field.validate)for(let validateFn of field.validate)validateFn(value,field.name,{hints:options?.validationHints,input:mappedObj});field.pack(view,offset2+field.offset,value,mappedObj,options)}},unpack(buf){if(buf.byteLength<totalSize)fatalError(`Buffer size (${buf.byteLength}) is smaller than struct size (${totalSize}) for unpacking.`);let view=new DataView(buf),result2=structDefOptions?.default?{...structDefOptions.default}:{};for(let field of layout){if(!field.unpack)continue;try{result2[field.name]=field.unpack(view,field.offset)}catch(e){throw console.error(`Error unpacking field '${field.name}' at offset ${field.offset}:`,e),e}}if(structDefOptions?.reduceValue)return structDefOptions.reduceValue(result2);return result2},packList(objects,options){if(objects.length===0)return new ArrayBuffer(0);let buffer2=new ArrayBuffer(totalSize*objects.length),view=new DataView(buffer2);for(let i2=0;i2<objects.length;i2++){let mappedObj=objects[i2];if(structDefOptions?.mapValue)mappedObj=structDefOptions.mapValue(objects[i2]);for(let field of layout){let value=mappedObj[field.name]??field.default;if(!field.optional&&value===void 0)fatalError(`Packing non-optional field '${field.name}' at index ${i2} but value is undefined (and no default provided)`);if(field.validate)for(let validateFn of field.validate)validateFn(value,field.name,{hints:options?.validationHints,input:mappedObj});field.pack(view,i2*totalSize+field.offset,value,mappedObj,options)}}return buffer2},unpackList(buf,count){if(count===0)return[];let expectedSize=totalSize*count;if(buf.byteLength<expectedSize)fatalError(`Buffer size (${buf.byteLength}) is smaller than expected size (${expectedSize}) for unpacking ${count} structs.`);let view=new DataView(buf),results=[];for(let i2=0;i2<count;i2++){let offset2=i2*totalSize,result2=structDefOptions?.default?{...structDefOptions.default}:{};for(let field of layout){if(!field.unpack)continue;try{result2[field.name]=field.unpack(view,offset2+field.offset)}catch(e){throw console.error(`Error unpacking field '${field.name}' at index ${i2}, offset ${offset2+field.offset}:`,e),e}}if(structDefOptions?.reduceValue)results.push(structDefOptions.reduceValue(result2));else results.push(result2)}return results},describe(){return description}}}function toPointer(value){if(typeof value==="bigint"){if(value>BigInt(Number.MAX_SAFE_INTEGER))throw Error("Pointer exceeds safe integer range");return Number(value)}return value}function toNumber(value){return typeof value==="bigint"?Number(value):value}function getOpenTUILib(libPath){let rawSymbols=dlopen(libPath||targetLibPath,{setLogCallback:{args:["ptr"],returns:"void"},setEventCallback:{args:["ptr"],returns:"void"},createRenderer:{args:["u32","u32","bool","bool"],returns:"ptr"},setTerminalEnvVar:{args:["ptr","ptr","usize","ptr","usize"],returns:"bool"},destroyRenderer:{args:["ptr"],returns:"void"},setUseThread:{args:["ptr","bool"],returns:"void"},setBackgroundColor:{args:["ptr","ptr"],returns:"void"},setRenderOffset:{args:["ptr","u32"],returns:"void"},updateStats:{args:["ptr","f64","u32","f64"],returns:"void"},updateMemoryStats:{args:["ptr","u32","u32","u32"],returns:"void"},render:{args:["ptr","bool"],returns:"void"},getNextBuffer:{args:["ptr"],returns:"ptr"},getCurrentBuffer:{args:["ptr"],returns:"ptr"},queryPixelResolution:{args:["ptr"],returns:"void"},createOptimizedBuffer:{args:["u32","u32","bool","u8","ptr","usize"],returns:"ptr"},destroyOptimizedBuffer:{args:["ptr"],returns:"void"},drawFrameBuffer:{args:["ptr","i32","i32","ptr","u32","u32","u32","u32"],returns:"void"},getBufferWidth:{args:["ptr"],returns:"u32"},getBufferHeight:{args:["ptr"],returns:"u32"},bufferClear:{args:["ptr","ptr"],returns:"void"},bufferGetCharPtr:{args:["ptr"],returns:"ptr"},bufferGetFgPtr:{args:["ptr"],returns:"ptr"},bufferGetBgPtr:{args:["ptr"],returns:"ptr"},bufferGetAttributesPtr:{args:["ptr"],returns:"ptr"},bufferGetRespectAlpha:{args:["ptr"],returns:"bool"},bufferSetRespectAlpha:{args:["ptr","bool"],returns:"void"},bufferGetId:{args:["ptr","ptr","usize"],returns:"usize"},bufferGetRealCharSize:{args:["ptr"],returns:"u32"},bufferWriteResolvedChars:{args:["ptr","ptr","usize","bool"],returns:"u32"},bufferDrawText:{args:["ptr","ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},bufferSetCellWithAlphaBlending:{args:["ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},bufferSetCell:{args:["ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},bufferFillRect:{args:["ptr","u32","u32","u32","u32","ptr"],returns:"void"},bufferColorMatrix:{args:["ptr","ptr","ptr","usize","f32","u8"],returns:"void"},bufferColorMatrixUniform:{args:["ptr","ptr","f32","u8"],returns:"void"},bufferResize:{args:["ptr","u32","u32"],returns:"void"},linkAlloc:{args:["ptr","u32"],returns:"u32"},linkGetUrl:{args:["u32","ptr","u32"],returns:"u32"},attributesWithLink:{args:["u32","u32"],returns:"u32"},attributesGetLinkId:{args:["u32"],returns:"u32"},resizeRenderer:{args:["ptr","u32","u32"],returns:"void"},setCursorPosition:{args:["ptr","i32","i32","bool"],returns:"void"},setCursorColor:{args:["ptr","ptr"],returns:"void"},getCursorState:{args:["ptr","ptr"],returns:"void"},setCursorStyleOptions:{args:["ptr","ptr"],returns:"void"},setDebugOverlay:{args:["ptr","bool","u8"],returns:"void"},clearTerminal:{args:["ptr"],returns:"void"},setTerminalTitle:{args:["ptr","ptr","usize"],returns:"void"},copyToClipboardOSC52:{args:["ptr","u8","ptr","usize"],returns:"bool"},clearClipboardOSC52:{args:["ptr","u8"],returns:"bool"},bufferDrawSuperSampleBuffer:{args:["ptr","u32","u32","ptr","usize","u8","u32"],returns:"void"},bufferDrawPackedBuffer:{args:["ptr","ptr","usize","u32","u32","u32","u32"],returns:"void"},bufferDrawGrayscaleBuffer:{args:["ptr","i32","i32","ptr","u32","u32","ptr","ptr"],returns:"void"},bufferDrawGrayscaleBufferSupersampled:{args:["ptr","i32","i32","ptr","u32","u32","ptr","ptr"],returns:"void"},bufferDrawGrid:{args:["ptr","ptr","ptr","ptr","ptr","u32","ptr","u32","ptr"],returns:"void"},bufferDrawBox:{args:["ptr","i32","i32","u32","u32","ptr","u32","ptr","ptr","ptr","u32"],returns:"void"},bufferPushScissorRect:{args:["ptr","i32","i32","u32","u32"],returns:"void"},bufferPopScissorRect:{args:["ptr"],returns:"void"},bufferClearScissorRects:{args:["ptr"],returns:"void"},bufferPushOpacity:{args:["ptr","f32"],returns:"void"},bufferPopOpacity:{args:["ptr"],returns:"void"},bufferGetCurrentOpacity:{args:["ptr"],returns:"f32"},bufferClearOpacity:{args:["ptr"],returns:"void"},addToHitGrid:{args:["ptr","i32","i32","u32","u32","u32"],returns:"void"},clearCurrentHitGrid:{args:["ptr"],returns:"void"},hitGridPushScissorRect:{args:["ptr","i32","i32","u32","u32"],returns:"void"},hitGridPopScissorRect:{args:["ptr"],returns:"void"},hitGridClearScissorRects:{args:["ptr"],returns:"void"},addToCurrentHitGridClipped:{args:["ptr","i32","i32","u32","u32","u32"],returns:"void"},checkHit:{args:["ptr","u32","u32"],returns:"u32"},getHitGridDirty:{args:["ptr"],returns:"bool"},dumpHitGrid:{args:["ptr"],returns:"void"},dumpBuffers:{args:["ptr","i64"],returns:"void"},dumpStdoutBuffer:{args:["ptr","i64"],returns:"void"},restoreTerminalModes:{args:["ptr"],returns:"void"},enableMouse:{args:["ptr","bool"],returns:"void"},disableMouse:{args:["ptr"],returns:"void"},enableKittyKeyboard:{args:["ptr","u8"],returns:"void"},disableKittyKeyboard:{args:["ptr"],returns:"void"},setKittyKeyboardFlags:{args:["ptr","u8"],returns:"void"},getKittyKeyboardFlags:{args:["ptr"],returns:"u8"},setupTerminal:{args:["ptr","bool"],returns:"void"},suspendRenderer:{args:["ptr"],returns:"void"},resumeRenderer:{args:["ptr"],returns:"void"},writeOut:{args:["ptr","ptr","u64"],returns:"void"},createTextBuffer:{args:["u8"],returns:"ptr"},destroyTextBuffer:{args:["ptr"],returns:"void"},textBufferGetLength:{args:["ptr"],returns:"u32"},textBufferGetByteSize:{args:["ptr"],returns:"u32"},textBufferReset:{args:["ptr"],returns:"void"},textBufferClear:{args:["ptr"],returns:"void"},textBufferSetDefaultFg:{args:["ptr","ptr"],returns:"void"},textBufferSetDefaultBg:{args:["ptr","ptr"],returns:"void"},textBufferSetDefaultAttributes:{args:["ptr","ptr"],returns:"void"},textBufferResetDefaults:{args:["ptr"],returns:"void"},textBufferGetTabWidth:{args:["ptr"],returns:"u8"},textBufferSetTabWidth:{args:["ptr","u8"],returns:"void"},textBufferRegisterMemBuffer:{args:["ptr","ptr","usize","bool"],returns:"u16"},textBufferReplaceMemBuffer:{args:["ptr","u8","ptr","usize","bool"],returns:"bool"},textBufferClearMemRegistry:{args:["ptr"],returns:"void"},textBufferSetTextFromMem:{args:["ptr","u8"],returns:"void"},textBufferAppend:{args:["ptr","ptr","usize"],returns:"void"},textBufferAppendFromMemId:{args:["ptr","u8"],returns:"void"},textBufferLoadFile:{args:["ptr","ptr","usize"],returns:"bool"},textBufferSetStyledText:{args:["ptr","ptr","usize"],returns:"void"},textBufferGetLineCount:{args:["ptr"],returns:"u32"},textBufferGetPlainText:{args:["ptr","ptr","usize"],returns:"usize"},textBufferAddHighlightByCharRange:{args:["ptr","ptr"],returns:"void"},textBufferAddHighlight:{args:["ptr","u32","ptr"],returns:"void"},textBufferRemoveHighlightsByRef:{args:["ptr","u16"],returns:"void"},textBufferClearLineHighlights:{args:["ptr","u32"],returns:"void"},textBufferClearAllHighlights:{args:["ptr"],returns:"void"},textBufferSetSyntaxStyle:{args:["ptr","ptr"],returns:"void"},textBufferGetLineHighlightsPtr:{args:["ptr","u32","ptr"],returns:"ptr"},textBufferFreeLineHighlights:{args:["ptr","usize"],returns:"void"},textBufferGetHighlightCount:{args:["ptr"],returns:"u32"},textBufferGetTextRange:{args:["ptr","u32","u32","ptr","usize"],returns:"usize"},textBufferGetTextRangeByCoords:{args:["ptr","u32","u32","u32","u32","ptr","usize"],returns:"usize"},createTextBufferView:{args:["ptr"],returns:"ptr"},destroyTextBufferView:{args:["ptr"],returns:"void"},textBufferViewSetSelection:{args:["ptr","u32","u32","ptr","ptr"],returns:"void"},textBufferViewResetSelection:{args:["ptr"],returns:"void"},textBufferViewGetSelectionInfo:{args:["ptr"],returns:"u64"},textBufferViewSetLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr"],returns:"bool"},textBufferViewUpdateSelection:{args:["ptr","u32","ptr","ptr"],returns:"void"},textBufferViewUpdateLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr"],returns:"bool"},textBufferViewResetLocalSelection:{args:["ptr"],returns:"void"},textBufferViewSetWrapWidth:{args:["ptr","u32"],returns:"void"},textBufferViewSetWrapMode:{args:["ptr","u8"],returns:"void"},textBufferViewSetViewportSize:{args:["ptr","u32","u32"],returns:"void"},textBufferViewSetViewport:{args:["ptr","u32","u32","u32","u32"],returns:"void"},textBufferViewGetVirtualLineCount:{args:["ptr"],returns:"u32"},textBufferViewGetLineInfoDirect:{args:["ptr","ptr"],returns:"void"},textBufferViewGetLogicalLineInfoDirect:{args:["ptr","ptr"],returns:"void"},textBufferViewGetSelectedText:{args:["ptr","ptr","usize"],returns:"usize"},textBufferViewGetPlainText:{args:["ptr","ptr","usize"],returns:"usize"},textBufferViewSetTabIndicator:{args:["ptr","u32"],returns:"void"},textBufferViewSetTabIndicatorColor:{args:["ptr","ptr"],returns:"void"},textBufferViewSetTruncate:{args:["ptr","bool"],returns:"void"},textBufferViewMeasureForDimensions:{args:["ptr","u32","u32","ptr"],returns:"bool"},bufferDrawTextBufferView:{args:["ptr","ptr","i32","i32"],returns:"void"},bufferDrawEditorView:{args:["ptr","ptr","i32","i32"],returns:"void"},createEditorView:{args:["ptr","u32","u32"],returns:"ptr"},destroyEditorView:{args:["ptr"],returns:"void"},editorViewSetViewportSize:{args:["ptr","u32","u32"],returns:"void"},editorViewSetViewport:{args:["ptr","u32","u32","u32","u32","bool"],returns:"void"},editorViewGetViewport:{args:["ptr","ptr","ptr","ptr","ptr"],returns:"void"},editorViewSetScrollMargin:{args:["ptr","f32"],returns:"void"},editorViewSetWrapMode:{args:["ptr","u8"],returns:"void"},editorViewGetVirtualLineCount:{args:["ptr"],returns:"u32"},editorViewGetTotalVirtualLineCount:{args:["ptr"],returns:"u32"},editorViewGetTextBufferView:{args:["ptr"],returns:"ptr"},editorViewGetLineInfoDirect:{args:["ptr","ptr"],returns:"void"},editorViewGetLogicalLineInfoDirect:{args:["ptr","ptr"],returns:"void"},createEditBuffer:{args:["u8"],returns:"ptr"},destroyEditBuffer:{args:["ptr"],returns:"void"},editBufferSetText:{args:["ptr","ptr","usize"],returns:"void"},editBufferSetTextFromMem:{args:["ptr","u8"],returns:"void"},editBufferReplaceText:{args:["ptr","ptr","usize"],returns:"void"},editBufferReplaceTextFromMem:{args:["ptr","u8"],returns:"void"},editBufferGetText:{args:["ptr","ptr","usize"],returns:"usize"},editBufferInsertChar:{args:["ptr","ptr","usize"],returns:"void"},editBufferInsertText:{args:["ptr","ptr","usize"],returns:"void"},editBufferDeleteChar:{args:["ptr"],returns:"void"},editBufferDeleteCharBackward:{args:["ptr"],returns:"void"},editBufferDeleteRange:{args:["ptr","u32","u32","u32","u32"],returns:"void"},editBufferNewLine:{args:["ptr"],returns:"void"},editBufferDeleteLine:{args:["ptr"],returns:"void"},editBufferMoveCursorLeft:{args:["ptr"],returns:"void"},editBufferMoveCursorRight:{args:["ptr"],returns:"void"},editBufferMoveCursorUp:{args:["ptr"],returns:"void"},editBufferMoveCursorDown:{args:["ptr"],returns:"void"},editBufferGotoLine:{args:["ptr","u32"],returns:"void"},editBufferSetCursor:{args:["ptr","u32","u32"],returns:"void"},editBufferSetCursorToLineCol:{args:["ptr","u32","u32"],returns:"void"},editBufferSetCursorByOffset:{args:["ptr","u32"],returns:"void"},editBufferGetCursorPosition:{args:["ptr","ptr"],returns:"void"},editBufferGetId:{args:["ptr"],returns:"u16"},editBufferGetTextBuffer:{args:["ptr"],returns:"ptr"},editBufferDebugLogRope:{args:["ptr"],returns:"void"},editBufferUndo:{args:["ptr","ptr","usize"],returns:"usize"},editBufferRedo:{args:["ptr","ptr","usize"],returns:"usize"},editBufferCanUndo:{args:["ptr"],returns:"bool"},editBufferCanRedo:{args:["ptr"],returns:"bool"},editBufferClearHistory:{args:["ptr"],returns:"void"},editBufferClear:{args:["ptr"],returns:"void"},editBufferGetNextWordBoundary:{args:["ptr","ptr"],returns:"void"},editBufferGetPrevWordBoundary:{args:["ptr","ptr"],returns:"void"},editBufferGetEOL:{args:["ptr","ptr"],returns:"void"},editBufferOffsetToPosition:{args:["ptr","u32","ptr"],returns:"bool"},editBufferPositionToOffset:{args:["ptr","u32","u32"],returns:"u32"},editBufferGetLineStartOffset:{args:["ptr","u32"],returns:"u32"},editBufferGetTextRange:{args:["ptr","u32","u32","ptr","usize"],returns:"usize"},editBufferGetTextRangeByCoords:{args:["ptr","u32","u32","u32","u32","ptr","usize"],returns:"usize"},editorViewSetSelection:{args:["ptr","u32","u32","ptr","ptr"],returns:"void"},editorViewResetSelection:{args:["ptr"],returns:"void"},editorViewGetSelection:{args:["ptr"],returns:"u64"},editorViewSetLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr","bool","bool"],returns:"bool"},editorViewUpdateSelection:{args:["ptr","u32","ptr","ptr"],returns:"void"},editorViewUpdateLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr","bool","bool"],returns:"bool"},editorViewResetLocalSelection:{args:["ptr"],returns:"void"},editorViewGetSelectedTextBytes:{args:["ptr","ptr","usize"],returns:"usize"},editorViewGetCursor:{args:["ptr","ptr","ptr"],returns:"void"},editorViewGetText:{args:["ptr","ptr","usize"],returns:"usize"},editorViewGetVisualCursor:{args:["ptr","ptr"],returns:"void"},editorViewMoveUpVisual:{args:["ptr"],returns:"void"},editorViewMoveDownVisual:{args:["ptr"],returns:"void"},editorViewDeleteSelectedText:{args:["ptr"],returns:"void"},editorViewSetCursorByOffset:{args:["ptr","u32"],returns:"void"},editorViewGetNextWordBoundary:{args:["ptr","ptr"],returns:"void"},editorViewGetPrevWordBoundary:{args:["ptr","ptr"],returns:"void"},editorViewGetEOL:{args:["ptr","ptr"],returns:"void"},editorViewGetVisualSOL:{args:["ptr","ptr"],returns:"void"},editorViewGetVisualEOL:{args:["ptr","ptr"],returns:"void"},editorViewSetPlaceholderStyledText:{args:["ptr","ptr","usize"],returns:"void"},editorViewSetTabIndicator:{args:["ptr","u32"],returns:"void"},editorViewSetTabIndicatorColor:{args:["ptr","ptr"],returns:"void"},getArenaAllocatedBytes:{args:[],returns:"usize"},getBuildOptions:{args:["ptr"],returns:"void"},getAllocatorStats:{args:["ptr"],returns:"void"},createSyntaxStyle:{args:[],returns:"ptr"},destroySyntaxStyle:{args:["ptr"],returns:"void"},syntaxStyleRegister:{args:["ptr","ptr","usize","ptr","ptr","u8"],returns:"u32"},syntaxStyleResolveByName:{args:["ptr","ptr","usize"],returns:"u32"},syntaxStyleGetStyleCount:{args:["ptr"],returns:"usize"},getTerminalCapabilities:{args:["ptr","ptr"],returns:"void"},processCapabilityResponse:{args:["ptr","ptr","usize"],returns:"void"},encodeUnicode:{args:["ptr","usize","ptr","ptr","u8"],returns:"bool"},freeUnicode:{args:["ptr","usize"],returns:"void"},bufferDrawChar:{args:["ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},createNativeSpanFeed:{args:["ptr"],returns:"ptr"},attachNativeSpanFeed:{args:["ptr"],returns:"i32"},destroyNativeSpanFeed:{args:["ptr"],returns:"void"},streamWrite:{args:["ptr","ptr","u64"],returns:"i32"},streamCommit:{args:["ptr"],returns:"i32"},streamDrainSpans:{args:["ptr","ptr","u32"],returns:"u32"},streamClose:{args:["ptr"],returns:"i32"},streamReserve:{args:["ptr","u32","ptr"],returns:"i32"},streamCommitReserved:{args:["ptr","u32"],returns:"i32"},streamSetOptions:{args:["ptr","ptr"],returns:"i32"},streamGetStats:{args:["ptr","ptr"],returns:"i32"},streamSetCallback:{args:["ptr","ptr"],returns:"void"}});if(env.OTUI_DEBUG_FFI||env.OTUI_TRACE_FFI)return{symbols:convertToDebugSymbols(rawSymbols.symbols)};return rawSymbols}function convertToDebugSymbols(symbols){if(!globalTraceSymbols)globalTraceSymbols={};if(env.OTUI_DEBUG_FFI&&!globalFFILogPath)globalFFILogPath=`ffi_otui_debug_${new Date().toISOString().replace(/[:.]/g,"-").replace(/T/,"_").split("Z")[0]}.log`;let debugSymbols={},hasTracing=!1;if(Object.entries(symbols).forEach(([key,value])=>{debugSymbols[key]=value}),env.OTUI_DEBUG_FFI&&globalFFILogPath){let logPath=globalFFILogPath,writeSync=(msg)=>{writeFileSync24(logPath,msg+`
2272
+ `);for(let y=0;y<this._height;y++){let spans=[],currentSpan=null,lineChars=[...realTextLines[y]||""],charIdx=0;for(let x=0;x<this._width;x++){let i2=y*this._width+x,cp3=char[i2],cellFg=RGBA.fromValues(fg2[i2*4],fg2[i2*4+1],fg2[i2*4+2],fg2[i2*4+3]),cellBg=RGBA.fromValues(bg2[i2*4],bg2[i2*4+1],bg2[i2*4+2],bg2[i2*4+3]),cellAttrs=attributes[i2]&255,cellChar=(cp3&CHAR_FLAG_MASK)===CHAR_FLAG_CONTINUATION?"":lineChars[charIdx++]??" ";if(currentSpan&&currentSpan.fg.equals(cellFg)&&currentSpan.bg.equals(cellBg)&&currentSpan.attributes===cellAttrs)currentSpan.text+=cellChar,currentSpan.width+=1;else{if(currentSpan)spans.push(currentSpan);currentSpan={text:cellChar,fg:cellFg,bg:cellBg,attributes:cellAttrs,width:1}}}if(currentSpan)spans.push(currentSpan);lines.push({spans})}return lines}clear(bg2=RGBA.fromValues(0,0,0,1)){this.guard(),this.lib.bufferClear(this.bufferPtr,bg2)}setCell(x,y,char,fg2,bg2,attributes=0){this.guard(),this.lib.bufferSetCell(this.bufferPtr,x,y,char,fg2,bg2,attributes)}setCellWithAlphaBlending(x,y,char,fg2,bg2,attributes=0){this.guard(),this.lib.bufferSetCellWithAlphaBlending(this.bufferPtr,x,y,char,fg2,bg2,attributes)}drawText(text,x,y,fg2,bg2,attributes=0,selection2){if(this.guard(),!selection2){this.lib.bufferDrawText(this.bufferPtr,text,x,y,fg2,bg2,attributes);return}let{start:start2,end}=selection2,selectionBg,selectionFg;if(selection2.bgColor)selectionBg=selection2.bgColor,selectionFg=selection2.fgColor||fg2;else{let defaultBg=bg2||RGBA.fromValues(0,0,0,0);selectionFg=defaultBg.a>0?defaultBg:RGBA.fromValues(0,0,0,1),selectionBg=fg2}if(start2>0){let beforeText=text.slice(0,start2);this.lib.bufferDrawText(this.bufferPtr,beforeText,x,y,fg2,bg2,attributes)}if(end>start2){let selectedText=text.slice(start2,end);this.lib.bufferDrawText(this.bufferPtr,selectedText,x+start2,y,selectionFg,selectionBg,attributes)}if(end<text.length){let afterText=text.slice(end);this.lib.bufferDrawText(this.bufferPtr,afterText,x+end,y,fg2,bg2,attributes)}}fillRect(x,y,width,height2,bg2){this.lib.bufferFillRect(this.bufferPtr,x,y,width,height2,bg2)}colorMatrix(matrix,cellMask,strength=1,target=3){if(this.guard(),matrix.length!==16)throw RangeError(`colorMatrix matrix must have length 16, got ${matrix.length}`);let cellMaskCount=Math.floor(cellMask.length/3);this.lib.bufferColorMatrix(this.bufferPtr,ptr(matrix),ptr(cellMask),cellMaskCount,strength,target)}colorMatrixUniform(matrix,strength=1,target=3){if(this.guard(),matrix.length!==16)throw RangeError(`colorMatrixUniform matrix must have length 16, got ${matrix.length}`);if(strength===0)return;this.lib.bufferColorMatrixUniform(this.bufferPtr,ptr(matrix),strength,target)}drawFrameBuffer(destX,destY,frameBuffer,sourceX,sourceY,sourceWidth,sourceHeight){this.guard(),this.lib.drawFrameBuffer(this.bufferPtr,destX,destY,frameBuffer.ptr,sourceX,sourceY,sourceWidth,sourceHeight)}destroy(){if(this._destroyed)return;this._destroyed=!0,this.lib.destroyOptimizedBuffer(this.bufferPtr)}drawTextBuffer(textBufferView,x,y){this.guard(),this.lib.bufferDrawTextBufferView(this.bufferPtr,textBufferView.ptr,x,y)}drawEditorView(editorView,x,y){this.guard(),this.lib.bufferDrawEditorView(this.bufferPtr,editorView.ptr,x,y)}drawSuperSampleBuffer(x,y,pixelDataPtr,pixelDataLength,format,alignedBytesPerRow){this.guard(),this.lib.bufferDrawSuperSampleBuffer(this.bufferPtr,x,y,pixelDataPtr,pixelDataLength,format,alignedBytesPerRow)}drawPackedBuffer(dataPtr,dataLen,posX,posY,terminalWidthCells,terminalHeightCells){this.guard(),this.lib.bufferDrawPackedBuffer(this.bufferPtr,dataPtr,dataLen,posX,posY,terminalWidthCells,terminalHeightCells)}drawGrayscaleBuffer(posX,posY,intensities,srcWidth,srcHeight,fg2=null,bg2=null){this.guard(),this.lib.bufferDrawGrayscaleBuffer(this.bufferPtr,posX,posY,ptr(intensities),srcWidth,srcHeight,fg2,bg2)}drawGrayscaleBufferSupersampled(posX,posY,intensities,srcWidth,srcHeight,fg2=null,bg2=null){this.guard(),this.lib.bufferDrawGrayscaleBufferSupersampled(this.bufferPtr,posX,posY,ptr(intensities),srcWidth,srcHeight,fg2,bg2)}resize(width,height2){if(this.guard(),this._width===width&&this._height===height2)return;this._width=width,this._height=height2,this._rawBuffers=null,this.lib.bufferResize(this.bufferPtr,width,height2)}drawBox(options){this.guard();let style=parseBorderStyle(options.borderStyle,"single"),borderChars=options.customBorderChars??BorderCharArrays[style],packedOptions=packDrawOptions(options.border,options.shouldFill??!1,options.titleAlignment||"left");this.lib.bufferDrawBox(this.bufferPtr,options.x,options.y,options.width,options.height,borderChars,packedOptions,options.borderColor,options.backgroundColor,options.title??null)}pushScissorRect(x,y,width,height2){this.guard(),this.lib.bufferPushScissorRect(this.bufferPtr,x,y,width,height2)}popScissorRect(){this.guard(),this.lib.bufferPopScissorRect(this.bufferPtr)}clearScissorRects(){this.guard(),this.lib.bufferClearScissorRects(this.bufferPtr)}pushOpacity(opacity){this.guard(),this.lib.bufferPushOpacity(this.bufferPtr,Math.max(0,Math.min(1,opacity)))}popOpacity(){this.guard(),this.lib.bufferPopOpacity(this.bufferPtr)}getCurrentOpacity(){return this.guard(),this.lib.bufferGetCurrentOpacity(this.bufferPtr)}clearOpacity(){this.guard(),this.lib.bufferClearOpacity(this.bufferPtr)}encodeUnicode(text){return this.guard(),this.lib.encodeUnicode(text,this._widthMethod)}freeUnicode(encoded){this.guard(),this.lib.freeUnicode(encoded)}drawGrid(options){this.guard();let columnCount=Math.max(0,options.columnOffsets.length-1),rowCount=Math.max(0,options.rowOffsets.length-1);this.lib.bufferDrawGrid(this.bufferPtr,options.borderChars,options.borderFg,options.borderBg,options.columnOffsets,columnCount,options.rowOffsets,rowCount,{drawInner:options.drawInner,drawOuter:options.drawOuter})}drawChar(char,x,y,fg2,bg2,attributes=0){this.guard(),this.lib.bufferDrawChar(this.bufferPtr,char,x,y,fg2,bg2,attributes)}}function fatalError(...args){let message=args.join(" ");throw console.error("FATAL ERROR:",message),Error(message)}function isPrimitiveType(type2){return typeof type2==="string"&&primitiveKeys.includes(type2)}function isObjectPointerDef(type2){return typeof type2==="object"&&type2!==null&&type2.__type==="objectPointer"}function alignOffset(offset,align){return offset+(align-1)&~(align-1)}function enumTypeError(value){throw TypeError(`Invalid enum value: ${value}`)}function defineEnum(mapping,base="u32"){let reverse2=Object.fromEntries(Object.entries(mapping).map(([k,v])=>[v,k]));return{__type:"enum",type:base,to(value){return typeof value==="number"?value:mapping[value]??enumTypeError(String(value))},from(value){return reverse2[value]??enumTypeError(String(value))},enum:mapping}}function isEnum(type2){return typeof type2==="object"&&type2.__type==="enum"}function isStruct(type2){return typeof type2==="object"&&type2.__type==="struct"}function primitivePackers(type2){let pack,unpack;switch(type2){case"u8":pack=(view,off,val)=>view.setUint8(off,val),unpack=(view,off)=>view.getUint8(off);break;case"bool_u8":pack=(view,off,val)=>view.setUint8(off,val?1:0),unpack=(view,off)=>Boolean(view.getUint8(off));break;case"bool_u32":pack=(view,off,val)=>view.setUint32(off,val?1:0,!0),unpack=(view,off)=>Boolean(view.getUint32(off,!0));break;case"u16":pack=(view,off,val)=>view.setUint16(off,val,!0),unpack=(view,off)=>view.getUint16(off,!0);break;case"i16":pack=(view,off,val)=>view.setInt16(off,val,!0),unpack=(view,off)=>view.getInt16(off,!0);break;case"u32":pack=(view,off,val)=>view.setUint32(off,val,!0),unpack=(view,off)=>view.getUint32(off,!0);break;case"i32":pack=(view,off,val)=>view.setInt32(off,val,!0),unpack=(view,off)=>view.getInt32(off,!0);break;case"u64":pack=(view,off,val)=>view.setBigUint64(off,BigInt(val),!0),unpack=(view,off)=>view.getBigUint64(off,!0);break;case"f32":pack=(view,off,val)=>view.setFloat32(off,val,!0),unpack=(view,off)=>view.getFloat32(off,!0);break;case"f64":pack=(view,off,val)=>view.setFloat64(off,val,!0),unpack=(view,off)=>view.getFloat64(off,!0);break;case"pointer":pack=(view,off,val)=>{pointerSize===8?view.setBigUint64(off,val?BigInt(val):0n,!0):view.setUint32(off,val?Number(val):0,!0)},unpack=(view,off)=>{let bint=pointerSize===8?view.getBigUint64(off,!0):BigInt(view.getUint32(off,!0));return Number(bint)};break;default:fatalError(`Unsupported primitive type: ${type2}`)}return{pack,unpack}}function packObjectArray(val){let buffer2=new ArrayBuffer(val.length*pointerSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++){let ptrValue=val[i2]?.ptr??null;pointerPacker(bufferView,i2*pointerSize,ptrValue)}return bufferView}function defineStruct(fields,structDefOptions){let offset=0,maxAlign=1,layout=[],lengthOfFields={},lengthOfRequested=[],arrayFieldsMetadata={};for(let[name,typeOrStruct,options={}]of fields){if(options.condition&&!options.condition())continue;let size=0,align=0,pack,unpack,needsLengthOf=!1,lengthOfDef=null;if(isPrimitiveType(typeOrStruct))size=typeSizes[typeOrStruct],align=typeAlignments[typeOrStruct],{pack,unpack}=primitivePackers(typeOrStruct);else if(typeof typeOrStruct==="string"&&typeOrStruct==="cstring")size=pointerSize,align=pointerSize,pack=(view,off,val)=>{let bufPtr=val?ptr2(encoder.encode(val+"\x00")):null;pointerPacker(view,off,bufPtr)},unpack=(view,off)=>{return pointerUnpacker(view,off)};else if(typeof typeOrStruct==="string"&&typeOrStruct==="char*")size=pointerSize,align=pointerSize,pack=(view,off,val)=>{let bufPtr=val?ptr2(encoder.encode(val)):null;pointerPacker(view,off,bufPtr)},unpack=(view,off)=>{return pointerUnpacker(view,off)},needsLengthOf=!0;else if(isEnum(typeOrStruct)){let base=typeOrStruct.type;size=typeSizes[base],align=typeAlignments[base];let{pack:packEnum}=primitivePackers(base);pack=(view,off,val)=>{let num=typeOrStruct.to(val);packEnum(view,off,num)},unpack=(view,off)=>{let raw=typeGetters[base](view,off);return typeOrStruct.from(raw)}}else if(isStruct(typeOrStruct))if(options.asPointer===!0)size=pointerSize,align=pointerSize,pack=(view,off,val,obj,options2)=>{if(!val){pointerPacker(view,off,null);return}let nestedBuf=typeOrStruct.pack(val,options2);pointerPacker(view,off,ptr2(nestedBuf))},unpack=(view,off)=>{throw Error("Not implemented yet")};else size=typeOrStruct.size,align=typeOrStruct.align,pack=(view,off,val,obj,options2)=>{let nestedBuf=typeOrStruct.pack(val,options2),nestedView=new Uint8Array(nestedBuf);new Uint8Array(view.buffer).set(nestedView,off)},unpack=(view,off)=>{let slice=view.buffer.slice(off,off+size);return typeOrStruct.unpack(slice)};else if(isObjectPointerDef(typeOrStruct))size=pointerSize,align=pointerSize,pack=(view,off,value)=>{let ptrValue=value?.ptr??null;if(ptrValue===void 0)console.warn(`Field '${name}' expected object with '.ptr' property, but got undefined pointer value from:`,value),pointerPacker(view,off,null);else pointerPacker(view,off,ptrValue)},unpack=(view,off)=>{return pointerUnpacker(view,off)};else if(Array.isArray(typeOrStruct)&&typeOrStruct.length===1&&typeOrStruct[0]!==void 0){let[def]=typeOrStruct;size=pointerSize,align=pointerSize;let arrayElementSize;if(isEnum(def))arrayElementSize=typeSizes[def.type],pack=(view,off,val,obj)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let buffer2=new ArrayBuffer(val.length*arrayElementSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++){let num=def.to(val[i2]);bufferView.setUint32(i2*arrayElementSize,num,!0)}pointerPacker(view,off,ptr2(buffer2))},unpack=null,needsLengthOf=!0,lengthOfDef=def;else if(isStruct(def))arrayElementSize=def.size,pack=(view,off,val,obj,options2)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let buffer2=new ArrayBuffer(val.length*arrayElementSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++)def.packInto(val[i2],bufferView,i2*arrayElementSize,options2);pointerPacker(view,off,ptr2(buffer2))},unpack=(view,off)=>{throw Error("Not implemented yet")};else if(isPrimitiveType(def)){arrayElementSize=typeSizes[def];let{pack:primitivePack}=primitivePackers(def);pack=(view,off,val)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let buffer2=new ArrayBuffer(val.length*arrayElementSize),bufferView=new DataView(buffer2);for(let i2=0;i2<val.length;i2++)primitivePack(bufferView,i2*arrayElementSize,val[i2]);pointerPacker(view,off,ptr2(buffer2))},unpack=null,needsLengthOf=!0,lengthOfDef=def}else if(isObjectPointerDef(def))arrayElementSize=pointerSize,pack=(view,off,val)=>{if(!val||val.length===0){pointerPacker(view,off,null);return}let packedView=packObjectArray(val);pointerPacker(view,off,ptr2(packedView.buffer))},unpack=()=>{throw Error("not implemented yet")};else throw Error(`Unsupported array element type for ${name}: ${JSON.stringify(def)}`);let lengthOfField=Object.values(lengthOfFields).find((f)=>f.lengthOf===name);if(lengthOfField&&isPrimitiveType(lengthOfField.type)){let{pack:lengthPack}=primitivePackers(lengthOfField.type);arrayFieldsMetadata[name]={elementSize:arrayElementSize,arrayOffset:offset,lengthOffset:lengthOfField.offset,lengthPack}}}else throw Error(`Unsupported field type for ${name}: ${JSON.stringify(typeOrStruct)}`);if(offset=alignOffset(offset,align),options.unpackTransform){let originalUnpack=unpack;unpack=(view,off)=>options.unpackTransform(originalUnpack(view,off))}if(options.packTransform){let originalPack=pack;pack=(view,off,val,obj,packOptions)=>originalPack(view,off,options.packTransform(val),obj,packOptions)}if(options.optional){let originalPack=pack;if(isStruct(typeOrStruct)&&!options.asPointer)pack=(view,off,val,obj,packOptions)=>{if(val||options.mapOptionalInline)originalPack(view,off,val,obj,packOptions)};else pack=(view,off,val,obj,packOptions)=>originalPack(view,off,val??0,obj,packOptions)}if(options.lengthOf){let originalPack=pack;pack=(view,off,val,obj,packOptions)=>{let targetValue=obj[options.lengthOf],length=0;if(targetValue)if(typeof targetValue==="string")length=Buffer.byteLength(targetValue);else length=targetValue.length;return originalPack(view,off,length,obj,packOptions)}}let validateFunctions;if(options.validate)validateFunctions=Array.isArray(options.validate)?options.validate:[options.validate];let layoutField={name,offset,size,align,validate:validateFunctions,optional:!!options.optional||!!options.lengthOf||options.default!==void 0,default:options.default,pack,unpack,type:typeOrStruct,lengthOf:options.lengthOf};if(layout.push(layoutField),options.lengthOf)lengthOfFields[options.lengthOf]=layoutField;if(needsLengthOf){let def=typeof typeOrStruct==="string"&&typeOrStruct==="char*"?"char*":lengthOfDef;if(!def)fatalError(`Internal error: needsLengthOf=true but def is null for ${name}`);lengthOfRequested.push({requester:layoutField,def})}offset+=size,maxAlign=Math.max(maxAlign,align)}for(let{requester,def}of lengthOfRequested){let lengthOfField=lengthOfFields[requester.name];if(!lengthOfField){if(def==="char*")continue;throw Error(`lengthOf field not found for array field ${requester.name}`)}if(def==="char*")requester.unpack=(view,off)=>{let ptrAddress=pointerUnpacker(view,off),length=lengthOfField.unpack(view,lengthOfField.offset);if(ptrAddress===0)return null;let byteLength=typeof length==="bigint"?Number(length):length;if(byteLength===0)return"";let buffer2=toArrayBuffer2(ptrAddress,0,byteLength);return decoder.decode(buffer2)};else if(isPrimitiveType(def)){let elemSize=typeSizes[def],{unpack:primitiveUnpack}=primitivePackers(def);requester.unpack=(view,off)=>{let result2=[],length=lengthOfField.unpack(view,lengthOfField.offset),ptrAddress=pointerUnpacker(view,off);if(ptrAddress===0n&&length>0)throw Error(`Array field ${requester.name} has null pointer but length ${length}.`);if(ptrAddress===0n||length===0)return[];let buffer2=toArrayBuffer2(ptrAddress,0,length*elemSize),bufferView=new DataView(buffer2);for(let i2=0;i2<length;i2++)result2.push(primitiveUnpack(bufferView,i2*elemSize));return result2}}else{let elemSize=def.type==="u32"?4:8;requester.unpack=(view,off)=>{let result2=[],length=lengthOfField.unpack(view,lengthOfField.offset),ptrAddress=pointerUnpacker(view,off);if(ptrAddress===0n&&length>0)throw Error(`Array field ${requester.name} has null pointer but length ${length}.`);if(ptrAddress===0n||length===0)return[];let buffer2=toArrayBuffer2(ptrAddress,0,length*elemSize),bufferView=new DataView(buffer2);for(let i2=0;i2<length;i2++)result2.push(def.from(bufferView.getUint32(i2*elemSize,!0)));return result2}}}let totalSize=alignOffset(offset,maxAlign),description=layout.map((f)=>({name:f.name,offset:f.offset,size:f.size,align:f.align,optional:f.optional,type:f.type,lengthOf:f.lengthOf})),layoutByName=new Map(description.map((f)=>[f.name,f])),arrayFields=new Map(Object.entries(arrayFieldsMetadata));return{__type:"struct",size:totalSize,align:maxAlign,hasMapValue:!!structDefOptions?.mapValue,layoutByName,arrayFields,pack(obj,options){let buf=new ArrayBuffer(totalSize),view=new DataView(buf),mappedObj=obj;if(structDefOptions?.mapValue)mappedObj=structDefOptions.mapValue(obj);for(let field of layout){let value=mappedObj[field.name]??field.default;if(!field.optional&&value===void 0)fatalError(`Packing non-optional field '${field.name}' but value is undefined (and no default provided)`);if(field.validate)for(let validateFn of field.validate)validateFn(value,field.name,{hints:options?.validationHints,input:mappedObj});field.pack(view,field.offset,value,mappedObj,options)}return view.buffer},packInto(obj,view,offset2,options){let mappedObj=obj;if(structDefOptions?.mapValue)mappedObj=structDefOptions.mapValue(obj);for(let field of layout){let value=mappedObj[field.name]??field.default;if(!field.optional&&value===void 0)console.warn(`packInto missing value for non-optional field '${field.name}' at offset ${offset2+field.offset}. Writing default or zero.`);if(field.validate)for(let validateFn of field.validate)validateFn(value,field.name,{hints:options?.validationHints,input:mappedObj});field.pack(view,offset2+field.offset,value,mappedObj,options)}},unpack(buf){if(buf.byteLength<totalSize)fatalError(`Buffer size (${buf.byteLength}) is smaller than struct size (${totalSize}) for unpacking.`);let view=new DataView(buf),result2=structDefOptions?.default?{...structDefOptions.default}:{};for(let field of layout){if(!field.unpack)continue;try{result2[field.name]=field.unpack(view,field.offset)}catch(e){throw console.error(`Error unpacking field '${field.name}' at offset ${field.offset}:`,e),e}}if(structDefOptions?.reduceValue)return structDefOptions.reduceValue(result2);return result2},packList(objects,options){if(objects.length===0)return new ArrayBuffer(0);let buffer2=new ArrayBuffer(totalSize*objects.length),view=new DataView(buffer2);for(let i2=0;i2<objects.length;i2++){let mappedObj=objects[i2];if(structDefOptions?.mapValue)mappedObj=structDefOptions.mapValue(objects[i2]);for(let field of layout){let value=mappedObj[field.name]??field.default;if(!field.optional&&value===void 0)fatalError(`Packing non-optional field '${field.name}' at index ${i2} but value is undefined (and no default provided)`);if(field.validate)for(let validateFn of field.validate)validateFn(value,field.name,{hints:options?.validationHints,input:mappedObj});field.pack(view,i2*totalSize+field.offset,value,mappedObj,options)}}return buffer2},unpackList(buf,count){if(count===0)return[];let expectedSize=totalSize*count;if(buf.byteLength<expectedSize)fatalError(`Buffer size (${buf.byteLength}) is smaller than expected size (${expectedSize}) for unpacking ${count} structs.`);let view=new DataView(buf),results=[];for(let i2=0;i2<count;i2++){let offset2=i2*totalSize,result2=structDefOptions?.default?{...structDefOptions.default}:{};for(let field of layout){if(!field.unpack)continue;try{result2[field.name]=field.unpack(view,offset2+field.offset)}catch(e){throw console.error(`Error unpacking field '${field.name}' at index ${i2}, offset ${offset2+field.offset}:`,e),e}}if(structDefOptions?.reduceValue)results.push(structDefOptions.reduceValue(result2));else results.push(result2)}return results},describe(){return description}}}function toPointer(value){if(typeof value==="bigint"){if(value>BigInt(Number.MAX_SAFE_INTEGER))throw Error("Pointer exceeds safe integer range");return Number(value)}return value}function toNumber(value){return typeof value==="bigint"?Number(value):value}function getOpenTUILib(libPath){let rawSymbols=dlopen(libPath||targetLibPath,{setLogCallback:{args:["ptr"],returns:"void"},setEventCallback:{args:["ptr"],returns:"void"},createRenderer:{args:["u32","u32","bool","bool"],returns:"ptr"},setTerminalEnvVar:{args:["ptr","ptr","usize","ptr","usize"],returns:"bool"},destroyRenderer:{args:["ptr"],returns:"void"},setUseThread:{args:["ptr","bool"],returns:"void"},setBackgroundColor:{args:["ptr","ptr"],returns:"void"},setRenderOffset:{args:["ptr","u32"],returns:"void"},updateStats:{args:["ptr","f64","u32","f64"],returns:"void"},updateMemoryStats:{args:["ptr","u32","u32","u32"],returns:"void"},render:{args:["ptr","bool"],returns:"void"},getNextBuffer:{args:["ptr"],returns:"ptr"},getCurrentBuffer:{args:["ptr"],returns:"ptr"},queryPixelResolution:{args:["ptr"],returns:"void"},createOptimizedBuffer:{args:["u32","u32","bool","u8","ptr","usize"],returns:"ptr"},destroyOptimizedBuffer:{args:["ptr"],returns:"void"},drawFrameBuffer:{args:["ptr","i32","i32","ptr","u32","u32","u32","u32"],returns:"void"},getBufferWidth:{args:["ptr"],returns:"u32"},getBufferHeight:{args:["ptr"],returns:"u32"},bufferClear:{args:["ptr","ptr"],returns:"void"},bufferGetCharPtr:{args:["ptr"],returns:"ptr"},bufferGetFgPtr:{args:["ptr"],returns:"ptr"},bufferGetBgPtr:{args:["ptr"],returns:"ptr"},bufferGetAttributesPtr:{args:["ptr"],returns:"ptr"},bufferGetRespectAlpha:{args:["ptr"],returns:"bool"},bufferSetRespectAlpha:{args:["ptr","bool"],returns:"void"},bufferGetId:{args:["ptr","ptr","usize"],returns:"usize"},bufferGetRealCharSize:{args:["ptr"],returns:"u32"},bufferWriteResolvedChars:{args:["ptr","ptr","usize","bool"],returns:"u32"},bufferDrawText:{args:["ptr","ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},bufferSetCellWithAlphaBlending:{args:["ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},bufferSetCell:{args:["ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},bufferFillRect:{args:["ptr","u32","u32","u32","u32","ptr"],returns:"void"},bufferColorMatrix:{args:["ptr","ptr","ptr","usize","f32","u8"],returns:"void"},bufferColorMatrixUniform:{args:["ptr","ptr","f32","u8"],returns:"void"},bufferResize:{args:["ptr","u32","u32"],returns:"void"},linkAlloc:{args:["ptr","u32"],returns:"u32"},linkGetUrl:{args:["u32","ptr","u32"],returns:"u32"},attributesWithLink:{args:["u32","u32"],returns:"u32"},attributesGetLinkId:{args:["u32"],returns:"u32"},resizeRenderer:{args:["ptr","u32","u32"],returns:"void"},setCursorPosition:{args:["ptr","i32","i32","bool"],returns:"void"},setCursorColor:{args:["ptr","ptr"],returns:"void"},getCursorState:{args:["ptr","ptr"],returns:"void"},setCursorStyleOptions:{args:["ptr","ptr"],returns:"void"},setDebugOverlay:{args:["ptr","bool","u8"],returns:"void"},clearTerminal:{args:["ptr"],returns:"void"},setTerminalTitle:{args:["ptr","ptr","usize"],returns:"void"},copyToClipboardOSC52:{args:["ptr","u8","ptr","usize"],returns:"bool"},clearClipboardOSC52:{args:["ptr","u8"],returns:"bool"},bufferDrawSuperSampleBuffer:{args:["ptr","u32","u32","ptr","usize","u8","u32"],returns:"void"},bufferDrawPackedBuffer:{args:["ptr","ptr","usize","u32","u32","u32","u32"],returns:"void"},bufferDrawGrayscaleBuffer:{args:["ptr","i32","i32","ptr","u32","u32","ptr","ptr"],returns:"void"},bufferDrawGrayscaleBufferSupersampled:{args:["ptr","i32","i32","ptr","u32","u32","ptr","ptr"],returns:"void"},bufferDrawGrid:{args:["ptr","ptr","ptr","ptr","ptr","u32","ptr","u32","ptr"],returns:"void"},bufferDrawBox:{args:["ptr","i32","i32","u32","u32","ptr","u32","ptr","ptr","ptr","u32"],returns:"void"},bufferPushScissorRect:{args:["ptr","i32","i32","u32","u32"],returns:"void"},bufferPopScissorRect:{args:["ptr"],returns:"void"},bufferClearScissorRects:{args:["ptr"],returns:"void"},bufferPushOpacity:{args:["ptr","f32"],returns:"void"},bufferPopOpacity:{args:["ptr"],returns:"void"},bufferGetCurrentOpacity:{args:["ptr"],returns:"f32"},bufferClearOpacity:{args:["ptr"],returns:"void"},addToHitGrid:{args:["ptr","i32","i32","u32","u32","u32"],returns:"void"},clearCurrentHitGrid:{args:["ptr"],returns:"void"},hitGridPushScissorRect:{args:["ptr","i32","i32","u32","u32"],returns:"void"},hitGridPopScissorRect:{args:["ptr"],returns:"void"},hitGridClearScissorRects:{args:["ptr"],returns:"void"},addToCurrentHitGridClipped:{args:["ptr","i32","i32","u32","u32","u32"],returns:"void"},checkHit:{args:["ptr","u32","u32"],returns:"u32"},getHitGridDirty:{args:["ptr"],returns:"bool"},dumpHitGrid:{args:["ptr"],returns:"void"},dumpBuffers:{args:["ptr","i64"],returns:"void"},dumpStdoutBuffer:{args:["ptr","i64"],returns:"void"},restoreTerminalModes:{args:["ptr"],returns:"void"},enableMouse:{args:["ptr","bool"],returns:"void"},disableMouse:{args:["ptr"],returns:"void"},enableKittyKeyboard:{args:["ptr","u8"],returns:"void"},disableKittyKeyboard:{args:["ptr"],returns:"void"},setKittyKeyboardFlags:{args:["ptr","u8"],returns:"void"},getKittyKeyboardFlags:{args:["ptr"],returns:"u8"},setupTerminal:{args:["ptr","bool"],returns:"void"},suspendRenderer:{args:["ptr"],returns:"void"},resumeRenderer:{args:["ptr"],returns:"void"},writeOut:{args:["ptr","ptr","u64"],returns:"void"},createTextBuffer:{args:["u8"],returns:"ptr"},destroyTextBuffer:{args:["ptr"],returns:"void"},textBufferGetLength:{args:["ptr"],returns:"u32"},textBufferGetByteSize:{args:["ptr"],returns:"u32"},textBufferReset:{args:["ptr"],returns:"void"},textBufferClear:{args:["ptr"],returns:"void"},textBufferSetDefaultFg:{args:["ptr","ptr"],returns:"void"},textBufferSetDefaultBg:{args:["ptr","ptr"],returns:"void"},textBufferSetDefaultAttributes:{args:["ptr","ptr"],returns:"void"},textBufferResetDefaults:{args:["ptr"],returns:"void"},textBufferGetTabWidth:{args:["ptr"],returns:"u8"},textBufferSetTabWidth:{args:["ptr","u8"],returns:"void"},textBufferRegisterMemBuffer:{args:["ptr","ptr","usize","bool"],returns:"u16"},textBufferReplaceMemBuffer:{args:["ptr","u8","ptr","usize","bool"],returns:"bool"},textBufferClearMemRegistry:{args:["ptr"],returns:"void"},textBufferSetTextFromMem:{args:["ptr","u8"],returns:"void"},textBufferAppend:{args:["ptr","ptr","usize"],returns:"void"},textBufferAppendFromMemId:{args:["ptr","u8"],returns:"void"},textBufferLoadFile:{args:["ptr","ptr","usize"],returns:"bool"},textBufferSetStyledText:{args:["ptr","ptr","usize"],returns:"void"},textBufferGetLineCount:{args:["ptr"],returns:"u32"},textBufferGetPlainText:{args:["ptr","ptr","usize"],returns:"usize"},textBufferAddHighlightByCharRange:{args:["ptr","ptr"],returns:"void"},textBufferAddHighlight:{args:["ptr","u32","ptr"],returns:"void"},textBufferRemoveHighlightsByRef:{args:["ptr","u16"],returns:"void"},textBufferClearLineHighlights:{args:["ptr","u32"],returns:"void"},textBufferClearAllHighlights:{args:["ptr"],returns:"void"},textBufferSetSyntaxStyle:{args:["ptr","ptr"],returns:"void"},textBufferGetLineHighlightsPtr:{args:["ptr","u32","ptr"],returns:"ptr"},textBufferFreeLineHighlights:{args:["ptr","usize"],returns:"void"},textBufferGetHighlightCount:{args:["ptr"],returns:"u32"},textBufferGetTextRange:{args:["ptr","u32","u32","ptr","usize"],returns:"usize"},textBufferGetTextRangeByCoords:{args:["ptr","u32","u32","u32","u32","ptr","usize"],returns:"usize"},createTextBufferView:{args:["ptr"],returns:"ptr"},destroyTextBufferView:{args:["ptr"],returns:"void"},textBufferViewSetSelection:{args:["ptr","u32","u32","ptr","ptr"],returns:"void"},textBufferViewResetSelection:{args:["ptr"],returns:"void"},textBufferViewGetSelectionInfo:{args:["ptr"],returns:"u64"},textBufferViewSetLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr"],returns:"bool"},textBufferViewUpdateSelection:{args:["ptr","u32","ptr","ptr"],returns:"void"},textBufferViewUpdateLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr"],returns:"bool"},textBufferViewResetLocalSelection:{args:["ptr"],returns:"void"},textBufferViewSetWrapWidth:{args:["ptr","u32"],returns:"void"},textBufferViewSetWrapMode:{args:["ptr","u8"],returns:"void"},textBufferViewSetViewportSize:{args:["ptr","u32","u32"],returns:"void"},textBufferViewSetViewport:{args:["ptr","u32","u32","u32","u32"],returns:"void"},textBufferViewGetVirtualLineCount:{args:["ptr"],returns:"u32"},textBufferViewGetLineInfoDirect:{args:["ptr","ptr"],returns:"void"},textBufferViewGetLogicalLineInfoDirect:{args:["ptr","ptr"],returns:"void"},textBufferViewGetSelectedText:{args:["ptr","ptr","usize"],returns:"usize"},textBufferViewGetPlainText:{args:["ptr","ptr","usize"],returns:"usize"},textBufferViewSetTabIndicator:{args:["ptr","u32"],returns:"void"},textBufferViewSetTabIndicatorColor:{args:["ptr","ptr"],returns:"void"},textBufferViewSetTruncate:{args:["ptr","bool"],returns:"void"},textBufferViewMeasureForDimensions:{args:["ptr","u32","u32","ptr"],returns:"bool"},bufferDrawTextBufferView:{args:["ptr","ptr","i32","i32"],returns:"void"},bufferDrawEditorView:{args:["ptr","ptr","i32","i32"],returns:"void"},createEditorView:{args:["ptr","u32","u32"],returns:"ptr"},destroyEditorView:{args:["ptr"],returns:"void"},editorViewSetViewportSize:{args:["ptr","u32","u32"],returns:"void"},editorViewSetViewport:{args:["ptr","u32","u32","u32","u32","bool"],returns:"void"},editorViewGetViewport:{args:["ptr","ptr","ptr","ptr","ptr"],returns:"void"},editorViewSetScrollMargin:{args:["ptr","f32"],returns:"void"},editorViewSetWrapMode:{args:["ptr","u8"],returns:"void"},editorViewGetVirtualLineCount:{args:["ptr"],returns:"u32"},editorViewGetTotalVirtualLineCount:{args:["ptr"],returns:"u32"},editorViewGetTextBufferView:{args:["ptr"],returns:"ptr"},editorViewGetLineInfoDirect:{args:["ptr","ptr"],returns:"void"},editorViewGetLogicalLineInfoDirect:{args:["ptr","ptr"],returns:"void"},createEditBuffer:{args:["u8"],returns:"ptr"},destroyEditBuffer:{args:["ptr"],returns:"void"},editBufferSetText:{args:["ptr","ptr","usize"],returns:"void"},editBufferSetTextFromMem:{args:["ptr","u8"],returns:"void"},editBufferReplaceText:{args:["ptr","ptr","usize"],returns:"void"},editBufferReplaceTextFromMem:{args:["ptr","u8"],returns:"void"},editBufferGetText:{args:["ptr","ptr","usize"],returns:"usize"},editBufferInsertChar:{args:["ptr","ptr","usize"],returns:"void"},editBufferInsertText:{args:["ptr","ptr","usize"],returns:"void"},editBufferDeleteChar:{args:["ptr"],returns:"void"},editBufferDeleteCharBackward:{args:["ptr"],returns:"void"},editBufferDeleteRange:{args:["ptr","u32","u32","u32","u32"],returns:"void"},editBufferNewLine:{args:["ptr"],returns:"void"},editBufferDeleteLine:{args:["ptr"],returns:"void"},editBufferMoveCursorLeft:{args:["ptr"],returns:"void"},editBufferMoveCursorRight:{args:["ptr"],returns:"void"},editBufferMoveCursorUp:{args:["ptr"],returns:"void"},editBufferMoveCursorDown:{args:["ptr"],returns:"void"},editBufferGotoLine:{args:["ptr","u32"],returns:"void"},editBufferSetCursor:{args:["ptr","u32","u32"],returns:"void"},editBufferSetCursorToLineCol:{args:["ptr","u32","u32"],returns:"void"},editBufferSetCursorByOffset:{args:["ptr","u32"],returns:"void"},editBufferGetCursorPosition:{args:["ptr","ptr"],returns:"void"},editBufferGetId:{args:["ptr"],returns:"u16"},editBufferGetTextBuffer:{args:["ptr"],returns:"ptr"},editBufferDebugLogRope:{args:["ptr"],returns:"void"},editBufferUndo:{args:["ptr","ptr","usize"],returns:"usize"},editBufferRedo:{args:["ptr","ptr","usize"],returns:"usize"},editBufferCanUndo:{args:["ptr"],returns:"bool"},editBufferCanRedo:{args:["ptr"],returns:"bool"},editBufferClearHistory:{args:["ptr"],returns:"void"},editBufferClear:{args:["ptr"],returns:"void"},editBufferGetNextWordBoundary:{args:["ptr","ptr"],returns:"void"},editBufferGetPrevWordBoundary:{args:["ptr","ptr"],returns:"void"},editBufferGetEOL:{args:["ptr","ptr"],returns:"void"},editBufferOffsetToPosition:{args:["ptr","u32","ptr"],returns:"bool"},editBufferPositionToOffset:{args:["ptr","u32","u32"],returns:"u32"},editBufferGetLineStartOffset:{args:["ptr","u32"],returns:"u32"},editBufferGetTextRange:{args:["ptr","u32","u32","ptr","usize"],returns:"usize"},editBufferGetTextRangeByCoords:{args:["ptr","u32","u32","u32","u32","ptr","usize"],returns:"usize"},editorViewSetSelection:{args:["ptr","u32","u32","ptr","ptr"],returns:"void"},editorViewResetSelection:{args:["ptr"],returns:"void"},editorViewGetSelection:{args:["ptr"],returns:"u64"},editorViewSetLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr","bool","bool"],returns:"bool"},editorViewUpdateSelection:{args:["ptr","u32","ptr","ptr"],returns:"void"},editorViewUpdateLocalSelection:{args:["ptr","i32","i32","i32","i32","ptr","ptr","bool","bool"],returns:"bool"},editorViewResetLocalSelection:{args:["ptr"],returns:"void"},editorViewGetSelectedTextBytes:{args:["ptr","ptr","usize"],returns:"usize"},editorViewGetCursor:{args:["ptr","ptr","ptr"],returns:"void"},editorViewGetText:{args:["ptr","ptr","usize"],returns:"usize"},editorViewGetVisualCursor:{args:["ptr","ptr"],returns:"void"},editorViewMoveUpVisual:{args:["ptr"],returns:"void"},editorViewMoveDownVisual:{args:["ptr"],returns:"void"},editorViewDeleteSelectedText:{args:["ptr"],returns:"void"},editorViewSetCursorByOffset:{args:["ptr","u32"],returns:"void"},editorViewGetNextWordBoundary:{args:["ptr","ptr"],returns:"void"},editorViewGetPrevWordBoundary:{args:["ptr","ptr"],returns:"void"},editorViewGetEOL:{args:["ptr","ptr"],returns:"void"},editorViewGetVisualSOL:{args:["ptr","ptr"],returns:"void"},editorViewGetVisualEOL:{args:["ptr","ptr"],returns:"void"},editorViewSetPlaceholderStyledText:{args:["ptr","ptr","usize"],returns:"void"},editorViewSetTabIndicator:{args:["ptr","u32"],returns:"void"},editorViewSetTabIndicatorColor:{args:["ptr","ptr"],returns:"void"},getArenaAllocatedBytes:{args:[],returns:"usize"},getBuildOptions:{args:["ptr"],returns:"void"},getAllocatorStats:{args:["ptr"],returns:"void"},createSyntaxStyle:{args:[],returns:"ptr"},destroySyntaxStyle:{args:["ptr"],returns:"void"},syntaxStyleRegister:{args:["ptr","ptr","usize","ptr","ptr","u8"],returns:"u32"},syntaxStyleResolveByName:{args:["ptr","ptr","usize"],returns:"u32"},syntaxStyleGetStyleCount:{args:["ptr"],returns:"usize"},getTerminalCapabilities:{args:["ptr","ptr"],returns:"void"},processCapabilityResponse:{args:["ptr","ptr","usize"],returns:"void"},encodeUnicode:{args:["ptr","usize","ptr","ptr","u8"],returns:"bool"},freeUnicode:{args:["ptr","usize"],returns:"void"},bufferDrawChar:{args:["ptr","u32","u32","u32","ptr","ptr","u32"],returns:"void"},createNativeSpanFeed:{args:["ptr"],returns:"ptr"},attachNativeSpanFeed:{args:["ptr"],returns:"i32"},destroyNativeSpanFeed:{args:["ptr"],returns:"void"},streamWrite:{args:["ptr","ptr","u64"],returns:"i32"},streamCommit:{args:["ptr"],returns:"i32"},streamDrainSpans:{args:["ptr","ptr","u32"],returns:"u32"},streamClose:{args:["ptr"],returns:"i32"},streamReserve:{args:["ptr","u32","ptr"],returns:"i32"},streamCommitReserved:{args:["ptr","u32"],returns:"i32"},streamSetOptions:{args:["ptr","ptr"],returns:"i32"},streamGetStats:{args:["ptr","ptr"],returns:"i32"},streamSetCallback:{args:["ptr","ptr"],returns:"void"}});if(env.OTUI_DEBUG_FFI||env.OTUI_TRACE_FFI)return{symbols:convertToDebugSymbols(rawSymbols.symbols)};return rawSymbols}function convertToDebugSymbols(symbols){if(!globalTraceSymbols)globalTraceSymbols={};if(env.OTUI_DEBUG_FFI&&!globalFFILogPath)globalFFILogPath=`ffi_otui_debug_${new Date().toISOString().replace(/[:.]/g,"-").replace(/T/,"_").split("Z")[0]}.log`;let debugSymbols={},hasTracing=!1;if(Object.entries(symbols).forEach(([key,value])=>{debugSymbols[key]=value}),env.OTUI_DEBUG_FFI&&globalFFILogPath){let logPath=globalFFILogPath,writeSync=(msg)=>{writeFileSync23(logPath,msg+`
2265
2273
  `,{flag:"a"})};Object.entries(symbols).forEach(([key,value])=>{if(typeof value==="function")debugSymbols[key]=(...args)=>{writeSync(`${key}(${args.map((arg)=>String(arg)).join(", ")})`);let result2=value(...args);return writeSync(`${key} returned: ${String(result2)}`),result2}})}if(env.OTUI_TRACE_FFI)hasTracing=!0,Object.entries(symbols).forEach(([key,value])=>{if(typeof value==="function"){if(!globalTraceSymbols[key])globalTraceSymbols[key]=[];let originalFunc=debugSymbols[key];debugSymbols[key]=(...args)=>{let start2=performance.now(),result2=originalFunc(...args),end=performance.now();return globalTraceSymbols[key].push(end-start2),result2}}});if((env.OTUI_DEBUG_FFI||env.OTUI_TRACE_FFI)&&!exitHandlerRegistered2)exitHandlerRegistered2=!0,process.on("exit",()=>{if(globalTraceSymbols){let allStats=[];for(let[key,timings]of Object.entries(globalTraceSymbols)){if(!Array.isArray(timings)||timings.length===0)continue;let sortedTimings=[...timings].sort((a,b2)=>a-b2),count=sortedTimings.length,total=sortedTimings.reduce((acc,t2)=>acc+t2,0),average=total/count,min=sortedTimings[0],max=sortedTimings[count-1],medianIndex=Math.floor(count/2),p90Index=Math.floor(count*0.9),p99Index=Math.floor(count*0.99),median=sortedTimings[medianIndex],p90=sortedTimings[Math.min(p90Index,count-1)],p99=sortedTimings[Math.min(p99Index,count-1)];allStats.push({name:key,count,total,average,min,max,median,p90,p99})}allStats.sort((a,b2)=>b2.total-a.total);let lines=[];if(lines.push(`
2266
2274
  --- OpenTUI FFI Call Performance ---`),lines.push("Sorted by total time spent (descending)"),lines.push("-------------------------------------------------------------------------------------------------------------------------"),allStats.length===0)lines.push("No trace data collected or all symbols had zero calls.");else{let nameWidth=Math.max(6,...allStats.map((s2)=>s2.name.length)),countWidth=Math.max(5,...allStats.map((s2)=>String(s2.count).length)),totalWidth=Math.max(10,...allStats.map((s2)=>s2.total.toFixed(2).length)),avgWidth=Math.max(8,...allStats.map((s2)=>s2.average.toFixed(2).length)),statWidthMin=Math.max(8,...allStats.map((s2)=>s2.min.toFixed(2).length)),statWidthMax=Math.max(8,...allStats.map((s2)=>s2.max.toFixed(2).length)),medianWidth=Math.max(8,...allStats.map((s2)=>s2.median.toFixed(2).length)),p90Width=Math.max(8,...allStats.map((s2)=>s2.p90.toFixed(2).length)),p99Width=Math.max(8,...allStats.map((s2)=>s2.p99.toFixed(2).length));lines.push(`${"Symbol".padEnd(nameWidth)} | ${"Calls".padStart(countWidth)} | ${"Total (ms)".padStart(totalWidth)} | ${"Avg (ms)".padStart(avgWidth)} | ${"Min (ms)".padStart(statWidthMin)} | ${"Max (ms)".padStart(statWidthMax)} | ${"Med (ms)".padStart(medianWidth)} | ${"P90 (ms)".padStart(p90Width)} | ${"P99 (ms)".padStart(p99Width)}`),lines.push(`${"-".repeat(nameWidth)}-+-${"-".repeat(countWidth)}-+-${"-".repeat(totalWidth)}-+-${"-".repeat(avgWidth)}-+-${"-".repeat(statWidthMin)}-+-${"-".repeat(statWidthMax)}-+-${"-".repeat(medianWidth)}-+-${"-".repeat(p90Width)}-+-${"-".repeat(p99Width)}`),allStats.forEach((stat6)=>{lines.push(`${stat6.name.padEnd(nameWidth)} | ${String(stat6.count).padStart(countWidth)} | ${stat6.total.toFixed(2).padStart(totalWidth)} | ${stat6.average.toFixed(2).padStart(avgWidth)} | ${stat6.min.toFixed(2).padStart(statWidthMin)} | ${stat6.max.toFixed(2).padStart(statWidthMax)} | ${stat6.median.toFixed(2).padStart(medianWidth)} | ${stat6.p90.toFixed(2).padStart(p90Width)} | ${stat6.p99.toFixed(2).padStart(p99Width)}`)})}lines.push("-------------------------------------------------------------------------------------------------------------------------");let output=lines.join(`
2267
2275
  `);console.log(output);try{let traceFilePath=`ffi_otui_trace_${new Date().toISOString().replace(/[:.]/g,"-").replace(/T/,"_").split("Z")[0]}.log`;Bun.write(traceFilePath,output)}catch(e){console.error("Failed to write FFI trace file:",e)}}});return debugSymbols}class FFIRenderLib{opentui;encoder=new TextEncoder;decoder=new TextDecoder;logCallbackWrapper;eventCallbackWrapper;_nativeEvents=new EventEmitter4;_anyEventHandlers=[];nativeSpanFeedCallbackWrapper=null;nativeSpanFeedHandlers=new Map;constructor(libPath){this.opentui=getOpenTUILib(libPath),this.setupLogging(),this.setupEventBus()}setupLogging(){if(this.logCallbackWrapper)return;let logCallback=new JSCallback((level,msgPtr,msgLenBigInt)=>{try{let msgLen=typeof msgLenBigInt==="bigint"?Number(msgLenBigInt):msgLenBigInt;if(msgLen===0||!msgPtr)return;let msgBuffer=toArrayBuffer4(msgPtr,0,msgLen),msgBytes=new Uint8Array(msgBuffer),message=this.decoder.decode(msgBytes);switch(level){case 0:console.error(message);break;case 1:console.warn(message);break;case 2:console.info(message);break;case 3:console.debug(message);break;default:console.log(message)}}catch(error2){console.error("Error in Zig log callback:",error2)}},{args:["u8","ptr","usize"],returns:"void"});if(this.logCallbackWrapper=logCallback,!logCallback.ptr)throw Error("Failed to create log callback");this.setLogCallback(logCallback.ptr)}setLogCallback(callbackPtr){this.opentui.symbols.setLogCallback(callbackPtr)}setupEventBus(){if(this.eventCallbackWrapper)return;let eventCallback=new JSCallback((namePtr,nameLenBigInt,dataPtr,dataLenBigInt)=>{try{let nameLen=typeof nameLenBigInt==="bigint"?Number(nameLenBigInt):nameLenBigInt,dataLen=typeof dataLenBigInt==="bigint"?Number(dataLenBigInt):dataLenBigInt;if(nameLen===0||!namePtr)return;let nameBuffer=toArrayBuffer4(namePtr,0,nameLen),nameBytes=new Uint8Array(nameBuffer),eventName=this.decoder.decode(nameBytes),eventData;if(dataLen>0&&dataPtr)eventData=toArrayBuffer4(dataPtr,0,dataLen).slice();else eventData=new ArrayBuffer(0);queueMicrotask(()=>{this._nativeEvents.emit(eventName,eventData);for(let handler of this._anyEventHandlers)handler(eventName,eventData)})}catch(error2){console.error("Error in native event callback:",error2)}},{args:["ptr","usize","ptr","usize"],returns:"void"});if(this.eventCallbackWrapper=eventCallback,!eventCallback.ptr)throw Error("Failed to create event callback");this.setEventCallback(eventCallback.ptr)}ensureNativeSpanFeedCallback(){if(this.nativeSpanFeedCallbackWrapper)return this.nativeSpanFeedCallbackWrapper;let callback=new JSCallback((streamPtr,eventId,arg0,arg1)=>{let handler=this.nativeSpanFeedHandlers.get(toPointer(streamPtr));if(handler)handler(eventId,arg0,arg1)},{args:["ptr","u32","ptr","u64"],returns:"void"});if(this.nativeSpanFeedCallbackWrapper=callback,!callback.ptr)throw Error("Failed to create native span feed callback");return callback}setEventCallback(callbackPtr){this.opentui.symbols.setEventCallback(callbackPtr)}createRenderer(width,height2,options={}){let testing=options.testing??!1,remote=options.remote??!1;return this.opentui.symbols.createRenderer(width,height2,testing,remote)}setTerminalEnvVar(renderer,key,value){let keyBytes=this.encoder.encode(key),valueBytes=this.encoder.encode(value);return this.opentui.symbols.setTerminalEnvVar(renderer,keyBytes,keyBytes.length,valueBytes,valueBytes.length)}destroyRenderer(renderer){this.opentui.symbols.destroyRenderer(renderer)}setUseThread(renderer,useThread){this.opentui.symbols.setUseThread(renderer,useThread)}setBackgroundColor(renderer,color2){this.opentui.symbols.setBackgroundColor(renderer,color2.buffer)}setRenderOffset(renderer,offset){this.opentui.symbols.setRenderOffset(renderer,offset)}updateStats(renderer,time,fps,frameCallbackTime){this.opentui.symbols.updateStats(renderer,time,fps,frameCallbackTime)}updateMemoryStats(renderer,heapUsed,heapTotal,arrayBuffers){this.opentui.symbols.updateMemoryStats(renderer,heapUsed,heapTotal,arrayBuffers)}getNextBuffer(renderer){let bufferPtr=this.opentui.symbols.getNextBuffer(renderer);if(!bufferPtr)throw Error("Failed to get next buffer");let width=this.opentui.symbols.getBufferWidth(bufferPtr),height2=this.opentui.symbols.getBufferHeight(bufferPtr);return new OptimizedBuffer(this,bufferPtr,width,height2,{id:"next buffer",widthMethod:"unicode"})}getCurrentBuffer(renderer){let bufferPtr=this.opentui.symbols.getCurrentBuffer(renderer);if(!bufferPtr)throw Error("Failed to get current buffer");let width=this.opentui.symbols.getBufferWidth(bufferPtr),height2=this.opentui.symbols.getBufferHeight(bufferPtr);return new OptimizedBuffer(this,bufferPtr,width,height2,{id:"current buffer",widthMethod:"unicode"})}bufferGetCharPtr(buffer2){let ptr5=this.opentui.symbols.bufferGetCharPtr(buffer2);if(!ptr5)throw Error("Failed to get char pointer");return ptr5}bufferGetFgPtr(buffer2){let ptr5=this.opentui.symbols.bufferGetFgPtr(buffer2);if(!ptr5)throw Error("Failed to get fg pointer");return ptr5}bufferGetBgPtr(buffer2){let ptr5=this.opentui.symbols.bufferGetBgPtr(buffer2);if(!ptr5)throw Error("Failed to get bg pointer");return ptr5}bufferGetAttributesPtr(buffer2){let ptr5=this.opentui.symbols.bufferGetAttributesPtr(buffer2);if(!ptr5)throw Error("Failed to get attributes pointer");return ptr5}bufferGetRespectAlpha(buffer2){return this.opentui.symbols.bufferGetRespectAlpha(buffer2)}bufferSetRespectAlpha(buffer2,respectAlpha){this.opentui.symbols.bufferSetRespectAlpha(buffer2,respectAlpha)}bufferGetId(buffer2){let outBuffer=new Uint8Array(256),actualLen=this.opentui.symbols.bufferGetId(buffer2,outBuffer,256),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;return this.decoder.decode(outBuffer.slice(0,len))}bufferGetRealCharSize(buffer2){return this.opentui.symbols.bufferGetRealCharSize(buffer2)}bufferWriteResolvedChars(buffer2,outputBuffer,addLineBreaks){let bytesWritten=this.opentui.symbols.bufferWriteResolvedChars(buffer2,outputBuffer,outputBuffer.length,addLineBreaks);return typeof bytesWritten==="bigint"?Number(bytesWritten):bytesWritten}getBufferWidth(buffer2){return this.opentui.symbols.getBufferWidth(buffer2)}getBufferHeight(buffer2){return this.opentui.symbols.getBufferHeight(buffer2)}bufferClear(buffer2,color2){this.opentui.symbols.bufferClear(buffer2,color2.buffer)}bufferDrawText(buffer2,text,x,y,color2,bgColor,attributes){let textBytes=this.encoder.encode(text),textLength=textBytes.byteLength,bg2=bgColor?bgColor.buffer:null,fg2=color2.buffer;this.opentui.symbols.bufferDrawText(buffer2,textBytes,textLength,x,y,fg2,bg2,attributes??0)}bufferSetCellWithAlphaBlending(buffer2,x,y,char,color2,bgColor,attributes){let charPtr=char.codePointAt(0)??" ".codePointAt(0),bg2=bgColor.buffer,fg2=color2.buffer;this.opentui.symbols.bufferSetCellWithAlphaBlending(buffer2,x,y,charPtr,fg2,bg2,attributes??0)}bufferSetCell(buffer2,x,y,char,color2,bgColor,attributes){let charPtr=char.codePointAt(0)??" ".codePointAt(0),bg2=bgColor.buffer,fg2=color2.buffer;this.opentui.symbols.bufferSetCell(buffer2,x,y,charPtr,fg2,bg2,attributes??0)}bufferFillRect(buffer2,x,y,width,height2,color2){let bg2=color2.buffer;this.opentui.symbols.bufferFillRect(buffer2,x,y,width,height2,bg2)}bufferColorMatrix(buffer2,matrixPtr,cellMaskPtr,cellMaskCount,strength,target){this.opentui.symbols.bufferColorMatrix(buffer2,matrixPtr,cellMaskPtr,cellMaskCount,strength,target)}bufferColorMatrixUniform(buffer2,matrixPtr,strength,target){this.opentui.symbols.bufferColorMatrixUniform(buffer2,matrixPtr,strength,target)}bufferDrawSuperSampleBuffer(buffer2,x,y,pixelDataPtr,pixelDataLength,format,alignedBytesPerRow){let formatId=format==="bgra8unorm"?0:1;this.opentui.symbols.bufferDrawSuperSampleBuffer(buffer2,x,y,pixelDataPtr,pixelDataLength,formatId,alignedBytesPerRow)}bufferDrawPackedBuffer(buffer2,dataPtr,dataLen,posX,posY,terminalWidthCells,terminalHeightCells){this.opentui.symbols.bufferDrawPackedBuffer(buffer2,dataPtr,dataLen,posX,posY,terminalWidthCells,terminalHeightCells)}bufferDrawGrayscaleBuffer(buffer2,posX,posY,intensitiesPtr,srcWidth,srcHeight,fg2,bg2){this.opentui.symbols.bufferDrawGrayscaleBuffer(buffer2,posX,posY,intensitiesPtr,srcWidth,srcHeight,fg2?.buffer??null,bg2?.buffer??null)}bufferDrawGrayscaleBufferSupersampled(buffer2,posX,posY,intensitiesPtr,srcWidth,srcHeight,fg2,bg2){this.opentui.symbols.bufferDrawGrayscaleBufferSupersampled(buffer2,posX,posY,intensitiesPtr,srcWidth,srcHeight,fg2?.buffer??null,bg2?.buffer??null)}bufferDrawGrid(buffer2,borderChars,borderFg,borderBg,columnOffsets,columnCount,rowOffsets,rowCount,options){let optionsBuffer=GridDrawOptionsStruct.pack({drawInner:options.drawInner,drawOuter:options.drawOuter});this.opentui.symbols.bufferDrawGrid(buffer2,borderChars,borderFg.buffer,borderBg.buffer,columnOffsets,columnCount,rowOffsets,rowCount,ptr4(optionsBuffer))}bufferDrawBox(buffer2,x,y,width,height2,borderChars,packedOptions,borderColor,backgroundColor,title){let titleBytes=title?this.encoder.encode(title):null,titleLen=title?titleBytes.length:0,titlePtr=title?titleBytes:null;this.opentui.symbols.bufferDrawBox(buffer2,x,y,width,height2,borderChars,packedOptions,borderColor.buffer,backgroundColor.buffer,titlePtr,titleLen)}bufferResize(buffer2,width,height2){this.opentui.symbols.bufferResize(buffer2,width,height2)}linkAlloc(url){let urlBytes=this.encoder.encode(url);return this.opentui.symbols.linkAlloc(urlBytes,urlBytes.length)}linkGetUrl(linkId,maxLen=512){let outBuffer=new Uint8Array(maxLen),actualLen=this.opentui.symbols.linkGetUrl(linkId,outBuffer,maxLen);return this.decoder.decode(outBuffer.slice(0,actualLen))}attributesWithLink(baseAttributes,linkId){return this.opentui.symbols.attributesWithLink(baseAttributes,linkId)}attributesGetLinkId(attributes){return this.opentui.symbols.attributesGetLinkId(attributes)}resizeRenderer(renderer,width,height2){this.opentui.symbols.resizeRenderer(renderer,width,height2)}setCursorPosition(renderer,x,y,visible){this.opentui.symbols.setCursorPosition(renderer,x,y,visible)}setCursorColor(renderer,color2){this.opentui.symbols.setCursorColor(renderer,color2.buffer)}getCursorState(renderer){let cursorBuffer=new ArrayBuffer(CursorStateStruct.size);this.opentui.symbols.getCursorState(renderer,ptr4(cursorBuffer));let struct=CursorStateStruct.unpack(cursorBuffer);return{x:struct.x,y:struct.y,visible:struct.visible,style:CURSOR_ID_TO_STYLE[struct.style]??"block",blinking:struct.blinking,color:RGBA.fromValues(struct.r,struct.g,struct.b,struct.a)}}setCursorStyleOptions(renderer,options){let style=options.style!=null?CURSOR_STYLE_TO_ID[options.style]:255,blinking=options.blinking!=null?options.blinking?1:0:255,cursor=options.cursor!=null?MOUSE_STYLE_TO_ID[options.cursor]:255,buffer2=CursorStyleOptionsStruct.pack({style,blinking,color:options.color,cursor});this.opentui.symbols.setCursorStyleOptions(renderer,ptr4(buffer2))}render(renderer,force){this.opentui.symbols.render(renderer,force)}createOptimizedBuffer(width,height2,widthMethod,respectAlpha=!1,id){if(Number.isNaN(width)||Number.isNaN(height2))console.error(Error(`Invalid dimensions for OptimizedBuffer: ${width}x${height2}`).stack);let widthMethodCode=widthMethod==="wcwidth"?0:1,idToUse=id||"unnamed buffer",idBytes=this.encoder.encode(idToUse),bufferPtr=this.opentui.symbols.createOptimizedBuffer(width,height2,respectAlpha,widthMethodCode,idBytes,idBytes.length);if(!bufferPtr)throw Error(`Failed to create optimized buffer: ${width}x${height2}`);return new OptimizedBuffer(this,bufferPtr,width,height2,{respectAlpha,id,widthMethod})}destroyOptimizedBuffer(bufferPtr){this.opentui.symbols.destroyOptimizedBuffer(bufferPtr)}drawFrameBuffer(targetBufferPtr,destX,destY,bufferPtr,sourceX,sourceY,sourceWidth,sourceHeight){let srcX=sourceX??0,srcY=sourceY??0,srcWidth=sourceWidth??0,srcHeight=sourceHeight??0;this.opentui.symbols.drawFrameBuffer(targetBufferPtr,destX,destY,bufferPtr,srcX,srcY,srcWidth,srcHeight)}setDebugOverlay(renderer,enabled,corner){this.opentui.symbols.setDebugOverlay(renderer,enabled,corner)}clearTerminal(renderer){this.opentui.symbols.clearTerminal(renderer)}setTerminalTitle(renderer,title){let titleBytes=this.encoder.encode(title);this.opentui.symbols.setTerminalTitle(renderer,titleBytes,titleBytes.length)}copyToClipboardOSC52(renderer,target,payload){return this.opentui.symbols.copyToClipboardOSC52(renderer,target,payload,payload.length)}clearClipboardOSC52(renderer,target){return this.opentui.symbols.clearClipboardOSC52(renderer,target)}addToHitGrid(renderer,x,y,width,height2,id){this.opentui.symbols.addToHitGrid(renderer,x,y,width,height2,id)}clearCurrentHitGrid(renderer){this.opentui.symbols.clearCurrentHitGrid(renderer)}hitGridPushScissorRect(renderer,x,y,width,height2){this.opentui.symbols.hitGridPushScissorRect(renderer,x,y,width,height2)}hitGridPopScissorRect(renderer){this.opentui.symbols.hitGridPopScissorRect(renderer)}hitGridClearScissorRects(renderer){this.opentui.symbols.hitGridClearScissorRects(renderer)}addToCurrentHitGridClipped(renderer,x,y,width,height2,id){this.opentui.symbols.addToCurrentHitGridClipped(renderer,x,y,width,height2,id)}checkHit(renderer,x,y){return this.opentui.symbols.checkHit(renderer,x,y)}getHitGridDirty(renderer){return this.opentui.symbols.getHitGridDirty(renderer)}dumpHitGrid(renderer){this.opentui.symbols.dumpHitGrid(renderer)}dumpBuffers(renderer,timestamp2){let ts3=timestamp2??Date.now();this.opentui.symbols.dumpBuffers(renderer,ts3)}dumpStdoutBuffer(renderer,timestamp2){let ts3=timestamp2??Date.now();this.opentui.symbols.dumpStdoutBuffer(renderer,ts3)}restoreTerminalModes(renderer){this.opentui.symbols.restoreTerminalModes(renderer)}enableMouse(renderer,enableMovement){this.opentui.symbols.enableMouse(renderer,enableMovement)}disableMouse(renderer){this.opentui.symbols.disableMouse(renderer)}enableKittyKeyboard(renderer,flags){this.opentui.symbols.enableKittyKeyboard(renderer,flags)}disableKittyKeyboard(renderer){this.opentui.symbols.disableKittyKeyboard(renderer)}setKittyKeyboardFlags(renderer,flags){this.opentui.symbols.setKittyKeyboardFlags(renderer,flags)}getKittyKeyboardFlags(renderer){return this.opentui.symbols.getKittyKeyboardFlags(renderer)}setupTerminal(renderer,useAlternateScreen){this.opentui.symbols.setupTerminal(renderer,useAlternateScreen)}suspendRenderer(renderer){this.opentui.symbols.suspendRenderer(renderer)}resumeRenderer(renderer){this.opentui.symbols.resumeRenderer(renderer)}queryPixelResolution(renderer){this.opentui.symbols.queryPixelResolution(renderer)}writeOut(renderer,data){let bytes=typeof data==="string"?new TextEncoder().encode(data):data;if(bytes.length===0)return;this.opentui.symbols.writeOut(renderer,ptr4(bytes),bytes.length)}createTextBuffer(widthMethod){let widthMethodCode=widthMethod==="wcwidth"?0:1,bufferPtr=this.opentui.symbols.createTextBuffer(widthMethodCode);if(!bufferPtr)throw Error("Failed to create TextBuffer");return new TextBuffer(this,bufferPtr)}destroyTextBuffer(buffer2){this.opentui.symbols.destroyTextBuffer(buffer2)}textBufferGetLength(buffer2){return this.opentui.symbols.textBufferGetLength(buffer2)}textBufferGetByteSize(buffer2){return this.opentui.symbols.textBufferGetByteSize(buffer2)}textBufferReset(buffer2){this.opentui.symbols.textBufferReset(buffer2)}textBufferClear(buffer2){this.opentui.symbols.textBufferClear(buffer2)}textBufferSetDefaultFg(buffer2,fg2){let fgPtr=fg2?fg2.buffer:null;this.opentui.symbols.textBufferSetDefaultFg(buffer2,fgPtr)}textBufferSetDefaultBg(buffer2,bg2){let bgPtr=bg2?bg2.buffer:null;this.opentui.symbols.textBufferSetDefaultBg(buffer2,bgPtr)}textBufferSetDefaultAttributes(buffer2,attributes){let attrValue=attributes===null?null:new Uint8Array([attributes]);this.opentui.symbols.textBufferSetDefaultAttributes(buffer2,attrValue)}textBufferResetDefaults(buffer2){this.opentui.symbols.textBufferResetDefaults(buffer2)}textBufferGetTabWidth(buffer2){return this.opentui.symbols.textBufferGetTabWidth(buffer2)}textBufferSetTabWidth(buffer2,width){this.opentui.symbols.textBufferSetTabWidth(buffer2,width)}textBufferRegisterMemBuffer(buffer2,bytes,owned=!1){let result2=this.opentui.symbols.textBufferRegisterMemBuffer(buffer2,bytes,bytes.length,owned);if(result2===65535)throw Error("Failed to register memory buffer");return result2}textBufferReplaceMemBuffer(buffer2,memId,bytes,owned=!1){return this.opentui.symbols.textBufferReplaceMemBuffer(buffer2,memId,bytes,bytes.length,owned)}textBufferClearMemRegistry(buffer2){this.opentui.symbols.textBufferClearMemRegistry(buffer2)}textBufferSetTextFromMem(buffer2,memId){this.opentui.symbols.textBufferSetTextFromMem(buffer2,memId)}textBufferAppend(buffer2,bytes){this.opentui.symbols.textBufferAppend(buffer2,bytes,bytes.length)}textBufferAppendFromMemId(buffer2,memId){this.opentui.symbols.textBufferAppendFromMemId(buffer2,memId)}textBufferLoadFile(buffer2,path52){let pathBytes=this.encoder.encode(path52);return this.opentui.symbols.textBufferLoadFile(buffer2,pathBytes,pathBytes.length)}textBufferSetStyledText(buffer2,chunks){if(chunks.length===0){this.textBufferClear(buffer2);return}let chunksBuffer=StyledChunkStruct.packList(chunks);this.opentui.symbols.textBufferSetStyledText(buffer2,ptr4(chunksBuffer),chunks.length)}textBufferGetLineCount(buffer2){return this.opentui.symbols.textBufferGetLineCount(buffer2)}textBufferGetPlainText(buffer2,outPtr,maxLen){let result2=this.opentui.symbols.textBufferGetPlainText(buffer2,outPtr,maxLen);return typeof result2==="bigint"?Number(result2):result2}getPlainTextBytes(buffer2,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.textBufferGetPlainText(buffer2,ptr4(outBuffer),maxLength);if(actualLen===0)return null;return outBuffer.slice(0,actualLen)}textBufferGetTextRange(buffer2,startOffset,endOffset,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.textBufferGetTextRange(buffer2,startOffset,endOffset,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}textBufferGetTextRangeByCoords(buffer2,startRow,startCol,endRow,endCol,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.textBufferGetTextRangeByCoords(buffer2,startRow,startCol,endRow,endCol,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}createTextBufferView(textBuffer){let viewPtr=this.opentui.symbols.createTextBufferView(textBuffer);if(!viewPtr)throw Error("Failed to create TextBufferView");return viewPtr}destroyTextBufferView(view){this.opentui.symbols.destroyTextBufferView(view)}textBufferViewSetSelection(view,start2,end,bgColor,fgColor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;this.opentui.symbols.textBufferViewSetSelection(view,start2,end,bg2,fg2)}textBufferViewResetSelection(view){this.opentui.symbols.textBufferViewResetSelection(view)}textBufferViewGetSelection(view){let packedInfo=this.textBufferViewGetSelectionInfo(view);if(packedInfo===0xffff_ffff_ffff_ffffn)return null;let start2=Number(packedInfo>>32n),end=Number(packedInfo&0xffff_ffffn);return{start:start2,end}}textBufferViewGetSelectionInfo(view){return this.opentui.symbols.textBufferViewGetSelectionInfo(view)}textBufferViewSetLocalSelection(view,anchorX,anchorY,focusX,focusY,bgColor,fgColor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;return this.opentui.symbols.textBufferViewSetLocalSelection(view,anchorX,anchorY,focusX,focusY,bg2,fg2)}textBufferViewUpdateSelection(view,end,bgColor,fgColor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;this.opentui.symbols.textBufferViewUpdateSelection(view,end,bg2,fg2)}textBufferViewUpdateLocalSelection(view,anchorX,anchorY,focusX,focusY,bgColor,fgColor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;return this.opentui.symbols.textBufferViewUpdateLocalSelection(view,anchorX,anchorY,focusX,focusY,bg2,fg2)}textBufferViewResetLocalSelection(view){this.opentui.symbols.textBufferViewResetLocalSelection(view)}textBufferViewSetWrapWidth(view,width){this.opentui.symbols.textBufferViewSetWrapWidth(view,width)}textBufferViewSetWrapMode(view,mode){let modeValue=mode==="none"?0:mode==="char"?1:2;this.opentui.symbols.textBufferViewSetWrapMode(view,modeValue)}textBufferViewSetViewportSize(view,width,height2){this.opentui.symbols.textBufferViewSetViewportSize(view,width,height2)}textBufferViewSetViewport(view,x,y,width,height2){this.opentui.symbols.textBufferViewSetViewport(view,x,y,width,height2)}textBufferViewGetLineInfo(view){let outBuffer=new ArrayBuffer(LineInfoStruct.size);this.textBufferViewGetLineInfoDirect(view,ptr4(outBuffer));let struct=LineInfoStruct.unpack(outBuffer),lineStartCols=struct.startCols,lineWidthCols=struct.widthCols,lineWidthColsMax=struct.widthColsMax;return{lineStartCols,lineWidthCols,lineWidthColsMax,lineSources:struct.sources,lineWraps:struct.wraps}}textBufferViewGetLogicalLineInfo(view){let outBuffer=new ArrayBuffer(LineInfoStruct.size);this.textBufferViewGetLogicalLineInfoDirect(view,ptr4(outBuffer));let struct=LineInfoStruct.unpack(outBuffer),lineStartCols=struct.startCols,lineWidthCols=struct.widthCols,lineWidthColsMax=struct.widthColsMax;return{lineStartCols,lineWidthCols,lineWidthColsMax,lineSources:struct.sources,lineWraps:struct.wraps}}textBufferViewGetVirtualLineCount(view){return this.opentui.symbols.textBufferViewGetVirtualLineCount(view)}textBufferViewGetLineInfoDirect(view,outPtr){this.opentui.symbols.textBufferViewGetLineInfoDirect(view,outPtr)}textBufferViewGetLogicalLineInfoDirect(view,outPtr){this.opentui.symbols.textBufferViewGetLogicalLineInfoDirect(view,outPtr)}textBufferViewGetSelectedText(view,outPtr,maxLen){let result2=this.opentui.symbols.textBufferViewGetSelectedText(view,outPtr,maxLen);return typeof result2==="bigint"?Number(result2):result2}textBufferViewGetPlainText(view,outPtr,maxLen){let result2=this.opentui.symbols.textBufferViewGetPlainText(view,outPtr,maxLen);return typeof result2==="bigint"?Number(result2):result2}textBufferViewGetSelectedTextBytes(view,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.textBufferViewGetSelectedText(view,ptr4(outBuffer),maxLength);if(actualLen===0)return null;return outBuffer.slice(0,actualLen)}textBufferViewGetPlainTextBytes(view,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.textBufferViewGetPlainText(view,ptr4(outBuffer),maxLength);if(actualLen===0)return null;return outBuffer.slice(0,actualLen)}textBufferViewSetTabIndicator(view,indicator){this.opentui.symbols.textBufferViewSetTabIndicator(view,indicator)}textBufferViewSetTabIndicatorColor(view,color2){this.opentui.symbols.textBufferViewSetTabIndicatorColor(view,color2.buffer)}textBufferViewSetTruncate(view,truncate5){this.opentui.symbols.textBufferViewSetTruncate(view,truncate5)}textBufferViewMeasureForDimensions(view,width,height2){let resultBuffer=new ArrayBuffer(MeasureResultStruct.size),resultPtr=ptr4(new Uint8Array(resultBuffer));if(!this.opentui.symbols.textBufferViewMeasureForDimensions(view,width,height2,resultPtr))return null;return MeasureResultStruct.unpack(resultBuffer)}textBufferAddHighlightByCharRange(buffer2,highlight){let packedHighlight=HighlightStruct.pack(highlight);this.opentui.symbols.textBufferAddHighlightByCharRange(buffer2,ptr4(packedHighlight))}textBufferAddHighlight(buffer2,lineIdx,highlight){let packedHighlight=HighlightStruct.pack(highlight);this.opentui.symbols.textBufferAddHighlight(buffer2,lineIdx,ptr4(packedHighlight))}textBufferRemoveHighlightsByRef(buffer2,hlRef){this.opentui.symbols.textBufferRemoveHighlightsByRef(buffer2,hlRef)}textBufferClearLineHighlights(buffer2,lineIdx){this.opentui.symbols.textBufferClearLineHighlights(buffer2,lineIdx)}textBufferClearAllHighlights(buffer2){this.opentui.symbols.textBufferClearAllHighlights(buffer2)}textBufferSetSyntaxStyle(buffer2,style){this.opentui.symbols.textBufferSetSyntaxStyle(buffer2,style)}textBufferGetLineHighlights(buffer2,lineIdx){let outCountBuf=new BigUint64Array(1),nativePtr=this.opentui.symbols.textBufferGetLineHighlightsPtr(buffer2,lineIdx,ptr4(outCountBuf));if(!nativePtr)return[];let count=Number(outCountBuf[0]),byteLen=count*HighlightStruct.size,raw=toArrayBuffer4(nativePtr,0,byteLen),results=HighlightStruct.unpackList(raw,count);return this.opentui.symbols.textBufferFreeLineHighlights(nativePtr,count),results}textBufferGetHighlightCount(buffer2){return this.opentui.symbols.textBufferGetHighlightCount(buffer2)}getArenaAllocatedBytes(){let result2=this.opentui.symbols.getArenaAllocatedBytes();return typeof result2==="bigint"?Number(result2):result2}getBuildOptions(){let optionsBuffer=new ArrayBuffer(BuildOptionsStruct.size);this.opentui.symbols.getBuildOptions(ptr4(optionsBuffer));let options=BuildOptionsStruct.unpack(optionsBuffer);return{gpaSafeStats:!!options.gpaSafeStats,gpaMemoryLimitTracking:!!options.gpaMemoryLimitTracking}}getAllocatorStats(){let statsBuffer=new ArrayBuffer(AllocatorStatsStruct.size);this.opentui.symbols.getAllocatorStats(ptr4(statsBuffer));let stats=AllocatorStatsStruct.unpack(statsBuffer);return{totalRequestedBytes:toNumber(stats.totalRequestedBytes),activeAllocations:toNumber(stats.activeAllocations),smallAllocations:toNumber(stats.smallAllocations),largeAllocations:toNumber(stats.largeAllocations),requestedBytesValid:!!stats.requestedBytesValid}}bufferDrawTextBufferView(buffer2,view,x,y){this.opentui.symbols.bufferDrawTextBufferView(buffer2,view,x,y)}bufferDrawEditorView(buffer2,view,x,y){this.opentui.symbols.bufferDrawEditorView(buffer2,view,x,y)}createEditorView(editBufferPtr,viewportWidth,viewportHeight){let viewPtr=this.opentui.symbols.createEditorView(editBufferPtr,viewportWidth,viewportHeight);if(!viewPtr)throw Error("Failed to create EditorView");return viewPtr}destroyEditorView(view){this.opentui.symbols.destroyEditorView(view)}editorViewSetViewportSize(view,width,height2){this.opentui.symbols.editorViewSetViewportSize(view,width,height2)}editorViewSetViewport(view,x,y,width,height2,moveCursor){this.opentui.symbols.editorViewSetViewport(view,x,y,width,height2,moveCursor)}editorViewGetViewport(view){let x=new Uint32Array(1),y=new Uint32Array(1),width=new Uint32Array(1),height2=new Uint32Array(1);return this.opentui.symbols.editorViewGetViewport(view,ptr4(x),ptr4(y),ptr4(width),ptr4(height2)),{offsetX:x[0],offsetY:y[0],width:width[0],height:height2[0]}}editorViewSetScrollMargin(view,margin){this.opentui.symbols.editorViewSetScrollMargin(view,margin)}editorViewSetWrapMode(view,mode){let modeValue=mode==="none"?0:mode==="char"?1:2;this.opentui.symbols.editorViewSetWrapMode(view,modeValue)}editorViewGetVirtualLineCount(view){return this.opentui.symbols.editorViewGetVirtualLineCount(view)}editorViewGetTotalVirtualLineCount(view){return this.opentui.symbols.editorViewGetTotalVirtualLineCount(view)}editorViewGetTextBufferView(view){let result2=this.opentui.symbols.editorViewGetTextBufferView(view);if(!result2)throw Error("Failed to get TextBufferView from EditorView");return result2}editorViewGetLineInfo(view){let outBuffer=new ArrayBuffer(LineInfoStruct.size);this.opentui.symbols.editorViewGetLineInfoDirect(view,ptr4(outBuffer));let struct=LineInfoStruct.unpack(outBuffer),lineStartCols=struct.startCols,lineWidthCols=struct.widthCols,lineWidthColsMax=struct.widthColsMax;return{lineStartCols,lineWidthCols,lineWidthColsMax,lineSources:struct.sources,lineWraps:struct.wraps}}editorViewGetLogicalLineInfo(view){let outBuffer=new ArrayBuffer(LineInfoStruct.size);this.opentui.symbols.editorViewGetLogicalLineInfoDirect(view,ptr4(outBuffer));let struct=LineInfoStruct.unpack(outBuffer),lineStartCols=struct.startCols,lineWidthCols=struct.widthCols,lineWidthColsMax=struct.widthColsMax;return{lineStartCols,lineWidthCols,lineWidthColsMax,lineSources:struct.sources,lineWraps:struct.wraps}}createEditBuffer(widthMethod){let widthMethodCode=widthMethod==="wcwidth"?0:1,bufferPtr=this.opentui.symbols.createEditBuffer(widthMethodCode);if(!bufferPtr)throw Error("Failed to create EditBuffer");return bufferPtr}destroyEditBuffer(buffer2){this.opentui.symbols.destroyEditBuffer(buffer2)}editBufferSetText(buffer2,textBytes){this.opentui.symbols.editBufferSetText(buffer2,textBytes,textBytes.length)}editBufferSetTextFromMem(buffer2,memId){this.opentui.symbols.editBufferSetTextFromMem(buffer2,memId)}editBufferReplaceText(buffer2,textBytes){this.opentui.symbols.editBufferReplaceText(buffer2,textBytes,textBytes.length)}editBufferReplaceTextFromMem(buffer2,memId){this.opentui.symbols.editBufferReplaceTextFromMem(buffer2,memId)}editBufferGetText(buffer2,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.editBufferGetText(buffer2,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}editBufferInsertChar(buffer2,char){let charBytes=this.encoder.encode(char);this.opentui.symbols.editBufferInsertChar(buffer2,charBytes,charBytes.length)}editBufferInsertText(buffer2,text){let textBytes=this.encoder.encode(text);this.opentui.symbols.editBufferInsertText(buffer2,textBytes,textBytes.length)}editBufferDeleteChar(buffer2){this.opentui.symbols.editBufferDeleteChar(buffer2)}editBufferDeleteCharBackward(buffer2){this.opentui.symbols.editBufferDeleteCharBackward(buffer2)}editBufferDeleteRange(buffer2,startLine,startCol,endLine,endCol){this.opentui.symbols.editBufferDeleteRange(buffer2,startLine,startCol,endLine,endCol)}editBufferNewLine(buffer2){this.opentui.symbols.editBufferNewLine(buffer2)}editBufferDeleteLine(buffer2){this.opentui.symbols.editBufferDeleteLine(buffer2)}editBufferMoveCursorLeft(buffer2){this.opentui.symbols.editBufferMoveCursorLeft(buffer2)}editBufferMoveCursorRight(buffer2){this.opentui.symbols.editBufferMoveCursorRight(buffer2)}editBufferMoveCursorUp(buffer2){this.opentui.symbols.editBufferMoveCursorUp(buffer2)}editBufferMoveCursorDown(buffer2){this.opentui.symbols.editBufferMoveCursorDown(buffer2)}editBufferGotoLine(buffer2,line){this.opentui.symbols.editBufferGotoLine(buffer2,line)}editBufferSetCursor(buffer2,line,byteOffset){this.opentui.symbols.editBufferSetCursor(buffer2,line,byteOffset)}editBufferSetCursorToLineCol(buffer2,line,col){this.opentui.symbols.editBufferSetCursorToLineCol(buffer2,line,col)}editBufferSetCursorByOffset(buffer2,offset){this.opentui.symbols.editBufferSetCursorByOffset(buffer2,offset)}editBufferGetCursorPosition(buffer2){let cursorBuffer=new ArrayBuffer(LogicalCursorStruct.size);return this.opentui.symbols.editBufferGetCursorPosition(buffer2,ptr4(cursorBuffer)),LogicalCursorStruct.unpack(cursorBuffer)}editBufferGetId(buffer2){return this.opentui.symbols.editBufferGetId(buffer2)}editBufferGetTextBuffer(buffer2){let result2=this.opentui.symbols.editBufferGetTextBuffer(buffer2);if(!result2)throw Error("Failed to get TextBuffer from EditBuffer");return result2}editBufferDebugLogRope(buffer2){this.opentui.symbols.editBufferDebugLogRope(buffer2)}editBufferUndo(buffer2,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.editBufferUndo(buffer2,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}editBufferRedo(buffer2,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.editBufferRedo(buffer2,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}editBufferCanUndo(buffer2){return this.opentui.symbols.editBufferCanUndo(buffer2)}editBufferCanRedo(buffer2){return this.opentui.symbols.editBufferCanRedo(buffer2)}editBufferClearHistory(buffer2){this.opentui.symbols.editBufferClearHistory(buffer2)}editBufferClear(buffer2){this.opentui.symbols.editBufferClear(buffer2)}editBufferGetNextWordBoundary(buffer2){let cursorBuffer=new ArrayBuffer(LogicalCursorStruct.size);return this.opentui.symbols.editBufferGetNextWordBoundary(buffer2,ptr4(cursorBuffer)),LogicalCursorStruct.unpack(cursorBuffer)}editBufferGetPrevWordBoundary(buffer2){let cursorBuffer=new ArrayBuffer(LogicalCursorStruct.size);return this.opentui.symbols.editBufferGetPrevWordBoundary(buffer2,ptr4(cursorBuffer)),LogicalCursorStruct.unpack(cursorBuffer)}editBufferGetEOL(buffer2){let cursorBuffer=new ArrayBuffer(LogicalCursorStruct.size);return this.opentui.symbols.editBufferGetEOL(buffer2,ptr4(cursorBuffer)),LogicalCursorStruct.unpack(cursorBuffer)}editBufferOffsetToPosition(buffer2,offset){let cursorBuffer=new ArrayBuffer(LogicalCursorStruct.size);if(!this.opentui.symbols.editBufferOffsetToPosition(buffer2,offset,ptr4(cursorBuffer)))return null;return LogicalCursorStruct.unpack(cursorBuffer)}editBufferPositionToOffset(buffer2,row,col){return this.opentui.symbols.editBufferPositionToOffset(buffer2,row,col)}editBufferGetLineStartOffset(buffer2,row){return this.opentui.symbols.editBufferGetLineStartOffset(buffer2,row)}editBufferGetTextRange(buffer2,startOffset,endOffset,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.editBufferGetTextRange(buffer2,startOffset,endOffset,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}editBufferGetTextRangeByCoords(buffer2,startRow,startCol,endRow,endCol,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.editBufferGetTextRangeByCoords(buffer2,startRow,startCol,endRow,endCol,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}editorViewSetSelection(view,start2,end,bgColor,fgColor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;this.opentui.symbols.editorViewSetSelection(view,start2,end,bg2,fg2)}editorViewResetSelection(view){this.opentui.symbols.editorViewResetSelection(view)}editorViewGetSelection(view){let packedInfo=this.opentui.symbols.editorViewGetSelection(view);if(packedInfo===0xffff_ffff_ffff_ffffn)return null;let start2=Number(packedInfo>>32n),end=Number(packedInfo&0xffff_ffffn);return{start:start2,end}}editorViewSetLocalSelection(view,anchorX,anchorY,focusX,focusY,bgColor,fgColor,updateCursor,followCursor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;return this.opentui.symbols.editorViewSetLocalSelection(view,anchorX,anchorY,focusX,focusY,bg2,fg2,updateCursor,followCursor)}editorViewUpdateSelection(view,end,bgColor,fgColor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;this.opentui.symbols.editorViewUpdateSelection(view,end,bg2,fg2)}editorViewUpdateLocalSelection(view,anchorX,anchorY,focusX,focusY,bgColor,fgColor,updateCursor,followCursor){let bg2=bgColor?bgColor.buffer:null,fg2=fgColor?fgColor.buffer:null;return this.opentui.symbols.editorViewUpdateLocalSelection(view,anchorX,anchorY,focusX,focusY,bg2,fg2,updateCursor,followCursor)}editorViewResetLocalSelection(view){this.opentui.symbols.editorViewResetLocalSelection(view)}editorViewGetSelectedTextBytes(view,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.editorViewGetSelectedTextBytes(view,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}editorViewGetCursor(view){let row=new Uint32Array(1),col=new Uint32Array(1);return this.opentui.symbols.editorViewGetCursor(view,ptr4(row),ptr4(col)),{row:row[0],col:col[0]}}editorViewGetText(view,maxLength){let outBuffer=new Uint8Array(maxLength),actualLen=this.opentui.symbols.editorViewGetText(view,ptr4(outBuffer),maxLength),len=typeof actualLen==="bigint"?Number(actualLen):actualLen;if(len===0)return null;return outBuffer.slice(0,len)}editorViewGetVisualCursor(view){let cursorBuffer=new ArrayBuffer(VisualCursorStruct.size);return this.opentui.symbols.editorViewGetVisualCursor(view,ptr4(cursorBuffer)),VisualCursorStruct.unpack(cursorBuffer)}editorViewMoveUpVisual(view){this.opentui.symbols.editorViewMoveUpVisual(view)}editorViewMoveDownVisual(view){this.opentui.symbols.editorViewMoveDownVisual(view)}editorViewDeleteSelectedText(view){this.opentui.symbols.editorViewDeleteSelectedText(view)}editorViewSetCursorByOffset(view,offset){this.opentui.symbols.editorViewSetCursorByOffset(view,offset)}editorViewGetNextWordBoundary(view){let cursorBuffer=new ArrayBuffer(VisualCursorStruct.size);return this.opentui.symbols.editorViewGetNextWordBoundary(view,ptr4(cursorBuffer)),VisualCursorStruct.unpack(cursorBuffer)}editorViewGetPrevWordBoundary(view){let cursorBuffer=new ArrayBuffer(VisualCursorStruct.size);return this.opentui.symbols.editorViewGetPrevWordBoundary(view,ptr4(cursorBuffer)),VisualCursorStruct.unpack(cursorBuffer)}editorViewGetEOL(view){let cursorBuffer=new ArrayBuffer(VisualCursorStruct.size);return this.opentui.symbols.editorViewGetEOL(view,ptr4(cursorBuffer)),VisualCursorStruct.unpack(cursorBuffer)}editorViewGetVisualSOL(view){let cursorBuffer=new ArrayBuffer(VisualCursorStruct.size);return this.opentui.symbols.editorViewGetVisualSOL(view,ptr4(cursorBuffer)),VisualCursorStruct.unpack(cursorBuffer)}editorViewGetVisualEOL(view){let cursorBuffer=new ArrayBuffer(VisualCursorStruct.size);return this.opentui.symbols.editorViewGetVisualEOL(view,ptr4(cursorBuffer)),VisualCursorStruct.unpack(cursorBuffer)}bufferPushScissorRect(buffer2,x,y,width,height2){this.opentui.symbols.bufferPushScissorRect(buffer2,x,y,width,height2)}bufferPopScissorRect(buffer2){this.opentui.symbols.bufferPopScissorRect(buffer2)}bufferClearScissorRects(buffer2){this.opentui.symbols.bufferClearScissorRects(buffer2)}bufferPushOpacity(buffer2,opacity){this.opentui.symbols.bufferPushOpacity(buffer2,opacity)}bufferPopOpacity(buffer2){this.opentui.symbols.bufferPopOpacity(buffer2)}bufferGetCurrentOpacity(buffer2){return this.opentui.symbols.bufferGetCurrentOpacity(buffer2)}bufferClearOpacity(buffer2){this.opentui.symbols.bufferClearOpacity(buffer2)}getTerminalCapabilities(renderer){let capsBuffer=new ArrayBuffer(TerminalCapabilitiesStruct.size);this.opentui.symbols.getTerminalCapabilities(renderer,ptr4(capsBuffer));let caps=TerminalCapabilitiesStruct.unpack(capsBuffer);return{kitty_keyboard:caps.kitty_keyboard,kitty_graphics:caps.kitty_graphics,rgb:caps.rgb,unicode:caps.unicode,sgr_pixels:caps.sgr_pixels,color_scheme_updates:caps.color_scheme_updates,explicit_width:caps.explicit_width,scaled_text:caps.scaled_text,sixel:caps.sixel,focus_tracking:caps.focus_tracking,sync:caps.sync,bracketed_paste:caps.bracketed_paste,hyperlinks:caps.hyperlinks,osc52:caps.osc52,explicit_cursor_positioning:caps.explicit_cursor_positioning,terminal:{name:caps.term_name??"",version:caps.term_version??"",from_xtversion:caps.term_from_xtversion}}}processCapabilityResponse(renderer,response){let responseBytes=this.encoder.encode(response);this.opentui.symbols.processCapabilityResponse(renderer,responseBytes,responseBytes.length)}encodeUnicode(text,widthMethod){let textBytes=this.encoder.encode(text),widthMethodCode=widthMethod==="wcwidth"?0:1,outPtrBuffer=new ArrayBuffer(8),outLenBuffer=new ArrayBuffer(8);if(!this.opentui.symbols.encodeUnicode(textBytes,textBytes.length,ptr4(outPtrBuffer),ptr4(outLenBuffer),widthMethodCode))return null;let outPtrView=new BigUint64Array(outPtrBuffer),outLenView=new BigUint64Array(outLenBuffer),resultPtr=Number(outPtrView[0]),resultLen=Number(outLenView[0]);if(resultLen===0)return{ptr:resultPtr,data:[]};let byteLen=resultLen*EncodedCharStruct.size,raw=toArrayBuffer4(resultPtr,0,byteLen),data=EncodedCharStruct.unpackList(raw,resultLen);return{ptr:resultPtr,data}}freeUnicode(encoded){this.opentui.symbols.freeUnicode(encoded.ptr,encoded.data.length)}bufferDrawChar(buffer2,char,x,y,fg2,bg2,attributes=0){this.opentui.symbols.bufferDrawChar(buffer2,char,x,y,fg2.buffer,bg2.buffer,attributes)}registerNativeSpanFeedStream(stream,handler){let callback=this.ensureNativeSpanFeedCallback();this.nativeSpanFeedHandlers.set(toPointer(stream),handler),this.opentui.symbols.streamSetCallback(stream,callback.ptr)}unregisterNativeSpanFeedStream(stream){this.opentui.symbols.streamSetCallback(stream,null),this.nativeSpanFeedHandlers.delete(toPointer(stream))}createNativeSpanFeed(options){let optionsBuffer=options==null?null:NativeSpanFeedOptionsStruct.pack(options),streamPtr=this.opentui.symbols.createNativeSpanFeed(optionsBuffer?ptr4(optionsBuffer):null);if(!streamPtr)throw Error("Failed to create stream");return toPointer(streamPtr)}attachNativeSpanFeed(stream){return this.opentui.symbols.attachNativeSpanFeed(stream)}destroyNativeSpanFeed(stream){this.opentui.symbols.destroyNativeSpanFeed(stream),this.nativeSpanFeedHandlers.delete(toPointer(stream))}streamWrite(stream,data){let bytes=typeof data==="string"?this.encoder.encode(data):data;return this.opentui.symbols.streamWrite(stream,ptr4(bytes),bytes.length)}streamCommit(stream){return this.opentui.symbols.streamCommit(stream)}streamDrainSpans(stream,outBuffer,maxSpans){let count=this.opentui.symbols.streamDrainSpans(stream,ptr4(outBuffer),maxSpans);return toNumber(count)}streamClose(stream){return this.opentui.symbols.streamClose(stream)}streamSetOptions(stream,options){let optionsBuffer=NativeSpanFeedOptionsStruct.pack(options);return this.opentui.symbols.streamSetOptions(stream,ptr4(optionsBuffer))}streamGetStats(stream){let statsBuffer=new ArrayBuffer(NativeSpanFeedStatsStruct.size);if(this.opentui.symbols.streamGetStats(stream,ptr4(statsBuffer))!==0)return null;let stats=NativeSpanFeedStatsStruct.unpack(statsBuffer);return{bytesWritten:typeof stats.bytesWritten==="bigint"?stats.bytesWritten:BigInt(stats.bytesWritten),spansCommitted:typeof stats.spansCommitted==="bigint"?stats.spansCommitted:BigInt(stats.spansCommitted),chunks:stats.chunks,pendingSpans:stats.pendingSpans}}streamReserve(stream,minLen){let reserveBuffer=new ArrayBuffer(ReserveInfoStruct.size),status=this.opentui.symbols.streamReserve(stream,minLen,ptr4(reserveBuffer));if(status!==0)return{status,info:null};return{status,info:ReserveInfoStruct.unpack(reserveBuffer)}}streamCommitReserved(stream,length){return this.opentui.symbols.streamCommitReserved(stream,length)}createSyntaxStyle(){let stylePtr=this.opentui.symbols.createSyntaxStyle();if(!stylePtr)throw Error("Failed to create SyntaxStyle");return stylePtr}destroySyntaxStyle(style){this.opentui.symbols.destroySyntaxStyle(style)}syntaxStyleRegister(style,name,fg2,bg2,attributes){let nameBytes=this.encoder.encode(name),fgPtr=fg2?fg2.buffer:null,bgPtr=bg2?bg2.buffer:null;return this.opentui.symbols.syntaxStyleRegister(style,nameBytes,nameBytes.length,fgPtr,bgPtr,attributes)}syntaxStyleResolveByName(style,name){let nameBytes=this.encoder.encode(name),id=this.opentui.symbols.syntaxStyleResolveByName(style,nameBytes,nameBytes.length);return id===0?null:id}syntaxStyleGetStyleCount(style){let result2=this.opentui.symbols.syntaxStyleGetStyleCount(style);return typeof result2==="bigint"?Number(result2):result2}editorViewSetPlaceholderStyledText(view,chunks){let nonEmptyChunks=chunks.filter((c)=>c.text.length>0);if(nonEmptyChunks.length===0){this.opentui.symbols.editorViewSetPlaceholderStyledText(view,null,0);return}let chunksBuffer=StyledChunkStruct.packList(nonEmptyChunks);this.opentui.symbols.editorViewSetPlaceholderStyledText(view,ptr4(chunksBuffer),nonEmptyChunks.length)}editorViewSetTabIndicator(view,indicator){this.opentui.symbols.editorViewSetTabIndicator(view,indicator)}editorViewSetTabIndicatorColor(view,color2){this.opentui.symbols.editorViewSetTabIndicatorColor(view,color2.buffer)}onNativeEvent(name,handler){this._nativeEvents.on(name,handler)}onceNativeEvent(name,handler){this._nativeEvents.once(name,handler)}offNativeEvent(name,handler){this._nativeEvents.off(name,handler)}onAnyNativeEvent(handler){this._anyEventHandlers.push(handler)}}function setRenderLibPath(libPath){if(opentuiLibPath!==libPath)opentuiLibPath=libPath,opentuiLib=void 0}function resolveRenderLib(){if(!opentuiLib)try{opentuiLib=new FFIRenderLib(opentuiLibPath)}catch(error2){throw Error(`Failed to initialize OpenTUI render library: ${error2 instanceof Error?error2.message:"Unknown error"}`)}return opentuiLib}class TextBuffer{lib;bufferPtr;_length=0;_byteSize=0;_lineInfo;_destroyed=!1;_syntaxStyle;_textBytes;_memId;_appendedChunks=[];constructor(lib,ptr5){this.lib=lib,this.bufferPtr=ptr5}static create(widthMethod){return resolveRenderLib().createTextBuffer(widthMethod)}guard(){if(this._destroyed)throw Error("TextBuffer is destroyed")}setText(text){if(this.guard(),this._textBytes=this.lib.encoder.encode(text),this._memId===void 0)this._memId=this.lib.textBufferRegisterMemBuffer(this.bufferPtr,this._textBytes,!1);else this.lib.textBufferReplaceMemBuffer(this.bufferPtr,this._memId,this._textBytes,!1);this.lib.textBufferSetTextFromMem(this.bufferPtr,this._memId),this._length=this.lib.textBufferGetLength(this.bufferPtr),this._byteSize=this.lib.textBufferGetByteSize(this.bufferPtr),this._lineInfo=void 0,this._appendedChunks=[]}append(text){this.guard();let textBytes=this.lib.encoder.encode(text);this._appendedChunks.push(textBytes),this.lib.textBufferAppend(this.bufferPtr,textBytes),this._length=this.lib.textBufferGetLength(this.bufferPtr),this._byteSize=this.lib.textBufferGetByteSize(this.bufferPtr),this._lineInfo=void 0}loadFile(path52){if(this.guard(),!this.lib.textBufferLoadFile(this.bufferPtr,path52))throw Error(`Failed to load file: ${path52}`);this._length=this.lib.textBufferGetLength(this.bufferPtr),this._byteSize=this.lib.textBufferGetByteSize(this.bufferPtr),this._lineInfo=void 0,this._textBytes=void 0}setStyledText(text){this.guard(),this.lib.textBufferSetStyledText(this.bufferPtr,text.chunks),this._length=this.lib.textBufferGetLength(this.bufferPtr),this._byteSize=this.lib.textBufferGetByteSize(this.bufferPtr),this._lineInfo=void 0}setDefaultFg(fg2){this.guard(),this.lib.textBufferSetDefaultFg(this.bufferPtr,fg2)}setDefaultBg(bg2){this.guard(),this.lib.textBufferSetDefaultBg(this.bufferPtr,bg2)}setDefaultAttributes(attributes){this.guard(),this.lib.textBufferSetDefaultAttributes(this.bufferPtr,attributes)}resetDefaults(){this.guard(),this.lib.textBufferResetDefaults(this.bufferPtr)}getLineCount(){return this.guard(),this.lib.textBufferGetLineCount(this.bufferPtr)}get length(){return this.guard(),this._length}get byteSize(){return this.guard(),this._byteSize}get ptr(){return this.guard(),this.bufferPtr}getPlainText(){if(this.guard(),this._byteSize===0)return"";let plainBytes=this.lib.getPlainTextBytes(this.bufferPtr,this._byteSize);if(!plainBytes)return"";return this.lib.decoder.decode(plainBytes)}getTextRange(startOffset,endOffset){if(this.guard(),startOffset>=endOffset)return"";if(this._byteSize===0)return"";let rangeBytes=this.lib.textBufferGetTextRange(this.bufferPtr,startOffset,endOffset,this._byteSize);if(!rangeBytes)return"";return this.lib.decoder.decode(rangeBytes)}addHighlightByCharRange(highlight){this.guard(),this.lib.textBufferAddHighlightByCharRange(this.bufferPtr,highlight)}addHighlight(lineIdx,highlight){this.guard(),this.lib.textBufferAddHighlight(this.bufferPtr,lineIdx,highlight)}removeHighlightsByRef(hlRef){this.guard(),this.lib.textBufferRemoveHighlightsByRef(this.bufferPtr,hlRef)}clearLineHighlights(lineIdx){this.guard(),this.lib.textBufferClearLineHighlights(this.bufferPtr,lineIdx)}clearAllHighlights(){this.guard(),this.lib.textBufferClearAllHighlights(this.bufferPtr)}getLineHighlights(lineIdx){return this.guard(),this.lib.textBufferGetLineHighlights(this.bufferPtr,lineIdx)}getHighlightCount(){return this.guard(),this.lib.textBufferGetHighlightCount(this.bufferPtr)}setSyntaxStyle(style){this.guard(),this._syntaxStyle=style??void 0,this.lib.textBufferSetSyntaxStyle(this.bufferPtr,style?.ptr??null)}getSyntaxStyle(){return this.guard(),this._syntaxStyle??null}setTabWidth(width){this.guard(),this.lib.textBufferSetTabWidth(this.bufferPtr,width)}getTabWidth(){return this.guard(),this.lib.textBufferGetTabWidth(this.bufferPtr)}clear(){this.guard(),this.lib.textBufferClear(this.bufferPtr),this._length=0,this._byteSize=0,this._lineInfo=void 0,this._textBytes=void 0,this._appendedChunks=[]}reset(){this.guard(),this.lib.textBufferReset(this.bufferPtr),this._length=0,this._byteSize=0,this._lineInfo=void 0,this._textBytes=void 0,this._memId=void 0,this._appendedChunks=[]}destroy(){if(this._destroyed)return;this._destroyed=!0,this.lib.destroyTextBuffer(this.bufferPtr)}}function validateOptions(id,options){if(typeof options.width==="number"){if(options.width<0)throw TypeError(`Invalid width for Renderable ${id}: ${options.width}`)}if(typeof options.height==="number"){if(options.height<0)throw TypeError(`Invalid height for Renderable ${id}: ${options.height}`)}}function isValidPercentage(value){if(typeof value==="string"&&value.endsWith("%")){let numPart=value.slice(0,-1),num=parseFloat(numPart);return!Number.isNaN(num)}return!1}function isMarginType(value){if(typeof value==="number"&&!Number.isNaN(value))return!0;if(value==="auto")return!0;return isValidPercentage(value)}function isPaddingType(value){if(typeof value==="number"&&!Number.isNaN(value))return!0;return isValidPercentage(value)}function isPositionType(value){if(typeof value==="number"&&!Number.isNaN(value))return!0;if(value==="auto")return!0;return isValidPercentage(value)}function isPositionTypeType(value){return value==="relative"||value==="absolute"}function isOverflowType(value){return value==="visible"||value==="hidden"||value==="scroll"}function isDimensionType(value){return isPositionType(value)}function isFlexBasisType(value){if(value===void 0||value==="auto")return!0;if(typeof value==="number"&&!Number.isNaN(value))return!0;return!1}function isSizeType(value){if(value===void 0)return!0;if(typeof value==="number"&&!Number.isNaN(value))return!0;return isValidPercentage(value)}function isRenderable(obj){return!!obj?.[BrandedRenderable]}function isRenderableConstructor(value){return typeof value==="function"&&value.prototype&&Renderable.prototype.isPrototypeOf(value.prototype)}function flattenChildren(children){let result2=[];for(let child of children)if(Array.isArray(child))result2.push(...flattenChildren(child));else if(child!==null&&child!==void 0&&child!==!1)result2.push(child);return result2}function h(type2,props,...children){if(typeof type2!=="function")throw TypeError("h() received an invalid vnode type");let vnode={[BrandedVNode]:!0,type:type2,props,children:flattenChildren(children),__pendingCalls:[]};if(isRenderableConstructor(type2))return new Proxy(vnode,{get(target,prop,receiver){if(prop in target)return Reflect.get(target,prop,receiver);if(typeof prop==="string"){let prototype=type2.prototype;if(prototype&&(typeof prototype[prop]==="function"||Object.getOwnPropertyDescriptor(prototype,prop)||Object.getOwnPropertyDescriptor(Object.getPrototypeOf(prototype),prop)))return(...args)=>{return target.__pendingCalls=target.__pendingCalls||[],target.__pendingCalls.push({method:prop,args}),target}}return Reflect.get(target,prop,receiver)},set(target,prop,value,receiver){if(typeof prop==="string"&&isRenderableConstructor(type2)){let prototype=type2.prototype,descriptor=Object.getOwnPropertyDescriptor(prototype,prop)||Object.getOwnPropertyDescriptor(Object.getPrototypeOf(prototype),prop);if(descriptor&&descriptor.set)return target.__pendingCalls=target.__pendingCalls||[],target.__pendingCalls.push({method:prop,args:[value],isProperty:!0}),!0}return Reflect.set(target,prop,value,receiver)}});return vnode}function isVNode(node){return node&&node[BrandedVNode]}function maybeMakeRenderable(ctx,node){if(isRenderable(node))return node;if(isVNode(node))return instantiate(ctx,node);return console.warn("maybeMakeRenderable received an invalid node",util3.inspect(node,{depth:2})),null}function wrapWithDelegates(instance,delegateMap){if(!delegateMap||Object.keys(delegateMap).length===0)return instance;let descendantCache=new Map,getDescendant=(id)=>{if(descendantCache.has(id)){let cached=descendantCache.get(id);if(cached!==void 0)return cached}let descendant=instance.findDescendantById(id);if(descendant)descendantCache.set(id,descendant);return descendant};return new Proxy(instance,{get(target,prop,receiver){if(typeof prop==="string"&&delegateMap[prop]){let host=getDescendant(delegateMap[prop]);if(host){let value=host[prop];if(typeof value==="function")return value.bind(host);return value}}return Reflect.get(target,prop,receiver)},set(target,prop,value,receiver){if(typeof prop==="string"&&delegateMap[prop]){let host=getDescendant(delegateMap[prop]);if(host)return Reflect.set(host,prop,value)}return Reflect.set(target,prop,value,receiver)}})}function instantiate(ctx,node){if(isRenderable(node))return node;if(!node||typeof node!=="object")throw TypeError("mount() received an invalid vnode");let vnode=node,{type:type2,props}=vnode,children=flattenChildren(vnode.children||[]),delegateMap=vnode.__delegateMap;if(isRenderableConstructor(type2)){let instance=new type2(ctx,props||{});for(let child of children)if(isRenderable(child))instance.add(child);else{let mounted=instantiate(ctx,child);instance.add(mounted)}let delegatedInstance=wrapWithDelegates(instance,delegateMap),pendingCalls=vnode.__pendingCalls;if(pendingCalls)for(let call of pendingCalls)if(call.isProperty)delegatedInstance[call.method]=call.args[0];else delegatedInstance[call.method].apply(delegatedInstance,call.args);return delegatedInstance}let resolved=type2(props||{},children),inst=instantiate(ctx,resolved);return wrapWithDelegates(inst,delegateMap)}function delegate(mapping,vnode){if(isRenderable(vnode))return wrapWithDelegates(vnode,mapping);if(!vnode||typeof vnode!=="object")return vnode;return vnode.__delegateMap={...vnode.__delegateMap||{},...mapping},vnode}function mergeKeyAliases(defaults,custom2){return{...defaults,...custom2}}function mergeKeyBindings(defaults,custom2){let map2=new Map;for(let binding of defaults){let key=getKeyBindingKey(binding);map2.set(key,binding)}for(let binding of custom2){let key=getKeyBindingKey(binding);map2.set(key,binding)}return Array.from(map2.values())}function getKeyBindingKey(binding){return`${binding.name}:${binding.ctrl?1:0}:${binding.shift?1:0}:${binding.meta?1:0}:${binding.super?1:0}`}function buildKeyBindingsMap(bindings,aliasMap){let map2=new Map,aliases=aliasMap||{};for(let binding of bindings){let key=getKeyBindingKey(binding);map2.set(key,binding.action)}for(let binding of bindings){let normalizedName=aliases[binding.name]||binding.name;if(normalizedName!==binding.name){let aliasedKey=getKeyBindingKey({...binding,name:normalizedName});map2.set(aliasedKey,binding.action)}}return map2}function keyBindingToString(binding){let parts=[];if(binding.ctrl)parts.push("ctrl");if(binding.shift)parts.push("shift");if(binding.meta)parts.push("meta");if(binding.super)parts.push("super");return parts.push(binding.name),parts.join("+")}function getCallerInfo(){let stackLines=Error().stack?.split(`
@@ -3039,7 +3047,7 @@ Bus `);for(let i2=1;i2<parts.length;i2++){let usb2=parseLinuxUsb(parts[i2]);resu
3039
3047
  `);if(util4.getValue(lines,"class",":",!0).toLowerCase().indexOf("audio")>=0){let audio2=parseLinuxAudioPciMM(lines,audioPCI);result2.push(audio2)}})}if(callback)callback(result2);resolve13(result2)});if(_darwin)exec3("system_profiler SPAudioDataType -json",(error2,stdout)=>{if(!error2)try{let outObj=JSON.parse(stdout.toString());if(outObj.SPAudioDataType&&outObj.SPAudioDataType.length&&outObj.SPAudioDataType[0]&&outObj.SPAudioDataType[0]._items&&outObj.SPAudioDataType[0]._items.length)for(let i2=0;i2<outObj.SPAudioDataType[0]._items.length;i2++){let audio2=parseDarwinAudio(outObj.SPAudioDataType[0]._items[i2],i2);result2.push(audio2)}}catch{util4.noop()}if(callback)callback(result2);resolve13(result2)});if(_windows)util4.powerShell("Get-CimInstance Win32_SoundDevice | select DeviceID,StatusInfo,Name,Manufacturer | fl").then((stdout,error2)=>{if(!error2)stdout.toString().split(/\n\s*\n/).forEach((element)=>{let lines=element.split(`
3040
3048
  `);if(util4.getValue(lines,"name",":"))result2.push(parseWindowsAudio(lines))});if(callback)callback(result2);resolve13(result2)});if(_sunos)resolve13(null)})})}exports.audio=audio});var require_bluetoothVendors=__commonJS((exports,module2)=>{module2.exports={0:"Ericsson Technology Licensing",1:"Nokia Mobile Phones",2:"Intel Corp.",3:"IBM Corp.",4:"Toshiba Corp.",5:"3Com",6:"Microsoft",7:"Lucent",8:"Motorola",9:"Infineon Technologies AG",10:"Cambridge Silicon Radio",11:"Silicon Wave",12:"Digianswer A/S",13:"Texas Instruments Inc.",14:"Ceva, Inc. (formerly Parthus Technologies, Inc.)",15:"Broadcom Corporation",16:"Mitel Semiconductor",17:"Widcomm, Inc",18:"Zeevo, Inc.",19:"Atmel Corporation",20:"Mitsubishi Electric Corporation",21:"RTX Telecom A/S",22:"KC Technology Inc.",23:"NewLogic",24:"Transilica, Inc.",25:"Rohde & Schwarz GmbH & Co. KG",26:"TTPCom Limited",27:"Signia Technologies, Inc.",28:"Conexant Systems Inc.",29:"Qualcomm",30:"Inventel",31:"AVM Berlin",32:"BandSpeed, Inc.",33:"Mansella Ltd",34:"NEC Corporation",35:"WavePlus Technology Co., Ltd.",36:"Alcatel",37:"NXP Semiconductors (formerly Philips Semiconductors)",38:"C Technologies",39:"Open Interface",40:"R F Micro Devices",41:"Hitachi Ltd",42:"Symbol Technologies, Inc.",43:"Tenovis",44:"Macronix International Co. Ltd.",45:"GCT Semiconductor",46:"Norwood Systems",47:"MewTel Technology Inc.",48:"ST Microelectronics",49:"Synopsis",50:"Red-M (Communications) Ltd",51:"Commil Ltd",52:"Computer Access Technology Corporation (CATC)",53:"Eclipse (HQ Espana) S.L.",54:"Renesas Electronics Corporation",55:"Mobilian Corporation",56:"Terax",57:"Integrated System Solution Corp.",58:"Matsushita Electric Industrial Co., Ltd.",59:"Gennum Corporation",60:"BlackBerry Limited (formerly Research In Motion)",61:"IPextreme, Inc.",62:"Systems and Chips, Inc.",63:"Bluetooth SIG, Inc.",64:"Seiko Epson Corporation",65:"Integrated Silicon Solution Taiwan, Inc.",66:"CONWISE Technology Corporation Ltd",67:"PARROT SA",68:"Socket Mobile",69:"Atheros Communications, Inc.",70:"MediaTek, Inc.",71:"Bluegiga",72:"Marvell Technology Group Ltd.",73:"3DSP Corporation",74:"Accel Semiconductor Ltd.",75:"Continental Automotive Systems",76:"Apple, Inc.",77:"Staccato Communications, Inc.",78:"Avago Technologies",79:"APT Licensing Ltd.",80:"SiRF Technology",81:"Tzero Technologies, Inc.",82:"J&M Corporation",83:"Free2move AB",84:"3DiJoy Corporation",85:"Plantronics, Inc.",86:"Sony Ericsson Mobile Communications",87:"Harman International Industries, Inc.",88:"Vizio, Inc.",89:"Nordic Semiconductor ASA",90:"EM Microelectronic-Marin SA",91:"Ralink Technology Corporation",92:"Belkin International, Inc.",93:"Realtek Semiconductor Corporation",94:"Stonestreet One, LLC",95:"Wicentric, Inc.",96:"RivieraWaves S.A.S",97:"RDA Microelectronics",98:"Gibson Guitars",99:"MiCommand Inc.",100:"Band XI International, LLC",101:"Hewlett-Packard Company",102:"9Solutions Oy",103:"GN Netcom A/S",104:"General Motors",105:"A&D Engineering, Inc.",106:"MindTree Ltd.",107:"Polar Electro OY",108:"Beautiful Enterprise Co., Ltd.",109:"BriarTek, Inc.",110:"Summit Data Communications, Inc.",111:"Sound ID",112:"Monster, LLC",113:"connectBlue AB",114:"ShangHai Super Smart Electronics Co. Ltd.",115:"Group Sense Ltd.",116:"Zomm, LLC",117:"Samsung Electronics Co. Ltd.",118:"Creative Technology Ltd.",119:"Laird Technologies",120:"Nike, Inc.",121:"lesswire AG",122:"MStar Semiconductor, Inc.",123:"Hanlynn Technologies",124:"A & R Cambridge",125:"Seers Technology Co. Ltd",126:"Sports Tracking Technologies Ltd.",127:"Autonet Mobile",128:"DeLorme Publishing Company, Inc.",129:"WuXi Vimicro",130:"Sennheiser Communications A/S",131:"TimeKeeping Systems, Inc.",132:"Ludus Helsinki Ltd.",133:"BlueRadios, Inc.",134:"equinox AG",135:"Garmin International, Inc.",136:"Ecotest",137:"GN ReSound A/S",138:"Jawbone",139:"Topcorn Positioning Systems, LLC",140:"Gimbal Inc. (formerly Qualcomm Labs, Inc. and Qualcomm Retail Solutions, Inc.)",141:"Zscan Software",142:"Quintic Corp.",143:"Stollman E+V GmbH",144:"Funai Electric Co., Ltd.",145:"Advanced PANMOBIL Systems GmbH & Co. KG",146:"ThinkOptics, Inc.",147:"Universal Electronics, Inc.",148:"Airoha Technology Corp.",149:"NEC Lighting, Ltd.",150:"ODM Technology, Inc.",151:"ConnecteDevice Ltd.",152:"zer01.tv GmbH",153:"i.Tech Dynamic Global Distribution Ltd.",154:"Alpwise",155:"Jiangsu Toppower Automotive Electronics Co., Ltd.",156:"Colorfy, Inc.",157:"Geoforce Inc.",158:"Bose Corporation",159:"Suunto Oy",160:"Kensington Computer Products Group",161:"SR-Medizinelektronik",162:"Vertu Corporation Limited",163:"Meta Watch Ltd.",164:"LINAK A/S",165:"OTL Dynamics LLC",166:"Panda Ocean Inc.",167:"Visteon Corporation",168:"ARP Devices Limited",169:"Magneti Marelli S.p.A",170:"CAEN RFID srl",171:"Ingenieur-Systemgruppe Zahn GmbH",172:"Green Throttle Games",173:"Peter Systemtechnik GmbH",174:"Omegawave Oy",175:"Cinetix",176:"Passif Semiconductor Corp",177:"Saris Cycling Group, Inc",178:"Bekey A/S",179:"Clarinox Technologies Pty. Ltd.",180:"BDE Technology Co., Ltd.",181:"Swirl Networks",182:"Meso international",183:"TreLab Ltd",184:"Qualcomm Innovation Center, Inc. (QuIC)",185:"Johnson Controls, Inc.",186:"Starkey Laboratories Inc.",187:"S-Power Electronics Limited",188:"Ace Sensor Inc",189:"Aplix Corporation",190:"AAMP of America",191:"Stalmart Technology Limited",192:"AMICCOM Electronics Corporation",193:"Shenzhen Excelsecu Data Technology Co.,Ltd",194:"Geneq Inc.",195:"adidas AG",196:"LG Electronics",197:"Onset Computer Corporation",198:"Selfly BV",199:"Quuppa Oy.",200:"GeLo Inc",201:"Evluma",202:"MC10",203:"Binauric SE",204:"Beats Electronics",205:"Microchip Technology Inc.",206:"Elgato Systems GmbH",207:"ARCHOS SA",208:"Dexcom, Inc.",209:"Polar Electro Europe B.V.",210:"Dialog Semiconductor B.V.",211:"Taixingbang\xA0Technology (HK) Co,. LTD.",212:"Kawantech",213:"Austco Communication Systems",214:"Timex Group USA, Inc.",215:"Qualcomm Technologies, Inc.",216:"Qualcomm Connected Experiences, Inc.",217:"Voyetra Turtle Beach",218:"txtr GmbH",219:"Biosentronics",220:"Procter & Gamble",221:"Hosiden Corporation",222:"Muzik LLC",223:"Misfit Wearables Corp",224:"Google",225:"Danlers Ltd",226:"Semilink Inc",227:"inMusic Brands, Inc",228:"L.S. Research Inc.",229:"Eden Software Consultants Ltd.",230:"Freshtemp",231:"KS Technologies",232:"ACTS Technologies",233:"Vtrack Systems",234:"Nielsen-Kellerman Company",235:"Server Technology, Inc.",236:"BioResearch Associates",237:"Jolly Logic, LLC",238:"Above Average Outcomes, Inc.",239:"Bitsplitters GmbH",240:"PayPal, Inc.",241:"Witron Technology Limited",242:"Aether Things\xA0Inc. (formerly Morse Project Inc.)",243:"Kent Displays Inc.",244:"Nautilus Inc.",245:"Smartifier Oy",246:"Elcometer Limited",247:"VSN Technologies Inc.",248:"AceUni Corp., Ltd.",249:"StickNFind",250:"Crystal Code AB",251:"KOUKAAM a.s.",252:"Delphi Corporation",253:"ValenceTech Limited",254:"Reserved",255:"Typo Products, LLC",256:"TomTom International BV",257:"Fugoo, Inc",258:"Keiser Corporation",259:"Bang & Olufsen A/S",260:"PLUS Locations Systems Pty Ltd",261:"Ubiquitous Computing Technology Corporation",262:"Innovative Yachtter Solutions",263:"William Demant Holding A/S",264:"Chicony Electronics Co., Ltd.",265:"Atus BV",266:"Codegate Ltd.",267:"ERi, Inc.",268:"Transducers Direct, LLC",269:"Fujitsu Ten Limited",270:"Audi AG",271:"HiSilicon Technologies Co., Ltd.",272:"Nippon Seiki Co., Ltd.",273:"Steelseries ApS",274:"vyzybl Inc.",275:"Openbrain Technologies, Co., Ltd.",276:"Xensr",277:"e.solutions",278:"1OAK Technologies",279:"Wimoto Technologies Inc",280:"Radius Networks, Inc.",281:"Wize Technology Co., Ltd.",282:"Qualcomm Labs, Inc.",283:"Aruba Networks",284:"Baidu",285:"Arendi AG",286:"Skoda Auto a.s.",287:"Volkswagon AG",288:"Porsche AG",289:"Sino Wealth Electronic Ltd.",290:"AirTurn, Inc.",291:"Kinsa, Inc.",292:"HID Global",293:"SEAT es",294:"Promethean Ltd.",295:"Salutica Allied Solutions",296:"GPSI Group Pty Ltd",297:"Nimble Devices Oy",298:"Changzhou Yongse Infotech Co., Ltd",299:"SportIQ",300:"TEMEC Instruments B.V.",301:"Sony Corporation",302:"ASSA ABLOY",303:"Clarion Co., Ltd.",304:"Warehouse Innovations",305:"Cypress Semiconductor Corporation",306:"MADS Inc",307:"Blue Maestro Limited",308:"Resolution Products, Inc.",309:"Airewear LLC",310:"Seed Labs, Inc. (formerly ETC sp. z.o.o.)",311:"Prestigio Plaza Ltd.",312:"NTEO Inc.",313:"Focus Systems Corporation",314:"Tencent Holdings Limited",315:"Allegion",316:"Murata Manufacuring Co., Ltd.",318:"Nod, Inc.",319:"B&B Manufacturing Company",320:"Alpine\xA0Electronics\xA0(China)\xA0Co.,\xA0Ltd",321:"FedEx Services",322:"Grape Systems Inc.",323:"Bkon Connect",324:"Lintech GmbH",325:"Novatel Wireless",326:"Ciright",327:"Mighty Cast, Inc.",328:"Ambimat Electronics",329:"Perytons Ltd.",330:"Tivoli Audio, LLC",331:"Master Lock",332:"Mesh-Net Ltd",333:"Huizhou Desay SV Automotive CO., LTD.",334:"Tangerine, Inc.",335:"B&W Group Ltd.",336:"Pioneer Corporation",337:"OnBeep",338:"Vernier Software & Technology",339:"ROL Ergo",340:"Pebble Technology",341:"NETATMO",342:"Accumulate AB",343:"Anhui Huami Information Technology Co., Ltd.",344:"Inmite s.r.o.",345:"ChefSteps, Inc.",346:"micas AG",347:"Biomedical Research Ltd.",348:"Pitius Tec S.L.",349:"Estimote, Inc.",350:"Unikey Technologies, Inc.",351:"Timer Cap Co.",352:"AwoX",353:"yikes",354:"MADSGlobal NZ Ltd.",355:"PCH International",356:"Qingdao Yeelink Information Technology Co., Ltd.",357:"Milwaukee Tool (formerly Milwaukee Electric Tools)",358:"MISHIK Pte Ltd",359:"Bayer HealthCare",360:"Spicebox LLC",361:"emberlight",362:"Cooper-Atkins Corporation",363:"Qblinks",364:"MYSPHERA",365:"LifeScan Inc",366:"Volantic AB",367:"Podo Labs, Inc",368:"Roche Diabetes Care AG",369:"Amazon Fulfillment Service",370:"Connovate Technology Private Limited",371:"Kocomojo, LLC",372:"Everykey LLC",373:"Dynamic Controls",374:"SentriLock",375:"I-SYST inc.",376:"CASIO COMPUTER CO., LTD.",377:"LAPIS Semiconductor Co., Ltd.",378:"Telemonitor, Inc.",379:"taskit GmbH",380:"Daimler AG",381:"BatAndCat",382:"BluDotz Ltd",383:"XTel ApS",384:"Gigaset Communications GmbH",385:"Gecko Health Innovations, Inc.",386:"HOP Ubiquitous",387:"To Be Assigned",388:"Nectar",389:"bel\u2019apps LLC",390:"CORE Lighting Ltd",391:"Seraphim Sense Ltd",392:"Unico RBC",393:"Physical Enterprises Inc.",394:"Able Trend Technology Limited",395:"Konica Minolta, Inc.",396:"Wilo SE",397:"Extron Design Services",398:"Fitbit, Inc.",399:"Fireflies Systems",400:"Intelletto Technologies Inc.",401:"FDK CORPORATION",402:"Cloudleaf, Inc",403:"Maveric Automation LLC",404:"Acoustic Stream Corporation",405:"Zuli",406:"Paxton Access Ltd",407:"WiSilica Inc",408:"Vengit Limited",409:"SALTO SYSTEMS S.L.",410:"TRON Forum (formerly T-Engine Forum)",411:"CUBETECH s.r.o.",412:"Cokiya Incorporated",413:"CVS Health",414:"Ceruus",415:"Strainstall Ltd",416:"Channel Enterprises (HK) Ltd.",417:"FIAMM",418:"GIGALANE.CO.,LTD",419:"EROAD",420:"Mine Safety Appliances",421:"Icon Health and Fitness",422:"Asandoo GmbH",423:"ENERGOUS CORPORATION",424:"Taobao",425:"Canon Inc.",426:"Geophysical Technology Inc.",427:"Facebook, Inc.",428:"Nipro Diagnostics, Inc.",429:"FlightSafety International",430:"Earlens Corporation",431:"Sunrise Micro Devices, Inc.",432:"Star Micronics Co., Ltd.",433:"Netizens Sp. z o.o.",434:"Nymi Inc.",435:"Nytec, Inc.",436:"Trineo Sp. z o.o.",437:"Nest Labs Inc.",438:"LM Technologies Ltd",439:"General Electric Company",440:"i+D3 S.L.",441:"HANA Micron",442:"Stages Cycling LLC",443:"Cochlear Bone Anchored Solutions AB",444:"SenionLab AB",445:"Syszone Co., Ltd",446:"Pulsate Mobile Ltd.",447:"Hong Kong HunterSun Electronic Limited",448:"pironex GmbH",449:"BRADATECH Corp.",450:"Transenergooil AG",451:"Bunch",452:"DME Microelectronics",453:"Bitcraze AB",454:"HASWARE Inc.",455:"Abiogenix Inc.",456:"Poly-Control ApS",457:"Avi-on",458:"Laerdal Medical AS",459:"Fetch My Pet",460:"Sam Labs Ltd.",461:"Chengdu Synwing Technology Ltd",462:"HOUWA SYSTEM DESIGN, k.k.",463:"BSH",464:"Primus Inter Pares Ltd",465:"August",466:"Gill Electronics",467:"Sky Wave Design",468:"Newlab S.r.l.",469:"ELAD srl",470:"G-wearables inc.",471:"Squadrone Systems Inc.",472:"Code Corporation",473:"Savant Systems LLC",474:"Logitech International SA",475:"Innblue Consulting",476:"iParking Ltd.",477:"Koninklijke Philips Electronics N.V.",478:"Minelab Electronics Pty Limited",479:"Bison Group Ltd.",480:"Widex A/S",481:"Jolla Ltd",482:"Lectronix, Inc.",483:"Caterpillar Inc",484:"Freedom Innovations",485:"Dynamic Devices Ltd",486:"Technology Solutions (UK) Ltd",487:"IPS Group Inc.",488:"STIR",489:"Sano, Inc",490:"Advanced Application Design, Inc.",491:"AutoMap LLC",492:"Spreadtrum Communications Shanghai Ltd",493:"CuteCircuit LTD",494:"Valeo Service",495:"Fullpower Technologies, Inc.",496:"KloudNation",497:"Zebra Technologies Corporation",498:"Itron, Inc.",499:"The University of Tokyo",500:"UTC Fire and Security",501:"Cool Webthings Limited",502:"DJO Global",503:"Gelliner Limited",504:"Anyka (Guangzhou) Microelectronics Technology Co, LTD",505:"Medtronic, Inc.",506:"Gozio, Inc.",507:"Form Lifting, LLC",508:"Wahoo Fitness, LLC",509:"Kontakt Micro-Location Sp. z o.o.",510:"Radio System Corporation",511:"Freescale Semiconductor, Inc.",512:"Verifone Systems PTe Ltd. Taiwan Branch",513:"AR Timing",514:"Rigado LLC",515:"Kemppi Oy",516:"Tapcentive Inc.",517:"Smartbotics Inc.",518:"Otter Products, LLC",519:"STEMP Inc.",520:"LumiGeek LLC",521:"InvisionHeart Inc.",522:"Macnica Inc. ",523:"Jaguar Land Rover Limited",524:"CoroWare Technologies, Inc",525:"Simplo Technology Co., LTD",526:"Omron Healthcare Co., LTD",527:"Comodule GMBH",528:"ikeGPS",529:"Telink Semiconductor Co. Ltd",530:"Interplan Co., Ltd",531:"Wyler AG",532:"IK Multimedia Production srl",533:"Lukoton Experience Oy",534:"MTI Ltd",535:"Tech4home, Lda",536:"Hiotech AB",537:"DOTT Limited",538:"Blue Speck Labs, LLC",539:"Cisco Systems, Inc",540:"Mobicomm Inc",541:"Edamic",542:"Goodnet, Ltd",543:"Luster Leaf Products Inc",544:"Manus Machina BV",545:"Mobiquity Networks Inc",546:"Praxis Dynamics",547:"Philip Morris Products S.A.",548:"Comarch SA",549:"Nestl Nespresso S.A.",550:"Merlinia A/S",551:"LifeBEAM Technologies",552:"Twocanoes Labs, LLC",553:"Muoverti Limited",554:"Stamer Musikanlagen GMBH",555:"Tesla Motors",556:"Pharynks Corporation",557:"Lupine",558:"Siemens AG",559:"Huami (Shanghai) Culture Communication CO., LTD",560:"Foster Electric Company, Ltd",561:"ETA SA",562:"x-Senso Solutions Kft",563:"Shenzhen SuLong Communication Ltd",564:"FengFan (BeiJing) Technology Co, Ltd",565:"Qrio Inc",566:"Pitpatpet Ltd",567:"MSHeli s.r.l.",568:"Trakm8 Ltd",569:"JIN CO, Ltd",570:"Alatech Tehnology",571:"Beijing CarePulse Electronic Technology Co, Ltd",572:"Awarepoint",573:"ViCentra B.V.",574:"Raven Industries",575:"WaveWare Technologies Inc.",576:"Argenox Technologies",577:"Bragi GmbH",578:"16Lab Inc",579:"Masimo Corp",580:"Iotera Inc",581:"Endress+Hauser",582:"ACKme Networks, Inc.",583:"FiftyThree Inc.",584:"Parker Hannifin Corp",585:"Transcranial Ltd",586:"Uwatec AG",587:"Orlan LLC",588:"Blue Clover Devices",589:"M-Way Solutions GmbH",590:"Microtronics Engineering GmbH",591:"Schneider Schreibgerte GmbH",592:"Sapphire Circuits LLC",593:"Lumo Bodytech Inc.",594:"UKC Technosolution",595:"Xicato Inc.",596:"Playbrush",597:"Dai Nippon Printing Co., Ltd.",598:"G24 Power Limited",599:"AdBabble Local Commerce Inc.",600:"Devialet SA",601:"ALTYOR",602:"University of Applied Sciences Valais/Haute Ecole Valaisanne",603:"Five Interactive, LLC dba Zendo",604:"NetEaseHangzhouNetwork co.Ltd.",605:"Lexmark International Inc.",606:"Fluke Corporation",607:"Yardarm Technologies",608:"SensaRx",609:"SECVRE GmbH",610:"Glacial Ridge Technologies",611:"Identiv, Inc.",612:"DDS, Inc.",613:"SMK Corporation",614:"Schawbel Technologies LLC",615:"XMI Systems SA",616:"Cerevo",617:"Torrox GmbH & Co KG",618:"Gemalto",619:"DEKA Research & Development Corp.",620:"Domster Tadeusz Szydlowski",621:"Technogym SPA",622:"FLEURBAEY BVBA",623:"Aptcode Solutions",624:"LSI ADL Technology",625:"Animas Corp",626:"Alps Electric Co., Ltd.",627:"OCEASOFT",628:"Motsai Research",629:"Geotab",630:"E.G.O. Elektro-Gertebau GmbH",631:"bewhere inc",632:"Johnson Outdoors Inc",633:"steute Schaltgerate GmbH & Co. KG",634:"Ekomini inc.",635:"DEFA AS",636:"Aseptika Ltd",637:"HUAWEI Technologies Co., Ltd. ( )",638:"HabitAware, LLC",639:"ruwido austria gmbh",640:"ITEC corporation",641:"StoneL",642:"Sonova AG",643:"Maven Machines, Inc.",644:"Synapse Electronics",645:"Standard Innovation Inc.",646:"RF Code, Inc.",647:"Wally Ventures S.L.",648:"Willowbank Electronics Ltd",649:"SK Telecom",650:"Jetro AS",651:"Code Gears LTD",652:"NANOLINK APS",653:"IF, LLC",654:"RF Digital Corp",655:"Church & Dwight Co., Inc",656:"Multibit Oy",657:"CliniCloud Inc",658:"SwiftSensors",659:"Blue Bite",660:"ELIAS GmbH",661:"Sivantos GmbH",662:"Petzl",663:"storm power ltd",664:"EISST Ltd",665:"Inexess Technology Simma KG",666:"Currant, Inc.",667:"C2 Development, Inc.",668:"Blue Sky Scientific, LLC",669:"ALOTTAZS LABS, LLC",670:"Kupson spol. s r.o.",671:"Areus Engineering GmbH",672:"Impossible Camera GmbH",673:"InventureTrack Systems",674:"LockedUp",675:"Itude",676:"Pacific Lock Company",677:"Tendyron Corporation ( )",678:"Robert Bosch GmbH",679:"Illuxtron international B.V.",680:"miSport Ltd.",681:"Chargelib",682:"Doppler Lab",683:"BBPOS Limited",684:"RTB Elektronik GmbH & Co. KG",685:"Rx Networks, Inc.",686:"WeatherFlow, Inc.",687:"Technicolor USA Inc.",688:"Bestechnic(Shanghai),Ltd",689:"Raden Inc",690:"JouZen Oy",691:"CLABER S.P.A.",692:"Hyginex, Inc.",693:"HANSHIN ELECTRIC RAILWAY CO.,LTD.",694:"Schneider Electric",695:"Oort Technologies LLC",696:"Chrono Therapeutics",697:"Rinnai Corporation",698:"Swissprime Technologies AG",699:"Koha.,Co.Ltd",700:"Genevac Ltd",701:"Chemtronics",702:"Seguro Technology Sp. z o.o.",703:"Redbird Flight Simulations",704:"Dash Robotics",705:"LINE Corporation",706:"Guillemot Corporation",707:"Techtronic Power Tools Technology Limited",708:"Wilson Sporting Goods",709:"Lenovo (Singapore) Pte Ltd. ( )",710:"Ayatan Sensors",711:"Electronics Tomorrow Limited",712:"VASCO Data Security International, Inc.",713:"PayRange Inc.",714:"ABOV Semiconductor",715:"AINA-Wireless Inc.",716:"Eijkelkamp Soil & Water",717:"BMA ergonomics b.v.",718:"Teva Branded Pharmaceutical Products R&D, Inc.",719:"Anima",720:"3M",721:"Empatica Srl",722:"Afero, Inc.",723:"Powercast Corporation",724:"Secuyou ApS",725:"OMRON Corporation",726:"Send Solutions",727:"NIPPON SYSTEMWARE CO.,LTD.",728:"Neosfar",729:"Fliegl Agrartechnik GmbH",730:"Gilvader",731:"Digi International Inc (R)",732:"DeWalch Technologies, Inc.",733:"Flint Rehabilitation Devices, LLC",734:"Samsung SDS Co., Ltd.",735:"Blur Product Development",736:"University of Michigan",737:"Victron Energy BV",738:"NTT docomo",739:"Carmanah Technologies Corp.",740:"Bytestorm Ltd.",741:"Espressif Incorporated ( () )",742:"Unwire",743:"Connected Yard, Inc.",744:"American Music Environments",745:"Sensogram Technologies, Inc.",746:"Fujitsu Limited",747:"Ardic Technology",748:"Delta Systems, Inc",749:"HTC Corporation",750:"Citizen Holdings Co., Ltd.",751:"SMART-INNOVATION.inc",752:"Blackrat Software",753:"The Idea Cave, LLC",754:"GoPro, Inc.",755:"AuthAir, Inc",756:"Vensi, Inc.",757:"Indagem Tech LLC",758:"Intemo Technologies",759:"DreamVisions co., Ltd.",760:"Runteq Oy Ltd",761:"IMAGINATION TECHNOLOGIES LTD",762:"CoSTAR TEchnologies",763:"Clarius Mobile Health Corp.",764:"Shanghai Frequen Microelectronics Co., Ltd.",765:"Uwanna, Inc.",766:"Lierda Science & Technology Group Co., Ltd.",767:"Silicon Laboratories",768:"World Moto Inc.",769:"Giatec Scientific Inc.",770:"Loop Devices, Inc",771:"IACA electronique",772:"Martians Inc",773:"Swipp ApS",774:"Life Laboratory Inc.",775:"FUJI INDUSTRIAL CO.,LTD.",776:"Surefire, LLC",777:"Dolby Labs",778:"Ellisys",779:"Magnitude Lighting Converters",780:"Hilti AG",781:"Devdata S.r.l.",782:"Deviceworx",783:"Shortcut Labs",784:"SGL Italia S.r.l.",785:"PEEQ DATA",786:"Ducere Technologies Pvt Ltd",787:"DiveNav, Inc.",788:"RIIG AI Sp. z o.o.",789:"Thermo Fisher Scientific",790:"AG Measurematics Pvt. Ltd.",791:"CHUO Electronics CO., LTD.",792:"Aspenta International",793:"Eugster Frismag AG",794:"Amber wireless GmbH",795:"HQ Inc",796:"Lab Sensor Solutions",797:"Enterlab ApS",798:"Eyefi, Inc.",799:"MetaSystem S.p.A.",800:"SONO ELECTRONICS. CO., LTD",801:"Jewelbots",802:"Compumedics Limited",803:"Rotor Bike Components",804:"Astro, Inc.",805:"Amotus Solutions",806:"Healthwear Technologies (Changzhou)Ltd",807:"Essex Electronics",808:"Grundfos A/S",809:"Eargo, Inc.",810:"Electronic Design Lab",811:"ESYLUX",812:"NIPPON SMT.CO.,Ltd",813:"BM innovations GmbH",814:"indoormap",815:"OttoQ Inc",816:"North Pole Engineering",817:"3flares Technologies Inc.",818:"Electrocompaniet A.S.",819:"Mul-T-Lock",820:"Corentium AS",821:"Enlighted Inc",822:"GISTIC",823:"AJP2 Holdings, LLC",824:"COBI GmbH",825:"Blue Sky Scientific, LLC",826:"Appception, Inc.",827:"Courtney Thorne Limited",828:"Virtuosys",829:"TPV Technology Limited",830:"Monitra SA",831:"Automation Components, Inc.",832:"Letsense s.r.l.",833:"Etesian Technologies LLC",834:"GERTEC BRASIL LTDA.",835:"Drekker Development Pty. Ltd.",836:"Whirl Inc",837:"Locus Positioning",838:"Acuity Brands Lighting, Inc",839:"Prevent Biometrics",840:"Arioneo",841:"VersaMe",842:"Vaddio",843:"Libratone A/S",844:"HM Electronics, Inc.",845:"TASER International, Inc.",846:"SafeTrust Inc.",847:"Heartland Payment Systems",848:"Bitstrata Systems Inc.",849:"Pieps GmbH",850:"iRiding(Xiamen)Technology Co.,Ltd.",851:"Alpha Audiotronics, Inc.",852:"TOPPAN FORMS CO.,LTD.",853:"Sigma Designs, Inc.",854:"Spectrum Brands, Inc.",855:"Polymap Wireless",856:"MagniWare Ltd.",857:"Novotec Medical GmbH",858:"Medicom Innovation Partner a/s",859:"Matrix Inc.",860:"Eaton Corporation",861:"KYS",862:"Naya Health, Inc.",863:"Acromag",864:"Insulet Corporation",865:"Wellinks Inc.",866:"ON Semiconductor",867:"FREELAP SA",868:"Favero Electronics Srl",869:"BioMech Sensor LLC",870:"BOLTT Sports technologies Private limited",871:"Saphe International",872:"Metormote AB",873:"littleBits",874:"SetPoint Medical",875:"BRControls Products BV",876:"Zipcar",877:"AirBolt Pty Ltd",878:"KeepTruckin Inc",879:"Motiv, Inc.",880:"Wazombi Labs O",881:"ORBCOMM",882:"Nixie Labs, Inc.",883:"AppNearMe Ltd",884:"Holman Industries",885:"Expain AS",886:"Electronic Temperature Instruments Ltd",887:"Plejd AB",888:"Propeller Health",889:"Shenzhen iMCO Electronic Technology Co.,Ltd",890:"Algoria",891:"Apption Labs Inc.",892:"Cronologics Corporation",893:"MICRODIA Ltd.",894:"lulabytes S.L.",895:"Nestec S.A.",896:"LLC MEGA - F service",897:"Sharp Corporation",898:"Precision Outcomes Ltd",899:"Kronos Incorporated",900:"OCOSMOS Co., Ltd.",901:"Embedded Electronic Solutions Ltd. dba e2Solutions",902:"Aterica Inc.",903:"BluStor PMC, Inc.",904:"Kapsch TrafficCom AB",905:"ActiveBlu Corporation",906:"Kohler Mira Limited",907:"Noke",908:"Appion Inc.",909:"Resmed Ltd",910:"Crownstone B.V.",911:"Xiaomi Inc.",912:"INFOTECH s.r.o.",913:"Thingsquare AB",914:"T&D",915:"LAVAZZA S.p.A.",916:"Netclearance Systems, Inc.",917:"SDATAWAY",918:"BLOKS GmbH",919:"LEGO System A/S",920:"Thetatronics Ltd",921:"Nikon Corporation",922:"NeST",923:"South Silicon Valley Microelectronics",924:"ALE International",925:"CareView Communications, Inc.",926:"SchoolBoard Limited",927:"Molex Corporation",928:"IVT Wireless Limited",929:"Alpine Labs LLC",930:"Candura Instruments",931:"SmartMovt Technology Co., Ltd",932:"Token Zero Ltd",933:"ACE CAD Enterprise Co., Ltd. (ACECAD)",934:"Medela, Inc",935:"AeroScout",936:"Esrille Inc.",937:"THINKERLY SRL",938:"Exon Sp. z o.o.",939:"Meizu Technology Co., Ltd.",940:"Smablo LTD",941:"XiQ",942:"Allswell Inc.",943:"Comm-N-Sense Corp DBA Verigo",944:"VIBRADORM GmbH",945:"Otodata Wireless Network Inc.",946:"Propagation Systems Limited",947:"Midwest Instruments & Controls",948:"Alpha Nodus, inc.",949:"petPOMM, Inc",950:"Mattel",951:"Airbly Inc.",952:"A-Safe Limited",953:"FREDERIQUE CONSTANT SA",954:"Maxscend Microelectronics Company Limited",955:"Abbott Diabetes Care",956:"ASB Bank Ltd",957:"amadas",958:"Applied Science, Inc.",959:"iLumi Solutions Inc.",960:"Arch Systems Inc.",961:"Ember Technologies, Inc.",962:"Snapchat Inc",963:"Casambi Technologies Oy",964:"Pico Technology Inc.",965:"St. Jude Medical, Inc.",966:"Intricon",967:"Structural Health Systems, Inc.",968:"Avvel International",969:"Gallagher Group",970:"In2things Automation Pvt. Ltd.",971:"SYSDEV Srl",972:"Vonkil Technologies Ltd",973:"Wynd Technologies, Inc.",974:"CONTRINEX S.A.",975:"MIRA, Inc.",976:"Watteam Ltd",977:"Density Inc.",978:"IOT Pot India Private Limited",979:"Sigma Connectivity AB",980:"PEG PEREGO SPA",981:"Wyzelink Systems Inc.",982:"Yota Devices LTD",983:"FINSECUR",984:"Zen-Me Labs Ltd",985:"3IWare Co., Ltd.",986:"EnOcean GmbH",987:"Instabeat, Inc",988:"Nima Labs",989:"Andreas Stihl AG & Co. KG",990:"Nathan Rhoades LLC",991:"Grob Technologies, LLC",992:"Actions (Zhuhai) Technology Co., Limited",993:"SPD Development Company Ltd",994:"Sensoan Oy",995:"Qualcomm Life Inc",996:"Chip-ing AG",997:"ffly4u",998:"IoT Instruments Oy",999:"TRUE Fitness Technology",1000:"Reiner Kartengeraete GmbH & Co. KG.",1001:"SHENZHEN LEMONJOY TECHNOLOGY CO., LTD.",1002:"Hello Inc.",1003:"Evollve Inc.",1004:"Jigowatts Inc.",1005:"BASIC MICRO.COM,INC.",1006:"CUBE TECHNOLOGIES",1007:"foolography GmbH",1008:"CLINK",1009:"Hestan Smart Cooking Inc.",1010:"WindowMaster A/S",1011:"Flowscape AB",1012:"PAL Technologies Ltd",1013:"WHERE, Inc.",1014:"Iton Technology Corp.",1015:"Owl Labs Inc.",1016:"Rockford Corp.",1017:"Becon Technologies Co.,Ltd.",1018:"Vyassoft Technologies Inc",1019:"Nox Medical",1020:"Kimberly-Clark",1021:"Trimble Navigation Ltd.",1022:"Littelfuse",1023:"Withings",1024:"i-developer IT Beratung UG",1026:"Sears Holdings Corporation",1027:"Gantner Electronic GmbH",1028:"Authomate Inc",1029:"Vertex International, Inc.",1030:"Airtago",1031:"Swiss Audio SA",1032:"ToGetHome Inc.",1033:"AXIS",1034:"Openmatics",1035:"Jana Care Inc.",1036:"Senix Corporation",1037:"NorthStar Battery Company, LLC",1038:"SKF (U.K.) Limited",1039:"CO-AX Technology, Inc.",1040:"Fender Musical Instruments",1041:"Luidia Inc",1042:"SEFAM",1043:"Wireless Cables Inc",1044:"Lightning Protection International Pty Ltd",1045:"Uber Technologies Inc",1046:"SODA GmbH",1047:"Fatigue Science",1048:"Alpine Electronics Inc.",1049:"Novalogy LTD",1050:"Friday Labs Limited",1051:"OrthoAccel Technologies",1052:"WaterGuru, Inc.",1053:"Benning Elektrotechnik und Elektronik GmbH & Co. KG",1054:"Dell Computer Corporation",1055:"Kopin Corporation",1056:"TecBakery GmbH",1057:"Backbone Labs, Inc.",1058:"DELSEY SA",1059:"Chargifi Limited",1060:"Trainesense Ltd.",1061:"Unify Software and Solutions GmbH & Co. KG",1062:"Husqvarna AB",1063:"Focus fleet and fuel management inc",1064:"SmallLoop, LLC",1065:"Prolon Inc.",1066:"BD Medical",1067:"iMicroMed Incorporated",1068:"Ticto N.V.",1069:"Meshtech AS",1070:"MemCachier Inc.",1071:"Danfoss A/S",1072:"SnapStyk Inc.",1073:"Amyway Corporation",1074:"Silk Labs, Inc.",1075:"Pillsy Inc.",1076:"Hatch Baby, Inc.",1077:"Blocks Wearables Ltd.",1078:"Drayson Technologies (Europe) Limited",1079:"eBest IOT Inc.",1080:"Helvar Ltd",1081:"Radiance Technologies",1082:"Nuheara Limited",1083:"Appside co., ltd.",1084:"DeLaval",1085:"Coiler Corporation",1086:"Thermomedics, Inc.",1087:"Tentacle Sync GmbH",1088:"Valencell, Inc.",1089:"iProtoXi Oy",1090:"SECOM CO., LTD.",1091:"Tucker International LLC",1092:"Metanate Limited",1093:"Kobian Canada Inc.",1094:"NETGEAR, Inc.",1095:"Fabtronics Australia Pty Ltd",1096:"Grand Centrix GmbH",1097:"1UP USA.com llc",1098:"SHIMANO INC.",1099:"Nain Inc.",1100:"LifeStyle Lock, LLC",1101:"VEGA Grieshaber KG",1102:"Xtrava Inc.",1103:"TTS Tooltechnic Systems AG & Co. KG",1104:"Teenage Engineering AB",1105:"Tunstall Nordic AB",1106:"Svep Design Center AB",1107:"GreenPeak Technologies BV",1108:"Sphinx Electronics GmbH & Co KG",1109:"Atomation",1110:"Nemik Consulting Inc",1111:"RF INNOVATION",1112:"Mini Solution Co., Ltd.",1113:"Lumenetix, Inc",1114:"2048450 Ontario Inc",1115:"SPACEEK LTD",1116:"Delta T Corporation",1117:"Boston Scientific Corporation",1118:"Nuviz, Inc.",1119:"Real Time Automation, Inc.",1120:"Kolibree",1121:"vhf elektronik GmbH",1122:"Bonsai Systems GmbH",1123:"Fathom Systems Inc.",1124:"Bellman & Symfon",1125:"International Forte Group LLC",1126:"CycleLabs Solutions inc.",1127:"Codenex Oy",1128:"Kynesim Ltd",1129:"Palago AB",1130:"INSIGMA INC.",1131:"PMD Solutions",1132:"Qingdao Realtime Technology Co., Ltd.",1133:"BEGA Gantenbrink-Leuchten KG",1134:"Pambor Ltd.",65535:"SPECIAL USE/DEFAULT"}});var require_bluetooth=__commonJS((exports)=>{var exec3=__require("child_process").exec,execSync17=__require("child_process").execSync,path6=__require("path"),util4=require_util3(),bluetoothVendors=require_bluetoothVendors(),fs3=__require("fs"),_platform=process.platform,_linux=_platform==="linux"||_platform==="android",_darwin=_platform==="darwin",_windows=_platform==="win32",_freebsd=_platform==="freebsd",_openbsd=_platform==="openbsd",_netbsd=_platform==="netbsd",_sunos=_platform==="sunos";function parseBluetoothType(str5){let result2="";if(str5.indexOf("keyboard")>=0)result2="Keyboard";if(str5.indexOf("mouse")>=0)result2="Mouse";if(str5.indexOf("trackpad")>=0)result2="Trackpad";if(str5.indexOf("audio")>=0)result2="Audio";if(str5.indexOf("sound")>=0)result2="Audio";if(str5.indexOf("microph")>=0)result2="Microphone";if(str5.indexOf("speaker")>=0)result2="Speaker";if(str5.indexOf("headset")>=0)result2="Headset";if(str5.indexOf("phone")>=0)result2="Phone";if(str5.indexOf("macbook")>=0)result2="Computer";if(str5.indexOf("imac")>=0)result2="Computer";if(str5.indexOf("ipad")>=0)result2="Tablet";if(str5.indexOf("watch")>=0)result2="Watch";if(str5.indexOf("headphone")>=0)result2="Headset";return result2}function parseBluetoothManufacturer(str5){let result2=str5.split(" ")[0];if(str5=str5.toLowerCase(),str5.indexOf("apple")>=0)result2="Apple";if(str5.indexOf("ipad")>=0)result2="Apple";if(str5.indexOf("imac")>=0)result2="Apple";if(str5.indexOf("iphone")>=0)result2="Apple";if(str5.indexOf("magic mouse")>=0)result2="Apple";if(str5.indexOf("magic track")>=0)result2="Apple";if(str5.indexOf("macbook")>=0)result2="Apple";return result2}function parseBluetoothVendor(str5){let id=parseInt(str5);if(!isNaN(id))return bluetoothVendors[id]}function parseLinuxBluetoothInfo(lines,macAddr1,macAddr2){let result2={};return result2.device=null,result2.name=util4.getValue(lines,"name","="),result2.manufacturer=null,result2.macDevice=macAddr1,result2.macHost=macAddr2,result2.batteryPercent=null,result2.type=parseBluetoothType(result2.name.toLowerCase()),result2.connected=!1,result2}function parseDarwinBluetoothDevices(bluetoothObject,macAddr2){let result2={},typeStr=((bluetoothObject.device_minorClassOfDevice_string||bluetoothObject.device_majorClassOfDevice_string||bluetoothObject.device_minorType||"")+(bluetoothObject.device_name||"")).toLowerCase();return result2.device=bluetoothObject.device_services||"",result2.name=bluetoothObject.device_name||"",result2.manufacturer=bluetoothObject.device_manufacturer||parseBluetoothVendor(bluetoothObject.device_vendorID)||parseBluetoothManufacturer(bluetoothObject.device_name||"")||"",result2.macDevice=(bluetoothObject.device_addr||bluetoothObject.device_address||"").toLowerCase().replace(/-/g,":"),result2.macHost=macAddr2,result2.batteryPercent=bluetoothObject.device_batteryPercent||null,result2.type=parseBluetoothType(typeStr),result2.connected=bluetoothObject.device_isconnected==="attrib_Yes"||!1,result2}function parseWindowsBluetooth(lines){let result2={};return result2.device=null,result2.name=util4.getValue(lines,"name",":"),result2.manufacturer=util4.getValue(lines,"manufacturer",":"),result2.macDevice=null,result2.macHost=null,result2.batteryPercent=null,result2.type=parseBluetoothType(result2.name.toLowerCase()),result2.connected=null,result2}function bluetoothDevices(callback){return new Promise((resolve13)=>{process.nextTick(()=>{let result2=[];if(_linux){util4.getFilesInPath("/var/lib/bluetooth/").forEach((element)=>{let filename=path6.basename(element),pathParts=element.split("/"),macAddr1=pathParts.length>=6?pathParts[pathParts.length-2]:null,macAddr2=pathParts.length>=7?pathParts[pathParts.length-3]:null;if(filename==="info"){let infoFile=fs3.readFileSync(element,{encoding:"utf8"}).split(`
3041
3049
  `);result2.push(parseLinuxBluetoothInfo(infoFile,macAddr1,macAddr2))}});try{let hdicon=execSync17("hcitool con",util4.execOptsLinux).toString().toLowerCase();for(let i2=0;i2<result2.length;i2++)if(result2[i2].macDevice&&result2[i2].macDevice.length>10&&hdicon.indexOf(result2[i2].macDevice.toLowerCase())>=0)result2[i2].connected=!0}catch{util4.noop()}if(callback)callback(result2);resolve13(result2)}if(_darwin)exec3("system_profiler SPBluetoothDataType -json",(error2,stdout)=>{if(!error2)try{let outObj=JSON.parse(stdout.toString());if(outObj.SPBluetoothDataType&&outObj.SPBluetoothDataType.length&&outObj.SPBluetoothDataType[0]&&outObj.SPBluetoothDataType[0].device_title&&outObj.SPBluetoothDataType[0].device_title.length){let macAddr2=null;if(outObj.SPBluetoothDataType[0].local_device_title&&outObj.SPBluetoothDataType[0].local_device_title.general_address)macAddr2=outObj.SPBluetoothDataType[0].local_device_title.general_address.toLowerCase().replace(/-/g,":");outObj.SPBluetoothDataType[0].device_title.forEach((element)=>{let obj=element,objKey=Object.keys(obj);if(objKey&&objKey.length===1){let innerObject=obj[objKey[0]];innerObject.device_name=objKey[0];let bluetoothDevice=parseDarwinBluetoothDevices(innerObject,macAddr2);result2.push(bluetoothDevice)}})}if(outObj.SPBluetoothDataType&&outObj.SPBluetoothDataType.length&&outObj.SPBluetoothDataType[0]&&outObj.SPBluetoothDataType[0].device_connected&&outObj.SPBluetoothDataType[0].device_connected.length){let macAddr2=outObj.SPBluetoothDataType[0].controller_properties&&outObj.SPBluetoothDataType[0].controller_properties.controller_address?outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g,":"):null;outObj.SPBluetoothDataType[0].device_connected.forEach((element)=>{let obj=element,objKey=Object.keys(obj);if(objKey&&objKey.length===1){let innerObject=obj[objKey[0]];innerObject.device_name=objKey[0],innerObject.device_isconnected="attrib_Yes";let bluetoothDevice=parseDarwinBluetoothDevices(innerObject,macAddr2);result2.push(bluetoothDevice)}})}if(outObj.SPBluetoothDataType&&outObj.SPBluetoothDataType.length&&outObj.SPBluetoothDataType[0]&&outObj.SPBluetoothDataType[0].device_not_connected&&outObj.SPBluetoothDataType[0].device_not_connected.length){let macAddr2=outObj.SPBluetoothDataType[0].controller_properties&&outObj.SPBluetoothDataType[0].controller_properties.controller_address?outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g,":"):null;outObj.SPBluetoothDataType[0].device_not_connected.forEach((element)=>{let obj=element,objKey=Object.keys(obj);if(objKey&&objKey.length===1){let innerObject=obj[objKey[0]];innerObject.device_name=objKey[0],innerObject.device_isconnected="attrib_No";let bluetoothDevice=parseDarwinBluetoothDevices(innerObject,macAddr2);result2.push(bluetoothDevice)}})}}catch{util4.noop()}if(callback)callback(result2);resolve13(result2)});if(_windows)util4.powerShell("Get-CimInstance Win32_PNPEntity | select PNPClass, Name, Manufacturer, Status, Service, ConfigManagerErrorCode, Present | fl").then((stdout,error2)=>{if(!error2)stdout.toString().split(/\n\s*\n/).forEach((part)=>{let lines=part.split(`
3042
- `),service=util4.getValue(lines,"Service",":"),errorCode=util4.getValue(lines,"ConfigManagerErrorCode",":");if(util4.getValue(lines,"PNPClass",":").toLowerCase()==="bluetooth"&&errorCode==="0"&&service==="")result2.push(parseWindowsBluetooth(lines))});if(callback)callback(result2);resolve13(result2)});if(_freebsd||_netbsd||_openbsd||_sunos)resolve13(null)})})}exports.bluetoothDevices=bluetoothDevices});var require_lib5=__commonJS((exports)=>{var lib_version=require_package().version,util4=require_util3(),system=require_system(),osInfo=require_osinfo(),cpu=require_cpu(),memory=require_memory(),battery=require_battery(),graphics=require_graphics(),filesystem=require_filesystem(),network=require_network(),wifi=require_wifi(),processes=require_processes(),users=require_users(),internet=require_internet(),docker=require_docker(),vbox=require_virtualbox(),printer=require_printer(),usb=require_usb(),audio=require_audio(),bluetooth=require_bluetooth(),_platform=process.platform,_windows=_platform==="win32",_freebsd=_platform==="freebsd",_openbsd=_platform==="openbsd",_netbsd=_platform==="netbsd",_sunos=_platform==="sunos";if(_windows)util4.getCodepage(),util4.getPowershell();function version(){return lib_version}function getStaticData(callback){return new Promise((resolve13)=>{process.nextTick(()=>{let data={};data.version=version(),Promise.all([system.system(),system.bios(),system.baseboard(),system.chassis(),osInfo.osInfo(),osInfo.uuid(),osInfo.versions(),cpu.cpu(),cpu.cpuFlags(),graphics.graphics(),network.networkInterfaces(),memory.memLayout(),filesystem.diskLayout(),audio.audio(),bluetooth.bluetoothDevices(),usb.usb(),printer.printer()]).then((res)=>{if(data.system=res[0],data.bios=res[1],data.baseboard=res[2],data.chassis=res[3],data.os=res[4],data.uuid=res[5],data.versions=res[6],data.cpu=res[7],data.cpu.flags=res[8],data.graphics=res[9],data.net=res[10],data.memLayout=res[11],data.diskLayout=res[12],data.audio=res[13],data.bluetooth=res[14],data.usb=res[15],data.printer=res[16],callback)callback(data);resolve13(data)})})})}function getDynamicData(srv,iface,callback){if(util4.isFunction(iface))callback=iface,iface="";if(util4.isFunction(srv))callback=srv,srv="";return new Promise((resolve13)=>{process.nextTick(()=>{iface=iface||network.getDefaultNetworkInterface(),srv=srv||"";let functionProcessed=(()=>{let totalFunctions=15;if(_windows)totalFunctions=13;if(_freebsd||_openbsd||_netbsd)totalFunctions=11;if(_sunos)totalFunctions=6;return function(){if(--totalFunctions===0){if(callback)callback(data);resolve13(data)}}})(),data={};if(data.time=osInfo.time(),data.node=process.versions.node,data.v8=process.versions.v8,cpu.cpuCurrentSpeed().then((res)=>{data.cpuCurrentSpeed=res,functionProcessed()}),users.users().then((res)=>{data.users=res,functionProcessed()}),processes.processes().then((res)=>{data.processes=res,functionProcessed()}),cpu.currentLoad().then((res)=>{data.currentLoad=res,functionProcessed()}),!_sunos)cpu.cpuTemperature().then((res)=>{data.temp=res,functionProcessed()});if(!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)network.networkStats(iface).then((res)=>{data.networkStats=res,functionProcessed()});if(!_sunos)network.networkConnections().then((res)=>{data.networkConnections=res,functionProcessed()});if(memory.mem().then((res)=>{data.mem=res,functionProcessed()}),!_sunos)battery().then((res)=>{data.battery=res,functionProcessed()});if(!_sunos)processes.services(srv).then((res)=>{data.services=res,functionProcessed()});if(!_sunos)filesystem.fsSize().then((res)=>{data.fsSize=res,functionProcessed()});if(!_windows&&!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)filesystem.fsStats().then((res)=>{data.fsStats=res,functionProcessed()});if(!_windows&&!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)filesystem.disksIO().then((res)=>{data.disksIO=res,functionProcessed()});if(!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)wifi.wifiNetworks().then((res)=>{data.wifiNetworks=res,functionProcessed()});internet.inetLatency().then((res)=>{data.inetLatency=res,functionProcessed()})})})}function getAllData(srv,iface,callback){return new Promise((resolve13)=>{process.nextTick(()=>{let data={};if(iface&&util4.isFunction(iface)&&!callback)callback=iface,iface="";if(srv&&util4.isFunction(srv)&&!iface&&!callback)callback=srv,srv="",iface="";getStaticData().then((res)=>{data=res,getDynamicData(srv,iface).then((res2)=>{for(let key in res2)if({}.hasOwnProperty.call(res2,key))data[key]=res2[key];if(callback)callback(data);resolve13(data)})})})})}function get3(valueObject,callback){return new Promise((resolve13)=>{process.nextTick(()=>{let allPromises=Object.keys(valueObject).filter((func)=>({}).hasOwnProperty.call(exports,func)).map((func)=>{let params=valueObject[func].substring(valueObject[func].lastIndexOf("(")+1,valueObject[func].lastIndexOf(")")),funcWithoutParams=func.indexOf(")")>=0?func.split(")")[1].trim():func;if(funcWithoutParams=func.indexOf("|")>=0?func.split("|")[0].trim():funcWithoutParams,params)return exports[funcWithoutParams](params);else return exports[funcWithoutParams]("")});Promise.all(allPromises).then((data)=>{let result2={},i2=0;for(let key in valueObject)if({}.hasOwnProperty.call(valueObject,key)&&{}.hasOwnProperty.call(exports,key)&&data.length>i2){if(valueObject[key]==="*"||valueObject[key]==="all")result2[key]=data[i2];else{let keys=valueObject[key],filter="",filterParts=[];if(keys.indexOf(")")>=0)keys=keys.split(")")[1].trim();if(keys.indexOf("|")>=0)filter=keys.split("|")[1].trim(),filterParts=filter.split(":"),keys=keys.split("|")[0].trim();if(keys=keys.replace(/,/g," ").replace(/ +/g," ").split(" "),data[i2])if(Array.isArray(data[i2])){let partialArray=[];data[i2].forEach((element)=>{let partialRes={};if(keys.length===1&&(keys[0]==="*"||keys[0]==="all"))partialRes=element;else keys.forEach((k2)=>{if({}.hasOwnProperty.call(element,k2))partialRes[k2]=element[k2]});if(filter&&filterParts.length===2){if({}.hasOwnProperty.call(partialRes,filterParts[0].trim())){let val=partialRes[filterParts[0].trim()];if(typeof val==="number"){if(val===parseFloat(filterParts[1].trim()))partialArray.push(partialRes)}else if(typeof val==="string"){if(val.toLowerCase()===filterParts[1].trim().toLowerCase())partialArray.push(partialRes)}}}else partialArray.push(partialRes)}),result2[key]=partialArray}else{let partialRes={};keys.forEach((k2)=>{if({}.hasOwnProperty.call(data[i2],k2))partialRes[k2]=data[i2][k2]}),result2[key]=partialRes}else result2[key]={}}i2++}if(callback)callback(result2);resolve13(result2)})})})}function observe(valueObject,interval,callback){let _data=null;return setInterval(()=>{get3(valueObject).then((data)=>{if(JSON.stringify(_data)!==JSON.stringify(data))_data=Object.assign({},data),callback(data)})},interval)}exports.version=version;exports.system=system.system;exports.bios=system.bios;exports.baseboard=system.baseboard;exports.chassis=system.chassis;exports.time=osInfo.time;exports.osInfo=osInfo.osInfo;exports.versions=osInfo.versions;exports.shell=osInfo.shell;exports.uuid=osInfo.uuid;exports.cpu=cpu.cpu;exports.cpuFlags=cpu.cpuFlags;exports.cpuCache=cpu.cpuCache;exports.cpuCurrentSpeed=cpu.cpuCurrentSpeed;exports.cpuTemperature=cpu.cpuTemperature;exports.currentLoad=cpu.currentLoad;exports.fullLoad=cpu.fullLoad;exports.mem=memory.mem;exports.memLayout=memory.memLayout;exports.battery=battery;exports.graphics=graphics.graphics;exports.fsSize=filesystem.fsSize;exports.fsOpenFiles=filesystem.fsOpenFiles;exports.blockDevices=filesystem.blockDevices;exports.fsStats=filesystem.fsStats;exports.disksIO=filesystem.disksIO;exports.diskLayout=filesystem.diskLayout;exports.networkInterfaceDefault=network.networkInterfaceDefault;exports.networkGatewayDefault=network.networkGatewayDefault;exports.networkInterfaces=network.networkInterfaces;exports.networkStats=network.networkStats;exports.networkConnections=network.networkConnections;exports.wifiNetworks=wifi.wifiNetworks;exports.wifiInterfaces=wifi.wifiInterfaces;exports.wifiConnections=wifi.wifiConnections;exports.services=processes.services;exports.processes=processes.processes;exports.processLoad=processes.processLoad;exports.users=users.users;exports.inetChecksite=internet.inetChecksite;exports.inetLatency=internet.inetLatency;exports.dockerInfo=docker.dockerInfo;exports.dockerImages=docker.dockerImages;exports.dockerContainers=docker.dockerContainers;exports.dockerContainerStats=docker.dockerContainerStats;exports.dockerContainerProcesses=docker.dockerContainerProcesses;exports.dockerVolumes=docker.dockerVolumes;exports.dockerAll=docker.dockerAll;exports.vboxInfo=vbox.vboxInfo;exports.printer=printer.printer;exports.usb=usb.usb;exports.audio=audio.audio;exports.bluetoothDevices=bluetooth.bluetoothDevices;exports.getStaticData=getStaticData;exports.getDynamicData=getDynamicData;exports.getAllData=getAllData;exports.get=get3;exports.observe=observe;exports.powerShellStart=util4.powerShellStart;exports.powerShellRelease=util4.powerShellRelease});import os4 from"os";function toGB(bytes){return Math.round(bytes/1073741824*10)/10}function bar(percent,width){let p=Math.max(0,Math.min(100,percent)),filled=Math.round(p/100*width);return`[${"=".repeat(filled)}${"-".repeat(width-filled)}]`}function pickColor(percent){if(percent>80)return palette.error;if(percent>50)return palette.warning;return palette.emerald}function SystemStats(){let[stats,setStats]=import_react15.useState(null),mountedRef=import_react15.useRef(!0);if(import_react15.useEffect(()=>{mountedRef.current=!0;async function refresh(){try{let[cpu2,mem]=await Promise.all([import_systeminformation.default.currentLoad(),import_systeminformation.default.mem()]);if(!mountedRef.current)return;let coreCount=os4.cpus().length,avg1=os4.loadavg()[0],sorted=cpu2.cpus.map((c,i2)=>({id:i2,load:Math.round(c.load)})).sort((a,b3)=>b3.load-a.load);setStats({cpu:{combined:Math.round(cpu2.currentLoad),hotCores:sorted.slice(0,3),coreCount},ram:{usedGB:toGB(mem.active),totalGB:toGB(mem.total),percent:mem.total>0?Math.round(mem.active/mem.total*100):0},swap:{usedGB:toGB(mem.swapused),totalGB:toGB(mem.swaptotal),percent:mem.swaptotal>0?Math.round(mem.swapused/mem.swaptotal*100):0},load:{percent:coreCount>0?Math.round(avg1/coreCount*100):0,busy:Math.round(avg1*10)/10,total:coreCount}})}catch{}}refresh();let timer2=setInterval(refresh,3000);return()=>{mountedRef.current=!1,clearInterval(timer2)}},[]),!stats)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgLight,children:import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:"genie"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` v${VERSION}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);let{cpu,ram,swap,load:load3}=stats,hotStr=cpu.hotCores.map((c)=>`#${c.id} ${c.load}%`).join(" ");return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgLight,children:[import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:"genie"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` v${VERSION}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"CPU "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(cpu.combined),children:`${String(cpu.combined).padStart(3)}% ${bar(cpu.combined,8)}`},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` ${cpu.coreCount}c`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:" hot "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.warning,children:hotStr},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"RAM "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(ram.percent),children:`${ram.usedGB}/${ram.totalGB}G ${bar(ram.percent,8)}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),swap.totalGB>0?import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"SWP "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(swap.percent),children:`${swap.usedGB}/${swap.totalGB}G ${bar(swap.percent,8)}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"Load "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(load3.percent),children:`${load3.percent}%`},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` (${load3.busy}/${load3.total} busy)`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var import_react15,import_systeminformation;var init_SystemStats=__esm(()=>{init_version();init_theme2();init_jsx_dev_runtime();import_react15=__toESM(require_react_development(),1),import_systeminformation=__toESM(require_lib5(),1)});function getNodeIcon(node){if(node.type==="agent")return getAgentIcon(node);switch(node.type){case"session":return node.data.attached?"\u25B6":"\u25B8";case"window":return node.data.active?"\u25A0":"\u25A1";case"pane":return getPaneIcon(node);default:return" "}}function getAgentIcon(node){switch(node.wsAgentState){case"running":return"\u25CF";case"stopped":return"\u25CB";case"error":return"\u2298";case"spawning":return"\u231B";default:return"\u25CB"}}function getPaneIcon(node){if(node.data.isDead)return"\u2718";if(node.agentState==="working")return"\u25CF";if(node.agentState==="idle")return"\u25CB";if(node.agentState==="permission")return"\u26A0";if(node.agentState==="error")return"\u2718";if(node.data.command==="claude")return"\u25C6";return"\u25CB"}function getNodeColor(node){if(node.type==="agent")return getAgentColor(node);switch(node.type){case"session":return node.data.attached?palette.emerald:palette.textDim;case"window":return node.data.active?palette.cyan:palette.text;case"pane":return getPaneColor(node);default:return palette.text}}function getAgentColor(node){switch(node.wsAgentState){case"running":return palette.emerald;case"stopped":return palette.textDim;case"error":return palette.error;case"spawning":return palette.warning;default:return palette.textDim}}function getPaneColor(node){if(node.data.isDead)return palette.error;if(node.agentState==="working")return palette.cyan;if(node.agentState==="permission")return palette.warning;if(node.agentState==="error")return palette.error;if(node.agentState==="idle")return palette.textDim;if(node.data.command==="claude")return palette.cyan;return palette.textDim}function getNodeSuffix(node){if(node.type==="agent"){if(node.wsAgentState==="spawning"&&node.activePanes===0)return" [stuck \u2014 press R to retry]";let wc=node.data.windowCount;if(wc>1)return` (${wc} windows)`;if(wc===1)return" (1 window)";return""}if(node.type==="session"||node.type==="pane"){let count=node.activePanes;if(count>0)return` ${icons.agent}${count}`}return""}function getStateColor(state){switch(state){case"working":return palette.cyan;case"idle":return palette.textDim;case"permission":return palette.warning;case"error":return palette.error;default:return palette.textMuted}}var import_react16,TreeNodeRow;var init_TreeNode=__esm(()=>{init_theme2();init_jsx_dev_runtime();import_react16=__toESM(require_react_development(),1),TreeNodeRow=import_react16.memo(function({node,selected,onSelect,onToggle,onContextMenu}){let indent=" ".repeat(node.depth),hasChildren=node.children.length>0,expandIcon=hasChildren?node.expanded?icons.expanded:icons.collapsed:" ",icon=getNodeIcon(node),color2=getNodeColor(node),suffix=getNodeSuffix(node);return import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",backgroundColor:selected?palette.violet:void 0,onMouseDown:(event)=>{if(event.button===2&&onContextMenu){onSelect(node.id),onContextMenu(node.id);return}if(onSelect(node.id),hasChildren)onToggle(node.id)},children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:[indent,expandIcon," "]},void 0,!0,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:color2,children:[icon," "]},void 0,!0,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:selected?"#ffffff":palette.text,children:node.label},void 0,!1,void 0,this),suffix?import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:suffix},void 0,!1,void 0,this):null,node.agentState?import_jsx_dev_runtime2.jsxDEV("span",{fg:getStateColor(node.agentState),children:[" ",node.agentState]},void 0,!0,void 0,this):null,import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:` [${node.type}]`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)})});function Nav({onTmuxSessionSelect,onNewAgentWindow,workspaceRoot,initialAgent,keyboardDisabled=!1}){let[diagnostics,setDiagnostics]=import_react18.useState(null),[sessionTree,setSessionTree]=import_react18.useState([]),[selectedIndex,setSelectedIndex]=import_react18.useState(0),[requestedInitialAgent,setRequestedInitialAgent]=import_react18.useState(initialAgent),[contextMenuNodeId,setContextMenuNodeId]=import_react18.useState(null),lastTarget=import_react18.useRef(null),selectedNodeId=import_react18.useRef(null);import_react18.useEffect(()=>{let active=!0;async function refresh(){try{let snap=await collectDiagnostics();if(!active)return;setDiagnostics(snap);let signaledAgent=consumeInitialAgentSignal();if(signaledAgent)setRequestedInitialAgent(signaledAgent)}catch(err){console.error("TUI: diagnostics failed:",err)}}refresh();let timer2=setInterval(refresh,2000);return()=>{active=!1,clearInterval(timer2)}},[]),import_react18.useEffect(()=>{if(!diagnostics)return;let newTree;if(workspaceRoot){let agentNames=scanAgents2(workspaceRoot);newTree=buildWorkspaceTree({agentNames,sessions:diagnostics.sessions,executors:diagnostics.executors})}else newTree=buildSessionTree(diagnostics);setSessionTree((prev)=>mergeExpandedState(prev,newTree))},[diagnostics,workspaceRoot]);let flatNodes=import_react18.useMemo(()=>flattenTree(sessionTree),[sessionTree]);import_react18.useEffect(()=>{let node=flatNodes[selectedIndex]?.node;if(node)selectedNodeId.current=node.id},[selectedIndex,flatNodes]),import_react18.useLayoutEffect(()=>{if(flatNodes.length===0)return;if(selectedIndex>=flatNodes.length){setSelectedIndex(flatNodes.length-1);return}if(!selectedNodeId.current)return;let currentAtIndex=flatNodes[selectedIndex]?.node;if(currentAtIndex&&currentAtIndex.id===selectedNodeId.current)return;let restored=flatNodes.findIndex((n)=>n.node.id===selectedNodeId.current);if(restored>=0)setSelectedIndex(restored)},[flatNodes]),import_react18.useEffect(()=>{if(!requestedInitialAgent||flatNodes.length===0)return;let idx=flatNodes.findIndex((n)=>n.node.id===`agent:${requestedInitialAgent}`);if(idx>=0){setSelectedIndex(idx);let node=flatNodes[idx].node;if(node.type==="agent"&&node.wsAgentState!=="running"&&node.wsAgentState!=="spawning")spawnAgent(agentNameFromNode(node),onTmuxSessionSelect);setRequestedInitialAgent(void 0)}},[requestedInitialAgent,flatNodes,onTmuxSessionSelect]),import_react18.useEffect(()=>{let current=flatNodes[selectedIndex]?.node;if(!current)return;let target=getSessionTarget(current);if(!target)return;if(current.type==="agent"&&current.wsAgentState!=="running")return;let key=`${target.sessionName}:${target.windowIndex??""}`;if(key===lastTarget.current)return;lastTarget.current=key,onTmuxSessionSelect(target.sessionName,target.windowIndex)},[selectedIndex,flatNodes,onTmuxSessionSelect]);let handleSelect=import_react18.useCallback((id)=>{let idx=flatNodes.findIndex((n)=>n.node.id===id);if(idx>=0)setSelectedIndex(idx)},[flatNodes]),handleToggle=import_react18.useCallback((id)=>{setSessionTree((prev)=>toggleNode(prev,id))},[]),handleVerticalNav=import_react18.useCallback((keyName2)=>{let rowCount=flatNodes.length;if(rowCount===0)return;if(keyName2==="up"||keyName2==="k")setSelectedIndex((prev)=>prev===0?rowCount-1:prev-1);else if(keyName2==="down"||keyName2==="j")setSelectedIndex((prev)=>prev>=rowCount-1?0:prev+1)},[flatNodes.length]),handleExpandCollapse=import_react18.useCallback((keyName2)=>{let node=flatNodes[selectedIndex]?.node;if(!node)return;if((keyName2==="right"||keyName2==="l")&&node.children.length>0&&!node.expanded)handleToggle(node.id);else if((keyName2==="left"||keyName2==="h")&&node.expanded)handleToggle(node.id)},[flatNodes,selectedIndex,handleToggle]),handleEnter=import_react18.useCallback(()=>{let node=flatNodes[selectedIndex]?.node;if(!node)return;if(node.type==="agent"){handleEnterAgent(node,onTmuxSessionSelect);return}if(node.children.length>0)handleToggle(node.id);let target=getSessionTarget(node);if(target)onTmuxSessionSelect(target.sessionName,target.windowIndex)},[flatNodes,selectedIndex,handleToggle,onTmuxSessionSelect]),handleRetry=import_react18.useCallback(()=>{let node=flatNodes[selectedIndex]?.node;if(!node||node.type!=="agent")return;if(node.wsAgentState!=="spawning"&&node.wsAgentState!=="error")return;(async()=>{try{let{reconcileStaleSpawns:reconcileStaleSpawns2}=await Promise.resolve().then(() => (init_agent_registry(),exports_agent_registry));await reconcileStaleSpawns2()}catch{}spawnAgent(agentNameFromNode(node),onTmuxSessionSelect)})()},[flatNodes,selectedIndex,onTmuxSessionSelect]),handleContextMenu=import_react18.useCallback((nodeId)=>{let flat=flatNodes.find((n)=>n.node.id===nodeId);if(flat&&buildMenuItems(flat.node).length>0)setContextMenuNodeId(nodeId)},[flatNodes]),handleContextMenuAction=import_react18.useCallback((action,payload)=>{let node=flatNodes.find((n)=>n.node.id===contextMenuNodeId)?.node;if(!node)return;setContextMenuNodeId(null),dispatchContextMenuAction(action,node,payload,{sessionTree,onTmuxSessionSelect,onNewAgentWindow})},[flatNodes,contextMenuNodeId,sessionTree,onTmuxSessionSelect,onNewAgentWindow]),_menuDisabled=keyboardDisabled||contextMenuNodeId!==null;useKeyboard((key)=>{if(keyboardDisabled)return;handleKeyboardInput(key,{contextMenuNodeId,flatNodes,selectedIndex,setContextMenuNodeId,handleVerticalNav,handleExpandCollapse,handleEnter,handleRetry,onNewAgentWindow})});let agentCount=workspaceRoot?sessionTree.filter((n)=>n.type==="agent").length:diagnostics?.sessions.length??0,runningCount=workspaceRoot?sessionTree.filter((n)=>n.wsAgentState==="running").length:diagnostics?.sessions.reduce((sum,s2)=>sum+s2.windows.reduce((ws,w2)=>ws+w2.panes.length,0),0)??0,headerLabel=workspaceRoot?"Agents":"Sessions";return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",width:"100%",height:"100%",backgroundColor:palette.bg,children:[import_jsx_dev_runtime2.jsxDEV("box",{height:1,paddingX:1,backgroundColor:palette.bgLight,children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:headerLabel},void 0,!1,void 0,this),diagnostics?import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:[" ",workspaceRoot?`${runningCount}/${agentCount}`:`${agentCount}s ${runningCount}p`]},void 0,!0,void 0,this):null]},void 0,!0,void 0,this)},void 0,!1,void 0,this),diagnostics?import_jsx_dev_runtime2.jsxDEV("scrollbox",{focused:!0,height:"100%",style:{scrollbarOptions:{showArrows:!1,trackOptions:{foregroundColor:palette.scrollThumb,backgroundColor:palette.scrollTrack}}},children:flatNodes.map((flat,i2)=>import_jsx_dev_runtime2.jsxDEV(TreeNodeRow,{node:flat.node,selected:i2===selectedIndex,onSelect:handleSelect,onToggle:handleToggle,onContextMenu:handleContextMenu},flat.node.id,!1,void 0,this))},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:import_jsx_dev_runtime2.jsxDEV("text",{fg:palette.textDim,children:"Collecting..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),contextMenuNodeId?import_jsx_dev_runtime2.jsxDEV(ContextMenu,{items:buildMenuItems(flatNodes.find((n)=>n.node.id===contextMenuNodeId)?.node??{}),onAction:handleContextMenuAction,onClose:()=>setContextMenuNodeId(null),positionY:flatNodes.findIndex((n)=>n.node.id===contextMenuNodeId)+1},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV(SystemStats,{},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,paddingX:1,backgroundColor:palette.bgLight,children:import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:["\u2191\u2193",":nav ","\u2190\u2192",":expand Enter:",workspaceRoot?"spawn/attach":"attach"," ^T:new R:retry .:menu"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function handleEnterAgent(node,onTmuxSessionSelect){if(node.wsAgentState!=="running"&&node.wsAgentState!=="spawning")spawnAgent(agentNameFromNode(node),onTmuxSessionSelect);else if(node.wsAgentState==="running"){let target=getSessionTarget(node);if(target)onTmuxSessionSelect(target.sessionName,target.windowIndex)}}function dispatchContextMenuAction(action,node,payload,deps){let name=node.label;if(handleAttachAction(action,node,deps.onTmuxSessionSelect))return;if(handleRetryAction(action,name,deps.onTmuxSessionSelect))return;if(handleGenieAction(action,name,payload))return;let tmuxServer=process.env.GENIE_TMUX_SERVER||"genie";if(handleRenameAction(action,node,tmuxServer,payload))return;if(handleAgentWindowActions(action,node,name,tmuxServer,deps.onNewAgentWindow))return;if(handleSessionNodeActions(action,node,tmuxServer,payload))return;if(handleWindowNodeActions(action,node,deps.sessionTree,tmuxServer,payload))return;handlePaneNodeActions(action,node,deps.sessionTree,tmuxServer,deps.onNewAgentWindow)}function handleAttachAction(action,node,onTmuxSessionSelect){if(action!=="attach")return!1;let target=getSessionTarget(node);if(target)onTmuxSessionSelect(target.sessionName,target.windowIndex);return!0}function handleRetryAction(action,name,onTmuxSessionSelect){if(action!=="retry")return!1;return(async()=>{try{let{reconcileStaleSpawns:reconcileStaleSpawns2}=await Promise.resolve().then(() => (init_agent_registry(),exports_agent_registry));await reconcileStaleSpawns2()}catch{}spawnAgent(name,onTmuxSessionSelect)})(),!0}function handleGenieAction(action,name,payload){if(action==="send"&&payload)return executeGenie(["agent","send",payload,"--to",name]),!0;if(action==="answer-text"&&payload)return executeGenie(["agent","answer",name,`text:${payload}`]),!0;let genieArgs={spawn:["spawn",name],"spawn-plan":["spawn",name,"--plan-mode"],stop:["agent","stop",name],kill:["agent","kill",name],log:["agent","log",name],show:["agent","show",name],read:["read",name],"answer-yes":["agent","answer",name,"yes"],"answer-no":["agent","answer",name,"no"]}[action];if(genieArgs)return executeGenie(genieArgs),!0;return!1}function handleRenameAction(action,node,tmuxServer,payload){if(action==="rename-session"&&payload){let sess=node.type==="agent"?node.data.sessionName||node.label:node.id.split(":").slice(1).join(":");return executeTmux3(["-L",tmuxServer,"rename-session","-t",sess,payload]),!0}if(action==="rename-window"&&payload){let idParts=node.id.split(":"),windowTarget=`${idParts[1]}:${idParts[2]}`;return executeTmux3(["-L",tmuxServer,"rename-window","-t",windowTarget,payload]),!0}if(action==="rename-pane"&&payload&&node.type==="pane"){let paneId=node.data.paneId;return executeTmux3(["-L",tmuxServer,"select-pane","-t",`${paneId}`,"-T",payload]),!0}return!1}function handleAgentWindowActions(action,node,name,tmuxServer,onNewAgentWindow){if(action==="agent-new-window"&&node.type==="agent"){if(onNewAgentWindow)onNewAgentWindow(agentNameFromNode(node));return!0}if(action==="new-empty-window"&&node.type==="agent"){let sessionName=node.data.sessionName||name;return executeTmux3(["-L",tmuxServer,"new-window","-a","-t",sessionName]),!0}return!1}function handleSessionNodeActions(action,node,tmuxServer,payload){if(node.type!=="session")return!1;let sess=node.id.split(":").slice(1).join(":");if(action==="kill-session")return executeTmux3(["-L",tmuxServer,"kill-session","-t",sess]),!0;if(action==="new-window")return executeTmux3(["-L",tmuxServer,"new-window","-a","-t",sess]),!0;if(action==="clone-session")return executeTmux3(["-L",tmuxServer,"new-session","-d","-s",`${sess}-clone`,"-t",sess]),!0;if(action==="spawn-in-session"&&payload)return executeGenie(["spawn",payload,"--session",sess]),!0;return!1}function handleWindowNodeActions(action,node,sessionTree,tmuxServer,payload){if(node.type!=="window")return!1;let idParts=node.id.split(":"),windowTarget=`${idParts[1]}:${idParts[2]}`;if(action==="kill-window")return executeTmux3(["-L",tmuxServer,"kill-window","-t",windowTarget]),!0;if(action==="window-new-agent"){let parentAgent=findParentAgent(sessionTree,node.id);if(parentAgent){let agentFullName=agentNameFromNode(parentAgent),suffix=Date.now()%1e4,role=`${agentFullName}-${suffix}`;executeGenie(["spawn",agentFullName,"--role",role,"--window",windowTarget])}return!0}if(action==="split-pane")return executeTmux3(["-L",tmuxServer,"split-window","-t",windowTarget]),!0;if(action==="spawn-in-window"&&payload)return executeGenie(["spawn",payload,"--session",idParts[1]]),!0;return!1}function handlePaneNodeActions(action,node,sessionTree,tmuxServer,onNewAgentWindow){if(node.type!=="pane")return!1;let paneId=node.data.paneId;if(action==="clone-agent"){let parentAgent=findParentAgent(sessionTree,node.id);if(parentAgent&&onNewAgentWindow)onNewAgentWindow(agentNameFromNode(parentAgent));return!0}if(action==="kill-pane")return executeTmux3(["-L",tmuxServer,"kill-pane","-t",`${paneId}`]),!0;if(action==="split-h")return executeTmux3(["-L",tmuxServer,"split-window","-h","-t",`${paneId}`]),!0;if(action==="split-v")return executeTmux3(["-L",tmuxServer,"split-window","-v","-t",`${paneId}`]),!0;return!1}function tryOpenContextMenu(flatNodes,selectedIndex,setContextMenuNodeId){let node=flatNodes[selectedIndex]?.node;if(node&&buildMenuItems(node).length>0)return setContextMenuNodeId(node.id),!0;return!1}function dispatchNavKey(key,handlers2,agentAction){let n=key.name;if(n==="up"||n==="k"||n==="down"||n==="j")handlers2.handleVerticalNav(n);else if(n==="right"||n==="l"||n==="left"||n==="h")handlers2.handleExpandCollapse(n);else if(n==="enter"||n==="return")handlers2.handleEnter();else if(n==="r")handlers2.handleRetry();else if(key.ctrl&&n==="t")agentAction()}function handleKeyboardInput(key,opts){if(key.name==="."&&!opts.contextMenuNodeId){if(tryOpenContextMenu(opts.flatNodes,opts.selectedIndex,opts.setContextMenuNodeId))return}if(opts.contextMenuNodeId)return;dispatchNavKey(key,opts,()=>{let node=opts.flatNodes[opts.selectedIndex]?.node;if(node?.type==="agent"&&node.wsAgentState==="running"&&opts.onNewAgentWindow)opts.onNewAgentWindow(agentNameFromNode(node))})}function agentNameFromNode(node){return node.id.replace(/^agent:/,"")}function spawnAgent(name,onTmuxSessionSelect){try{let{spawn:spawn5}=__require("child_process"),{join:join60,resolve:resolve13}=__require("path"),{existsSync:existsSync45}=__require("fs"),bunPath=process.execPath||"bun",genieBin=process.argv[1],wsRoot=process.env.GENIE_TUI_WORKSPACE,sessionName=name.replace(/\//g,"-"),cwd;if(wsRoot){let parentName=name.includes("/")?name.slice(0,name.indexOf("/")):name,agentDir=resolve13(join60(wsRoot,"agents",parentName));if(existsSync45(agentDir))cwd=agentDir}let{GENIE_TUI_PANE:_a,GENIE_TUI_RIGHT:_b,GENIE_TUI_WORKSPACE:_c,GENIE_IS_DAEMON:_d,...cleanEnv}=process.env,spawnOpts={detached:!0,stdio:"ignore",cwd,env:cleanEnv};if((genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,"spawn",name,"--session",sessionName,"--new-window"],spawnOpts):spawn5("genie",["spawn",name,"--session",sessionName,"--new-window"],spawnOpts)).unref(),onTmuxSessionSelect)attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect)}catch{}}function attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect,attempt=0){(async()=>{try{let session=(await collectDiagnostics()).sessions.find((candidate)=>candidate.name===sessionName);if(session){let windowIndex=resolvePreferredWindowIndex(session,sessionName);if(windowIndex!==void 0){onTmuxSessionSelect(sessionName,windowIndex);return}}}catch{}if(attempt>=40){onTmuxSessionSelect(sessionName);return}setTimeout(()=>{attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect,attempt+1)},250)})()}function executeTmux3(args){try{let{spawn:spawn5}=__require("child_process");spawn5("tmux",args,{detached:!0,stdio:"ignore"}).unref()}catch{}}function executeGenie(args){try{let{spawn:spawn5}=__require("child_process"),bunPath=process.execPath||"bun",genieBin=process.argv[1];(genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,...args],{detached:!0,stdio:"ignore"}):spawn5("genie",args,{detached:!0,stdio:"ignore"})).unref()}catch{}}function findParentAgent(tree,targetId){for(let node of tree){if(node.type==="agent"&&containsNode(node,targetId))return node;let found=findParentAgent(node.children,targetId);if(found)return found}return null}function containsNode(node,targetId){if(node.id===targetId)return!0;return node.children.some((c)=>containsNode(c,targetId))}function mergeExpandedState(oldTree,newTree){if(oldTree.length===0)return newTree;let oldState=new Map;function collect(nodes){for(let n of nodes)oldState.set(n.id,{expanded:n.expanded,childCount:n.children.length}),collect(n.children)}collect(oldTree);function apply(nodes){return nodes.map((n)=>({...n,expanded:(()=>{let previous=oldState.get(n.id);if(!previous)return n.expanded;if(previous.childCount===0&&n.children.length>0)return n.expanded;return previous.expanded})(),children:apply(n.children)}))}return apply(newTree)}var import_react18;var init_Nav=__esm(async()=>{init_workspace();init_diagnostics();init_initial_agent();init_theme2();init_SystemStats();init_TreeNode();init_jsx_dev_runtime();await __promiseAll([init_react(),init_ContextMenu()]);import_react18=__toESM(require_react_development(),1)});function QuitDialog({onConfirm,onCancel}){return useKeyboard((key)=>{if(key.name==="enter"||key.name==="return"||key.name==="y")onConfirm();else if(key.name==="escape"||key.name==="n")onCancel()}),import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:"#0a0a0a",children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderColor:palette.violet,backgroundColor:"#111111",paddingX:3,paddingY:1,flexDirection:"column",alignItems:"center",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:"Quit genie?"},void 0,!1,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:"Enter"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:" to quit "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:" | "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:" Esc"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:" to cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"Hint: Ctrl+D to detach (keep running)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var init_QuitDialog=__esm(async()=>{init_theme2();init_jsx_dev_runtime();await init_react()});import{execSync as execSync17}from"child_process";import{readFileSync as readFileSync28}from"fs";function App({rightPane,workspaceRoot,initialAgent}){let[showQuit,setShowQuit]=import_react21.useState(!1);useKeyboard((key)=>{if(key.ctrl&&key.name==="q")if(showQuit)handleQuit();else setShowQuit(!0)});let handleQuit=import_react21.useCallback(()=>{try{let genieHome5=process.env.GENIE_HOME??`${process.env.HOME}/.genie`,pid=readFileSync28(`${genieHome5}/serve.pid`,"utf-8").trim();process.kill(Number.parseInt(pid,10),"SIGTERM")}catch{}try{execSync17("tmux -L genie-tui kill-server",{stdio:"ignore"})}catch{}},[]),handleTmuxSessionSelect=import_react21.useCallback((sessionName,windowIndex)=>{if(!rightPane)return;attachProjectWindow(rightPane,sessionName,windowIndex)},[rightPane]);return import_jsx_dev_runtime2.jsxDEV("box",{width:"100%",height:"100%",children:[import_jsx_dev_runtime2.jsxDEV(Nav,{onTmuxSessionSelect:handleTmuxSessionSelect,onNewAgentWindow:newAgentWindow,workspaceRoot,initialAgent,keyboardDisabled:showQuit},void 0,!1,void 0,this),showQuit?import_jsx_dev_runtime2.jsxDEV(QuitDialog,{onConfirm:handleQuit,onCancel:()=>setShowQuit(!1)},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)}var import_react21;var init_app=__esm(async()=>{init_tmux2();init_jsx_dev_runtime();await __promiseAll([init_react(),init_Nav(),init_QuitDialog()]);import_react21=__toESM(require_react_development(),1)});var exports_render={};__export(exports_render,{renderNav:()=>renderNav});async function renderNav(){let rightPane=process.env.GENIE_TUI_RIGHT||void 0,workspaceRoot=process.env.GENIE_TUI_WORKSPACE||void 0,initialAgent=process.env.GENIE_TUI_AGENT||void 0,renderer=await createCliRenderer({exitOnCtrlC:!1,useMouse:!0});createRoot(renderer).render(import_jsx_dev_runtime2.jsxDEV(App,{rightPane,workspaceRoot,initialAgent},void 0,!1,void 0,this)),await new Promise((resolve13)=>{renderer.once("destroy",resolve13)})}var init_render=__esm(async()=>{init_jsx_dev_runtime();await __promiseAll([init_core(),init_react(),init_app()])});var exports_tui={};__export(exports_tui,{launchTui:()=>launchTui});async function launchTui(){let{renderNav:renderNav2}=await init_render().then(() => exports_render);await renderNav2()}var exports_resolve_agent_cwd={};__export(exports_resolve_agent_cwd,{resolveAgentFromCwd:()=>resolveAgentFromCwd});import{existsSync as existsSync45}from"fs";import{basename as basename13,dirname as dirname15,join as join60,relative as relative6,sep as sep3}from"path";function isRelativeWithin(rel,original){return!rel.startsWith("..")&&rel!==original}function resolveFromCanonicalDir(cwd,agentsDir){let relToAgents=relative6(agentsDir,cwd);if(!isRelativeWithin(relToAgents,cwd))return null;let segments=relToAgents.split(sep3).filter(Boolean);if(segments.length===0)return null;let agentName=segments[0];if(!existsSync45(join60(agentsDir,agentName,"AGENTS.md")))return null;let source=segments.length===1?"exact":"parent";return{agent:agentName,source}}function resolveFromWalkUp(cwd,workspaceRoot){let wsRel=relative6(workspaceRoot,cwd);if(!isRelativeWithin(wsRel,cwd))return null;let current=cwd;while(current!==workspaceRoot&&current!==dirname15(current)){if(existsSync45(join60(current,"AGENTS.md")))return{agent:basename13(current),source:"parent"};current=dirname15(current)}return null}function resolveAgentFromCwd(cwd,workspaceRoot){return resolveFromCanonicalDir(cwd,join60(workspaceRoot,"agents"))??resolveFromWalkUp(cwd,workspaceRoot)??{agent:"genie",source:"default"}}var init_resolve_agent_cwd=()=>{};var import__=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import__.default;init_claude_settings();init_ensure_tmux();init_genie_config2();init_system_detect();import{existsSync as existsSync4,unlinkSync as unlinkSync3}from"fs";import{homedir as homedir4}from"os";import{join as join4}from"path";var{$:$2}=globalThis.Bun;function printSectionHeader(title){console.log(),console.log(`\x1B[1m${title}:\x1B[0m`)}function printCheckResult(result2){let icon={pass:"\x1B[32m\u2713\x1B[0m",fail:"\x1B[31m\u2717\x1B[0m",warn:"\x1B[33m!\x1B[0m"}[result2.status],message=result2.message?` ${result2.message}`:"";if(console.log(` ${icon} ${result2.name}${message}`),result2.suggestion)console.log(` \x1B[2m${result2.suggestion}\x1B[0m`)}async function checkPrerequisites(){let results=[],tmuxCheck=await checkCommand("tmux");if(tmuxCheck.exists)results.push({name:"tmux",status:"pass",message:tmuxCheck.version||""});else results.push({name:"tmux",status:"fail",suggestion:"Install with: brew install tmux (or apt install tmux)"});let jqCheck=await checkCommand("jq");if(jqCheck.exists)results.push({name:"jq",status:"pass",message:jqCheck.version||""});else results.push({name:"jq",status:"fail",suggestion:"Install with: brew install jq (or apt install jq)"});let bunCheck=await checkCommand("bun");if(bunCheck.exists)results.push({name:"bun",status:"pass",message:bunCheck.version||""});else results.push({name:"bun",status:"fail",suggestion:"Install with: curl -fsSL https://bun.sh/install | bash"});let claudeCheck=await checkCommand("claude");if(claudeCheck.exists)results.push({name:"Claude Code",status:"pass",message:claudeCheck.version||""});else results.push({name:"Claude Code",status:"warn",suggestion:"Install with: npm install -g @anthropic-ai/claude-code"});return results}async function checkConfiguration(){let results=[];if(genieConfigExists())results.push({name:"Genie config exists",status:"pass",message:contractClaudePath(getGenieConfigPath())});else results.push({name:"Genie config exists",status:"warn",message:"not found",suggestion:"Run: genie setup"});if(isSetupComplete())results.push({name:"Setup complete",status:"pass"});else results.push({name:"Setup complete",status:"warn",message:"not completed",suggestion:"Run: genie setup"});let claudeSettingsPath=getClaudeSettingsPath();if(existsSync4(claudeSettingsPath))results.push({name:"Claude settings exists",status:"pass",message:contractClaudePath(claudeSettingsPath)});else results.push({name:"Claude settings exists",status:"warn",message:"not found",suggestion:"Claude Code creates this on first run"});return results}async function checkTmux(){let results=[];try{if((await $2`${tmuxBin()} -L genie list-sessions 2>/dev/null`.quiet()).exitCode===0)results.push({name:"Server running",status:"pass"});else return results.push({name:"Server running",status:"warn",message:"no sessions",suggestion:"Start with: tmux new-session -d -s genie"}),results}catch{return results.push({name:"Server running",status:"warn",message:"could not check"}),results}let sessionName=(await loadGenieConfig()).session.name;try{if((await $2`${tmuxBin()} -L genie has-session -t ${sessionName} 2>/dev/null`.quiet()).exitCode===0)results.push({name:`Session '${sessionName}' exists`,status:"pass"});else results.push({name:`Session '${sessionName}' exists`,status:"warn",suggestion:`Start with: tmux new-session -d -s ${sessionName}`})}catch{results.push({name:`Session '${sessionName}' exists`,status:"warn",message:"could not check"})}return results}async function checkWorkerProfiles(){let results=[];if(!genieConfigExists())return results.push({name:"Worker profiles",status:"warn",message:"no genie config",suggestion:"Run: genie setup"}),results;let config=await loadGenieConfig(),profiles=config.workerProfiles;if(!profiles||Object.keys(profiles).length===0)return results.push({name:"Worker profiles",status:"pass",message:"none configured (using defaults)"}),results;let totalProfiles=Object.keys(profiles).length;results.push({name:"Profiles configured",status:"pass",message:`${totalProfiles} profile${totalProfiles===1?"":"s"}`});for(let name of Object.keys(profiles))results.push({name:`Profile '${name}'`,status:"pass",message:"claude (direct)"});if(config.defaultWorkerProfile)if(profiles[config.defaultWorkerProfile])results.push({name:"Default profile",status:"pass",message:config.defaultWorkerProfile});else results.push({name:"Default profile",status:"warn",message:`'${config.defaultWorkerProfile}' not found`,suggestion:"Run: genie profiles default <profile>"});return results}function runCheckSection(label,results,counts){printSectionHeader(label);for(let result2 of results){if(printCheckResult(result2),result2.status==="fail")counts.errors=!0;if(result2.status==="warn")counts.warnings=!0}}async function doctorCommand(options){if(options?.fix){await doctorFix();return}console.log(),console.log("\x1B[1mGenie Doctor\x1B[0m"),console.log(`\x1B[2m${"\u2500".repeat(40)}\x1B[0m`);let counts={errors:!1,warnings:!1};if(runCheckSection("Prerequisites",await checkPrerequisites(),counts),runCheckSection("Configuration",await checkConfiguration(),counts),runCheckSection("Tmux",await checkTmux(),counts),runCheckSection("Worker Profiles",await checkWorkerProfiles(),counts),console.log(),console.log(`\x1B[2m${"\u2500".repeat(40)}\x1B[0m`),counts.errors)console.log("\x1B[31mSome checks failed.\x1B[0m Run \x1B[36mgenie setup\x1B[0m to fix.");else if(counts.warnings)console.log("\x1B[33mSome warnings detected.\x1B[0m Everything should still work.");else console.log("\x1B[32mAll checks passed!\x1B[0m");if(console.log(),counts.errors)process.exit(1)}async function killStalePostgres(){console.log(" Killing stale postgres processes...");try{let{execSync:execSync2}=await import("child_process");execSync2('pkill -9 -f "postgres.*pgserve" 2>/dev/null || true',{stdio:"ignore",timeout:5000}),console.log(" \x1B[32m\u2713\x1B[0m Stale postgres processes killed")}catch{console.log(" \x1B[33m!\x1B[0m Could not kill stale postgres processes")}}async function cleanSharedMemory(){console.log(" Cleaning shared memory...");try{let{execSync:execSync2}=await import("child_process");execSync2("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000}),console.log(" \x1B[32m\u2713\x1B[0m Shared memory cleaned")}catch{console.log(" \x1B[32m\u2713\x1B[0m No stale shared memory")}}async function stopExistingDaemon(pidFile){try{let{readFileSync:readFileSync3}=await import("fs"),pid=Number.parseInt(readFileSync3(pidFile,"utf-8").trim(),10);if(!Number.isNaN(pid)&&pid>0)try{process.kill(pid,"SIGTERM"),console.log(` \x1B[32m\u2713\x1B[0m Stopped existing daemon (PID ${pid})`),await new Promise((r)=>setTimeout(r,1000))}catch{}}catch{}}function removeStaleFiles(genieHome2,pidFile){let portFile=join4(genieHome2,"pgserve.port"),postmasterPid=join4(genieHome2,"data","pgserve","postmaster.pid");for(let file of[portFile,pidFile,postmasterPid])if(existsSync4(file))try{unlinkSync3(file),console.log(` \x1B[32m\u2713\x1B[0m Removed ${file}`)}catch{console.log(` \x1B[33m!\x1B[0m Could not remove ${file}`)}}async function restartDaemon(){console.log(" Restarting daemon...");try{let{spawn}=await import("child_process"),bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"daemon","start"],{detached:!0,stdio:"ignore"}).unref(),await new Promise((resolve)=>setTimeout(resolve,2000)),console.log(" \x1B[32m\u2713\x1B[0m Daemon restart initiated")}catch{console.log(" \x1B[33m!\x1B[0m Could not restart daemon \u2014 run: genie daemon start")}}async function doctorFix(){console.log(`
3050
+ `),service=util4.getValue(lines,"Service",":"),errorCode=util4.getValue(lines,"ConfigManagerErrorCode",":");if(util4.getValue(lines,"PNPClass",":").toLowerCase()==="bluetooth"&&errorCode==="0"&&service==="")result2.push(parseWindowsBluetooth(lines))});if(callback)callback(result2);resolve13(result2)});if(_freebsd||_netbsd||_openbsd||_sunos)resolve13(null)})})}exports.bluetoothDevices=bluetoothDevices});var require_lib5=__commonJS((exports)=>{var lib_version=require_package().version,util4=require_util3(),system=require_system(),osInfo=require_osinfo(),cpu=require_cpu(),memory=require_memory(),battery=require_battery(),graphics=require_graphics(),filesystem=require_filesystem(),network=require_network(),wifi=require_wifi(),processes=require_processes(),users=require_users(),internet=require_internet(),docker=require_docker(),vbox=require_virtualbox(),printer=require_printer(),usb=require_usb(),audio=require_audio(),bluetooth=require_bluetooth(),_platform=process.platform,_windows=_platform==="win32",_freebsd=_platform==="freebsd",_openbsd=_platform==="openbsd",_netbsd=_platform==="netbsd",_sunos=_platform==="sunos";if(_windows)util4.getCodepage(),util4.getPowershell();function version(){return lib_version}function getStaticData(callback){return new Promise((resolve13)=>{process.nextTick(()=>{let data={};data.version=version(),Promise.all([system.system(),system.bios(),system.baseboard(),system.chassis(),osInfo.osInfo(),osInfo.uuid(),osInfo.versions(),cpu.cpu(),cpu.cpuFlags(),graphics.graphics(),network.networkInterfaces(),memory.memLayout(),filesystem.diskLayout(),audio.audio(),bluetooth.bluetoothDevices(),usb.usb(),printer.printer()]).then((res)=>{if(data.system=res[0],data.bios=res[1],data.baseboard=res[2],data.chassis=res[3],data.os=res[4],data.uuid=res[5],data.versions=res[6],data.cpu=res[7],data.cpu.flags=res[8],data.graphics=res[9],data.net=res[10],data.memLayout=res[11],data.diskLayout=res[12],data.audio=res[13],data.bluetooth=res[14],data.usb=res[15],data.printer=res[16],callback)callback(data);resolve13(data)})})})}function getDynamicData(srv,iface,callback){if(util4.isFunction(iface))callback=iface,iface="";if(util4.isFunction(srv))callback=srv,srv="";return new Promise((resolve13)=>{process.nextTick(()=>{iface=iface||network.getDefaultNetworkInterface(),srv=srv||"";let functionProcessed=(()=>{let totalFunctions=15;if(_windows)totalFunctions=13;if(_freebsd||_openbsd||_netbsd)totalFunctions=11;if(_sunos)totalFunctions=6;return function(){if(--totalFunctions===0){if(callback)callback(data);resolve13(data)}}})(),data={};if(data.time=osInfo.time(),data.node=process.versions.node,data.v8=process.versions.v8,cpu.cpuCurrentSpeed().then((res)=>{data.cpuCurrentSpeed=res,functionProcessed()}),users.users().then((res)=>{data.users=res,functionProcessed()}),processes.processes().then((res)=>{data.processes=res,functionProcessed()}),cpu.currentLoad().then((res)=>{data.currentLoad=res,functionProcessed()}),!_sunos)cpu.cpuTemperature().then((res)=>{data.temp=res,functionProcessed()});if(!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)network.networkStats(iface).then((res)=>{data.networkStats=res,functionProcessed()});if(!_sunos)network.networkConnections().then((res)=>{data.networkConnections=res,functionProcessed()});if(memory.mem().then((res)=>{data.mem=res,functionProcessed()}),!_sunos)battery().then((res)=>{data.battery=res,functionProcessed()});if(!_sunos)processes.services(srv).then((res)=>{data.services=res,functionProcessed()});if(!_sunos)filesystem.fsSize().then((res)=>{data.fsSize=res,functionProcessed()});if(!_windows&&!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)filesystem.fsStats().then((res)=>{data.fsStats=res,functionProcessed()});if(!_windows&&!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)filesystem.disksIO().then((res)=>{data.disksIO=res,functionProcessed()});if(!_openbsd&&!_freebsd&&!_netbsd&&!_sunos)wifi.wifiNetworks().then((res)=>{data.wifiNetworks=res,functionProcessed()});internet.inetLatency().then((res)=>{data.inetLatency=res,functionProcessed()})})})}function getAllData(srv,iface,callback){return new Promise((resolve13)=>{process.nextTick(()=>{let data={};if(iface&&util4.isFunction(iface)&&!callback)callback=iface,iface="";if(srv&&util4.isFunction(srv)&&!iface&&!callback)callback=srv,srv="",iface="";getStaticData().then((res)=>{data=res,getDynamicData(srv,iface).then((res2)=>{for(let key in res2)if({}.hasOwnProperty.call(res2,key))data[key]=res2[key];if(callback)callback(data);resolve13(data)})})})})}function get3(valueObject,callback){return new Promise((resolve13)=>{process.nextTick(()=>{let allPromises=Object.keys(valueObject).filter((func)=>({}).hasOwnProperty.call(exports,func)).map((func)=>{let params=valueObject[func].substring(valueObject[func].lastIndexOf("(")+1,valueObject[func].lastIndexOf(")")),funcWithoutParams=func.indexOf(")")>=0?func.split(")")[1].trim():func;if(funcWithoutParams=func.indexOf("|")>=0?func.split("|")[0].trim():funcWithoutParams,params)return exports[funcWithoutParams](params);else return exports[funcWithoutParams]("")});Promise.all(allPromises).then((data)=>{let result2={},i2=0;for(let key in valueObject)if({}.hasOwnProperty.call(valueObject,key)&&{}.hasOwnProperty.call(exports,key)&&data.length>i2){if(valueObject[key]==="*"||valueObject[key]==="all")result2[key]=data[i2];else{let keys=valueObject[key],filter="",filterParts=[];if(keys.indexOf(")")>=0)keys=keys.split(")")[1].trim();if(keys.indexOf("|")>=0)filter=keys.split("|")[1].trim(),filterParts=filter.split(":"),keys=keys.split("|")[0].trim();if(keys=keys.replace(/,/g," ").replace(/ +/g," ").split(" "),data[i2])if(Array.isArray(data[i2])){let partialArray=[];data[i2].forEach((element)=>{let partialRes={};if(keys.length===1&&(keys[0]==="*"||keys[0]==="all"))partialRes=element;else keys.forEach((k2)=>{if({}.hasOwnProperty.call(element,k2))partialRes[k2]=element[k2]});if(filter&&filterParts.length===2){if({}.hasOwnProperty.call(partialRes,filterParts[0].trim())){let val=partialRes[filterParts[0].trim()];if(typeof val==="number"){if(val===parseFloat(filterParts[1].trim()))partialArray.push(partialRes)}else if(typeof val==="string"){if(val.toLowerCase()===filterParts[1].trim().toLowerCase())partialArray.push(partialRes)}}}else partialArray.push(partialRes)}),result2[key]=partialArray}else{let partialRes={};keys.forEach((k2)=>{if({}.hasOwnProperty.call(data[i2],k2))partialRes[k2]=data[i2][k2]}),result2[key]=partialRes}else result2[key]={}}i2++}if(callback)callback(result2);resolve13(result2)})})})}function observe(valueObject,interval,callback){let _data=null;return setInterval(()=>{get3(valueObject).then((data)=>{if(JSON.stringify(_data)!==JSON.stringify(data))_data=Object.assign({},data),callback(data)})},interval)}exports.version=version;exports.system=system.system;exports.bios=system.bios;exports.baseboard=system.baseboard;exports.chassis=system.chassis;exports.time=osInfo.time;exports.osInfo=osInfo.osInfo;exports.versions=osInfo.versions;exports.shell=osInfo.shell;exports.uuid=osInfo.uuid;exports.cpu=cpu.cpu;exports.cpuFlags=cpu.cpuFlags;exports.cpuCache=cpu.cpuCache;exports.cpuCurrentSpeed=cpu.cpuCurrentSpeed;exports.cpuTemperature=cpu.cpuTemperature;exports.currentLoad=cpu.currentLoad;exports.fullLoad=cpu.fullLoad;exports.mem=memory.mem;exports.memLayout=memory.memLayout;exports.battery=battery;exports.graphics=graphics.graphics;exports.fsSize=filesystem.fsSize;exports.fsOpenFiles=filesystem.fsOpenFiles;exports.blockDevices=filesystem.blockDevices;exports.fsStats=filesystem.fsStats;exports.disksIO=filesystem.disksIO;exports.diskLayout=filesystem.diskLayout;exports.networkInterfaceDefault=network.networkInterfaceDefault;exports.networkGatewayDefault=network.networkGatewayDefault;exports.networkInterfaces=network.networkInterfaces;exports.networkStats=network.networkStats;exports.networkConnections=network.networkConnections;exports.wifiNetworks=wifi.wifiNetworks;exports.wifiInterfaces=wifi.wifiInterfaces;exports.wifiConnections=wifi.wifiConnections;exports.services=processes.services;exports.processes=processes.processes;exports.processLoad=processes.processLoad;exports.users=users.users;exports.inetChecksite=internet.inetChecksite;exports.inetLatency=internet.inetLatency;exports.dockerInfo=docker.dockerInfo;exports.dockerImages=docker.dockerImages;exports.dockerContainers=docker.dockerContainers;exports.dockerContainerStats=docker.dockerContainerStats;exports.dockerContainerProcesses=docker.dockerContainerProcesses;exports.dockerVolumes=docker.dockerVolumes;exports.dockerAll=docker.dockerAll;exports.vboxInfo=vbox.vboxInfo;exports.printer=printer.printer;exports.usb=usb.usb;exports.audio=audio.audio;exports.bluetoothDevices=bluetooth.bluetoothDevices;exports.getStaticData=getStaticData;exports.getDynamicData=getDynamicData;exports.getAllData=getAllData;exports.get=get3;exports.observe=observe;exports.powerShellStart=util4.powerShellStart;exports.powerShellRelease=util4.powerShellRelease});import os4 from"os";function toGB(bytes){return Math.round(bytes/1073741824*10)/10}function bar(percent,width){let p=Math.max(0,Math.min(100,percent)),filled=Math.round(p/100*width);return`[${"=".repeat(filled)}${"-".repeat(width-filled)}]`}function pickColor(percent){if(percent>80)return palette.error;if(percent>50)return palette.warning;return palette.emerald}function SystemStats(){let[stats,setStats]=import_react15.useState(null),mountedRef=import_react15.useRef(!0);if(import_react15.useEffect(()=>{mountedRef.current=!0;async function refresh(){try{let[cpu2,mem]=await Promise.all([import_systeminformation.default.currentLoad(),import_systeminformation.default.mem()]);if(!mountedRef.current)return;let coreCount=os4.cpus().length,avg1=os4.loadavg()[0],sorted=cpu2.cpus.map((c,i2)=>({id:i2,load:Math.round(c.load)})).sort((a,b3)=>b3.load-a.load);setStats({cpu:{combined:Math.round(cpu2.currentLoad),hotCores:sorted.slice(0,3),coreCount},ram:{usedGB:toGB(mem.active),totalGB:toGB(mem.total),percent:mem.total>0?Math.round(mem.active/mem.total*100):0},swap:{usedGB:toGB(mem.swapused),totalGB:toGB(mem.swaptotal),percent:mem.swaptotal>0?Math.round(mem.swapused/mem.swaptotal*100):0},load:{percent:coreCount>0?Math.round(avg1/coreCount*100):0,busy:Math.round(avg1*10)/10,total:coreCount}})}catch{}}refresh();let timer2=setInterval(refresh,3000);return()=>{mountedRef.current=!1,clearInterval(timer2)}},[]),!stats)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgLight,children:import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:"genie"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` v${VERSION}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);let{cpu,ram,swap,load:load3}=stats,hotStr=cpu.hotCores.map((c)=>`#${c.id} ${c.load}%`).join(" ");return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgLight,children:[import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:"genie"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` v${VERSION}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"CPU "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(cpu.combined),children:`${String(cpu.combined).padStart(3)}% ${bar(cpu.combined,8)}`},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` ${cpu.coreCount}c`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:" hot "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.warning,children:hotStr},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"RAM "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(ram.percent),children:`${ram.usedGB}/${ram.totalGB}G ${bar(ram.percent,8)}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),swap.totalGB>0?import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"SWP "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(swap.percent),children:`${swap.usedGB}/${swap.totalGB}G ${bar(swap.percent,8)}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"Load "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:pickColor(load3.percent),children:`${load3.percent}%`},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` (${load3.busy}/${load3.total} busy)`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var import_react15,import_systeminformation;var init_SystemStats=__esm(()=>{init_version();init_theme2();init_jsx_dev_runtime();import_react15=__toESM(require_react_development(),1),import_systeminformation=__toESM(require_lib5(),1)});function getNodeIcon(node){if(node.type==="agent")return getAgentIcon(node);switch(node.type){case"session":return node.data.attached?"\u25B6":"\u25B8";case"window":return node.data.active?"\u25A0":"\u25A1";case"pane":return getPaneIcon(node);default:return" "}}function getAgentIcon(node){switch(node.wsAgentState){case"running":return"\u25CF";case"stopped":return"\u25CB";case"error":return"\u2298";case"spawning":return"\u231B";default:return"\u25CB"}}function getPaneIcon(node){if(node.data.isDead)return"\u2718";if(node.agentState==="working")return"\u25CF";if(node.agentState==="idle")return"\u25CB";if(node.agentState==="permission")return"\u26A0";if(node.agentState==="error")return"\u2718";if(node.data.command==="claude")return"\u25C6";return"\u25CB"}function getNodeColor(node){if(node.type==="agent")return getAgentColor(node);switch(node.type){case"session":return node.data.attached?palette.emerald:palette.textDim;case"window":return node.data.active?palette.cyan:palette.text;case"pane":return getPaneColor(node);default:return palette.text}}function getAgentColor(node){switch(node.wsAgentState){case"running":return palette.emerald;case"stopped":return palette.textDim;case"error":return palette.error;case"spawning":return palette.warning;default:return palette.textDim}}function getPaneColor(node){if(node.data.isDead)return palette.error;if(node.agentState==="working")return palette.cyan;if(node.agentState==="permission")return palette.warning;if(node.agentState==="error")return palette.error;if(node.agentState==="idle")return palette.textDim;if(node.data.command==="claude")return palette.cyan;return palette.textDim}function getNodeSuffix(node){if(node.type==="agent"){if(node.wsAgentState==="spawning"&&node.activePanes===0)return" [stuck \u2014 press R to retry]";let wc=node.data.windowCount;if(wc>1)return` (${wc} windows)`;if(wc===1)return" (1 window)";return""}if(node.type==="session"||node.type==="pane"){let count=node.activePanes;if(count>0)return` ${icons.agent}${count}`}return""}function getStateColor(state){switch(state){case"working":return palette.cyan;case"idle":return palette.textDim;case"permission":return palette.warning;case"error":return palette.error;default:return palette.textMuted}}var import_react16,TreeNodeRow;var init_TreeNode=__esm(()=>{init_theme2();init_jsx_dev_runtime();import_react16=__toESM(require_react_development(),1),TreeNodeRow=import_react16.memo(function({node,selected,onSelect,onToggle,onContextMenu}){let indent=" ".repeat(node.depth),hasChildren=node.children.length>0,expandIcon=hasChildren?node.expanded?icons.expanded:icons.collapsed:" ",icon=getNodeIcon(node),color2=getNodeColor(node),suffix=getNodeSuffix(node);return import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",backgroundColor:selected?palette.violet:void 0,onMouseDown:(event)=>{if(event.button===2&&onContextMenu){onSelect(node.id),onContextMenu(node.id);return}if(onSelect(node.id),hasChildren)onToggle(node.id)},children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:[indent,expandIcon," "]},void 0,!0,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:color2,children:[icon," "]},void 0,!0,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:selected?"#ffffff":palette.text,children:node.label},void 0,!1,void 0,this),suffix?import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:suffix},void 0,!1,void 0,this):null,node.agentState?import_jsx_dev_runtime2.jsxDEV("span",{fg:getStateColor(node.agentState),children:[" ",node.agentState]},void 0,!0,void 0,this):null,import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:` [${node.type}]`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)})});function Nav({onTmuxSessionSelect,onNewAgentWindow,workspaceRoot,initialAgent,keyboardDisabled=!1}){let[diagnostics,setDiagnostics]=import_react18.useState(null),[sessionTree,setSessionTree]=import_react18.useState([]),[selectedIndex,setSelectedIndex]=import_react18.useState(0),[requestedInitialAgent,setRequestedInitialAgent]=import_react18.useState(initialAgent),[contextMenuNodeId,setContextMenuNodeId]=import_react18.useState(null),lastTarget=import_react18.useRef(null),selectedNodeId=import_react18.useRef(null);import_react18.useEffect(()=>{let active=!0;async function refresh(){try{let snap=await collectDiagnostics();if(!active)return;setDiagnostics(snap);let signaledAgent=consumeInitialAgentSignal();if(signaledAgent)setRequestedInitialAgent(signaledAgent)}catch(err){console.error("TUI: diagnostics failed:",err)}}refresh();let timer2=setInterval(refresh,2000);return()=>{active=!1,clearInterval(timer2)}},[]),import_react18.useEffect(()=>{if(!diagnostics)return;let newTree;if(workspaceRoot){let agentNames=scanAgents2(workspaceRoot);newTree=buildWorkspaceTree({agentNames,sessions:diagnostics.sessions,executors:diagnostics.executors})}else newTree=buildSessionTree(diagnostics);setSessionTree((prev)=>mergeExpandedState(prev,newTree))},[diagnostics,workspaceRoot]);let flatNodes=import_react18.useMemo(()=>flattenTree(sessionTree),[sessionTree]);import_react18.useEffect(()=>{let node=flatNodes[selectedIndex]?.node;if(node)selectedNodeId.current=node.id},[selectedIndex,flatNodes]),import_react18.useLayoutEffect(()=>{if(flatNodes.length===0)return;if(selectedIndex>=flatNodes.length){setSelectedIndex(flatNodes.length-1);return}if(!selectedNodeId.current)return;let currentAtIndex=flatNodes[selectedIndex]?.node;if(currentAtIndex&&currentAtIndex.id===selectedNodeId.current)return;let restored=flatNodes.findIndex((n)=>n.node.id===selectedNodeId.current);if(restored>=0)setSelectedIndex(restored)},[flatNodes]),import_react18.useEffect(()=>{if(!requestedInitialAgent||flatNodes.length===0)return;let idx=flatNodes.findIndex((n)=>n.node.id===`agent:${requestedInitialAgent}`);if(idx>=0){setSelectedIndex(idx);let node=flatNodes[idx].node;if(node.type==="agent"&&node.wsAgentState!=="running"&&node.wsAgentState!=="spawning")spawnAgent(agentNameFromNode(node),onTmuxSessionSelect);setRequestedInitialAgent(void 0)}},[requestedInitialAgent,flatNodes,onTmuxSessionSelect]),import_react18.useEffect(()=>{let current=flatNodes[selectedIndex]?.node;if(!current)return;let target=getSessionTarget(current);if(!target)return;if(current.type==="agent"&&current.wsAgentState!=="running")return;let key=`${target.sessionName}:${target.windowIndex??""}`;if(key===lastTarget.current)return;lastTarget.current=key,onTmuxSessionSelect(target.sessionName,target.windowIndex)},[selectedIndex,flatNodes,onTmuxSessionSelect]);let handleSelect=import_react18.useCallback((id)=>{let idx=flatNodes.findIndex((n)=>n.node.id===id);if(idx>=0)setSelectedIndex(idx)},[flatNodes]),handleToggle=import_react18.useCallback((id)=>{setSessionTree((prev)=>toggleNode(prev,id))},[]),handleVerticalNav=import_react18.useCallback((keyName2)=>{let rowCount=flatNodes.length;if(rowCount===0)return;if(keyName2==="up"||keyName2==="k")setSelectedIndex((prev)=>prev===0?rowCount-1:prev-1);else if(keyName2==="down"||keyName2==="j")setSelectedIndex((prev)=>prev>=rowCount-1?0:prev+1)},[flatNodes.length]),handleExpandCollapse=import_react18.useCallback((keyName2)=>{let node=flatNodes[selectedIndex]?.node;if(!node)return;if((keyName2==="right"||keyName2==="l")&&node.children.length>0&&!node.expanded)handleToggle(node.id);else if((keyName2==="left"||keyName2==="h")&&node.expanded)handleToggle(node.id)},[flatNodes,selectedIndex,handleToggle]),handleEnter=import_react18.useCallback(()=>{let node=flatNodes[selectedIndex]?.node;if(!node)return;if(node.type==="agent"){handleEnterAgent(node,onTmuxSessionSelect);return}if(node.children.length>0)handleToggle(node.id);let target=getSessionTarget(node);if(target)onTmuxSessionSelect(target.sessionName,target.windowIndex)},[flatNodes,selectedIndex,handleToggle,onTmuxSessionSelect]),handleRetry=import_react18.useCallback(()=>{let node=flatNodes[selectedIndex]?.node;if(!node||node.type!=="agent")return;if(node.wsAgentState!=="spawning"&&node.wsAgentState!=="error")return;(async()=>{try{let{reconcileStaleSpawns:reconcileStaleSpawns2}=await Promise.resolve().then(() => (init_agent_registry(),exports_agent_registry));await reconcileStaleSpawns2()}catch{}spawnAgent(agentNameFromNode(node),onTmuxSessionSelect)})()},[flatNodes,selectedIndex,onTmuxSessionSelect]),handleContextMenu=import_react18.useCallback((nodeId)=>{let flat=flatNodes.find((n)=>n.node.id===nodeId);if(flat&&buildMenuItems(flat.node).length>0)setContextMenuNodeId(nodeId)},[flatNodes]),handleContextMenuAction=import_react18.useCallback((action,payload)=>{let node=flatNodes.find((n)=>n.node.id===contextMenuNodeId)?.node;if(!node)return;setContextMenuNodeId(null),dispatchContextMenuAction(action,node,payload,{sessionTree,onTmuxSessionSelect,onNewAgentWindow})},[flatNodes,contextMenuNodeId,sessionTree,onTmuxSessionSelect,onNewAgentWindow]),_menuDisabled=keyboardDisabled||contextMenuNodeId!==null;useKeyboard((key)=>{if(keyboardDisabled)return;handleKeyboardInput(key,{contextMenuNodeId,flatNodes,selectedIndex,setContextMenuNodeId,handleVerticalNav,handleExpandCollapse,handleEnter,handleRetry,onNewAgentWindow})});let agentCount=workspaceRoot?sessionTree.filter((n)=>n.type==="agent").length:diagnostics?.sessions.length??0,runningCount=workspaceRoot?sessionTree.filter((n)=>n.wsAgentState==="running").length:diagnostics?.sessions.reduce((sum,s2)=>sum+s2.windows.reduce((ws,w2)=>ws+w2.panes.length,0),0)??0,headerLabel=workspaceRoot?"Agents":"Sessions";return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",width:"100%",height:"100%",backgroundColor:palette.bg,children:[import_jsx_dev_runtime2.jsxDEV("box",{height:1,paddingX:1,backgroundColor:palette.bgLight,children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:headerLabel},void 0,!1,void 0,this),diagnostics?import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:[" ",workspaceRoot?`${runningCount}/${agentCount}`:`${agentCount}s ${runningCount}p`]},void 0,!0,void 0,this):null]},void 0,!0,void 0,this)},void 0,!1,void 0,this),diagnostics?import_jsx_dev_runtime2.jsxDEV("scrollbox",{focused:!0,height:"100%",style:{scrollbarOptions:{showArrows:!1,trackOptions:{foregroundColor:palette.scrollThumb,backgroundColor:palette.scrollTrack}}},children:flatNodes.map((flat,i2)=>import_jsx_dev_runtime2.jsxDEV(TreeNodeRow,{node:flat.node,selected:i2===selectedIndex,onSelect:handleSelect,onToggle:handleToggle,onContextMenu:handleContextMenu},flat.node.id,!1,void 0,this))},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV("box",{flexGrow:1,justifyContent:"center",alignItems:"center",children:import_jsx_dev_runtime2.jsxDEV("text",{fg:palette.textDim,children:"Collecting..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),contextMenuNodeId?import_jsx_dev_runtime2.jsxDEV(ContextMenu,{items:buildMenuItems(flatNodes.find((n)=>n.node.id===contextMenuNodeId)?.node??{}),onAction:handleContextMenuAction,onClose:()=>setContextMenuNodeId(null),positionY:flatNodes.findIndex((n)=>n.node.id===contextMenuNodeId)+1},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV(SystemStats,{},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{height:1,paddingX:1,backgroundColor:palette.bgLight,children:import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:["\u2191\u2193",":nav ","\u2190\u2192",":expand Enter:",workspaceRoot?"spawn/attach":"attach"," ^T:new R:retry .:menu"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function handleEnterAgent(node,onTmuxSessionSelect){if(node.wsAgentState!=="running"&&node.wsAgentState!=="spawning")spawnAgent(agentNameFromNode(node),onTmuxSessionSelect);else if(node.wsAgentState==="running"){let target=getSessionTarget(node);if(target)onTmuxSessionSelect(target.sessionName,target.windowIndex)}}function dispatchContextMenuAction(action,node,payload,deps){let name=node.label;if(handleAttachAction(action,node,deps.onTmuxSessionSelect))return;if(handleRetryAction(action,name,deps.onTmuxSessionSelect))return;if(handleGenieAction(action,name,payload))return;let tmuxServer=process.env.GENIE_TMUX_SERVER||"genie";if(handleRenameAction(action,node,tmuxServer,payload))return;if(handleAgentWindowActions(action,node,name,tmuxServer,deps.onNewAgentWindow))return;if(handleSessionNodeActions(action,node,tmuxServer,payload))return;if(handleWindowNodeActions(action,node,deps.sessionTree,tmuxServer,payload))return;handlePaneNodeActions(action,node,deps.sessionTree,tmuxServer,deps.onNewAgentWindow)}function handleAttachAction(action,node,onTmuxSessionSelect){if(action!=="attach")return!1;let target=getSessionTarget(node);if(target)onTmuxSessionSelect(target.sessionName,target.windowIndex);return!0}function handleRetryAction(action,name,onTmuxSessionSelect){if(action!=="retry")return!1;return(async()=>{try{let{reconcileStaleSpawns:reconcileStaleSpawns2}=await Promise.resolve().then(() => (init_agent_registry(),exports_agent_registry));await reconcileStaleSpawns2()}catch{}spawnAgent(name,onTmuxSessionSelect)})(),!0}function handleGenieAction(action,name,payload){if(action==="send"&&payload)return executeGenie(["agent","send",payload,"--to",name]),!0;if(action==="answer-text"&&payload)return executeGenie(["agent","answer",name,`text:${payload}`]),!0;let genieArgs={spawn:["spawn",name],"spawn-plan":["spawn",name,"--plan-mode"],stop:["agent","stop",name],kill:["agent","kill",name],log:["agent","log",name],show:["agent","show",name],read:["read",name],"answer-yes":["agent","answer",name,"yes"],"answer-no":["agent","answer",name,"no"]}[action];if(genieArgs)return executeGenie(genieArgs),!0;return!1}function handleRenameAction(action,node,tmuxServer,payload){if(action==="rename-session"&&payload){let sess=node.type==="agent"?node.data.sessionName||node.label:node.id.split(":").slice(1).join(":");return executeTmux3(["-L",tmuxServer,"rename-session","-t",sess,payload]),!0}if(action==="rename-window"&&payload){let idParts=node.id.split(":"),windowTarget=`${idParts[1]}:${idParts[2]}`;return executeTmux3(["-L",tmuxServer,"rename-window","-t",windowTarget,payload]),!0}if(action==="rename-pane"&&payload&&node.type==="pane"){let paneId=node.data.paneId;return executeTmux3(["-L",tmuxServer,"select-pane","-t",`${paneId}`,"-T",payload]),!0}return!1}function handleAgentWindowActions(action,node,name,tmuxServer,onNewAgentWindow){if(action==="agent-new-window"&&node.type==="agent"){if(onNewAgentWindow)onNewAgentWindow(agentNameFromNode(node));return!0}if(action==="new-empty-window"&&node.type==="agent"){let sessionName=node.data.sessionName||name;return executeTmux3(["-L",tmuxServer,"new-window","-a","-t",sessionName]),!0}return!1}function handleSessionNodeActions(action,node,tmuxServer,payload){if(node.type!=="session")return!1;let sess=node.id.split(":").slice(1).join(":");if(action==="kill-session")return executeTmux3(["-L",tmuxServer,"kill-session","-t",sess]),!0;if(action==="new-window")return executeTmux3(["-L",tmuxServer,"new-window","-a","-t",sess]),!0;if(action==="clone-session")return executeTmux3(["-L",tmuxServer,"new-session","-d","-s",`${sess}-clone`,"-t",sess]),!0;if(action==="spawn-in-session"&&payload)return executeGenie(["spawn",payload,"--session",sess]),!0;return!1}function handleWindowNodeActions(action,node,sessionTree,tmuxServer,payload){if(node.type!=="window")return!1;let idParts=node.id.split(":"),windowTarget=`${idParts[1]}:${idParts[2]}`;if(action==="kill-window")return executeTmux3(["-L",tmuxServer,"kill-window","-t",windowTarget]),!0;if(action==="window-new-agent"){let parentAgent=findParentAgent(sessionTree,node.id);if(parentAgent){let agentFullName=agentNameFromNode(parentAgent),suffix=Date.now()%1e4,role=`${agentFullName}-${suffix}`;executeGenie(["spawn",agentFullName,"--role",role,"--window",windowTarget])}return!0}if(action==="split-pane")return executeTmux3(["-L",tmuxServer,"split-window","-t",windowTarget]),!0;if(action==="spawn-in-window"&&payload)return executeGenie(["spawn",payload,"--session",idParts[1]]),!0;return!1}function handlePaneNodeActions(action,node,sessionTree,tmuxServer,onNewAgentWindow){if(node.type!=="pane")return!1;let paneId=node.data.paneId;if(action==="clone-agent"){let parentAgent=findParentAgent(sessionTree,node.id);if(parentAgent&&onNewAgentWindow)onNewAgentWindow(agentNameFromNode(parentAgent));return!0}if(action==="kill-pane")return executeTmux3(["-L",tmuxServer,"kill-pane","-t",`${paneId}`]),!0;if(action==="split-h")return executeTmux3(["-L",tmuxServer,"split-window","-h","-t",`${paneId}`]),!0;if(action==="split-v")return executeTmux3(["-L",tmuxServer,"split-window","-v","-t",`${paneId}`]),!0;return!1}function tryOpenContextMenu(flatNodes,selectedIndex,setContextMenuNodeId){let node=flatNodes[selectedIndex]?.node;if(node&&buildMenuItems(node).length>0)return setContextMenuNodeId(node.id),!0;return!1}function dispatchNavKey(key,handlers2,agentAction){let n=key.name;if(n==="up"||n==="k"||n==="down"||n==="j")handlers2.handleVerticalNav(n);else if(n==="right"||n==="l"||n==="left"||n==="h")handlers2.handleExpandCollapse(n);else if(n==="enter"||n==="return")handlers2.handleEnter();else if(n==="r")handlers2.handleRetry();else if(key.ctrl&&n==="t")agentAction()}function handleKeyboardInput(key,opts){if(key.name==="."&&!opts.contextMenuNodeId){if(tryOpenContextMenu(opts.flatNodes,opts.selectedIndex,opts.setContextMenuNodeId))return}if(opts.contextMenuNodeId)return;dispatchNavKey(key,opts,()=>{let node=opts.flatNodes[opts.selectedIndex]?.node;if(node?.type==="agent"&&node.wsAgentState==="running"&&opts.onNewAgentWindow)opts.onNewAgentWindow(agentNameFromNode(node))})}function agentNameFromNode(node){return node.id.replace(/^agent:/,"")}function spawnAgent(name,onTmuxSessionSelect){try{let{spawn:spawn5}=__require("child_process"),{join:join60,resolve:resolve13}=__require("path"),{existsSync:existsSync45}=__require("fs"),bunPath=process.execPath||"bun",genieBin=process.argv[1],wsRoot=process.env.GENIE_TUI_WORKSPACE,sessionName=name.replace(/\//g,"-"),cwd;if(wsRoot){let parentName=name.includes("/")?name.slice(0,name.indexOf("/")):name,agentDir=resolve13(join60(wsRoot,"agents",parentName));if(existsSync45(agentDir))cwd=agentDir}let{GENIE_TUI_PANE:_a,GENIE_TUI_RIGHT:_b,GENIE_TUI_WORKSPACE:_c,GENIE_IS_DAEMON:_d,...cleanEnv}=process.env,spawnOpts={detached:!0,stdio:"ignore",cwd,env:cleanEnv};if((genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,"spawn",name,"--session",sessionName,"--new-window"],spawnOpts):spawn5("genie",["spawn",name,"--session",sessionName,"--new-window"],spawnOpts)).unref(),onTmuxSessionSelect)attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect)}catch{}}function attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect,attempt=0){(async()=>{try{let session=(await collectDiagnostics()).sessions.find((candidate)=>candidate.name===sessionName);if(session){let windowIndex=resolvePreferredWindowIndex(session,sessionName);if(windowIndex!==void 0){onTmuxSessionSelect(sessionName,windowIndex);return}}}catch{}if(attempt>=40){onTmuxSessionSelect(sessionName);return}setTimeout(()=>{attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect,attempt+1)},250)})()}function executeTmux3(args){try{let{spawn:spawn5}=__require("child_process");spawn5("tmux",args,{detached:!0,stdio:"ignore"}).unref()}catch{}}function executeGenie(args){try{let{spawn:spawn5}=__require("child_process"),bunPath=process.execPath||"bun",genieBin=process.argv[1];(genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,...args],{detached:!0,stdio:"ignore"}):spawn5("genie",args,{detached:!0,stdio:"ignore"})).unref()}catch{}}function findParentAgent(tree,targetId){for(let node of tree){if(node.type==="agent"&&containsNode(node,targetId))return node;let found=findParentAgent(node.children,targetId);if(found)return found}return null}function containsNode(node,targetId){if(node.id===targetId)return!0;return node.children.some((c)=>containsNode(c,targetId))}function mergeExpandedState(oldTree,newTree){if(oldTree.length===0)return newTree;let oldState=new Map;function collect(nodes){for(let n of nodes)oldState.set(n.id,{expanded:n.expanded,childCount:n.children.length}),collect(n.children)}collect(oldTree);function apply(nodes){return nodes.map((n)=>({...n,expanded:(()=>{let previous=oldState.get(n.id);if(!previous)return n.expanded;if(previous.childCount===0&&n.children.length>0)return n.expanded;return previous.expanded})(),children:apply(n.children)}))}return apply(newTree)}var import_react18;var init_Nav=__esm(async()=>{init_workspace();init_diagnostics();init_initial_agent();init_theme2();init_SystemStats();init_TreeNode();init_jsx_dev_runtime();await __promiseAll([init_react(),init_ContextMenu()]);import_react18=__toESM(require_react_development(),1)});function QuitDialog({onConfirm,onCancel}){return useKeyboard((key)=>{if(key.name==="enter"||key.name==="return"||key.name==="y")onConfirm();else if(key.name==="escape"||key.name==="n")onCancel()}),import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:"#0a0a0a",children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderColor:palette.violet,backgroundColor:"#111111",paddingX:3,paddingY:1,flexDirection:"column",alignItems:"center",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.purple,children:"Quit genie?"},void 0,!1,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:"Enter"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:" to quit "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:" | "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:" Esc"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:" to cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"Hint: Ctrl+D to detach (keep running)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var init_QuitDialog=__esm(async()=>{init_theme2();init_jsx_dev_runtime();await init_react()});import{execSync as execSync17}from"child_process";import{readFileSync as readFileSync28}from"fs";function App({rightPane,workspaceRoot,initialAgent}){let[showQuit,setShowQuit]=import_react21.useState(!1);useKeyboard((key)=>{if(key.ctrl&&key.name==="q")if(showQuit)handleQuit();else setShowQuit(!0)});let handleQuit=import_react21.useCallback(()=>{try{let genieHome5=process.env.GENIE_HOME??`${process.env.HOME}/.genie`,pid=readFileSync28(`${genieHome5}/serve.pid`,"utf-8").trim();process.kill(Number.parseInt(pid,10),"SIGTERM")}catch{}try{execSync17("tmux -L genie-tui kill-server",{stdio:"ignore"})}catch{}},[]),handleTmuxSessionSelect=import_react21.useCallback((sessionName,windowIndex)=>{if(!rightPane)return;attachProjectWindow(rightPane,sessionName,windowIndex)},[rightPane]);return import_jsx_dev_runtime2.jsxDEV("box",{width:"100%",height:"100%",children:[import_jsx_dev_runtime2.jsxDEV(Nav,{onTmuxSessionSelect:handleTmuxSessionSelect,onNewAgentWindow:newAgentWindow,workspaceRoot,initialAgent,keyboardDisabled:showQuit},void 0,!1,void 0,this),showQuit?import_jsx_dev_runtime2.jsxDEV(QuitDialog,{onConfirm:handleQuit,onCancel:()=>setShowQuit(!1)},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)}var import_react21;var init_app=__esm(async()=>{init_tmux2();init_jsx_dev_runtime();await __promiseAll([init_react(),init_Nav(),init_QuitDialog()]);import_react21=__toESM(require_react_development(),1)});var exports_render={};__export(exports_render,{renderNav:()=>renderNav});async function renderNav(){let rightPane=process.env.GENIE_TUI_RIGHT||void 0,workspaceRoot=process.env.GENIE_TUI_WORKSPACE||void 0,initialAgent=process.env.GENIE_TUI_AGENT||void 0,renderer=await createCliRenderer({exitOnCtrlC:!1,useMouse:!0});createRoot(renderer).render(import_jsx_dev_runtime2.jsxDEV(App,{rightPane,workspaceRoot,initialAgent},void 0,!1,void 0,this)),await new Promise((resolve13)=>{renderer.once("destroy",resolve13)})}var init_render=__esm(async()=>{init_jsx_dev_runtime();await __promiseAll([init_core(),init_react(),init_app()])});var exports_tui={};__export(exports_tui,{launchTui:()=>launchTui});async function launchTui(){let{renderNav:renderNav2}=await init_render().then(() => exports_render);await renderNav2()}var exports_resolve_agent_cwd={};__export(exports_resolve_agent_cwd,{resolveAgentFromCwd:()=>resolveAgentFromCwd});import{existsSync as existsSync45}from"fs";import{basename as basename13,dirname as dirname14,join as join60,relative as relative6,sep as sep3}from"path";function isRelativeWithin(rel,original){return!rel.startsWith("..")&&rel!==original}function resolveFromCanonicalDir(cwd,agentsDir){let relToAgents=relative6(agentsDir,cwd);if(!isRelativeWithin(relToAgents,cwd))return null;let segments=relToAgents.split(sep3).filter(Boolean);if(segments.length===0)return null;let agentName=segments[0];if(!existsSync45(join60(agentsDir,agentName,"AGENTS.md")))return null;let source=segments.length===1?"exact":"parent";return{agent:agentName,source}}function resolveFromWalkUp(cwd,workspaceRoot){let wsRel=relative6(workspaceRoot,cwd);if(!isRelativeWithin(wsRel,cwd))return null;let current=cwd;while(current!==workspaceRoot&&current!==dirname14(current)){if(existsSync45(join60(current,"AGENTS.md")))return{agent:basename13(current),source:"parent"};current=dirname14(current)}return null}function resolveAgentFromCwd(cwd,workspaceRoot){return resolveFromCanonicalDir(cwd,join60(workspaceRoot,"agents"))??resolveFromWalkUp(cwd,workspaceRoot)??{agent:"genie",source:"default"}}var init_resolve_agent_cwd=()=>{};var import__=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import__.default;init_claude_settings();init_ensure_tmux();init_genie_config2();init_system_detect();import{existsSync as existsSync4,unlinkSync as unlinkSync3}from"fs";import{homedir as homedir4}from"os";import{join as join4}from"path";var{$:$2}=globalThis.Bun;function printSectionHeader(title){console.log(),console.log(`\x1B[1m${title}:\x1B[0m`)}function printCheckResult(result2){let icon={pass:"\x1B[32m\u2713\x1B[0m",fail:"\x1B[31m\u2717\x1B[0m",warn:"\x1B[33m!\x1B[0m"}[result2.status],message=result2.message?` ${result2.message}`:"";if(console.log(` ${icon} ${result2.name}${message}`),result2.suggestion)console.log(` \x1B[2m${result2.suggestion}\x1B[0m`)}async function checkPrerequisites(){let results=[],tmuxCheck=await checkCommand("tmux");if(tmuxCheck.exists)results.push({name:"tmux",status:"pass",message:tmuxCheck.version||""});else results.push({name:"tmux",status:"fail",suggestion:"Install with: brew install tmux (or apt install tmux)"});let jqCheck=await checkCommand("jq");if(jqCheck.exists)results.push({name:"jq",status:"pass",message:jqCheck.version||""});else results.push({name:"jq",status:"fail",suggestion:"Install with: brew install jq (or apt install jq)"});let bunCheck=await checkCommand("bun");if(bunCheck.exists)results.push({name:"bun",status:"pass",message:bunCheck.version||""});else results.push({name:"bun",status:"fail",suggestion:"Install with: curl -fsSL https://bun.sh/install | bash"});let claudeCheck=await checkCommand("claude");if(claudeCheck.exists)results.push({name:"Claude Code",status:"pass",message:claudeCheck.version||""});else results.push({name:"Claude Code",status:"warn",suggestion:"Install with: npm install -g @anthropic-ai/claude-code"});return results}async function checkConfiguration(){let results=[];if(genieConfigExists())results.push({name:"Genie config exists",status:"pass",message:contractClaudePath(getGenieConfigPath())});else results.push({name:"Genie config exists",status:"warn",message:"not found",suggestion:"Run: genie setup"});if(isSetupComplete())results.push({name:"Setup complete",status:"pass"});else results.push({name:"Setup complete",status:"warn",message:"not completed",suggestion:"Run: genie setup"});let claudeSettingsPath=getClaudeSettingsPath();if(existsSync4(claudeSettingsPath))results.push({name:"Claude settings exists",status:"pass",message:contractClaudePath(claudeSettingsPath)});else results.push({name:"Claude settings exists",status:"warn",message:"not found",suggestion:"Claude Code creates this on first run"});return results}async function checkTmux(){let results=[];try{if((await $2`${tmuxBin()} -L genie list-sessions 2>/dev/null`.quiet()).exitCode===0)results.push({name:"Server running",status:"pass"});else return results.push({name:"Server running",status:"warn",message:"no sessions",suggestion:"Start with: tmux new-session -d -s genie"}),results}catch{return results.push({name:"Server running",status:"warn",message:"could not check"}),results}let sessionName=(await loadGenieConfig()).session.name;try{if((await $2`${tmuxBin()} -L genie has-session -t ${sessionName} 2>/dev/null`.quiet()).exitCode===0)results.push({name:`Session '${sessionName}' exists`,status:"pass"});else results.push({name:`Session '${sessionName}' exists`,status:"warn",suggestion:`Start with: tmux new-session -d -s ${sessionName}`})}catch{results.push({name:`Session '${sessionName}' exists`,status:"warn",message:"could not check"})}return results}async function checkWorkerProfiles(){let results=[];if(!genieConfigExists())return results.push({name:"Worker profiles",status:"warn",message:"no genie config",suggestion:"Run: genie setup"}),results;let config=await loadGenieConfig(),profiles=config.workerProfiles;if(!profiles||Object.keys(profiles).length===0)return results.push({name:"Worker profiles",status:"pass",message:"none configured (using defaults)"}),results;let totalProfiles=Object.keys(profiles).length;results.push({name:"Profiles configured",status:"pass",message:`${totalProfiles} profile${totalProfiles===1?"":"s"}`});for(let name of Object.keys(profiles))results.push({name:`Profile '${name}'`,status:"pass",message:"claude (direct)"});if(config.defaultWorkerProfile)if(profiles[config.defaultWorkerProfile])results.push({name:"Default profile",status:"pass",message:config.defaultWorkerProfile});else results.push({name:"Default profile",status:"warn",message:`'${config.defaultWorkerProfile}' not found`,suggestion:"Run: genie profiles default <profile>"});return results}function runCheckSection(label,results,counts){printSectionHeader(label);for(let result2 of results){if(printCheckResult(result2),result2.status==="fail")counts.errors=!0;if(result2.status==="warn")counts.warnings=!0}}async function doctorCommand(options){if(options?.fix){await doctorFix();return}console.log(),console.log("\x1B[1mGenie Doctor\x1B[0m"),console.log(`\x1B[2m${"\u2500".repeat(40)}\x1B[0m`);let counts={errors:!1,warnings:!1};if(runCheckSection("Prerequisites",await checkPrerequisites(),counts),runCheckSection("Configuration",await checkConfiguration(),counts),runCheckSection("Tmux",await checkTmux(),counts),runCheckSection("Worker Profiles",await checkWorkerProfiles(),counts),console.log(),console.log(`\x1B[2m${"\u2500".repeat(40)}\x1B[0m`),counts.errors)console.log("\x1B[31mSome checks failed.\x1B[0m Run \x1B[36mgenie setup\x1B[0m to fix.");else if(counts.warnings)console.log("\x1B[33mSome warnings detected.\x1B[0m Everything should still work.");else console.log("\x1B[32mAll checks passed!\x1B[0m");if(console.log(),counts.errors)process.exit(1)}async function killStalePostgres(){console.log(" Killing stale postgres processes...");try{let{execSync:execSync2}=await import("child_process");execSync2('pkill -9 -f "postgres.*pgserve" 2>/dev/null || true',{stdio:"ignore",timeout:5000}),console.log(" \x1B[32m\u2713\x1B[0m Stale postgres processes killed")}catch{console.log(" \x1B[33m!\x1B[0m Could not kill stale postgres processes")}}async function cleanSharedMemory(){console.log(" Cleaning shared memory...");try{let{execSync:execSync2}=await import("child_process");execSync2("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000}),console.log(" \x1B[32m\u2713\x1B[0m Shared memory cleaned")}catch{console.log(" \x1B[32m\u2713\x1B[0m No stale shared memory")}}async function stopExistingDaemon(pidFile){try{let{readFileSync:readFileSync3}=await import("fs"),pid=Number.parseInt(readFileSync3(pidFile,"utf-8").trim(),10);if(!Number.isNaN(pid)&&pid>0)try{process.kill(pid,"SIGTERM"),console.log(` \x1B[32m\u2713\x1B[0m Stopped existing daemon (PID ${pid})`),await new Promise((r)=>setTimeout(r,1000))}catch{}}catch{}}function removeStaleFiles(genieHome2,pidFile){let portFile=join4(genieHome2,"pgserve.port"),postmasterPid=join4(genieHome2,"data","pgserve","postmaster.pid");for(let file of[portFile,pidFile,postmasterPid])if(existsSync4(file))try{unlinkSync3(file),console.log(` \x1B[32m\u2713\x1B[0m Removed ${file}`)}catch{console.log(` \x1B[33m!\x1B[0m Could not remove ${file}`)}}async function restartDaemon(){console.log(" Restarting daemon...");try{let{spawn}=await import("child_process"),bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"daemon","start"],{detached:!0,stdio:"ignore"}).unref(),await new Promise((resolve)=>setTimeout(resolve,2000)),console.log(" \x1B[32m\u2713\x1B[0m Daemon restart initiated")}catch{console.log(" \x1B[33m!\x1B[0m Could not restart daemon \u2014 run: genie daemon start")}}async function doctorFix(){console.log(`
3043
3051
  \x1B[1mGenie Doctor \u2014 Auto Fix\x1B[0m`),console.log(`\x1B[2m${"\u2500".repeat(40)}\x1B[0m
3044
3052
  `),await killStalePostgres(),await cleanSharedMemory();let genieHome2=process.env.GENIE_HOME??join4(homedir4(),".genie"),pidFile=join4(genieHome2,"scheduler.pid");await stopExistingDaemon(pidFile),removeStaleFiles(genieHome2,pidFile),await restartDaemon(),console.log(`
3045
3053
  \x1B[2m${"\u2500".repeat(40)}\x1B[0m`),console.log(`\x1B[32mFix complete.\x1B[0m Run \x1B[36mgenie doctor\x1B[0m to verify.
@@ -3237,8 +3245,8 @@ Omni Bridge Status`),console.log("\u2500".repeat(50)),console.log(` Bridge:
3237
3245
  Project: ${p.name}`),console.log("\u2500".repeat(50)),console.log(` ID: ${p.id}`),console.log(` Type: ${p.repoPath?"repo":"virtual"}`),p.repoPath)console.log(` Path: ${p.repoPath}`);if(p.description)console.log(` Desc: ${p.description}`);if(console.log(` Created: ${formatDate(p.createdAt)}`),console.log(` Tasks: ${tasks.length}`),tasks.length>0){console.log(`
3238
3246
  By status:`);for(let[status,count]of Object.entries(byStatus).sort())console.log(` ${padRight(status,15)} ${count}`);console.log(`
3239
3247
  By stage:`);for(let[stage,count]of Object.entries(byStage).sort())console.log(` ${padRight(stage,15)} ${count}`)}}function registerProjectCommands(program2){let project=program2.command("project").description("Project management \u2014 named task boards");project.command("list").description("List all projects").option("--all","Include archived projects").option("--json","Output as JSON").action(async(options)=>{try{let ts3=await getTaskService5(),projects=await ts3.listProjectsFiltered(options.all);if(options.json){console.log(JSON.stringify(projects,null,2));return}if(projects.length===0){console.log("No projects found. Projects are auto-created when you run `genie task create`.");return}await printProjectList(ts3,projects)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),project.command("create <name>").description("Create a new project").option("--virtual","Create a virtual project (not tied to a repo)").option("--repo <path>","Repo path for the project").option("--description <text>","Project description").action(async(name,options)=>{try{let ts3=await getTaskService5(),repoPath=options.virtual?null:options.repo??null,p=await ts3.createProject({name,repoPath,description:options.description});if(console.log(`Created project "${p.name}"`),console.log(` ID: ${p.id}`),console.log(` Type: ${p.repoPath?"repo":"virtual"}`),p.repoPath)console.log(` Path: ${p.repoPath}`);if(p.description)console.log(` Desc: ${p.description}`)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),project.command("show <name>").description("Show project detail with task stats").option("--json","Output as JSON").action(async(name,options)=>{try{let ts3=await getTaskService5(),p=await ts3.getProjectByName(name);if(!p){console.error(`Error: Project not found: ${name}`),process.exit(1);return}if(options.json){console.log(JSON.stringify(p,null,2));return}let tasks=await ts3.listTasks({projectName:name,allProjects:!0});printProjectDetail(p,tasks)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),project.command("archive <name>").description("Archive a project (cascades to boards and unfinished tasks)").action(async(name)=>{try{await(await getTaskService5()).archiveProject(name),console.log(`Archived project "${name}" and cascaded to boards + unfinished tasks.`)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),project.command("unarchive <name>").description("Restore an archived project and its boards (tasks stay as-is)").action(async(name)=>{try{await(await getTaskService5()).unarchiveProject(name),console.log(`Unarchived project "${name}" and restored boards.`)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),project.command("set-default <name>").description("Set default project for when outside any repo").action(async(name)=>{try{if(!await(await getTaskService5()).getProjectByName(name))console.error(`Error: Project not found: ${name}`),process.exit(1);let{loadGenieConfig:loadGenieConfig2,saveGenieConfig:saveGenieConfig2}=await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config)),config=await loadGenieConfig2();config.defaultProject=name,await saveGenieConfig2(config),console.log(`Default project set to "${name}"`)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_agent_registry();import{readFile as readFile12,stat as stat5}from"fs/promises";import{join as join55}from"path";import{readFile as readFile10}from"fs/promises";async function parseQaSpec(filePath){let content=await readFile10(filePath,"utf-8");return parseQaSpecContent(content,filePath)}var SECTION_MAP={setup:"setup",actions:"actions",expect:"expect"};function detectSection(line){for(let[keyword,section]of Object.entries(SECTION_MAP))if(new RegExp(`^##\\s+${keyword}`,"i").test(line))return section;if(line.startsWith("## "))return"none";return null}function parseQaSpecContent(content,filePath="<inline>"){let lines=content.split(`
3240
- `),name="",currentSection="none",setup=[],actions=[],expect=[],parsers2={none:()=>{},setup:(line)=>{let step=parseSetupLine(line);if(step)setup.push(step)},actions:(line)=>{let step=parseActionLine(line);if(step)actions.push(step)},expect:(line)=>{let exp=parseExpectLine(line);if(exp)expect.push(exp)}};for(let line of lines){let trimmed=line.trim();if(trimmed.startsWith("# ")&&!trimmed.startsWith("## ")){let match=trimmed.match(/^#\s+(?:Test:\s*)?(.+)$/);if(match)name=match[1].trim();continue}let section=detectSection(trimmed);if(section!==null){currentSection=section;continue}if(!trimmed||trimmed.startsWith("//")||trimmed.startsWith("<!--"))continue;parsers2[currentSection](trimmed)}if(!name)name=filePath.replace(/.*\//,"").replace(/\.md$/,"");return{name,file:filePath,setup,actions,expect}}function parseSetupLine(line){let text=stripListPrefix(line);if(!text)return null;let spawnMatch=text.match(/^spawn\s+(\S+)(?:\s+\((.+)\))?$/i);if(spawnMatch)return{kind:"spawn",target:spawnMatch[1],options:spawnMatch[2]?parseOptions2(spawnMatch[2]):{}};let followMatch=text.match(/^(?:start\s+)?follow(?:\s+(?:on\s+)?(\S+))?(?:\s+\((.+)\))?$/i);if(followMatch)return{kind:"follow",target:followMatch[1]||"team",options:followMatch[2]?parseOptions2(followMatch[2]):{}};return null}function parseActionLine(line){let text=stripListPrefix(line);if(!text)return null;let sendMatch=text.match(/^send\s+"([^"]+)"\s+to\s+(\S+)/i);if(sendMatch)return{kind:"send",message:sendMatch[1],to:sendMatch[2]};let waitMatch=text.match(/^wait\s+(?:for\s+.+?\s+)?\(?(?:max\s+)?(\d+)s\)?/i);if(waitMatch)return{kind:"wait",seconds:Number.parseInt(waitMatch[1],10)};let runMatch=text.match(/^run\s+(.+)$/i);if(runMatch)return{kind:"run",command:runMatch[1]};return null}function detectSource(text){if(/\binbox\b/i.test(text))return"inbox";if(/\blog\b/i.test(text))return"log";if(/\boutput\b/i.test(text))return"output";return"log"}function extractMatchers(text){let matchers={},matcherRegex=/(\w+)\s*([~!]?=)\s*(?:"([^"]+)"|(\S+))/g;for(let match of text.matchAll(matcherRegex)){let op=match[2]==="~="?"~":"",value=(match[3]??match[4]).trim();matchers[match[1]]=`${op}${value}`}return matchers}function parseExpectLine(line){let text=line.replace(/^[-*]\s*\[[ x]\]\s*/i,"").trim();if(!text)return null;return{description:text,source:detectSource(text),matchers:extractMatchers(text)}}function stripListPrefix(line){return line.replace(/^[-*]\s+/,"").replace(/^\d+\.\s+/,"").trim()}function parseOptions2(text){let opts={};for(let pair of text.split(",")){let[key,...rest]=pair.split(":");if(key&&rest.length>0)opts[key.trim()]=rest.join(":").trim()}return opts}import{cp as cp2,mkdir as mkdir8,rm as rm4,writeFile as writeFile5}from"fs/promises";import{tmpdir as tmpdir4}from"os";import{dirname as dirname11,join as join54,resolve as resolve10}from"path";var{$:$4}=globalThis.Bun;import{createHash as createHash4}from"crypto";import{mkdir as mkdir7,readFile as readFile11,readdir as readdir6,stat as stat4,writeFile as writeFile4}from"fs/promises";import{homedir as homedir29}from"os";import{join as join53,relative as relative4,resolve as resolve9}from"path";function repoHash(repoPath){return createHash4("sha256").update(resolve9(repoPath)).digest("hex").slice(0,12)}function resultsDir(repoPath){let base=process.env.GENIE_HOME??join53(homedir29(),".genie");return join53(base,"qa",repoHash(repoPath))}function resultsPath(repoPath){return join53(resultsDir(repoPath),"results.json")}async function loadResults(repoPath){try{let raw=await readFile11(resultsPath(repoPath),"utf-8");return JSON.parse(raw)}catch{return{}}}async function saveResult(repoPath,specKey,report){let dir=resultsDir(repoPath);await mkdir7(dir,{recursive:!0});let results=await loadResults(repoPath),specHash=await hashSpecFile(report.file);results[specKey]={lastRun:new Date().toISOString(),result:report.result,durationMs:report.durationMs,specHash,expectations:report.expectations,error:report.error},await writeFile4(resultsPath(repoPath),JSON.stringify(results,null,2))}async function isStale(repoPath,specKey,specFilePath){let stored=(await loadResults(repoPath))[specKey];if(!stored)return!1;return await hashSpecFile(specFilePath)!==stored.specHash}async function listAllSpecs(specDir){let entries=[];return await walkSpecs(specDir,specDir,entries),entries.sort((a,b2)=>{if(a.domain!==b2.domain)return a.domain.localeCompare(b2.domain);return a.name.localeCompare(b2.name)})}async function hashSpecFile(filePath){try{let content=await readFile11(filePath,"utf-8");return createHash4("sha256").update(content).digest("hex").slice(0,12)}catch{return"unknown"}}async function walkSpecs(baseDir,dir,entries){let items=await readdir6(dir);for(let item of items){let fullPath=join53(dir,item);if((await stat4(fullPath)).isDirectory())await walkSpecs(baseDir,fullPath,entries);else if(item.endsWith(".md")){let rel=relative4(baseDir,fullPath),parts=rel.replace(/\.md$/,"").split("/"),domain=parts.length>1?parts.slice(0,-1).join("/"):"(root)",name=parts[parts.length-1];entries.push({key:rel.replace(/\.md$/,""),domain,name,filePath:fullPath})}}}function specKeyFromPath(specDir,filePath){return relative4(specDir,filePath).replace(/\.md$/,"")}function formatTimeAgo(isoDate){let ms=Date.now()-new Date(isoDate).getTime(),seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s ago`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h ago`;return`${Math.floor(hours/24)}d ago`}init_runtime_events();init_team_manager();function emitNdjson(event){process.stdout.write(`${JSON.stringify(event)}
3241
- `)}async function publishQaEvent(repoPath,qaType,payload){let{specKey,domain,team,...rest}=payload;await publishSubjectEvent(repoPath,`genie.qa.${qaType}`,{kind:"qa",agent:"qa",team,text:`${qaType}: ${specKey}`,data:{qaType,specKey,domain,...rest},source:"hook"})}async function emitQaEvent(repoPath,qaType,payload,ndjson){if(await publishQaEvent(repoPath,qaType,payload),ndjson)emitNdjson(payload)}function parseStatusEntry(status,parts,index){if(status.startsWith("R")){let from=parts[index]??"",to=parts[index+1]??"";if(from&&to)return{op:{kind:"rename",from,to},nextIndex:index+2};return{op:null,nextIndex:index+2}}let path3=parts[index]??"";if(!path3)return{op:null,nextIndex:index+1};return{op:{kind:status.startsWith("D")?"delete":"copy",path:path3},nextIndex:index+1}}function parseNameStatusZ(output){if(!output)return[];let parts=output.split("\x00").filter(Boolean),ops=[],i2=0;while(i2<parts.length){let status=parts[i2++]??"";if(!status)break;let{op,nextIndex}=parseStatusEntry(status,parts,i2);if(i2=nextIndex,op)ops.push(op)}return ops}async function overlayDirtyWorkingTree(repoPath,worktreePath){let tracked=(await $4`git -C ${repoPath} diff --name-status --find-renames -z HEAD --`.quiet().nothrow().text()).trim(),untracked=(await $4`git -C ${repoPath} ls-files --others --exclude-standard -z`.quiet().nothrow().text()).trim(),ops=parseNameStatusZ(tracked);for(let path3 of untracked.split("\x00").filter(Boolean))ops.push({kind:"copy",path:path3});for(let op of ops){if(op.kind==="delete"){await rm4(join54(worktreePath,op.path),{recursive:!0,force:!0});continue}if(op.kind==="rename"){await rm4(join54(worktreePath,op.from),{recursive:!0,force:!0});let src2=join54(repoPath,op.to),dest2=join54(worktreePath,op.to);await mkdir8(dirname11(dest2),{recursive:!0}),await cp2(src2,dest2,{recursive:!0,force:!0});continue}let src=join54(repoPath,op.path),dest=join54(worktreePath,op.path);await mkdir8(dirname11(dest),{recursive:!0}),await cp2(src,dest,{recursive:!0,force:!0})}}async function runAllSpecs(specDir,options){let entries=await listAllSpecs(specDir);return runSpecEntries(entries,specDir,options)}async function runDomainSpecs(specDir,domain,options){let filtered=(await listAllSpecs(specDir)).filter((e)=>e.domain===domain);return runSpecEntries(filtered,specDir,options)}async function prepareTeams(entries,repoPath,ndjson){let prepared=[];console.error(`
3248
+ `),name="",currentSection="none",setup=[],actions=[],expect=[],parsers2={none:()=>{},setup:(line)=>{let step=parseSetupLine(line);if(step)setup.push(step)},actions:(line)=>{let step=parseActionLine(line);if(step)actions.push(step)},expect:(line)=>{let exp=parseExpectLine(line);if(exp)expect.push(exp)}};for(let line of lines){let trimmed=line.trim();if(trimmed.startsWith("# ")&&!trimmed.startsWith("## ")){let match=trimmed.match(/^#\s+(?:Test:\s*)?(.+)$/);if(match)name=match[1].trim();continue}let section=detectSection(trimmed);if(section!==null){currentSection=section;continue}if(!trimmed||trimmed.startsWith("//")||trimmed.startsWith("<!--"))continue;parsers2[currentSection](trimmed)}if(!name)name=filePath.replace(/.*\//,"").replace(/\.md$/,"");return{name,file:filePath,setup,actions,expect}}function parseSetupLine(line){let text=stripListPrefix(line);if(!text)return null;let spawnMatch=text.match(/^spawn\s+(\S+)(?:\s+\((.+)\))?$/i);if(spawnMatch)return{kind:"spawn",target:spawnMatch[1],options:spawnMatch[2]?parseOptions2(spawnMatch[2]):{}};let followMatch=text.match(/^(?:start\s+)?follow(?:\s+(?:on\s+)?(\S+))?(?:\s+\((.+)\))?$/i);if(followMatch)return{kind:"follow",target:followMatch[1]||"team",options:followMatch[2]?parseOptions2(followMatch[2]):{}};return null}function parseActionLine(line){let text=stripListPrefix(line);if(!text)return null;let sendMatch=text.match(/^send\s+"([^"]+)"\s+to\s+(\S+)/i);if(sendMatch)return{kind:"send",message:sendMatch[1],to:sendMatch[2]};let waitMatch=text.match(/^wait\s+(?:for\s+.+?\s+)?\(?(?:max\s+)?(\d+)s\)?/i);if(waitMatch)return{kind:"wait",seconds:Number.parseInt(waitMatch[1],10)};let runMatch=text.match(/^run\s+(.+)$/i);if(runMatch)return{kind:"run",command:runMatch[1]};return null}function detectSource(text){if(/\binbox\b/i.test(text))return"inbox";if(/\blog\b/i.test(text))return"log";if(/\boutput\b/i.test(text))return"output";return"log"}function extractMatchers(text){let matchers={},matcherRegex=/(\w+)\s*([~!]?=)\s*(?:"([^"]+)"|(\S+))/g;for(let match of text.matchAll(matcherRegex)){let op=match[2]==="~="?"~":"",value=(match[3]??match[4]).trim();matchers[match[1]]=`${op}${value}`}return matchers}function parseExpectLine(line){let text=line.replace(/^[-*]\s*\[[ x]\]\s*/i,"").trim();if(!text)return null;return{description:text,source:detectSource(text),matchers:extractMatchers(text)}}function stripListPrefix(line){return line.replace(/^[-*]\s+/,"").replace(/^\d+\.\s+/,"").trim()}function parseOptions2(text){let opts={};for(let pair of text.split(",")){let[key,...rest]=pair.split(":");if(key&&rest.length>0)opts[key.trim()]=rest.join(":").trim()}return opts}import{cp as cp2,mkdir as mkdir8,rm as rm4,writeFile as writeFile5}from"fs/promises";import{tmpdir as tmpdir4}from"os";import{dirname as dirname10,join as join54,resolve as resolve10}from"path";var{$:$4}=globalThis.Bun;import{createHash as createHash4}from"crypto";import{mkdir as mkdir7,readFile as readFile11,readdir as readdir6,stat as stat4,writeFile as writeFile4}from"fs/promises";import{homedir as homedir29}from"os";import{join as join53,relative as relative4,resolve as resolve9}from"path";function repoHash(repoPath){return createHash4("sha256").update(resolve9(repoPath)).digest("hex").slice(0,12)}function resultsDir(repoPath){let base=process.env.GENIE_HOME??join53(homedir29(),".genie");return join53(base,"qa",repoHash(repoPath))}function resultsPath(repoPath){return join53(resultsDir(repoPath),"results.json")}async function loadResults(repoPath){try{let raw=await readFile11(resultsPath(repoPath),"utf-8");return JSON.parse(raw)}catch{return{}}}async function saveResult(repoPath,specKey,report){let dir=resultsDir(repoPath);await mkdir7(dir,{recursive:!0});let results=await loadResults(repoPath),specHash=await hashSpecFile(report.file);results[specKey]={lastRun:new Date().toISOString(),result:report.result,durationMs:report.durationMs,specHash,expectations:report.expectations,error:report.error},await writeFile4(resultsPath(repoPath),JSON.stringify(results,null,2))}async function isStale(repoPath,specKey,specFilePath){let stored=(await loadResults(repoPath))[specKey];if(!stored)return!1;return await hashSpecFile(specFilePath)!==stored.specHash}async function listAllSpecs(specDir){let entries=[];return await walkSpecs(specDir,specDir,entries),entries.sort((a,b2)=>{if(a.domain!==b2.domain)return a.domain.localeCompare(b2.domain);return a.name.localeCompare(b2.name)})}async function hashSpecFile(filePath){try{let content=await readFile11(filePath,"utf-8");return createHash4("sha256").update(content).digest("hex").slice(0,12)}catch{return"unknown"}}async function walkSpecs(baseDir,dir,entries){let items=await readdir6(dir);for(let item of items){let fullPath=join53(dir,item);if((await stat4(fullPath)).isDirectory())await walkSpecs(baseDir,fullPath,entries);else if(item.endsWith(".md")){let rel=relative4(baseDir,fullPath),parts=rel.replace(/\.md$/,"").split("/"),domain=parts.length>1?parts.slice(0,-1).join("/"):"(root)",name=parts[parts.length-1];entries.push({key:rel.replace(/\.md$/,""),domain,name,filePath:fullPath})}}}function specKeyFromPath(specDir,filePath){return relative4(specDir,filePath).replace(/\.md$/,"")}function formatTimeAgo(isoDate){let ms=Date.now()-new Date(isoDate).getTime(),seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s ago`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h ago`;return`${Math.floor(hours/24)}d ago`}init_runtime_events();init_team_manager();function emitNdjson(event){process.stdout.write(`${JSON.stringify(event)}
3249
+ `)}async function publishQaEvent(repoPath,qaType,payload){let{specKey,domain,team,...rest}=payload;await publishSubjectEvent(repoPath,`genie.qa.${qaType}`,{kind:"qa",agent:"qa",team,text:`${qaType}: ${specKey}`,data:{qaType,specKey,domain,...rest},source:"hook"})}async function emitQaEvent(repoPath,qaType,payload,ndjson){if(await publishQaEvent(repoPath,qaType,payload),ndjson)emitNdjson(payload)}function parseStatusEntry(status,parts,index){if(status.startsWith("R")){let from=parts[index]??"",to=parts[index+1]??"";if(from&&to)return{op:{kind:"rename",from,to},nextIndex:index+2};return{op:null,nextIndex:index+2}}let path3=parts[index]??"";if(!path3)return{op:null,nextIndex:index+1};return{op:{kind:status.startsWith("D")?"delete":"copy",path:path3},nextIndex:index+1}}function parseNameStatusZ(output){if(!output)return[];let parts=output.split("\x00").filter(Boolean),ops=[],i2=0;while(i2<parts.length){let status=parts[i2++]??"";if(!status)break;let{op,nextIndex}=parseStatusEntry(status,parts,i2);if(i2=nextIndex,op)ops.push(op)}return ops}async function overlayDirtyWorkingTree(repoPath,worktreePath){let tracked=(await $4`git -C ${repoPath} diff --name-status --find-renames -z HEAD --`.quiet().nothrow().text()).trim(),untracked=(await $4`git -C ${repoPath} ls-files --others --exclude-standard -z`.quiet().nothrow().text()).trim(),ops=parseNameStatusZ(tracked);for(let path3 of untracked.split("\x00").filter(Boolean))ops.push({kind:"copy",path:path3});for(let op of ops){if(op.kind==="delete"){await rm4(join54(worktreePath,op.path),{recursive:!0,force:!0});continue}if(op.kind==="rename"){await rm4(join54(worktreePath,op.from),{recursive:!0,force:!0});let src2=join54(repoPath,op.to),dest2=join54(worktreePath,op.to);await mkdir8(dirname10(dest2),{recursive:!0}),await cp2(src2,dest2,{recursive:!0,force:!0});continue}let src=join54(repoPath,op.path),dest=join54(worktreePath,op.path);await mkdir8(dirname10(dest),{recursive:!0}),await cp2(src,dest,{recursive:!0,force:!0})}}async function runAllSpecs(specDir,options){let entries=await listAllSpecs(specDir);return runSpecEntries(entries,specDir,options)}async function runDomainSpecs(specDir,domain,options){let filtered=(await listAllSpecs(specDir)).filter((e)=>e.domain===domain);return runSpecEntries(filtered,specDir,options)}async function prepareTeams(entries,repoPath,ndjson){let prepared=[];console.error(`
3242
3250
  [qa] Creating ${entries.length} teams...`);for(let entry of entries){let teamName=`qa-${Date.now().toString(36)}-${entry.name.slice(0,8)}`;try{let spec=await parseQaSpec(entry.filePath),config=await createTeam(teamName,repoPath);await overlayDirtyWorkingTree(repoPath,config.worktreePath),await hireAgent(teamName,"qa");let prompt2=buildTeamLeadPrompt(spec,teamName,repoPath),promptFile=join54(tmpdir4(),`genie-qa-${teamName}.md`);await writeFile5(promptFile,prompt2),prepared.push({entry,spec,teamName,worktreePath:config.worktreePath,promptFile}),console.error(` \u2713 ${entry.name}`),await emitQaEvent(repoPath,"team-created",{type:"qa:team-created",specKey:entry.key,domain:entry.domain,team:teamName},ndjson)}catch(err){console.error(` \u2717 ${entry.name}: ${err instanceof Error?err.message:err}`)}await new Promise((r)=>setTimeout(r,200))}return prepared}async function emitSpecDone(repoPath,specKey,domain,team,report,ndjson){await emitQaEvent(repoPath,"spec-done",{type:"qa:spec-done",specKey,domain,team,result:report.result,durationMs:report.durationMs,expectations:report.expectations,error:report.error},ndjson)}async function runSpecEntries(entries,specDir,options){let repoPath=resolve10(options?.repoPath??process.cwd()),maxConcurrency=options?.parallel??5,timeoutMs=(options?.timeout??3600)*1000,ndjson=options?.ndjson??!1,GREEN="\x1B[32m",RED="\x1B[31m",RESET2="\x1B[0m",DIM2="\x1B[90m",prepared=await prepareTeams(entries,repoPath,ndjson);if(prepared.length===0)return[];let timelineSub=await followRuntimeEvents({repoPath,teamPrefix:"qa-"},(event)=>{if(!event?.timestamp||!event?.kind)return;let team=event.team??"";if(!team.startsWith("qa-"))return;let match=prepared.find((p)=>p.teamName===team),specKey=match?.entry.key??team,specName=match?.entry.name??team,domain=match?.entry.domain??"",time=new Date(event.timestamp).toLocaleTimeString("en-US",{hour12:!1}),text=(event.text??"").slice(0,100);if(console.error(` \x1B[90m${time}\x1B[0m \x1B[90m[${event.kind}]\x1B[0m ${specName} \x1B[90m${text}\x1B[0m`),ndjson)emitNdjson({type:"qa:event",specKey,domain,team,event:{timestamp:event.timestamp,kind:event.kind,agent:event.agent??"",text:event.text??""}})},{pollIntervalMs:250});console.error(`
3243
3251
  [qa] Running ${prepared.length} specs (max ${maxConcurrency} parallel)
3244
3252
  `);let reports=[],running2=0,nextIdx=0,startTime=Date.now();await new Promise((resolveAll)=>{let tryStartNext=()=>{while(running2<maxConcurrency&&nextIdx<prepared.length){let p=prepared[nextIdx++];running2++,emitQaEvent(repoPath,"spec-started",{type:"qa:spec-started",specKey:p.entry.key,domain:p.entry.domain,team:p.teamName},ndjson),runPreparedSpec(repoPath,p.spec,p.teamName,p.worktreePath,p.promptFile,timeoutMs).then(async(report)=>{let key=specKeyFromPath(specDir,p.entry.filePath);await saveResult(repoPath,key,report);let icon=report.result==="pass"?`${"\x1B[32m"}\u2713${"\x1B[0m"}`:`${"\x1B[31m"}\u2717${"\x1B[0m"}`,elapsed=((Date.now()-startTime)/1000).toFixed(0);console.error(` ${icon} ${p.entry.name} (${(report.durationMs/1000).toFixed(0)}s) [${elapsed}s total]`),await emitSpecDone(repoPath,p.entry.key,p.entry.domain,p.teamName,report,ndjson),reports.push(report)}).catch((err)=>{let errorReport=makeErrorReport(p.spec,Date.now(),String(err));reports.push(errorReport),console.error(` ${"\x1B[31m"}\u2717${"\x1B[0m"} ${p.entry.name}: ${err}`),emitSpecDone(repoPath,p.entry.key,p.entry.domain,p.teamName,errorReport,ndjson)}).finally(()=>{if(running2--,reports.length===prepared.length)resolveAll();else tryStartNext()})}};tryStartNext()}),await timelineSub.stop(),console.error(`
@@ -3471,5 +3479,5 @@ Examples:
3471
3479
  genie spawn engineer # Spawn built-in engineer role
3472
3480
  genie spawn researcher --model sonnet # Spawn with model override
3473
3481
  genie spawn my-agent --team my-feature # Spawn into a specific team
3474
- genie spawn council--questioner --provider codex # Use Codex provider`).action(async(name,options)=>{try{await handleWorkerSpawn(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("kill <name>").description("Force kill an agent by name").action(async(name)=>{try{await handleWorkerKill(name)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("stop <name>").description("Stop an agent (preserves session for resume)").action(async(name)=>{try{await handleWorkerStop(name)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("resume [name]").description("Resume a suspended/failed agent with its Claude session").option("--all","Resume all eligible agents").action(async(name,options)=>{try{await handleWorkerResume(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("history <name>").description("Show compressed session history for an agent").option("--full","Show full conversation without compression").option("--since <n>","Show last N user/assistant exchanges",Number.parseInt).option("--last <n>","Show last N transcript entries",Number.parseInt).option("--type <role>","Filter by role (user, assistant, tool_call)").option("--after <timestamp>","Only entries after ISO timestamp").option("--json","Output as JSON").option("--ndjson","Output as newline-delimited JSON (pipeable to jq)").option("--raw","Output raw JSONL entries").option("--log-file <path>","Direct path to log file (for testing)").action(async(name,options)=>{await historyCommand(name,options)});program2.command("log [agent]").description("Unified observability feed \u2014 aggregates transcript, DMs, team chat").option("--team <name>","Show interleaved feed for all agents in a team").option("--type <kind>","Filter by event kind (transcript, message, tool_call, state, system)").option("--since <timestamp>","Only events after ISO timestamp").option("--last <n>","Show last N events",Number.parseInt).option("--ndjson","Output as newline-delimited JSON (pipeable to jq)").option("--json","Output as pretty JSON").option("-f, --follow","Follow mode \u2014 real-time streaming").action(async(agent,options)=>{await logCommand(agent,options)});var qaCmd=program2.command("qa").description("QA \u2014 self-testing system for genie CLI");qaCmd.command("run [target]",{isDefault:!0}).description("Run QA specs (all, a domain, or a single spec)").option("--timeout <seconds>","Max seconds per spec",(v2)=>Number(v2),3600).option("--parallel <n>","Max specs to run in parallel",(v2)=>Number(v2),5).option("--verbose","Show all collected events").option("--ndjson","Machine-readable NDJSON output").action(async(target,options)=>{await qaCommand(target,options)});qaCmd.command("status").description("Show QA dashboard with last results per spec").option("--json","Output as JSON").action(async(options)=>{await qaStatusCommand(options)});qaCmd.command("history").description("Show recent QA runs").action(async()=>{await qaHistoryCommand()});qaCmd.command("check <specFile>").description("Evaluate a QA spec against current team logs and publish qa-report").option("--team <name>","Team name (defaults to GENIE_TEAM)").option("--since <timestamp>","Only consider events after this ISO timestamp").option("--since-file <path>","Read the lower-bound timestamp from a file").action(async(specFile,options)=>{await qaCheckCommand(specFile,options)});program2.command("qa-report <json>").description("Publish QA result to the PG event log (called by QA team-lead)").action(async(json2)=>{let team=process.env.GENIE_TEAM;if(!team)console.error("Error: GENIE_TEAM not set. This command must be run by a QA team-lead agent."),process.exit(1);try{let data=JSON.parse(json2),{publishSubjectEvent:publishSubjectEvent2}=await Promise.resolve().then(() => (init_runtime_events(),exports_runtime_events));await publishSubjectEvent2(process.cwd(),`genie.qa.${team}.result`,{kind:"qa",agent:"qa",team,text:`QA result: ${String(data.result??"unknown")}`,data,source:"hook"}),console.log(`QA result published to PG event log as genie.qa.${team}.result`)}catch(err){console.error(`Failed to publish QA result: ${err}`),process.exit(1)}});program2.command("read <name>").description("Read terminal output from an agent pane").option("-n, --lines <number>","Number of lines to read").option("--from <line>","Start line").option("--to <line>","End line").option("--range <range>",'Line range (e.g., "10-20")').option("--search <text>","Search for text").option("--grep <pattern>","Grep for pattern").option("-f, --follow","Follow mode (like tail -f)").option("--all","Show all output").option("-r, --reverse","Reverse order").option("--json","Output as JSON").action(async(name,options)=>{await readSessionLogs2(name,options)});program2.command("answer <name> <choice>").description('Answer a question for an agent (use "text:..." for text input)').action(async(name,choice)=>{await answerQuestion(name,choice)});program2.command("ls").description("List registered agents with runtime status").option("--json","Output as JSON").option("--source <name>","Filter by executor metadata source (e.g. omni)").action(async(options)=>{try{await handleLsCommand(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});var args=process.argv.slice(2),isTuiPane=process.env.GENIE_TUI_PANE==="left"&&args.length===0,tuiRightPane=process.env.GENIE_TUI_RIGHT;delete process.env.GENIE_TUI_PANE;delete process.env.GENIE_TUI_RIGHT;delete process.env.GENIE_IS_DAEMON;if(isTuiPane){if(tuiRightPane)process.env.GENIE_TUI_RIGHT=tuiRightPane;let{launchTui:launchTui2}=await Promise.resolve().then(() => exports_tui);await launchTui2(),process.exit(0)}if(args.length===0){if(process.env.TMUX?.includes("genie-tui"))console.log("Already inside the genie TUI. Use Ctrl-b d to detach, or run genie commands directly."),process.exit(0);if(process.env.TMUX)console.warn("Note: switching to genie TUI from within another tmux session.");let{findWorkspace:findWorkspace2}=await Promise.resolve().then(() => (init_workspace(),exports_workspace)),ws=findWorkspace2();if(!ws){let{isInteractive:isInteractive2}=await Promise.resolve().then(() => (init_interactivity(),exports_interactivity));if(!isInteractive2())console.error("No workspace found. Run `genie init` to set up."),process.exit(2);let{confirm:confirm2}=await Promise.resolve().then(() => (init_esm14(),exports_esm));if(!await confirm2({message:"No workspace found. Initialize? [Y/n]",default:!0}))console.error("No workspace found. Run `genie init` to set up."),process.exit(2);let{mkdirSync:mkdirSync21,writeFileSync:writeFileSync25}=await import("fs"),{basename:basename14,join:join61}=await import("path"),cwd=process.cwd(),genieDir=join61(cwd,".genie");mkdirSync21(genieDir,{recursive:!0});let config={name:basename14(cwd),agents:{defaults:{}},tmux:{socket:"genie"},sdk:{}};if(writeFileSync25(join61(genieDir,"workspace.json"),`${JSON.stringify(config,null,2)}
3475
- `),console.log(`Workspace initialized: ${cwd}`),ws=findWorkspace2(),!ws)console.error("Failed to initialize workspace."),process.exit(1)}let{resolveAgentFromCwd:resolveAgentFromCwd2}=await Promise.resolve().then(() => (init_resolve_agent_cwd(),exports_resolve_agent_cwd)),resolved=resolveAgentFromCwd2(process.cwd(),ws.root),initialAgent=resolved.agent,{isServeRunning:isServeRunning2,autoStartServe:autoStartServe2,isTuiSessionReady:isTuiSessionReady2,ensureTuiSession:ensureTuiSession2}=await Promise.resolve().then(() => (init_serve(),exports_serve));if(!isServeRunning2())console.log("Starting genie serve..."),await autoStartServe2();else if(!isTuiSessionReady2())ensureTuiSession2(ws.root);if(ws.root)process.env.GENIE_TUI_WORKSPACE=ws.root;if(initialAgent)process.env.GENIE_TUI_AGENT=initialAgent;if(resolved.source!=="default"){let{execSync:execSync18}=await import("child_process");try{execSync18(`tmux has-session -t ${initialAgent} 2>/dev/null`,{stdio:"pipe"})}catch{console.log(`Spawning ${initialAgent}...`);try{execSync18(`genie spawn ${initialAgent}`,{stdio:"inherit",timeout:15000})}catch{}}}if(initialAgent){let{writeFileSync:writeFileSync25}=await import("fs"),{join:join61}=await import("path"),home=process.env.GENIE_HOME??join61((await import("os")).homedir(),".genie");try{writeFileSync25(join61(home,"tui-initial-agent"),initialAgent,"utf-8")}catch{}}let{attachTuiSession:attachTuiSession2}=await Promise.resolve().then(() => (init_tmux2(),exports_tmux2));attachTuiSession2(),process.exit(0)}if(args.every((a)=>a==="--reset")){let{sessionCommand:sessionCommand2}=await Promise.resolve().then(() => (init_session(),exports_session));await sessionCommand2({reset:!0}),process.exit(0)}var sessionIdx=args.indexOf("--session");if(sessionIdx!==-1&&sessionIdx+1<args.length){let sessionName=args[sessionIdx+1];if(!args.filter((_2,i2)=>i2!==sessionIdx&&i2!==sessionIdx+1).some((a)=>!a.startsWith("-")))try{await startNamedSession(sessionName),process.exit(0)}catch(err){console.error(`Error: ${err instanceof Error?err.message:err}`),process.exit(1)}else try{await program2.parseAsync(process.argv)}finally{stopOtelReceiver(),await shutdown().catch(()=>{})}}else try{let _cmdStart=Date.now();if(await program2.parseAsync(process.argv),process.env.GENIE_PROFILE_DB)console.error(`[profile] parseAsync=${Date.now()-_cmdStart}ms`)}finally{let _shutStart=Date.now();if(stopOtelReceiver(),await shutdown().catch(()=>{}),process.env.GENIE_PROFILE_DB)console.error(`[profile] shutdown=${Date.now()-_shutStart}ms`)}
3482
+ genie spawn council--questioner --provider codex # Use Codex provider`).action(async(name,options)=>{try{await handleWorkerSpawn(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("kill <name>").description("Force kill an agent by name").action(async(name)=>{try{await handleWorkerKill(name)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("stop <name>").description("Stop an agent (preserves session for resume)").action(async(name)=>{try{await handleWorkerStop(name)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("resume [name]").description("Resume a suspended/failed agent with its Claude session").option("--all","Resume all eligible agents").action(async(name,options)=>{try{await handleWorkerResume(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});program2.command("history <name>").description("Show compressed session history for an agent").option("--full","Show full conversation without compression").option("--since <n>","Show last N user/assistant exchanges",Number.parseInt).option("--last <n>","Show last N transcript entries",Number.parseInt).option("--type <role>","Filter by role (user, assistant, tool_call)").option("--after <timestamp>","Only entries after ISO timestamp").option("--json","Output as JSON").option("--ndjson","Output as newline-delimited JSON (pipeable to jq)").option("--raw","Output raw JSONL entries").option("--log-file <path>","Direct path to log file (for testing)").action(async(name,options)=>{await historyCommand(name,options)});program2.command("log [agent]").description("Unified observability feed \u2014 aggregates transcript, DMs, team chat").option("--team <name>","Show interleaved feed for all agents in a team").option("--type <kind>","Filter by event kind (transcript, message, tool_call, state, system)").option("--since <timestamp>","Only events after ISO timestamp").option("--last <n>","Show last N events",Number.parseInt).option("--ndjson","Output as newline-delimited JSON (pipeable to jq)").option("--json","Output as pretty JSON").option("-f, --follow","Follow mode \u2014 real-time streaming").action(async(agent,options)=>{await logCommand(agent,options)});var qaCmd=program2.command("qa").description("QA \u2014 self-testing system for genie CLI");qaCmd.command("run [target]",{isDefault:!0}).description("Run QA specs (all, a domain, or a single spec)").option("--timeout <seconds>","Max seconds per spec",(v2)=>Number(v2),3600).option("--parallel <n>","Max specs to run in parallel",(v2)=>Number(v2),5).option("--verbose","Show all collected events").option("--ndjson","Machine-readable NDJSON output").action(async(target,options)=>{await qaCommand(target,options)});qaCmd.command("status").description("Show QA dashboard with last results per spec").option("--json","Output as JSON").action(async(options)=>{await qaStatusCommand(options)});qaCmd.command("history").description("Show recent QA runs").action(async()=>{await qaHistoryCommand()});qaCmd.command("check <specFile>").description("Evaluate a QA spec against current team logs and publish qa-report").option("--team <name>","Team name (defaults to GENIE_TEAM)").option("--since <timestamp>","Only consider events after this ISO timestamp").option("--since-file <path>","Read the lower-bound timestamp from a file").action(async(specFile,options)=>{await qaCheckCommand(specFile,options)});program2.command("qa-report <json>").description("Publish QA result to the PG event log (called by QA team-lead)").action(async(json2)=>{let team=process.env.GENIE_TEAM;if(!team)console.error("Error: GENIE_TEAM not set. This command must be run by a QA team-lead agent."),process.exit(1);try{let data=JSON.parse(json2),{publishSubjectEvent:publishSubjectEvent2}=await Promise.resolve().then(() => (init_runtime_events(),exports_runtime_events));await publishSubjectEvent2(process.cwd(),`genie.qa.${team}.result`,{kind:"qa",agent:"qa",team,text:`QA result: ${String(data.result??"unknown")}`,data,source:"hook"}),console.log(`QA result published to PG event log as genie.qa.${team}.result`)}catch(err){console.error(`Failed to publish QA result: ${err}`),process.exit(1)}});program2.command("read <name>").description("Read terminal output from an agent pane").option("-n, --lines <number>","Number of lines to read").option("--from <line>","Start line").option("--to <line>","End line").option("--range <range>",'Line range (e.g., "10-20")').option("--search <text>","Search for text").option("--grep <pattern>","Grep for pattern").option("-f, --follow","Follow mode (like tail -f)").option("--all","Show all output").option("-r, --reverse","Reverse order").option("--json","Output as JSON").action(async(name,options)=>{await readSessionLogs2(name,options)});program2.command("answer <name> <choice>").description('Answer a question for an agent (use "text:..." for text input)').action(async(name,choice)=>{await answerQuestion(name,choice)});program2.command("ls").description("List registered agents with runtime status").option("--json","Output as JSON").option("--source <name>","Filter by executor metadata source (e.g. omni)").action(async(options)=>{try{await handleLsCommand(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});var args=process.argv.slice(2),isTuiPane=process.env.GENIE_TUI_PANE==="left"&&args.length===0,tuiRightPane=process.env.GENIE_TUI_RIGHT;delete process.env.GENIE_TUI_PANE;delete process.env.GENIE_TUI_RIGHT;delete process.env.GENIE_IS_DAEMON;if(isTuiPane){if(tuiRightPane)process.env.GENIE_TUI_RIGHT=tuiRightPane;let{launchTui:launchTui2}=await Promise.resolve().then(() => exports_tui);await launchTui2(),process.exit(0)}if(args.length===0){if(process.env.TMUX?.includes("genie-tui"))console.log("Already inside the genie TUI. Use Ctrl-b d to detach, or run genie commands directly."),process.exit(0);if(process.env.TMUX)console.warn("Note: switching to genie TUI from within another tmux session.");let{findWorkspace:findWorkspace2}=await Promise.resolve().then(() => (init_workspace(),exports_workspace)),ws=findWorkspace2();if(!ws){let{isInteractive:isInteractive2}=await Promise.resolve().then(() => (init_interactivity(),exports_interactivity));if(!isInteractive2())console.error("No workspace found. Run `genie init` to set up."),process.exit(2);let{confirm:confirm2}=await Promise.resolve().then(() => (init_esm14(),exports_esm));if(!await confirm2({message:"No workspace found. Initialize? [Y/n]",default:!0}))console.error("No workspace found. Run `genie init` to set up."),process.exit(2);let{mkdirSync:mkdirSync20,writeFileSync:writeFileSync24}=await import("fs"),{basename:basename14,join:join61}=await import("path"),cwd=process.cwd(),genieDir=join61(cwd,".genie");mkdirSync20(genieDir,{recursive:!0});let config={name:basename14(cwd),agents:{defaults:{}},tmux:{socket:"genie"},sdk:{}};if(writeFileSync24(join61(genieDir,"workspace.json"),`${JSON.stringify(config,null,2)}
3483
+ `),console.log(`Workspace initialized: ${cwd}`),ws=findWorkspace2(),!ws)console.error("Failed to initialize workspace."),process.exit(1)}let{resolveAgentFromCwd:resolveAgentFromCwd2}=await Promise.resolve().then(() => (init_resolve_agent_cwd(),exports_resolve_agent_cwd)),resolved=resolveAgentFromCwd2(process.cwd(),ws.root),initialAgent=resolved.agent,{isServeRunning:isServeRunning2,autoStartServe:autoStartServe2,isTuiSessionReady:isTuiSessionReady2,ensureTuiSession:ensureTuiSession2}=await Promise.resolve().then(() => (init_serve(),exports_serve));if(!isServeRunning2())console.log("Starting genie serve..."),await autoStartServe2();else if(!isTuiSessionReady2())ensureTuiSession2(ws.root);if(ws.root)process.env.GENIE_TUI_WORKSPACE=ws.root;if(initialAgent)process.env.GENIE_TUI_AGENT=initialAgent;if(resolved.source!=="default"){let{execSync:execSync18}=await import("child_process");try{execSync18(`tmux has-session -t ${initialAgent} 2>/dev/null`,{stdio:"pipe"})}catch{console.log(`Spawning ${initialAgent}...`);try{execSync18(`genie spawn ${initialAgent}`,{stdio:"inherit",timeout:15000})}catch{}}}if(initialAgent){let{writeFileSync:writeFileSync24}=await import("fs"),{join:join61}=await import("path"),home=process.env.GENIE_HOME??join61((await import("os")).homedir(),".genie");try{writeFileSync24(join61(home,"tui-initial-agent"),initialAgent,"utf-8")}catch{}}let{attachTuiSession:attachTuiSession2}=await Promise.resolve().then(() => (init_tmux2(),exports_tmux2));attachTuiSession2(),process.exit(0)}if(args.every((a)=>a==="--reset")){let{sessionCommand:sessionCommand2}=await Promise.resolve().then(() => (init_session(),exports_session));await sessionCommand2({reset:!0}),process.exit(0)}var sessionIdx=args.indexOf("--session");if(sessionIdx!==-1&&sessionIdx+1<args.length){let sessionName=args[sessionIdx+1];if(!args.filter((_2,i2)=>i2!==sessionIdx&&i2!==sessionIdx+1).some((a)=>!a.startsWith("-")))try{await startNamedSession(sessionName),process.exit(0)}catch(err){console.error(`Error: ${err instanceof Error?err.message:err}`),process.exit(1)}else try{await program2.parseAsync(process.argv)}finally{stopOtelReceiver(),await shutdown().catch(()=>{})}}else try{let _cmdStart=Date.now();if(await program2.parseAsync(process.argv),process.env.GENIE_PROFILE_DB)console.error(`[profile] parseAsync=${Date.now()-_cmdStart}ms`)}finally{let _shutStart=Date.now();if(stopOtelReceiver(),await shutdown().catch(()=>{}),process.env.GENIE_PROFILE_DB)console.error(`[profile] shutdown=${Date.now()-_shutStart}ms`)}