@automagik/genie 4.260504.7 → 4.260504.8
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
|
@@ -2934,11 +2934,14 @@ Genie Serve`),console.log("\u2500".repeat(50)),console.log(` Status: ${runn
|
|
|
2934
2934
|
`;if(rows.length>0)console.log(` \uD83D\uDCE6 Archived ${rows.length} wish-named agent row${rows.length===1?"":"s"} (team="${slug}")`);return rows.length}catch(err){let detail=err instanceof Error?err.message:String(err);return console.warn(` \u26A0\uFE0F Could not archive wish-named agent rows: ${detail}`),0}}function autoKillPane(){let paneId=process.env.TMUX_PANE;if(paneId)setTimeout(()=>{try{let{genieTmuxCmd:genieTmuxCmd2}=(init_tmux_wrapper(),__toCommonJS(exports_tmux_wrapper));execSync13(genieTmuxCmd2(`kill-pane -t '${paneId}'`),{encoding:"utf-8"})}catch{process.exit(0)}},1000);else process.exit(0)}async function resolveNotificationTargets(){let teamName=process.env.GENIE_TEAM;if(!teamName)return{leader:"team-lead"};try{let teamManager=await Promise.resolve().then(() => (init_team_manager(),exports_team_manager)),leader=await teamManager.resolveLeaderName(teamName),config=await teamManager.getTeam(teamName);return{leader,spawner:config?.spawner}}catch{return{leader:teamName}}}async function notifyWaveCompletion(waveResult,wishComplete){console.log(` \uD83C\uDF0A ${waveResult.waveName} complete! All groups done: ${waveResult.waveGroups.join(", ")}`);try{let protocolRouter=await Promise.resolve().then(() => (init_protocol_router(),exports_protocol_router)),repoPath=process.cwd(),{leader,spawner}=await resolveNotificationTargets(),message=wishComplete?`WISH COMPLETE \u2014 all groups done: [${waveResult.waveGroups.join(", ")}]. Run \`genie team done\` to clean up.`:`${waveResult.waveName} complete. All groups done: [${waveResult.waveGroups.join(", ")}]. Run /review or advance to next wave.`,result2=await protocolRouter.sendMessage(repoPath,"cli",leader,message);if(result2&&typeof result2==="object"&&"delivered"in result2&&!result2.delivered)console.warn(` \u26A0\uFE0F Wave-complete notification to ${leader} may not have been delivered.`);else console.log(` Notified ${leader} of wave completion.`);if(spawner&&spawner!==leader&&spawner!=="cli")await protocolRouter.sendMessage(repoPath,"cli",spawner,message).catch(()=>{}),console.log(` Notified spawner (${spawner}) of wave completion.`)}catch{console.warn(" \u26A0\uFE0F Could not notify leader (messaging unavailable).")}}async function doneCommand(ref){try{let{slug,group}=parseRef(ref),result2=await completeGroup(slug,group);if(console.log(`\u2705 Group "${group}" marked as done in wish "${slug}"`),result2.completedAt)console.log(` Completed at: ${formatTimestamp(result2.completedAt)}`);let state=await getState(slug);if(state){let nowReady=Object.entries(state.groups).filter(([,g])=>g.status==="ready"&&g.dependsOn.includes(group)).map(([name])=>name);if(nowReady.length>0)console.log(` Unblocked: ${nowReady.join(", ")}`)}await ensureWorkPushed(slug,group);let wishComplete=await isWishComplete(slug),waveResult=await detectWaveCompletion(slug,group);if(waveResult)await notifyWaveCompletion(waveResult,wishComplete);if(wishComplete)console.log(" \uD83C\uDF89 Wish fully complete \u2014 all groups done."),await autoCleanupTeam(),await archiveWishNamedAgents(slug);autoKillPane()}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`\u274C ${message}`),process.exit(1)}}async function autoInitWishState(slug){let wishPath=resolveWishPath(slug);if(!wishPath)console.error(`\u274C No state found for wish "${slug}" and no WISH.md found in cwd or repo root`),console.error(` Create it first: genie wish <agent> ${slug}`),process.exit(1);let content=await readFile12(wishPath,"utf-8"),groups=parseWishGroups(content);if(groups.length===0)console.error(`\u274C No execution groups found in ${wishPath}`),process.exit(1);let state=await createState(slug,groups);return console.log(`\uD83D\uDCDD Auto-initialized state for wish "${slug}" (${groups.length} groups)`),state}function parseWishLifecycleStatus(content){let patterns2=[/^\|\s*\*\*Status\*\*\s*\|\s*([^|]+?)\s*\|/im,/^\*\*Status:\*\*\s*([A-Za-z][A-Za-z_-]*)/im,/^Status:\s*([A-Za-z][A-Za-z_-]*)/im];for(let pattern of patterns2){let token=content.match(pattern)?.[1]?.trim().match(/^[A-Za-z][A-Za-z_-]*/)?.[0];if(token)return token.toUpperCase()}return null}async function getTerminalWishLifecycleStatus(slug){let wishPath=resolveWishPath(slug);if(!wishPath)return null;let content=await readFile12(wishPath,"utf-8"),status2=parseWishLifecycleStatus(content);if(!status2||!TERMINAL_WISH_STATUSES.has(status2.toLowerCase()))return null;return{status:status2,wishPath}}function printTerminalWishLifecycleStatus(slug,terminal){console.log(`
|
|
2935
2935
|
Wish: ${slug}`),console.log("\u2500".repeat(60)),console.log(` Status: ${terminal.status}`),console.log(` Source: ${terminal.wishPath}`),console.log(""),console.log(" No active execution state initialized for terminal wish status."),console.log("")}async function printWishExecutors(slug){try{let{registry:registry3,executorRegistry,assignmentRegistry}=await loadExecutorInfo(),agents=await registry3.listAgents({team:process.env.GENIE_TEAM}),executorInfoLines=[];for(let agent of agents){if(!agent.currentExecutorId)continue;let executor=await executorRegistry.getExecutor(agent.currentExecutorId);if(!executor||executor.state==="terminated"||executor.state==="done")continue;let assignment=await assignmentRegistry.getActiveAssignment(executor.id);if(assignment?.wishSlug!==slug)continue;let taskLabel=`Group ${assignment.groupNumber??"?"}`,name=agent.customName??agent.role??agent.id.slice(0,12);executorInfoLines.push(` Agent: ${padRight(name,16)} | Executor: ${executor.id.slice(0,12)} (${executor.provider}) | State: ${padRight(executor.state,10)} | Task: ${taskLabel}`)}if(executorInfoLines.length>0){console.log(`
|
|
2936
2936
|
Active Executors:`),console.log("\u2500".repeat(60));for(let line of executorInfoLines)console.log(line)}}catch{}}async function statusCommand(slug){try{let terminal=await getTerminalWishLifecycleStatus(slug);if(terminal){printTerminalWishLifecycleStatus(slug,terminal);return}let state=await getState(slug)??await autoInitWishState(slug);console.log(`
|
|
2937
|
-
Wish: ${state.wish}`),console.log("\u2500".repeat(60));let entries=Object.entries(state.groups),maxNameLen=Math.max(...entries.map(([name])=>name.length),5);console.log(` ${padRight("GROUP",maxNameLen)} STATUS ASSIGNEE STARTED COMPLETED`),console.log(` ${"\u2500".repeat(maxNameLen+62)}`);for(let[name,group]of entries){let icon=STATUS_ICONS[group.status]??"\u2753",status2=padRight(`${icon} ${group.status}`,13),assignee=padRight(group.assignee??"-",13),started=padRight(formatTimestamp(group.startedAt)||"-",14),completed=formatTimestamp(group.completedAt)||"-";console.log(` ${padRight(name,maxNameLen)} ${status2} ${assignee} ${started} ${completed}`)}let total=entries.length,done=entries.filter(([,g])=>g.status==="done").length,inProgress=entries.filter(([,g])=>g.status==="in_progress").length,ready=entries.filter(([,g])=>g.status==="ready").length,blocked=entries.filter(([,g])=>g.status==="blocked").length;console.log(""),console.log(` Progress: ${done}/${total} done | ${inProgress} in progress | ${ready} ready | ${blocked} blocked`),await printWishExecutors(slug),console.log("")}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`\u274C ${message}`),process.exit(1)}}async function resetAction(ref,options){try{if(ref.includes("#")){let{slug,group}=parseRef(ref),result2=await resetGroup(slug,group);if(console.log(`\uD83D\uDD04 Group "${group}" reset to ready in wish "${slug}"`),result2.status==="ready")console.log(" Status: ready (assignee cleared)");return}await resetWishCommand(ref,options?.yes??!1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`\u274C ${message}`),process.exit(1)}}function registerStateCommands(_program){}async function confirmWipe(slug,existing,confirmed){let groupCount=Object.keys(existing.groups).length,inProgress=Object.values(existing.groups).filter((g)=>g.status==="in_progress").length,summary=`Wipe all state for "${slug}" (${groupCount} groups, ${inProgress} in-progress)?`;if(!isInteractive()){if(confirmed)return!0;console.error(`\u274C ${summary}`),console.error(" Refusing to wipe in non-interactive mode. Pass --yes to confirm."),process.exit(2)}let{confirm:confirm3}=await Promise.resolve().then(() => (init_esm14(),exports_esm));return confirm3({message:summary,default:!1})}function printResetState(state){console.log(""),console.log(`Wish: ${state.wish}`),console.log("\u2500".repeat(60));for(let[name,group]of Object.entries(state.groups)){let icon=STATUS_ICONS[group.status]??"\u2753";console.log(` ${name} ${icon} ${group.status}`)}}async function resetWishCommand(slug,confirmed){let wishPath=resolveWishPath(slug);if(!wishPath)throw Error(`No WISH.md found for "${slug}" \u2014 searched cwd and repo root`);let content=await readFile12(wishPath,"utf-8"),groups=parseWishGroups(content);if(groups.length===0)throw Error(`No execution groups found in ${wishPath}`);let existing=await getState(slug);if(existing){if(!await confirmWipe(slug,existing,confirmed)){console.log("Aborted.");return}console.log(`\uD83D\uDDD1\uFE0F Replacing existing state for wish "${slug}"`)}else console.log(`\u2139\uFE0F No existing state for wish "${slug}" \u2014 creating fresh`);let state=await createState(slug,groups);console.log(`\uD83D\uDCDD Recreated state from ${wishPath} (${groups.length} groups)`),printResetState(state)}var STATUS_ICONS,TERMINAL_WISH_STATUSES;var init_state=__esm(()=>{init_interactivity();init_term_format();init_wish_state();init_dispatch();STATUS_ICONS={blocked:"\uD83D\uDD12",ready:"\uD83D\uDFE2",in_progress:"\uD83D\uDD04",done:"\u2705"};TERMINAL_WISH_STATUSES=new Set(["shipped","done","complete","completed","archived"])});var exports_team={};__export(exports_team,{registerTeamNamespace:()=>registerTeamNamespace,handleTeamCreate:()=>handleTeamCreate});import{existsSync as existsSync61}from"fs";import{copyFile as copyFile3,cp,mkdir as mkdir8}from"fs/promises";import{join as join73,resolve as resolve14}from"path";function registerTeamNamespace(program2){let team=program2.command("team").description("Team lifecycle management");team.command("create <name>").description("Create a new team with a git worktree").requiredOption("--repo <path>","Path to the git repository").option("--branch <branch>","Base branch to create from","dev").option("--wish <slug>","Wish slug \u2014 auto-spawns a task leader with wish context").option("--tmux-session <name>","Tmux session to place team window in (default: derived from repo path)").option("--session <name>","Alias for --tmux-session (deprecated)").option("--no-spawn","Create team and copy wish without spawning the leader (useful for testing)").addHelpText("after",`
|
|
2937
|
+
Wish: ${state.wish}`),console.log("\u2500".repeat(60));let entries=Object.entries(state.groups),maxNameLen=Math.max(...entries.map(([name])=>name.length),5);console.log(` ${padRight("GROUP",maxNameLen)} STATUS ASSIGNEE STARTED COMPLETED`),console.log(` ${"\u2500".repeat(maxNameLen+62)}`);for(let[name,group]of entries){let icon=STATUS_ICONS[group.status]??"\u2753",status2=padRight(`${icon} ${group.status}`,13),assignee=padRight(group.assignee??"-",13),started=padRight(formatTimestamp(group.startedAt)||"-",14),completed=formatTimestamp(group.completedAt)||"-";console.log(` ${padRight(name,maxNameLen)} ${status2} ${assignee} ${started} ${completed}`)}let total=entries.length,done=entries.filter(([,g])=>g.status==="done").length,inProgress=entries.filter(([,g])=>g.status==="in_progress").length,ready=entries.filter(([,g])=>g.status==="ready").length,blocked=entries.filter(([,g])=>g.status==="blocked").length;console.log(""),console.log(` Progress: ${done}/${total} done | ${inProgress} in progress | ${ready} ready | ${blocked} blocked`),await printWishExecutors(slug),console.log("")}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`\u274C ${message}`),process.exit(1)}}async function resetAction(ref,options){try{if(ref.includes("#")){let{slug,group}=parseRef(ref),result2=await resetGroup(slug,group);if(console.log(`\uD83D\uDD04 Group "${group}" reset to ready in wish "${slug}"`),result2.status==="ready")console.log(" Status: ready (assignee cleared)");return}await resetWishCommand(ref,options?.yes??!1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`\u274C ${message}`),process.exit(1)}}function registerStateCommands(_program){}async function confirmWipe(slug,existing,confirmed){let groupCount=Object.keys(existing.groups).length,inProgress=Object.values(existing.groups).filter((g)=>g.status==="in_progress").length,summary=`Wipe all state for "${slug}" (${groupCount} groups, ${inProgress} in-progress)?`;if(!isInteractive()){if(confirmed)return!0;console.error(`\u274C ${summary}`),console.error(" Refusing to wipe in non-interactive mode. Pass --yes to confirm."),process.exit(2)}let{confirm:confirm3}=await Promise.resolve().then(() => (init_esm14(),exports_esm));return confirm3({message:summary,default:!1})}function printResetState(state){console.log(""),console.log(`Wish: ${state.wish}`),console.log("\u2500".repeat(60));for(let[name,group]of Object.entries(state.groups)){let icon=STATUS_ICONS[group.status]??"\u2753";console.log(` ${name} ${icon} ${group.status}`)}}async function resetWishCommand(slug,confirmed){let wishPath=resolveWishPath(slug);if(!wishPath)throw Error(`No WISH.md found for "${slug}" \u2014 searched cwd and repo root`);let content=await readFile12(wishPath,"utf-8"),groups=parseWishGroups(content);if(groups.length===0)throw Error(`No execution groups found in ${wishPath}`);let existing=await getState(slug);if(existing){if(!await confirmWipe(slug,existing,confirmed)){console.log("Aborted.");return}console.log(`\uD83D\uDDD1\uFE0F Replacing existing state for wish "${slug}"`)}else console.log(`\u2139\uFE0F No existing state for wish "${slug}" \u2014 creating fresh`);let state=await createState(slug,groups);console.log(`\uD83D\uDCDD Recreated state from ${wishPath} (${groups.length} groups)`),printResetState(state)}var STATUS_ICONS,TERMINAL_WISH_STATUSES;var init_state=__esm(()=>{init_interactivity();init_term_format();init_wish_state();init_dispatch();STATUS_ICONS={blocked:"\uD83D\uDD12",ready:"\uD83D\uDFE2",in_progress:"\uD83D\uDD04",done:"\u2705"};TERMINAL_WISH_STATUSES=new Set(["shipped","done","complete","completed","archived"])});var exports_team={};__export(exports_team,{registerTeamNamespace:()=>registerTeamNamespace,handleTeamRepair:()=>handleTeamRepair,handleTeamCreate:()=>handleTeamCreate});import{existsSync as existsSync61,mkdirSync as mkdirSync29,renameSync as renameSync11,statSync as statSync14}from"fs";import{copyFile as copyFile3,cp,mkdir as mkdir8}from"fs/promises";import{homedir as homedir47}from"os";import{join as join73,resolve as resolve14}from"path";function registerTeamNamespace(program2){let team=program2.command("team").description("Team lifecycle management");team.command("create <name>").description("Create a new team with a git worktree").requiredOption("--repo <path>","Path to the git repository").option("--branch <branch>","Base branch to create from","dev").option("--wish <slug>","Wish slug \u2014 auto-spawns a task leader with wish context").option("--tmux-session <name>","Tmux session to place team window in (default: derived from repo path)").option("--session <name>","Alias for --tmux-session (deprecated)").option("--no-spawn","Create team and copy wish without spawning the leader (useful for testing)").addHelpText("after",`
|
|
2938
2938
|
Examples:
|
|
2939
2939
|
genie team create my-feature --repo . # Create team in current repo
|
|
2940
2940
|
genie team create my-feature --repo . --wish my-feature-slug # Create team with a wish
|
|
2941
|
-
genie team create hotfix --repo . --branch main # Create from main branch`).action(async(name,options)=>{try{let merged={...options,tmuxSession:options.tmuxSession??options.session};await handleTeamCreate(name,merged)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("hire <agent>").description('Add an agent to a team ("council" hires all 10 council members)').option("--team <name>","Team name (auto-detects from leader context if omitted)").action(async(agent,options)=>{try{let teamName=options.team??await autoDetectTeam();if(!teamName)console.error("Error: Could not detect team. Use --team <name> to specify."),process.exit(1);let added=await hireAgent(teamName,agent);if(added.length===0)console.log(`Agent "${agent}" is already a member of "${teamName}".`);else if(agent==="council"){console.log(`Hired ${added.length} council members to "${teamName}":`);for(let name of added)console.log(` + ${name}`)}else console.log(`Hired "${agent}" to team "${teamName}".`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("fire <agent>").description("Remove an agent from a team").option("--team <name>","Team name (auto-detects from leader context if omitted)").action(async(agent,options)=>{try{let teamName=options.team??await autoDetectTeam();if(!teamName)console.error("Error: Could not detect team. Use --team <name> to specify."),process.exit(1);if(await fireAgent(teamName,agent))console.log(`Fired "${agent}" from team "${teamName}".`);else console.error(`Agent "${agent}" is not a member of "${teamName}".`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("ls [name]").alias("list").description("List teams or members of a team").option("--all","Include archived teams").option("--json","Output as JSON").action(async(name,options)=>{try{if(name)await printMembers(name,options.json);else await printTeams(options.json,options.all)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("archive <name>").description("Archive a team (preserves all data, kills members)").action(async(name)=>{try{if(await archiveTeam(name))console.log(`Team "${name}" archived.`);else console.error(`Team "${name}" not found.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("unarchive <name>").description("Restore an archived team").action(async(name)=>{try{if(await unarchiveTeam(name))console.log(`Team "${name}" unarchived.`);else console.error(`Team "${name}" not found.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("disband <name>").description("Disband a team (archives \u2014 preserves data). Use `genie team archive` directly.").action(async(name)=>{try{if(await disbandTeam(name))console.log("Note: disband now archives the team. Use `genie team archive` directly."),console.log(`Team "${name}" disbanded (archived).`);else console.error(`Team "${name}" not found.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("done <name>").description("Mark a team as done and kill all members").action(async(name)=>{try{await setTeamStatus(name,"done"),await killTeamMembers(name),console.log(`Team "${name}" marked as done. All members killed.`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("blocked <name>").description("Mark a team as blocked and kill all members").action(async(name)=>{try{await setTeamStatus(name,"blocked"),await killTeamMembers(name),console.log(`Team "${name}" marked as blocked. All members killed.`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("cleanup").description("Kill tmux windows for done/archived teams").option("--dry-run","Show what would be cleaned without doing it").action(async(options)=>{try{await handleTeamCleanup(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}})
|
|
2941
|
+
genie team create hotfix --repo . --branch main # Create from main branch`).action(async(name,options)=>{try{let merged={...options,tmuxSession:options.tmuxSession??options.session};await handleTeamCreate(name,merged)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("hire <agent>").description('Add an agent to a team ("council" hires all 10 council members)').option("--team <name>","Team name (auto-detects from leader context if omitted)").action(async(agent,options)=>{try{let teamName=options.team??await autoDetectTeam();if(!teamName)console.error("Error: Could not detect team. Use --team <name> to specify."),process.exit(1);let added=await hireAgent(teamName,agent);if(added.length===0)console.log(`Agent "${agent}" is already a member of "${teamName}".`);else if(agent==="council"){console.log(`Hired ${added.length} council members to "${teamName}":`);for(let name of added)console.log(` + ${name}`)}else console.log(`Hired "${agent}" to team "${teamName}".`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("fire <agent>").description("Remove an agent from a team").option("--team <name>","Team name (auto-detects from leader context if omitted)").action(async(agent,options)=>{try{let teamName=options.team??await autoDetectTeam();if(!teamName)console.error("Error: Could not detect team. Use --team <name> to specify."),process.exit(1);if(await fireAgent(teamName,agent))console.log(`Fired "${agent}" from team "${teamName}".`);else console.error(`Agent "${agent}" is not a member of "${teamName}".`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("ls [name]").alias("list").description("List teams or members of a team").option("--all","Include archived teams").option("--json","Output as JSON").action(async(name,options)=>{try{if(name)await printMembers(name,options.json);else await printTeams(options.json,options.all)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("archive <name>").description("Archive a team (preserves all data, kills members)").action(async(name)=>{try{if(await archiveTeam(name))console.log(`Team "${name}" archived.`);else console.error(`Team "${name}" not found.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("unarchive <name>").description("Restore an archived team").action(async(name)=>{try{if(await unarchiveTeam(name))console.log(`Team "${name}" unarchived.`);else console.error(`Team "${name}" not found.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("disband <name>").description("Disband a team (archives \u2014 preserves data). Use `genie team archive` directly.").action(async(name)=>{try{if(await disbandTeam(name))console.log("Note: disband now archives the team. Use `genie team archive` directly."),console.log(`Team "${name}" disbanded (archived).`);else console.error(`Team "${name}" not found.`),process.exit(1)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("done <name>").description("Mark a team as done and kill all members").action(async(name)=>{try{await setTeamStatus(name,"done"),await killTeamMembers(name),console.log(`Team "${name}" marked as done. All members killed.`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("blocked <name>").description("Mark a team as blocked and kill all members").action(async(name)=>{try{await setTeamStatus(name,"blocked"),await killTeamMembers(name),console.log(`Team "${name}" marked as blocked. All members killed.`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("cleanup").description("Kill tmux windows for done/archived teams").option("--dry-run","Show what would be cleaned without doing it").action(async(options)=>{try{await handleTeamCleanup(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}),team.command("repair <name>").description("Archive an orphaned team-config dir to ~/.claude/teams/_archive/").option("--dry-run","Show what would be archived without doing it").addHelpText("after",`
|
|
2942
|
+
This command resolves the doctor's "team_config_orphans" warning by moving
|
|
2943
|
+
~/.claude/teams/<name>/ (which has no corresponding PG team row) into the
|
|
2944
|
+
_archive/ subdirectory. Inboxes are preserved on disk; nothing is deleted.`).action(async(name,options)=>{try{await handleTeamRepair(name,options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}})}async function handleTeamCreate(name,options){let resolvedRepo=resolve14(options.repo);if(options.wish){let wishPath=join73(resolvedRepo,".genie","wishes",options.wish,"WISH.md");if(!existsSync61(wishPath)){let cwdWishDir=join73(process.cwd(),".genie","wishes",options.wish),cwdWishPath=join73(cwdWishDir,"WISH.md");if(existsSync61(cwdWishPath)){let destDir=join73(resolvedRepo,".genie","wishes",options.wish);await mkdir8(destDir,{recursive:!0}),await cp(cwdWishDir,destDir,{recursive:!0}),console.log(`Wish: copied ${options.wish}/WISH.md to repo`)}else console.error(`Error: Wish not found at ${wishPath}`),process.exit(1)}}let config=await createTeam(name,options.repo,options.branch),{findSessionByRepo:findSessionByRepo2}=await Promise.resolve().then(() => (init_agent_directory(),exports_agent_directory)),{resolveRepoSession:resolveRepoSession2}=await Promise.resolve().then(() => (init_tmux(),exports_tmux));if(config.tmuxSessionName=options.tmuxSession??await findSessionByRepo2(resolvedRepo)??await resolveRepoSession2(resolvedRepo),options.wish)config.wishSlug=options.wish;if(await updateTeamConfig(name,config),console.log(`Team "${config.name}" created.`),console.log(` Worktree: ${config.worktreePath}`),console.log(` Branch: ${config.name} (from ${config.baseBranch})`),config.tmuxSessionName)console.log(` Session: ${config.tmuxSessionName}`);if(config.nativeTeamsEnabled)console.log(" Native teams: enabled");if(options.wish&&options.spawn!==!1)await spawnLeaderWithWish(config,options.wish,options.repo,options.tmuxSession)}async function spawnLeaderWithWish(config,slug,repoPath,sessionOverride){let{handleWorkerSpawn:handleWorkerSpawn2}=await Promise.resolve().then(() => (init_agents(),exports_agents)),{findSessionByRepo:findSessionByRepo2}=await Promise.resolve().then(() => (init_agent_directory(),exports_agent_directory)),{resolveRepoSession:resolveRepoSession2}=await Promise.resolve().then(() => (init_tmux(),exports_tmux)),resolvedRepo=resolve14(repoPath),tmuxSession=sessionOverride??config.tmuxSessionName??await findSessionByRepo2(resolvedRepo)??await resolveRepoSession2(resolvedRepo);config.tmuxSessionName=tmuxSession,await updateTeamConfig(config.name,config);let leaderAgent=config.name;config.leader=leaderAgent,config.spawner=process.env.GENIE_AGENT_NAME||"cli",await updateTeamConfig(config.name,config);let sourceWishPath=join73(resolvedRepo,".genie","wishes",slug,"WISH.md");if(!existsSync61(sourceWishPath))console.error(`Error: Wish not found at ${sourceWishPath}`),process.exit(1);let destWishDir=join73(config.worktreePath,".genie","wishes",slug);await mkdir8(destWishDir,{recursive:!0});let destWishPath=join73(destWishDir,"WISH.md");await copyFile3(sourceWishPath,destWishPath),console.log(` Wish: copied ${slug}/WISH.md into worktree`);let standardRoles=["team-lead","engineer","reviewer","qa","fix"];for(let role of standardRoles)await hireAgent(config.name,role);console.log(` Team: hired ${standardRoles.join(", ")}`);let members=standardRoles.filter((r)=>r!=="team-lead").join(", "),spawner=config.spawner||"cli",kickoffPrompt=`Your team is "${config.name}". Repo: ${config.repo}. Branch: ${config.name}. Worktree: ${config.worktreePath}. Wish slug: ${slug}. Your team members are: ${members} (already hired \u2014 genie work will spawn them automatically). Report completion to: ${spawner} (via genie send --to ${spawner}). Read the wish at .genie/wishes/${slug}/WISH.md and execute the full lifecycle autonomously.`,broadcasts=await getRecentBroadcasts(config.name);if(broadcasts.length>0){let broadcastLines=broadcasts.map((b2)=>`[${b2.sender}] ${b2.text}`).join(`
|
|
2942
2945
|
`);kickoffPrompt+=`
|
|
2943
2946
|
|
|
2944
2947
|
Recent team broadcasts for context:
|
|
@@ -2953,7 +2956,7 @@ ${broadcastLines}`}await handleWorkerSpawn2("team-lead",{provider:"claude",team:
|
|
|
2953
2956
|
ORDER BY m.created_at ASC
|
|
2954
2957
|
LIMIT 20
|
|
2955
2958
|
`).map((r)=>({sender:String(r.sender_id),text:String(r.body),timestamp:r.created_at instanceof Date?r.created_at.toISOString():String(r.created_at)}))}catch{return[]}}async function printMembers(name,json2){let members=await listMembers(name);if(members===null)console.error(`Team "${name}" not found.`),process.exit(1);if(json2){console.log(JSON.stringify(members,null,2));return}if(members.length===0){console.log(`Team "${name}" has no members. Hire agents with: genie team hire <agent> --team ${name}`);return}console.log(""),console.log(`MEMBERS of "${name}"`),console.log("-".repeat(60));for(let m of members)console.log(` ${m}`);console.log("")}async function printTeams(json2,includeArchived){let teams=await listTeams(includeArchived);if(json2){console.log(JSON.stringify(teams,null,2));return}if(teams.length===0){console.log("No teams found. Create one with: genie team create <name> --repo <path>");return}console.log(""),console.log("TEAMS"),console.log("-".repeat(60));for(let t of teams)printTeamSummary(t);console.log("")}function printTeamSummary(t){let status2=t.status??"in_progress",dimmed=status2==="archived"?"\x1B[90m":"",reset2=status2==="archived"?"\x1B[0m":"";console.log(` ${dimmed}${t.name} [${status2}]${reset2}`),console.log(` Repo: ${t.repo}`),console.log(` Branch: ${t.name} (from ${t.baseBranch})`),console.log(` Worktree: ${t.worktreePath}`),console.log(` Members: ${t.members.length}`)}async function findTeamWindow(sessionName,teamName){let tmuxLib=await Promise.resolve().then(() => (init_tmux(),exports_tmux));if(!await tmuxLib.findSessionByName(sessionName))return null;try{return(await tmuxLib.listWindows(sessionName)).find((w)=>w.name===teamName||w.name===teamName.replace(/\./g,"_"))??null}catch{return null}}async function cleanupTeamWindow(t,dryRun){if(!t.tmuxSessionName)return null;let match=await findTeamWindow(t.tmuxSessionName,t.name);if(!match)return null;if(dryRun)return` [dry-run] Would kill window "${match.name}" in session "${t.tmuxSessionName}" (team "${t.name}" [${t.status}])`;if(!await(await Promise.resolve().then(() => (init_tmux(),exports_tmux))).killWindow(t.tmuxSessionName,match.name))return null;return` Killed window "${match.name}" in session "${t.tmuxSessionName}" (team "${t.name}")`}async function handleTeamCleanup(options){let cleanable=(await listTeams(!0)).filter((t)=>t.status==="done"||t.status==="archived");if(cleanable.length===0){console.log("No done/archived teams to clean up.");return}let cleaned=0;for(let t of cleanable){let msg=await cleanupTeamWindow(t,options.dryRun===!0);if(msg)console.log(msg),cleaned++}let verb=options.dryRun?"Would clean":"Cleaned";if(cleaned===0)console.log("No tmux windows found for done/archived teams.");else console.log(`
|
|
2956
|
-
${verb} ${cleaned} window${cleaned===1?"":"s"}.`)}var init_team=__esm(()=>{init_team_manager()});var exports_wish_sync={};__export(exports_wish_sync,{syncWishes:()=>syncWishes,parseWishStatus:()=>parseWishStatus,listWishes:()=>listWishes,getWish:()=>getWish});import{existsSync as existsSync62,readFileSync as readFileSync40,readdirSync as readdirSync13}from"fs";import{basename as basename11,join as join74}from"path";function parseWishStatus(content){let match=content.match(/\|\s*\*\*Status\*\*\s*\|\s*([^|]+)/i);if(match)return match[1].trim();return"DRAFT"}function scanRepoWishes(repoPath){let wishesDir=join74(repoPath,".genie","wishes");if(!existsSync62(wishesDir))return[];let results=[],namespace=basename11(repoPath);try{let entries=readdirSync13(wishesDir,{withFileTypes:!0});for(let entry2 of entries){if(!entry2.isDirectory())continue;let wishPath=join74(wishesDir,entry2.name,"WISH.md");if(!existsSync62(wishPath))continue;try{let content=readFileSync40(wishPath,"utf-8");results.push({slug:entry2.name,repo:repoPath,namespace,status:parseWishStatus(content),filePath:wishPath})}catch{}}}catch{}return results}function discoverWishes(repoPath){if(repoPath)return scanRepoWishes(repoPath);if(!existsSync62(REPOS_BASE2))return[];let results=[];try{let entries=readdirSync13(REPOS_BASE2,{withFileTypes:!0});for(let entry2 of entries){if(!entry2.isDirectory())continue;results.push(...scanRepoWishes(join74(REPOS_BASE2,entry2.name)))}}catch{}return results}async function syncWishes(repoPath){let wishes=discoverWishes(repoPath);if(wishes.length===0)return 0;let sql=await getConnection();for(let wish of wishes)await sql`
|
|
2959
|
+
${verb} ${cleaned} window${cleaned===1?"":"s"}.`)}function teamsBaseDir4(){return join73(process.env.CLAUDE_CONFIG_DIR??join73(homedir47(),".claude"),"teams")}async function handleTeamRepair(name,options){let teamsDir=teamsBaseDir4(),orphanPath=join73(teamsDir,name);if(!existsSync61(orphanPath)||!statSync14(orphanPath).isDirectory()){console.log(`No team-config directory at ${orphanPath}. Nothing to repair.`);return}let pgTeam=await getTeam(name).catch(()=>null);if(pgTeam)console.error(`Error: team '${name}' still exists in the registry (status=${pgTeam.status}).`),console.error("Refusing to archive a live team. Use `genie team disband` instead."),process.exit(2);let archiveRoot=join73(teamsDir,"_archive"),ts3=new Date().toISOString().replace(/[:.]/g,"-"),dest=join73(archiveRoot,`${name}-${ts3}`);if(options.dryRun){console.log(`[dry-run] Would archive ${orphanPath} \u2192 ${dest}`);return}mkdirSync29(archiveRoot,{recursive:!0}),renameSync11(orphanPath,dest),console.log(`Archived ${orphanPath} \u2192 ${dest}`)}var init_team=__esm(()=>{init_team_manager()});var exports_wish_sync={};__export(exports_wish_sync,{syncWishes:()=>syncWishes,parseWishStatus:()=>parseWishStatus,listWishes:()=>listWishes,getWish:()=>getWish});import{existsSync as existsSync62,readFileSync as readFileSync40,readdirSync as readdirSync13}from"fs";import{basename as basename11,join as join74}from"path";function parseWishStatus(content){let match=content.match(/\|\s*\*\*Status\*\*\s*\|\s*([^|]+)/i);if(match)return match[1].trim();return"DRAFT"}function scanRepoWishes(repoPath){let wishesDir=join74(repoPath,".genie","wishes");if(!existsSync62(wishesDir))return[];let results=[],namespace=basename11(repoPath);try{let entries=readdirSync13(wishesDir,{withFileTypes:!0});for(let entry2 of entries){if(!entry2.isDirectory())continue;let wishPath=join74(wishesDir,entry2.name,"WISH.md");if(!existsSync62(wishPath))continue;try{let content=readFileSync40(wishPath,"utf-8");results.push({slug:entry2.name,repo:repoPath,namespace,status:parseWishStatus(content),filePath:wishPath})}catch{}}}catch{}return results}function discoverWishes(repoPath){if(repoPath)return scanRepoWishes(repoPath);if(!existsSync62(REPOS_BASE2))return[];let results=[];try{let entries=readdirSync13(REPOS_BASE2,{withFileTypes:!0});for(let entry2 of entries){if(!entry2.isDirectory())continue;results.push(...scanRepoWishes(join74(REPOS_BASE2,entry2.name)))}}catch{}return results}async function syncWishes(repoPath){let wishes=discoverWishes(repoPath);if(wishes.length===0)return 0;let sql=await getConnection();for(let wish of wishes)await sql`
|
|
2957
2960
|
INSERT INTO wishes (slug, repo, namespace, status, file_path)
|
|
2958
2961
|
VALUES (${wish.slug}, ${wish.repo}, ${wish.namespace}, ${wish.status}, ${wish.filePath})
|
|
2959
2962
|
ON CONFLICT (slug, repo) DO UPDATE SET
|
|
@@ -2961,8 +2964,8 @@ ${verb} ${cleaned} window${cleaned===1?"":"s"}.`)}var init_team=__esm(()=>{init_
|
|
|
2961
2964
|
status = EXCLUDED.status,
|
|
2962
2965
|
file_path = EXCLUDED.file_path,
|
|
2963
2966
|
updated_at = now()
|
|
2964
|
-
`;return wishes.length}async function listWishes(filters){let sql=await getConnection();if(filters?.repo&&filters?.status)return sql`SELECT * FROM wishes WHERE repo = ${filters.repo} AND status = ${filters.status} ORDER BY updated_at DESC`;if(filters?.repo)return sql`SELECT * FROM wishes WHERE repo = ${filters.repo} ORDER BY updated_at DESC`;if(filters?.status)return sql`SELECT * FROM wishes WHERE status = ${filters.status} ORDER BY updated_at DESC`;if(filters?.namespace)return sql`SELECT * FROM wishes WHERE namespace = ${filters.namespace} ORDER BY updated_at DESC`;return sql`SELECT * FROM wishes ORDER BY updated_at DESC`}async function getWish(slug,repo){let sql=await getConnection(),rows=repo?await sql`SELECT * FROM wishes WHERE slug = ${slug} AND repo = ${repo} LIMIT 1`:await sql`SELECT * FROM wishes WHERE slug = ${slug} ORDER BY updated_at DESC LIMIT 1`;return rows.length>0?rows[0]:null}var REPOS_BASE2="/home/genie/workspace/repos";var init_wish_sync=__esm(()=>{init_db()});var exports_context_enrichment={};__export(exports_context_enrichment,{enrichContext:()=>enrichContext});import{execSync as execSync14}from"child_process";import{existsSync as existsSync63}from"fs";import{homedir as
|
|
2965
|
-
`))if(line.includes(agentBrain)){let pathMatch=line.match(/\u2192\s*(.+)/);if(pathMatch)return pathMatch[1].trim()}}catch{}let candidates=[join75(process.cwd(),"brain"),join75(
|
|
2967
|
+
`;return wishes.length}async function listWishes(filters){let sql=await getConnection();if(filters?.repo&&filters?.status)return sql`SELECT * FROM wishes WHERE repo = ${filters.repo} AND status = ${filters.status} ORDER BY updated_at DESC`;if(filters?.repo)return sql`SELECT * FROM wishes WHERE repo = ${filters.repo} ORDER BY updated_at DESC`;if(filters?.status)return sql`SELECT * FROM wishes WHERE status = ${filters.status} ORDER BY updated_at DESC`;if(filters?.namespace)return sql`SELECT * FROM wishes WHERE namespace = ${filters.namespace} ORDER BY updated_at DESC`;return sql`SELECT * FROM wishes ORDER BY updated_at DESC`}async function getWish(slug,repo){let sql=await getConnection(),rows=repo?await sql`SELECT * FROM wishes WHERE slug = ${slug} AND repo = ${repo} LIMIT 1`:await sql`SELECT * FROM wishes WHERE slug = ${slug} ORDER BY updated_at DESC LIMIT 1`;return rows.length>0?rows[0]:null}var REPOS_BASE2="/home/genie/workspace/repos";var init_wish_sync=__esm(()=>{init_db()});var exports_context_enrichment={};__export(exports_context_enrichment,{enrichContext:()=>enrichContext});import{execSync as execSync14}from"child_process";import{existsSync as existsSync63}from"fs";import{homedir as homedir48}from"os";import{join as join75}from"path";function detectBrainPath(){let agentBrain=process.env.AGENT_BRAIN;if(agentBrain)try{let vaultsOutput=execSync14("qmd vaults 2>/dev/null",{encoding:"utf-8",timeout:5000});for(let line of vaultsOutput.split(`
|
|
2968
|
+
`))if(line.includes(agentBrain)){let pathMatch=line.match(/\u2192\s*(.+)/);if(pathMatch)return pathMatch[1].trim()}}catch{}let candidates=[join75(process.cwd(),"brain"),join75(homedir48(),"brain")];for(let candidate of candidates)if(existsSync63(candidate))return candidate;return null}function enrichContext(options){let brainPath=options.brainPath??detectBrainPath();if(!brainPath)return"";try{execSync14("which rlmx",{encoding:"utf-8",timeout:5000})}catch{return""}let maxCost=options.maxCost??0.01,maxIterations=options.maxIterations??5,timeout=options.timeout??30000,rlmxQuery=`Given this task: "${options.query}"
|
|
2966
2969
|
|
|
2967
2970
|
Find the most relevant prior knowledge, decisions, and context from the brain vault.
|
|
2968
2971
|
Return ONLY a bulleted list of relevant excerpts with their source file paths.
|
|
@@ -3573,7 +3576,7 @@ $ bun add react-devtools-core@7 -d
|
|
|
3573
3576
|
ORDER BY a.started_at DESC
|
|
3574
3577
|
`).map(mapAssignment)}function mapExecutor(row2){let meta=row2.metadata;return{id:String(row2.id),agentId:String(row2.agent_id),agentName:row2.agent_name?String(row2.agent_name):null,provider:String(row2.provider),transport:String(row2.transport),pid:row2.pid!=null?Number(row2.pid):null,tmuxSession:row2.tmux_session?String(row2.tmux_session):null,tmuxPaneId:row2.tmux_pane_id?String(row2.tmux_pane_id):null,state:String(row2.state),metadata:typeof meta==="string"?JSON.parse(meta):meta??{},startedAt:row2.started_at instanceof Date?row2.started_at.toISOString():String(row2.started_at),role:row2.role?String(row2.role):null,team:row2.team?String(row2.team):null}}function mapAssignment(row2){return{id:String(row2.id),executorId:String(row2.executor_id),taskId:row2.task_id?String(row2.task_id):null,taskTitle:row2.task_title?String(row2.task_title):null,wishSlug:row2.wish_slug?String(row2.wish_slug):null,groupNumber:row2.group_number!=null?Number(row2.group_number):null,startedAt:row2.started_at instanceof Date?row2.started_at.toISOString():String(row2.started_at)}}async function loadAgentWorkStates(){let{listAgentsForRender:listAgentsForRender2}=await Promise.resolve().then(() => (init_agent_registry(),exports_agent_registry)),{shouldResume:shouldResume2,BOOT_PASS_CONCURRENCY_CAP:BOOT_PASS_CONCURRENCY_CAP2}=await Promise.resolve().then(() => (init_should_resume(),exports_should_resume)),agents=await listAgentsForRender2({includeArchived:!1});if(agents.length===0)return new Map;let out=new Map,cursor=0,cap=Math.min(BOOT_PASS_CONCURRENCY_CAP2,Math.max(1,agents.length)),workers=Array.from({length:cap},async()=>{while(cursor<agents.length){let i2=cursor++;if(i2>=agents.length)return;let a=agents[i2];try{let decision=await shouldResume2(a.id),work=reasonToWorkState(decision.reason);if(!work)continue;let name=a.customName??a.role??a.id;mergeWorkState(out,name,work)}catch{}}});return await Promise.all(workers),out}function mergeWorkState(states,name,next){let current=states.get(name);if(!current||WORK_STATE_PRIORITY[next]>WORK_STATE_PRIORITY[current])states.set(name,next)}function reasonToWorkState(reason){if(reason==="ok")return"in_flight";if(reason==="auto_resume_disabled")return"paused";if(reason==="assignment_closed")return"done";if(reason==="no_session_id")return"stuck";return}async function loadAgentObservabilityForTui(){try{return await loadAgentObservabilityMap()}catch{return new Map}}var WORK_STATE_PRIORITY;var init_db2=__esm(()=>{init_agent_observability();WORK_STATE_PRIORITY={in_flight:4,paused:3,stuck:2,done:1}});import{execSync as execSync17}from"child_process";function getProcessCommandByPid(pids){let uniquePids=[...new Set(pids.filter((pid)=>Number.isFinite(pid)&&pid>0))];if(uniquePids.length===0)return new Map;let output=execQuiet(`ps -p ${uniquePids.join(",")} -o pid=,command=`),commands=new Map;for(let line of output.split(`
|
|
3575
3578
|
`)){let match=line.trim().match(/^(\d+)\s+(.+)$/);if(!match)continue;commands.set(Number.parseInt(match[1],10),match[2])}return commands}function execQuiet(cmd){try{return execSync17(cmd,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return""}}function parsePaneLine(parts,processCommandByPid){let[sessionName,winIdxStr,winName,winActive,winPanes,paneIdxStr,paneId,panePidStr,paneCmd,paneTitle,paneSize,sessAttached,sessWindows,sessCreated,paneDead]=parts;return{sessionName,winIdxStr,session:{name:sessionName,attached:sessAttached==="1",windowCount:Number.parseInt(sessWindows,10)||0,created:Number.parseInt(sessCreated,10)||0},window:{sessionName,index:Number.parseInt(winIdxStr,10)||0,name:winName,active:winActive==="1",paneCount:Number.parseInt(winPanes,10)||0},pane:{sessionName,windowIndex:Number.parseInt(winIdxStr,10)||0,paneIndex:Number.parseInt(paneIdxStr,10)||0,paneId,pid:Number.parseInt(panePidStr,10)||0,command:paneCmd,processCommand:processCommandByPid.get(Number.parseInt(panePidStr,10)||0)??"",title:paneTitle,size:paneSize,isDead:paneDead==="1"}}}function getTmuxInventory(){let paneOutput=execQuiet(`${tmuxBin()} -L genie list-panes -a -F '#{session_name}|#{window_index}|#{window_name}|#{window_active}|#{window_panes}|#{pane_index}|#{pane_id}|#{pane_pid}|#{pane_current_command}|#{pane_title}|#{pane_width}x#{pane_height}|#{session_attached}|#{session_windows}|#{session_created}|#{pane_dead}'`);if(!paneOutput)return[];let paneLines=paneOutput.split(`
|
|
3576
|
-
`).filter(Boolean),panePids=paneLines.map((line)=>Number.parseInt(line.split("|")[7]??"",10)).filter((pid)=>Number.isFinite(pid)&&pid>0),processCommandByPid=getProcessCommandByPid(panePids),sessionMap=new Map,windowMap=new Map;for(let line of paneLines){let parts=line.split("|");if(parts.length<15)continue;let parsed=parsePaneLine(parts,processCommandByPid);if(!sessionMap.has(parsed.sessionName))sessionMap.set(parsed.sessionName,{...parsed.session,windows:[]});let winKey=`${parsed.sessionName}:${parsed.winIdxStr}`;if(!windowMap.has(winKey)){let win={...parsed.window,panes:[]};windowMap.set(winKey,win),sessionMap.get(parsed.sessionName)?.windows.push(win)}windowMap.get(winKey)?.panes.push(parsed.pane)}return Array.from(sessionMap.values()).sort((a,b3)=>a.name.localeCompare(b3.name))}function isPidAlive3(pid){try{return process.kill(pid,0),!0}catch{return!1}}function allClaudePanes(sessions2){return sessions2.flatMap((s2)=>s2.windows.flatMap((w2)=>w2.panes)).filter(isClaudeLikePane)}function detectGaps(executors,sessions2){let deadPidExecutors=executors.filter((e)=>e.pid!=null&&!isPidAlive3(e.pid)),executorPaneIds=new Set(executors.map((e)=>e.tmuxPaneId).filter(Boolean)),claudePanes=allClaudePanes(sessions2),orphanPanes=claudePanes.filter((p)=>!executorPaneIds.has(p.paneId)),linkedCount=executors.filter((e)=>e.tmuxPaneId&&!deadPidExecutors.some((d2)=>d2.id===e.id)).length,deadPaneCount=sessions2.flatMap((s2)=>s2.windows.flatMap((w2)=>w2.panes)).filter((p)=>p.isDead).length;return{deadPidExecutors,orphanPanes,linkedCount,totalExecutors:executors.length,totalClaudePanes:claudePanes.length,deadPaneCount}}async function collectDiagnostics(){let{loadExecutors:loadExecutors2,loadAssignments:loadAssignments2,loadAgentWorkStates:loadAgentWorkStates2,loadAgentObservabilityForTui:loadAgentObservabilityForTui2}=await Promise.resolve().then(() => (init_db2(),exports_db2)),sessions2=getTmuxInventory(),executors=[];try{executors=await loadExecutors2()}catch{}let executorIds=executors.map((e)=>e.id),assignments=[];try{assignments=await loadAssignments2(executorIds)}catch{}let workStates=new Map,alertCount=0,observability=new Map;try{workStates=await loadAgentWorkStates2()}catch{}observability=await loadAgentObservabilityForTui2();try{let{listActiveDerivedSignals:listActiveDerivedSignals2}=await Promise.resolve().then(() => (init_derived_signals(),exports_derived_signals));alertCount=(await listActiveDerivedSignals2()).length}catch{}let gaps=detectGaps(executors,sessions2);if(gaps.deadPidExecutors.length>0)try{let{terminateExecutor:terminateExecutor2}=await Promise.resolve().then(() => (init_executor_registry(),exports_executor_registry)),{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),sql=await getConnection2();await Promise.allSettled(gaps.deadPidExecutors.map(async(exec3)=>{if(await terminateExecutor2(exec3.id),exec3.agentId)await sql`UPDATE agents SET current_executor_id = NULL WHERE current_executor_id = ${exec3.id}`}))}catch{}return{sessions:sessions2,executors,assignments,gaps,workStates,observability,alertCount,timestamp:Date.now()}}var init_diagnostics=__esm(()=>{init_ensure_tmux();init_pane_detection()});import{existsSync as existsSync75,readFileSync as readFileSync48,unlinkSync as unlinkSync13}from"fs";import{homedir as homedir49}from"os";import{join as join92}from"path";function getInitialAgentFilePath(){let genieHome6=process.env.GENIE_HOME??join92(homedir49(),".genie");return join92(genieHome6,"tui-initial-agent")}function consumeInitialAgentSignal(){let filePath=getInitialAgentFilePath();if(!existsSync75(filePath))return;try{let agent=readFileSync48(filePath,"utf-8").trim();return unlinkSync13(filePath),agent||void 0}catch{return}}var init_initial_agent=()=>{};function toSessionName(agentName){return agentName.replace(/\//g,"-")}function buildSessionTree(snapshot){let executorByPaneId=new Map;for(let exec3 of snapshot.executors)if(exec3.tmuxPaneId)executorByPaneId.set(exec3.tmuxPaneId,exec3);return snapshot.sessions.filter((s2)=>s2.name!==TUI_SESSION2).map((session)=>sessionToNode(session,executorByPaneId))}function buildWorkspaceTree(input){let{agentNames,sessions:sessions2,executors}=input,workStates=input.workStates??new Map,sessionByName=new Map;for(let s2 of sessions2)if(s2.name!==TUI_SESSION2)sessionByName.set(s2.name,s2);let executorByPaneId=new Map;for(let exec3 of executors)if(exec3.tmuxPaneId)executorByPaneId.set(exec3.tmuxPaneId,exec3);let executorsByAgent=new Map;for(let exec3 of executors){let name=exec3.agentName??exec3.metadata?.agentName;if(typeof name==="string"){let list2=executorsByAgent.get(name)??[];list2.push(exec3),executorsByAgent.set(name,list2)}}let{topLevel,subsByParent}=groupAgentNames(agentNames),nodes=topLevel.map((name)=>{let node=buildAgentNode(name,sessionByName.get(toSessionName(name)),executorsByAgent.get(name)??[],executorByPaneId,workStates.get(name),"canonical");return appendSubAgentNodes(node,subsByParent.get(name),sessionByName,executorsByAgent,executorByPaneId,workStates),node}),claimedSessions=new Set(agentNames.map(toSessionName));for(let[name,session]of sessionByName)if(!claimedSessions.has(name))nodes.push(sessionToNode(session,executorByPaneId));return nodes}function resolvePreferredWindowIndex(session,agentName){let windows=[...session.windows].sort((a,b3)=>a.index-b3.index),hasClaudePane=(window2)=>window2.panes.some(isClaudeLikePane);return(windows.find((window2)=>window2.active&&hasClaudePane(window2))??(agentName?windows.find((window2)=>window2.name===agentName):void 0)??windows.find((window2)=>hasClaudePane(window2))??windows.find((window2)=>window2.active&&window2.index!==0)??windows.find((window2)=>window2.index!==0))?.index}function hasLiveClaudeWindow(session){return session.windows.some((window2)=>window2.panes.some(isClaudeLikePane))}function groupAgentNames(names){let topLevel=[],subsByParent=new Map;for(let name of names){let slashIdx=name.indexOf("/");if(slashIdx===-1)topLevel.push(name);else{let parent=name.slice(0,slashIdx),subs=subsByParent.get(parent)??[];subs.push(name),subsByParent.set(parent,subs)}}return{topLevel,subsByParent}}function appendSubAgentNodes(parent,subs,sessionByName,executorsByAgent,executorByPaneId,workStates){if(!subs)return;for(let subName of subs){let subLabel=subName.slice(subName.indexOf("/")+1),subNode=buildAgentNode(subName,sessionByName.get(toSessionName(subName)),executorsByAgent.get(subName)??[],executorByPaneId,workStates.get(subName),"subagent");subNode.label=subLabel,subNode.depth=1,parent.children.push(subNode)}}function countClaudePanes(session){return session.windows.reduce((sum,w2)=>sum+w2.panes.filter(isClaudeLikePane).length,0)}function buildAgentNode(name,session,agentExecutors,executorByPaneId,workState,kind){let wsState=deriveWsAgentState(session,agentExecutors),attachWindowIndex=session?resolvePreferredWindowIndex(session,name):void 0,children=[];if(session)for(let win of session.windows){if(win.index===0)continue;children.push(windowToNode(session.name,win,executorByPaneId))}let node={id:`agent:${name}`,type:"agent",label:name,depth:0,expanded:children.length>0,children,data:{sessionName:toSessionName(name),windowCount:session?session.windows.length:0,attachWindowIndex,provider:agentExecutors[0]?.provider??null},activePanes:session?countClaudePanes(session):0,agentState:agentExecutors.length>0?deriveExecutorState(agentExecutors):void 0,wsAgentState:wsState,kind};if(workState)node.workState=workState;return node}function deriveWsAgentState(session,agentExecutors){if(!session)return"stopped";if(hasLiveClaudeWindow(session))return"running";for(let exec3 of agentExecutors){if(exec3.state==="error"||exec3.state==="terminated")return"error";if(exec3.state==="spawning")return"spawning"}if(agentExecutors.length===0)return"stopped";return"running"}function deriveExecutorState(execs){for(let e of execs)if(e.state==="working")return"working";for(let e of execs)if(e.state==="permission")return"permission";for(let e of execs)if(e.state==="error"||e.state==="terminated")return"error";return"idle"}function sessionToNode(session,executorMap){let claudePanes=session.windows.reduce((sum,w2)=>sum+w2.panes.filter(isClaudeLikePane).length,0);return{id:`session:${session.name}`,type:"session",label:session.name,depth:0,expanded:!0,children:session.windows.map((w2)=>windowToNode(session.name,w2,executorMap)),data:{attached:session.attached,windowCount:session.windowCount},activePanes:claudePanes,agentState:void 0,wsAgentState:void 0}}function windowToNode(sessionName,window2,executorMap){let activePanes=window2.panes.filter(isClaudeLikePane).length;return{id:`window:${sessionName}:${window2.index}`,type:"window",label:window2.name,depth:1,expanded:!0,children:window2.panes.map((p)=>paneToNode(sessionName,window2.index,p,executorMap)),data:{active:window2.active,paneCount:window2.paneCount},activePanes,agentState:void 0,wsAgentState:void 0}}function paneToNode(sessionName,windowIndex,pane,executorMap){let executor=executorMap.get(pane.paneId),isClaude=isClaudeLikePane(pane);return{id:`pane:${pane.paneId}`,type:"pane",label:derivePaneLabel(pane,executor,isClaude),depth:2,expanded:!1,children:[],data:{command:pane.command,processCommand:pane.processCommand,title:pane.title,isClaudeLike:isClaude,isDead:pane.isDead,pid:pane.pid,size:pane.size,paneId:pane.paneId,sessionName,windowIndex},activePanes:0,agentState:derivePaneState(pane,executor),wsAgentState:void 0}}function derivePaneLabel(pane,executor,isClaude){if(executor?.agentName&&executor?.team)return`${executor.team}/${executor.agentName}`;if(executor?.agentName)return executor.agentName;if(pane.title&&pane.title!==pane.command&&!isDefaultPaneTitle(pane.title))return pane.title;if(isClaude)return"claude";return pane.command}function isDefaultPaneTitle(title){let hostname2=__require("os").hostname();return title===hostname2||title.startsWith(`${hostname2}.`)||title.startsWith("\u2733")}function derivePaneState(pane,executor){if(pane.isDead)return"error";if(!executor)return;let s2=executor.state;if(s2==="working")return"working";if(s2==="idle"||s2==="spawning")return"idle";if(s2==="permission")return"permission";if(s2==="error"||s2==="terminated")return"error";return}function getSessionTarget(node){if(node.type==="agent"){let sessionName=node.data.sessionName,attachWindowIndex=node.data.attachWindowIndex;if(typeof attachWindowIndex==="number")return{sessionName,windowIndex:attachWindowIndex};let firstWindowChild=node.children.find((child)=>child.type==="window");if(firstWindowChild){let parts=firstWindowChild.id.split(":");return{sessionName,windowIndex:Number(parts[2])}}return{sessionName}}if(node.type==="session")return{sessionName:node.label};if(node.type==="window"){let parts=node.id.split(":");return{sessionName:parts[1],windowIndex:Number(parts[2])}}if(node.type==="pane"){let data=node.data;return{sessionName:data.sessionName,windowIndex:data.windowIndex}}return null}var TUI_SESSION2="genie-tui";var init_session_tree=__esm(()=>{init_pane_detection()});function flattenTree(nodes){let result2=[];function walk(node,depth){if(result2.push({node,depth,visible:!0}),node.expanded)for(let child of node.children)walk(child,depth+1)}for(let node of nodes)walk(node,0);return result2}function toggleNode(nodes,id){return nodes.map((node)=>{if(node.id===id)return{...node,expanded:!node.expanded};return{...node,children:toggleNode(node.children,id)}})}function CliPreviewLine({intent,hint=DEFAULT_HINT}){let cli=null,errorMessage=null;try{cli=buildSpawnInvocation(intent).cli}catch(err){errorMessage=err instanceof Error?err.message:String(err)}if(errorMessage!==null)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:`\u26A0 ${errorMessage}`},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.textMuted,children:hint},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:"\u25B6 "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:cli},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},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var DEFAULT_HINT="Enter to run \xB7 Esc to cancel";var init_CliPreviewLine=__esm(()=>{init_spawn_invocation();init_theme2();init_jsx_dev_runtime()});async function defaultLoadAgents(){let{spawn:spawn5}=await import("child_process"),bunPath=process.execPath||"bun",genieBin=process.argv[1],[command,args]=genieBin&&genieBin!=="genie"?[bunPath,[genieBin,"dir","ls","--json"]]:["genie",["dir","ls","--json"]],stdout=await new Promise((resolve21,reject)=>{let child=spawn5(command,args,{stdio:["ignore","pipe","ignore"]}),chunks=[];child.stdout.on("data",(c)=>chunks.push(c)),child.on("error",reject),child.on("close",()=>resolve21(Buffer.concat(chunks).toString("utf-8")))});return JSON.parse(stdout).map((e)=>typeof e?.name==="string"?{name:e.name}:null).filter((e)=>e!==null)}function buildIntent(agentName,target){let intent={kind:"spawn-agent",name:agentName,session:target.session};if(target.window!==void 0&&target.window.length>0)intent.window=target.window;else intent.newWindow=!0;return intent}function applyFilter2(agents,filter){if(filter.length===0)return agents;let needle=filter.toLowerCase();return agents.filter((a)=>a.name.toLowerCase().includes(needle))}function handleControlKey(key,deps){if(key.name==="escape")return deps.onCancel(),!0;if(key.name==="up"&&deps.filteredLength>0)return deps.setSelectedIndex((prev)=>prev<=0?deps.filteredLength-1:prev-1),!0;if(key.name==="down"&&deps.filteredLength>0)return deps.setSelectedIndex((prev)=>prev>=deps.filteredLength-1?0:prev+1),!0;if((key.name==="return"||key.name==="enter")&&deps.highlighted)return deps.onConfirm(buildIntent(deps.highlighted.name,deps.target)),!0;if(key.name==="backspace")return deps.setFilter((prev)=>prev.slice(0,-1)),!0;if(key.name==="up"||key.name==="down"||key.name==="return"||key.name==="enter")return!0;return!1}function appendCharIfPrintable(key,setFilter){let ch=key.sequence??key.name;if(typeof ch==="string"&&ch.length===1&&ch>=" "&&ch!=="\x7F")setFilter((prev)=>prev+ch)}function AgentPicker({target,onConfirm,onCancel,loadAgents=defaultLoadAgents}){let[agents,setAgents]=import_react18.useState(null),[loadError,setLoadError]=import_react18.useState(null),[filter,setFilter]=import_react18.useState(""),[selectedIndex,setSelectedIndex]=import_react18.useState(0);import_react18.useEffect(()=>{let active=!0;return loadAgents().then((list2)=>{if(!active)return;setAgents(list2)}).catch((err)=>{if(!active)return;setLoadError(err instanceof Error?err.message:String(err)),setAgents([])}),()=>{active=!1}},[loadAgents]);let filtered=import_react18.useMemo(()=>agents?applyFilter2(agents,filter):[],[agents,filter]);import_react18.useEffect(()=>{if(filtered.length===0){if(selectedIndex!==0)setSelectedIndex(0);return}if(selectedIndex>=filtered.length)setSelectedIndex(filtered.length-1)},[filtered.length,selectedIndex]);let highlighted=filtered[selectedIndex],previewIntent=highlighted?buildIntent(highlighted.name,target):null,handleKey=import_react18.useCallback((key)=>{if(handleControlKey(key,{onCancel,onConfirm,target,highlighted,filteredLength:filtered.length,setSelectedIndex,setFilter}))return;if(key.ctrl||key.meta)return;appendCharIfPrintable(key,setFilter)},[filtered.length,highlighted,onCancel,onConfirm,target]);useKeyboard(handleKey);let targetLabel=target.window?target.window:target.session,modeHint=target.window?"in window":"new window in session",statusText=agents===null?"Loading agents\u2026":loadError!==null?`Load failed: ${loadError}`:null,selectOptions=filtered.map((agent)=>({name:agent.name,description:"",value:agent.name}));return import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderStyle:"rounded",borderColor:palette.borderActive,backgroundColor:palette.bgRaised,width:"100%",flexDirection:"column",paddingX:1,paddingY:1,gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:"Spawn here"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` \u2014 ${modeHint} `},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:targetLabel},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.textDim,children:"Filter: "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:filter.length>0?filter:" "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:filter.length>0?"":"(type to narrow)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),statusText!==null?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:loadError!==null?palette.error:palette.textDim,children:statusText},void 0,!1,void 0,this)},void 0,!1,void 0,this):filtered.length===0?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"No agents registered"},void 0,!1,void 0,this)},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV("select",{options:selectOptions,selectedIndex,showDescription:!1,focused:!1,height:Math.min(filtered.length,12),selectedBackgroundColor:palette.accentDim,selectedTextColor:palette.accentBright},void 0,!1,void 0,this),previewIntent!==null?import_jsx_dev_runtime2.jsxDEV(CliPreviewLine,{intent:previewIntent},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var import_react18;var init_AgentPicker=__esm(async()=>{init_theme2();init_CliPreviewLine();init_jsx_dev_runtime();await init_react2();import_react18=__toESM(require_react_development(),1)});function ContextMenu({items,onAction,onClose,positionY=0}){let[selectedIndex,setSelectedIndex]=import_react20.useState(0),[inputMode,setInputMode]=import_react20.useState(!1),inputRef=import_react20.useRef(""),selectOptions=items.map((item)=>({name:`${item.label}${item.shortcut?` ${item.shortcut}`:""}`,description:"",value:item.action}));useKeyboard(import_react20.useCallback((key)=>{if(inputMode)return;if(key.name==="escape"){onClose();return}for(let item of items)if(item.shortcut&&key.name===item.shortcut.toLowerCase()){if(item.needsInput)setInputMode(!0),inputRef.current="",setSelectedIndex(items.indexOf(item));else onAction(item.action);return}},[inputMode,items,onAction,onClose]));let handleSelect=import_react20.useCallback((_index,option)=>{let value=option?.value;if(!value)return;if(items.find((i2)=>i2.action===value)?.needsInput){setInputMode(!0),inputRef.current="";return}onAction(value)},[items,onAction]),handleInputChange=import_react20.useCallback((v2)=>{inputRef.current=v2},[]),handleInputSubmit=import_react20.useCallback(()=>{let item=items[selectedIndex],value=inputRef.current.trim();if(item&&value)onAction(item.action,value);setInputMode(!1),inputRef.current=""},[items,selectedIndex,onAction]);if(items.length===0)return onClose(),null;return import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",onMouseDown:()=>onClose(),children:[positionY>0?import_jsx_dev_runtime2.jsxDEV("box",{height:positionY},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderStyle:"rounded",borderColor:palette.borderActive,backgroundColor:palette.bgRaised,width:"100%",height:inputMode?items.length+5:items.length+2,flexDirection:"column",onMouseDown:(e)=>e.stopPropagation?.(),children:[import_jsx_dev_runtime2.jsxDEV("select",{options:selectOptions,selectedIndex,onSelect:handleSelect,onChange:(index)=>setSelectedIndex(index),focused:!inputMode,height:items.length,showDescription:!1,selectedBackgroundColor:palette.accentDim,selectedTextColor:palette.accentBright},void 0,!1,void 0,this),inputMode?import_jsx_dev_runtime2.jsxDEV("box",{paddingX:1,height:3,flexDirection:"column",children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:[items[selectedIndex]?.label??"Input",":"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("input",{onChange:handleInputChange,onSubmit:handleInputSubmit,placeholder:"Type and press Enter...",focused:!0,width:28,backgroundColor:palette.bg,textColor:palette.text,placeholderColor:palette.textMuted},void 0,!1,void 0,this)]},void 0,!0,void 0,this):null]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var import_react20;var init_ContextMenu=__esm(async()=>{init_theme2();init_jsx_dev_runtime();await init_react2();import_react20=__toESM(require_react_development(),1)});function buildRows(sessions2){let rows=[];for(let session of sessions2){if(session.name===TUI_SESSION3)continue;rows.push({kind:"session",sessionName:session.name,label:`${session.name} (new window)`});for(let win of session.windows){let windowLabel=win.name?` ${win.name}`:"";rows.push({kind:"window",sessionName:session.name,windowIndex:win.index,label:` ${session.name}:${win.index}${windowLabel}`})}}return rows}function pickFromRow(row2){if(row2.kind==="session")return{kind:"session",sessionName:row2.sessionName};return{kind:"window",sessionName:row2.sessionName,windowIndex:row2.windowIndex}}function picksEqual(a,b3){if(a.kind==="session"&&b3.kind==="session")return a.sessionName===b3.sessionName;if(a.kind==="window"&&b3.kind==="window")return a.sessionName===b3.sessionName&&a.windowIndex===b3.windowIndex;return!1}function pickExists(pick,sessions2){let session=sessions2.find((s2)=>s2.name===pick.sessionName);if(!session)return!1;if(pick.kind==="session")return!0;return session.windows.some((w2)=>w2.index===pick.windowIndex)}function pickToIntent(agentName,pick){if(!pick)return{kind:"spawn-agent",name:agentName};if(pick.kind==="session")return{kind:"spawn-agent",name:agentName,session:pick.sessionName,newWindow:!0};return{kind:"spawn-agent",name:agentName,window:`${pick.sessionName}:${pick.windowIndex}`}}function pickLabel(pick){if(pick.kind==="session")return pick.sessionName;return`${pick.sessionName}:${pick.windowIndex}`}function SpawnTargetPicker({agentName,sessions:sessions2,onConfirm,onCancel}){let rows=import_react22.useMemo(()=>buildRows(sessions2),[sessions2]),[pick,setPick]=import_react22.useState(()=>rows[0]?pickFromRow(rows[0]):null),[staleError,setStaleError]=import_react22.useState(null);if(pick===null&&rows[0])setPick(pickFromRow(rows[0]));let selectedIndex=import_react22.useMemo(()=>{if(!pick)return-1;return rows.findIndex((r)=>picksEqual(pick,r))},[pick,rows]),movePick=import_react22.useCallback((delta)=>{if(rows.length===0)return;let next=((selectedIndex<0?0:selectedIndex)+delta+rows.length)%rows.length;setPick(pickFromRow(rows[next])),setStaleError(null)},[rows,selectedIndex]),handleEnter=import_react22.useCallback(()=>{if(!pick)return;if(!pickExists(pick,sessions2)){setStaleError(`Target "${pickLabel(pick)}" no longer exists \u2014 pick another.`);return}onConfirm(pickToIntent(agentName,pick))},[pick,sessions2,agentName,onConfirm]);useKeyboard(import_react22.useCallback((key)=>{let n=key.name;if(n==="escape"){onCancel();return}if(n==="enter"||n==="return"){handleEnter();return}if(n==="up"||n==="k")movePick(-1);else if(n==="down"||n==="j")movePick(1)},[onCancel,handleEnter,movePick]));let intent=import_react22.useMemo(()=>pickToIntent(agentName,pick),[agentName,pick]);return import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderStyle:"rounded",borderColor:palette.borderActive,backgroundColor:palette.bgRaised,paddingX:2,paddingY:1,flexDirection:"column",width:"100%",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:`Spawn "${agentName}" into\u2026`},void 0,!1,void 0,this)},void 0,!1,void 0,this),rows.length===0?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"No tmux sessions available. Press Esc to cancel."},void 0,!1,void 0,this)},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV("select",{options:rows.map((row2,i2)=>({name:row2.label,description:"",value:`${row2.kind}:${row2.sessionName}:${row2.kind==="window"?row2.windowIndex:""}:${i2}`})),selectedIndex,showDescription:!1,focused:!1,height:Math.min(rows.length,12),selectedBackgroundColor:palette.accentDim,selectedTextColor:palette.accentBright},void 0,!1,void 0,this),staleError?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:`\u26A0 ${staleError}`},void 0,!1,void 0,this)},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV(CliPreviewLine,{intent},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var import_react22,TUI_SESSION3="genie-tui";var init_SpawnTargetPicker=__esm(async()=>{init_theme2();init_CliPreviewLine();init_jsx_dev_runtime();await init_react2();import_react22=__toESM(require_react_development(),1)});var require_package=__commonJS((exports,module2)=>{module2.exports={name:"systeminformation",version:"5.31.5",description:"Advanced, lightweight system and OS information library",license:"MIT",author:"Sebastian Hildebrandt <hildebrandt@plus-innovations.com> (https://plus-innovations.com)",homepage:"https://systeminformation.io",main:"./lib/index.js",type:"commonjs",bin:{systeminformation:"lib/cli.js"},types:"./lib/index.d.ts",scripts:{test:"node ./test/test.js",testDeno:"deno run -A ./test/test.js"},files:["lib/"],keywords:["system information","sysinfo","monitor","monitoring","os","linux","osx","windows","freebsd","openbsd","netbsd","cpu","cpuload","physical cores","logical cores","processor","cores","threads","socket type","memory","file system","fsstats","diskio","block devices","netstats","network","network interfaces","network connections","network stats","iface","printer","processes","users","internet","battery","docker","docker stats","docker processes","graphics","graphic card","graphic controller","gpu","display","smart","disk layout","usb","audio","bluetooth","wifi","wifinetworks","virtual box","virtualbox","vm","backend","hardware","BIOS","chassis"],repository:{type:"git",url:"git+https://github.com/sebhildebrandt/systeminformation.git"},funding:{type:"Buy me a coffee",url:"https://www.buymeacoffee.com/systeminfo"},os:["darwin","linux","win32","freebsd","openbsd","netbsd","sunos","android"],engines:{node:">=8.0.0"}}});var require_util3=__commonJS((exports)=>{var os4=__require("os"),fs3=__require("fs"),path6=__require("path"),spawn5=__require("child_process").spawn,exec3=__require("child_process").exec,execSync18=__require("child_process").execSync,util4=__require("util"),_platform=process.platform,_linux=_platform==="linux"||_platform==="android",_darwin=_platform==="darwin",_windows=_platform==="win32",_freebsd=_platform==="freebsd",_openbsd=_platform==="openbsd",_netbsd=_platform==="netbsd",_cores=0,codepage="",_smartMonToolsInstalled=null,_rpi_cpuinfo=null,WINDIR=process.env.WINDIR||"C:\\Windows",_psChild,_psResult="",_psCmds=[],_psPersistent=!1,_powerShell="",_psToUTF8="$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ",_psCmdStart="--###START###--",_psError="--ERROR--",_psCmdSeperator="--###ENDCMD###--",_psIdSeperator="--##ID##--",execOptsWin={windowsHide:!0,maxBuffer:104857600,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})},execOptsLinux={maxBuffer:104857600,encoding:"UTF-8",stdio:["pipe","pipe","ignore"]};function toInt(value){let result2=parseInt(value,10);if(isNaN(result2))result2=0;return result2}function splitByNumber(str5){let numberStarted=!1,num="",cpart="";for(let c of str5)if(c>="0"&&c<="9"||numberStarted)numberStarted=!0,num+=c;else cpart+=c;return[cpart,num]}var stringObj=new String,stringReplace=new String().replace,stringToLower=new String().toLowerCase,stringToString=new String().toString,stringSubstr=new String().substr,stringSubstring=new String().substring,stringTrim=new String().trim,stringStartWith=new String().startsWith,mathMin=Math.min;function isFunction(functionToCheck){return functionToCheck&&{}.toString.call(functionToCheck)==="[object Function]"}function unique(obj){let uniques=[],stringify2={};for(let i2=0;i2<obj.length;i2++){let keys=Object.keys(obj[i2]);keys.sort((a,b3)=>{return a-b3});let str5="";for(let j2=0;j2<keys.length;j2++)str5+=JSON.stringify(keys[j2]),str5+=JSON.stringify(obj[i2][keys[j2]]);if(!{}.hasOwnProperty.call(stringify2,str5))uniques.push(obj[i2]),stringify2[str5]=!0}return uniques}function sortByKey(array,keys){return array.sort((a,b3)=>{let x2="",y2="";return keys.forEach((key)=>{x2=x2+a[key],y2=y2+b3[key]}),x2<y2?-1:x2>y2?1:0})}function cores(){if(_cores===0)_cores=os4.cpus().length;return _cores}function getValue(lines,property,separator,trimmed,lineMatch){separator=separator||":",property=property.toLowerCase(),trimmed=trimmed||!1,lineMatch=lineMatch||!1;let result2="";return lines.some((line)=>{let lineLower=line.toLowerCase().replace(/\t/g,"");if(trimmed)lineLower=lineLower.trim();if(lineLower.startsWith(property)&&(lineMatch?lineLower.match(property+separator)||lineLower.match(property+" "+separator):!0)){let parts=trimmed?line.trim().split(separator):line.split(separator);if(parts.length>=2)return parts.shift(),result2=parts.join(separator).trim(),!0}return!1}),result2}function decodeEscapeSequence(str5,base){return base=base||16,str5.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],base))})}function detectSplit(str5){let seperator="",part=0;return str5.split("").forEach((element)=>{if(element>="0"&&element<="9"){if(part===1)part++}else{if(part===0)part++;if(part===1)seperator+=element}}),seperator}function parseTime(t2,pmDesignator){pmDesignator=pmDesignator||"",t2=t2.toUpperCase();let hour=0,min=0,splitter=detectSplit(t2),parts=t2.split(splitter);if(parts.length>=2){if(parts[2])parts[1]+=parts[2];let isPM=parts[1]&&parts[1].toLowerCase().indexOf("pm")>-1||parts[1].toLowerCase().indexOf("p.m.")>-1||parts[1].toLowerCase().indexOf("p. m.")>-1||parts[1].toLowerCase().indexOf("n")>-1||parts[1].toLowerCase().indexOf("ch")>-1||parts[1].toLowerCase().indexOf("\xF6s")>-1||pmDesignator&&parts[1].toLowerCase().indexOf(pmDesignator)>-1;return hour=parseInt(parts[0],10),min=parseInt(parts[1],10),hour=isPM&&hour<12?hour+12:hour,("0"+hour).substr(-2)+":"+("0"+min).substr(-2)}}function parseDateTime(dt,culture){let result2={date:"",time:""};culture=culture||{};let dateFormat=(culture.dateFormat||"").toLowerCase(),pmDesignator=culture.pmDesignator||"",parts=dt.split(" ");if(parts[0]){if(parts[0].indexOf("/")>=0){let dtparts=parts[0].split("/");if(dtparts.length===3)if(dtparts[0].length===4)result2.date=dtparts[0]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[2]).substr(-2);else if(dtparts[2].length===2)if(dateFormat.indexOf("/d/")>-1||dateFormat.indexOf("/dd/")>-1)result2.date="20"+dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2);else result2.date="20"+dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2);else if((dt.toLowerCase().indexOf("pm")>-1||dt.toLowerCase().indexOf("p.m.")>-1||dt.toLowerCase().indexOf("p. m.")>-1||dt.toLowerCase().indexOf("am")>-1||dt.toLowerCase().indexOf("a.m.")>-1||dt.toLowerCase().indexOf("a. m.")>-1||dateFormat.indexOf("/d/")>-1||dateFormat.indexOf("/dd/")>-1)&&dateFormat.indexOf("dd/")!==0)result2.date=dtparts[2]+"-"+("0"+dtparts[0]).substr(-2)+"-"+("0"+dtparts[1]).substr(-2);else result2.date=dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2)}if(parts[0].indexOf(".")>=0){let dtparts=parts[0].split(".");if(dtparts.length===3)if(dateFormat.indexOf(".d.")>-1||dateFormat.indexOf(".dd.")>-1)result2.date=dtparts[2]+"-"+("0"+dtparts[0]).substr(-2)+"-"+("0"+dtparts[1]).substr(-2);else result2.date=dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2)}if(parts[0].indexOf("-")>=0){let dtparts=parts[0].split("-");if(dtparts.length===3)result2.date=dtparts[0]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[2]).substr(-2)}}if(parts[1]){parts.shift();let time=parts.join(" ");result2.time=parseTime(time,pmDesignator)}return result2}function parseHead(head,rights){let space=rights>0,count=1,from=0,to=0,result2=[];for(let i2=0;i2<head.length;i2++)if(count<=rights){if(/\s/.test(head[i2])&&!space)to=i2-1,result2.push({from,to:to+1,cap:head.substring(from,to+1)}),from=to+2,count++;space=head[i2]===" "}else{if(!/\s/.test(head[i2])&&space){if(to=i2-1,from<to)result2.push({from,to,cap:head.substring(from,to)});from=to+1,count++}space=head[i2]===" "}to=5000,result2.push({from,to,cap:head.substring(from,to)});let len=result2.length;for(let i2=0;i2<len;i2++)if(result2[i2].cap.replace(/\s/g,"").length===0){if(i2+1<len)result2[i2].to=result2[i2+1].to,result2[i2].cap=result2[i2].cap+result2[i2+1].cap,result2.splice(i2+1,1),len=len-1}return result2}function findObjectByKey(array,key,value){for(let i2=0;i2<array.length;i2++)if(array[i2][key]===value)return i2;return-1}function getPowershell(){if(_powerShell="powershell.exe",_windows){let defaultPath=`${WINDIR}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;if(fs3.existsSync(defaultPath))_powerShell=defaultPath}}function getVboxmanage(){return _windows?`"${process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"`:"vboxmanage"}function powerShellProceedResults(data){let id="",parts,res="";if(data.indexOf(_psCmdStart)>=0){parts=data.split(_psCmdStart);let parts2=parts[1].split(_psIdSeperator);if(id=parts2[0],parts2.length>1)data=parts2.slice(1).join(_psIdSeperator)}if(data.indexOf(_psCmdSeperator)>=0)parts=data.split(_psCmdSeperator),res=parts[0];let remove=-1;for(let i2=0;i2<_psCmds.length;i2++)if(_psCmds[i2].id===id)remove=i2,_psCmds[i2].callback(res);if(remove>=0)_psCmds.splice(remove,1)}function powerShellStart(){if(!_psChild){if(_psChild=spawn5(_powerShell,["-NoProfile","-NoLogo","-InputFormat","Text","-NoExit","-Command","-"],{stdio:"pipe",windowsHide:!0,maxBuffer:104857600,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})}),_psChild&&_psChild.pid)_psPersistent=!0,_psChild.stdout.on("data",(data)=>{if(_psResult=_psResult+data.toString("utf8"),data.indexOf(_psCmdSeperator)>=0)powerShellProceedResults(_psResult),_psResult=""}),_psChild.stderr.on("data",()=>{powerShellProceedResults(_psResult+_psError)}),_psChild.on("error",()=>{powerShellProceedResults(_psResult+_psError)}),_psChild.on("close",()=>{if(_psChild)_psChild.kill()})}}function powerShellRelease(){try{if(_psChild)_psChild.stdin.write("exit"+os4.EOL),_psChild.stdin.end()}catch{if(_psChild)_psChild.kill()}_psPersistent=!1,_psChild=null}function powerShell(cmd){if(_psPersistent){let id=Math.random().toString(36).substring(2,12);return new Promise((resolve21)=>{process.nextTick(()=>{function callback(data){resolve21(data)}_psCmds.push({id,cmd,callback,start:new Date});try{if(_psChild&&_psChild.pid)_psChild.stdin.write(_psToUTF8+"echo "+_psCmdStart+id+_psIdSeperator+"; "+os4.EOL+cmd+os4.EOL+"echo "+_psCmdSeperator+os4.EOL)}catch{resolve21("")}})})}else{let result2="";return new Promise((resolve21)=>{process.nextTick(()=>{try{let osVersion=os4.release().split(".").map(Number),spanOptions=osVersion[0]<10?["-NoProfile","-NoLogo","-InputFormat","Text","-NoExit","-ExecutionPolicy","Unrestricted","-Command","-"]:["-NoProfile","-NoLogo","-InputFormat","Text","-ExecutionPolicy","Unrestricted","-Command",_psToUTF8+cmd],child=spawn5(_powerShell,spanOptions,{stdio:"pipe",windowsHide:!0,maxBuffer:104857600,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})});if(child&&!child.pid)child.on("error",()=>{resolve21(result2)});if(child&&child.pid){if(child.stdout.on("data",(data)=>{result2=result2+data.toString("utf8")}),child.stderr.on("data",()=>{child.kill(),resolve21(result2)}),child.on("close",()=>{child.kill(),resolve21(result2)}),child.on("error",()=>{child.kill(),resolve21(result2)}),osVersion[0]<10)try{child.stdin.write(_psToUTF8+cmd+os4.EOL),child.stdin.write("exit"+os4.EOL),child.stdin.end()}catch{child.kill(),resolve21(result2)}}else resolve21(result2)}catch{resolve21(result2)}})})}}function execSafe(cmd,args,options){let result2="";return options=options||{},new Promise((resolve21)=>{process.nextTick(()=>{try{let child=spawn5(cmd,args,options);if(child&&!child.pid)child.on("error",()=>{resolve21(result2)});if(child&&child.pid)child.stdout.on("data",(data)=>{result2+=data.toString()}),child.on("close",()=>{child.kill(),resolve21(result2)}),child.on("error",()=>{child.kill(),resolve21(result2)});else resolve21(result2)}catch{resolve21(result2)}})})}function getCodepage(){if(_windows){if(!codepage)try{let parts=execSync18("chcp",execOptsWin).toString().split(`\r
|
|
3579
|
+
`).filter(Boolean),panePids=paneLines.map((line)=>Number.parseInt(line.split("|")[7]??"",10)).filter((pid)=>Number.isFinite(pid)&&pid>0),processCommandByPid=getProcessCommandByPid(panePids),sessionMap=new Map,windowMap=new Map;for(let line of paneLines){let parts=line.split("|");if(parts.length<15)continue;let parsed=parsePaneLine(parts,processCommandByPid);if(!sessionMap.has(parsed.sessionName))sessionMap.set(parsed.sessionName,{...parsed.session,windows:[]});let winKey=`${parsed.sessionName}:${parsed.winIdxStr}`;if(!windowMap.has(winKey)){let win={...parsed.window,panes:[]};windowMap.set(winKey,win),sessionMap.get(parsed.sessionName)?.windows.push(win)}windowMap.get(winKey)?.panes.push(parsed.pane)}return Array.from(sessionMap.values()).sort((a,b3)=>a.name.localeCompare(b3.name))}function isPidAlive3(pid){try{return process.kill(pid,0),!0}catch{return!1}}function allClaudePanes(sessions2){return sessions2.flatMap((s2)=>s2.windows.flatMap((w2)=>w2.panes)).filter(isClaudeLikePane)}function detectGaps(executors,sessions2){let deadPidExecutors=executors.filter((e)=>e.pid!=null&&!isPidAlive3(e.pid)),executorPaneIds=new Set(executors.map((e)=>e.tmuxPaneId).filter(Boolean)),claudePanes=allClaudePanes(sessions2),orphanPanes=claudePanes.filter((p)=>!executorPaneIds.has(p.paneId)),linkedCount=executors.filter((e)=>e.tmuxPaneId&&!deadPidExecutors.some((d2)=>d2.id===e.id)).length,deadPaneCount=sessions2.flatMap((s2)=>s2.windows.flatMap((w2)=>w2.panes)).filter((p)=>p.isDead).length;return{deadPidExecutors,orphanPanes,linkedCount,totalExecutors:executors.length,totalClaudePanes:claudePanes.length,deadPaneCount}}async function collectDiagnostics(){let{loadExecutors:loadExecutors2,loadAssignments:loadAssignments2,loadAgentWorkStates:loadAgentWorkStates2,loadAgentObservabilityForTui:loadAgentObservabilityForTui2}=await Promise.resolve().then(() => (init_db2(),exports_db2)),sessions2=getTmuxInventory(),executors=[];try{executors=await loadExecutors2()}catch{}let executorIds=executors.map((e)=>e.id),assignments=[];try{assignments=await loadAssignments2(executorIds)}catch{}let workStates=new Map,alertCount=0,observability=new Map;try{workStates=await loadAgentWorkStates2()}catch{}observability=await loadAgentObservabilityForTui2();try{let{listActiveDerivedSignals:listActiveDerivedSignals2}=await Promise.resolve().then(() => (init_derived_signals(),exports_derived_signals));alertCount=(await listActiveDerivedSignals2()).length}catch{}let gaps=detectGaps(executors,sessions2);if(gaps.deadPidExecutors.length>0)try{let{terminateExecutor:terminateExecutor2}=await Promise.resolve().then(() => (init_executor_registry(),exports_executor_registry)),{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db)),sql=await getConnection2();await Promise.allSettled(gaps.deadPidExecutors.map(async(exec3)=>{if(await terminateExecutor2(exec3.id),exec3.agentId)await sql`UPDATE agents SET current_executor_id = NULL WHERE current_executor_id = ${exec3.id}`}))}catch{}return{sessions:sessions2,executors,assignments,gaps,workStates,observability,alertCount,timestamp:Date.now()}}var init_diagnostics=__esm(()=>{init_ensure_tmux();init_pane_detection()});import{existsSync as existsSync75,readFileSync as readFileSync48,unlinkSync as unlinkSync13}from"fs";import{homedir as homedir50}from"os";import{join as join92}from"path";function getInitialAgentFilePath(){let genieHome6=process.env.GENIE_HOME??join92(homedir50(),".genie");return join92(genieHome6,"tui-initial-agent")}function consumeInitialAgentSignal(){let filePath=getInitialAgentFilePath();if(!existsSync75(filePath))return;try{let agent=readFileSync48(filePath,"utf-8").trim();return unlinkSync13(filePath),agent||void 0}catch{return}}var init_initial_agent=()=>{};function toSessionName(agentName){return agentName.replace(/\//g,"-")}function buildSessionTree(snapshot){let executorByPaneId=new Map;for(let exec3 of snapshot.executors)if(exec3.tmuxPaneId)executorByPaneId.set(exec3.tmuxPaneId,exec3);return snapshot.sessions.filter((s2)=>s2.name!==TUI_SESSION2).map((session)=>sessionToNode(session,executorByPaneId))}function buildWorkspaceTree(input){let{agentNames,sessions:sessions2,executors}=input,workStates=input.workStates??new Map,sessionByName=new Map;for(let s2 of sessions2)if(s2.name!==TUI_SESSION2)sessionByName.set(s2.name,s2);let executorByPaneId=new Map;for(let exec3 of executors)if(exec3.tmuxPaneId)executorByPaneId.set(exec3.tmuxPaneId,exec3);let executorsByAgent=new Map;for(let exec3 of executors){let name=exec3.agentName??exec3.metadata?.agentName;if(typeof name==="string"){let list2=executorsByAgent.get(name)??[];list2.push(exec3),executorsByAgent.set(name,list2)}}let{topLevel,subsByParent}=groupAgentNames(agentNames),nodes=topLevel.map((name)=>{let node=buildAgentNode(name,sessionByName.get(toSessionName(name)),executorsByAgent.get(name)??[],executorByPaneId,workStates.get(name),"canonical");return appendSubAgentNodes(node,subsByParent.get(name),sessionByName,executorsByAgent,executorByPaneId,workStates),node}),claimedSessions=new Set(agentNames.map(toSessionName));for(let[name,session]of sessionByName)if(!claimedSessions.has(name))nodes.push(sessionToNode(session,executorByPaneId));return nodes}function resolvePreferredWindowIndex(session,agentName){let windows=[...session.windows].sort((a,b3)=>a.index-b3.index),hasClaudePane=(window2)=>window2.panes.some(isClaudeLikePane);return(windows.find((window2)=>window2.active&&hasClaudePane(window2))??(agentName?windows.find((window2)=>window2.name===agentName):void 0)??windows.find((window2)=>hasClaudePane(window2))??windows.find((window2)=>window2.active&&window2.index!==0)??windows.find((window2)=>window2.index!==0))?.index}function hasLiveClaudeWindow(session){return session.windows.some((window2)=>window2.panes.some(isClaudeLikePane))}function groupAgentNames(names){let topLevel=[],subsByParent=new Map;for(let name of names){let slashIdx=name.indexOf("/");if(slashIdx===-1)topLevel.push(name);else{let parent=name.slice(0,slashIdx),subs=subsByParent.get(parent)??[];subs.push(name),subsByParent.set(parent,subs)}}return{topLevel,subsByParent}}function appendSubAgentNodes(parent,subs,sessionByName,executorsByAgent,executorByPaneId,workStates){if(!subs)return;for(let subName of subs){let subLabel=subName.slice(subName.indexOf("/")+1),subNode=buildAgentNode(subName,sessionByName.get(toSessionName(subName)),executorsByAgent.get(subName)??[],executorByPaneId,workStates.get(subName),"subagent");subNode.label=subLabel,subNode.depth=1,parent.children.push(subNode)}}function countClaudePanes(session){return session.windows.reduce((sum,w2)=>sum+w2.panes.filter(isClaudeLikePane).length,0)}function buildAgentNode(name,session,agentExecutors,executorByPaneId,workState,kind){let wsState=deriveWsAgentState(session,agentExecutors),attachWindowIndex=session?resolvePreferredWindowIndex(session,name):void 0,children=[];if(session)for(let win of session.windows){if(win.index===0)continue;children.push(windowToNode(session.name,win,executorByPaneId))}let node={id:`agent:${name}`,type:"agent",label:name,depth:0,expanded:children.length>0,children,data:{sessionName:toSessionName(name),windowCount:session?session.windows.length:0,attachWindowIndex,provider:agentExecutors[0]?.provider??null},activePanes:session?countClaudePanes(session):0,agentState:agentExecutors.length>0?deriveExecutorState(agentExecutors):void 0,wsAgentState:wsState,kind};if(workState)node.workState=workState;return node}function deriveWsAgentState(session,agentExecutors){if(!session)return"stopped";if(hasLiveClaudeWindow(session))return"running";for(let exec3 of agentExecutors){if(exec3.state==="error"||exec3.state==="terminated")return"error";if(exec3.state==="spawning")return"spawning"}if(agentExecutors.length===0)return"stopped";return"running"}function deriveExecutorState(execs){for(let e of execs)if(e.state==="working")return"working";for(let e of execs)if(e.state==="permission")return"permission";for(let e of execs)if(e.state==="error"||e.state==="terminated")return"error";return"idle"}function sessionToNode(session,executorMap){let claudePanes=session.windows.reduce((sum,w2)=>sum+w2.panes.filter(isClaudeLikePane).length,0);return{id:`session:${session.name}`,type:"session",label:session.name,depth:0,expanded:!0,children:session.windows.map((w2)=>windowToNode(session.name,w2,executorMap)),data:{attached:session.attached,windowCount:session.windowCount},activePanes:claudePanes,agentState:void 0,wsAgentState:void 0}}function windowToNode(sessionName,window2,executorMap){let activePanes=window2.panes.filter(isClaudeLikePane).length;return{id:`window:${sessionName}:${window2.index}`,type:"window",label:window2.name,depth:1,expanded:!0,children:window2.panes.map((p)=>paneToNode(sessionName,window2.index,p,executorMap)),data:{active:window2.active,paneCount:window2.paneCount},activePanes,agentState:void 0,wsAgentState:void 0}}function paneToNode(sessionName,windowIndex,pane,executorMap){let executor=executorMap.get(pane.paneId),isClaude=isClaudeLikePane(pane);return{id:`pane:${pane.paneId}`,type:"pane",label:derivePaneLabel(pane,executor,isClaude),depth:2,expanded:!1,children:[],data:{command:pane.command,processCommand:pane.processCommand,title:pane.title,isClaudeLike:isClaude,isDead:pane.isDead,pid:pane.pid,size:pane.size,paneId:pane.paneId,sessionName,windowIndex},activePanes:0,agentState:derivePaneState(pane,executor),wsAgentState:void 0}}function derivePaneLabel(pane,executor,isClaude){if(executor?.agentName&&executor?.team)return`${executor.team}/${executor.agentName}`;if(executor?.agentName)return executor.agentName;if(pane.title&&pane.title!==pane.command&&!isDefaultPaneTitle(pane.title))return pane.title;if(isClaude)return"claude";return pane.command}function isDefaultPaneTitle(title){let hostname2=__require("os").hostname();return title===hostname2||title.startsWith(`${hostname2}.`)||title.startsWith("\u2733")}function derivePaneState(pane,executor){if(pane.isDead)return"error";if(!executor)return;let s2=executor.state;if(s2==="working")return"working";if(s2==="idle"||s2==="spawning")return"idle";if(s2==="permission")return"permission";if(s2==="error"||s2==="terminated")return"error";return}function getSessionTarget(node){if(node.type==="agent"){let sessionName=node.data.sessionName,attachWindowIndex=node.data.attachWindowIndex;if(typeof attachWindowIndex==="number")return{sessionName,windowIndex:attachWindowIndex};let firstWindowChild=node.children.find((child)=>child.type==="window");if(firstWindowChild){let parts=firstWindowChild.id.split(":");return{sessionName,windowIndex:Number(parts[2])}}return{sessionName}}if(node.type==="session")return{sessionName:node.label};if(node.type==="window"){let parts=node.id.split(":");return{sessionName:parts[1],windowIndex:Number(parts[2])}}if(node.type==="pane"){let data=node.data;return{sessionName:data.sessionName,windowIndex:data.windowIndex}}return null}var TUI_SESSION2="genie-tui";var init_session_tree=__esm(()=>{init_pane_detection()});function flattenTree(nodes){let result2=[];function walk(node,depth){if(result2.push({node,depth,visible:!0}),node.expanded)for(let child of node.children)walk(child,depth+1)}for(let node of nodes)walk(node,0);return result2}function toggleNode(nodes,id){return nodes.map((node)=>{if(node.id===id)return{...node,expanded:!node.expanded};return{...node,children:toggleNode(node.children,id)}})}function CliPreviewLine({intent,hint=DEFAULT_HINT}){let cli=null,errorMessage=null;try{cli=buildSpawnInvocation(intent).cli}catch(err){errorMessage=err instanceof Error?err.message:String(err)}if(errorMessage!==null)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:`\u26A0 ${errorMessage}`},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.textMuted,children:hint},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:"\u25B6 "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:cli},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},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var DEFAULT_HINT="Enter to run \xB7 Esc to cancel";var init_CliPreviewLine=__esm(()=>{init_spawn_invocation();init_theme2();init_jsx_dev_runtime()});async function defaultLoadAgents(){let{spawn:spawn5}=await import("child_process"),bunPath=process.execPath||"bun",genieBin=process.argv[1],[command,args]=genieBin&&genieBin!=="genie"?[bunPath,[genieBin,"dir","ls","--json"]]:["genie",["dir","ls","--json"]],stdout=await new Promise((resolve21,reject)=>{let child=spawn5(command,args,{stdio:["ignore","pipe","ignore"]}),chunks=[];child.stdout.on("data",(c)=>chunks.push(c)),child.on("error",reject),child.on("close",()=>resolve21(Buffer.concat(chunks).toString("utf-8")))});return JSON.parse(stdout).map((e)=>typeof e?.name==="string"?{name:e.name}:null).filter((e)=>e!==null)}function buildIntent(agentName,target){let intent={kind:"spawn-agent",name:agentName,session:target.session};if(target.window!==void 0&&target.window.length>0)intent.window=target.window;else intent.newWindow=!0;return intent}function applyFilter2(agents,filter){if(filter.length===0)return agents;let needle=filter.toLowerCase();return agents.filter((a)=>a.name.toLowerCase().includes(needle))}function handleControlKey(key,deps){if(key.name==="escape")return deps.onCancel(),!0;if(key.name==="up"&&deps.filteredLength>0)return deps.setSelectedIndex((prev)=>prev<=0?deps.filteredLength-1:prev-1),!0;if(key.name==="down"&&deps.filteredLength>0)return deps.setSelectedIndex((prev)=>prev>=deps.filteredLength-1?0:prev+1),!0;if((key.name==="return"||key.name==="enter")&&deps.highlighted)return deps.onConfirm(buildIntent(deps.highlighted.name,deps.target)),!0;if(key.name==="backspace")return deps.setFilter((prev)=>prev.slice(0,-1)),!0;if(key.name==="up"||key.name==="down"||key.name==="return"||key.name==="enter")return!0;return!1}function appendCharIfPrintable(key,setFilter){let ch=key.sequence??key.name;if(typeof ch==="string"&&ch.length===1&&ch>=" "&&ch!=="\x7F")setFilter((prev)=>prev+ch)}function AgentPicker({target,onConfirm,onCancel,loadAgents=defaultLoadAgents}){let[agents,setAgents]=import_react18.useState(null),[loadError,setLoadError]=import_react18.useState(null),[filter,setFilter]=import_react18.useState(""),[selectedIndex,setSelectedIndex]=import_react18.useState(0);import_react18.useEffect(()=>{let active=!0;return loadAgents().then((list2)=>{if(!active)return;setAgents(list2)}).catch((err)=>{if(!active)return;setLoadError(err instanceof Error?err.message:String(err)),setAgents([])}),()=>{active=!1}},[loadAgents]);let filtered=import_react18.useMemo(()=>agents?applyFilter2(agents,filter):[],[agents,filter]);import_react18.useEffect(()=>{if(filtered.length===0){if(selectedIndex!==0)setSelectedIndex(0);return}if(selectedIndex>=filtered.length)setSelectedIndex(filtered.length-1)},[filtered.length,selectedIndex]);let highlighted=filtered[selectedIndex],previewIntent=highlighted?buildIntent(highlighted.name,target):null,handleKey=import_react18.useCallback((key)=>{if(handleControlKey(key,{onCancel,onConfirm,target,highlighted,filteredLength:filtered.length,setSelectedIndex,setFilter}))return;if(key.ctrl||key.meta)return;appendCharIfPrintable(key,setFilter)},[filtered.length,highlighted,onCancel,onConfirm,target]);useKeyboard(handleKey);let targetLabel=target.window?target.window:target.session,modeHint=target.window?"in window":"new window in session",statusText=agents===null?"Loading agents\u2026":loadError!==null?`Load failed: ${loadError}`:null,selectOptions=filtered.map((agent)=>({name:agent.name,description:"",value:agent.name}));return import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderStyle:"rounded",borderColor:palette.borderActive,backgroundColor:palette.bgRaised,width:"100%",flexDirection:"column",paddingX:1,paddingY:1,gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:"Spawn here"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:` \u2014 ${modeHint} `},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:targetLabel},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.textDim,children:"Filter: "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:filter.length>0?filter:" "},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:filter.length>0?"":"(type to narrow)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),statusText!==null?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:loadError!==null?palette.error:palette.textDim,children:statusText},void 0,!1,void 0,this)},void 0,!1,void 0,this):filtered.length===0?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:"No agents registered"},void 0,!1,void 0,this)},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV("select",{options:selectOptions,selectedIndex,showDescription:!1,focused:!1,height:Math.min(filtered.length,12),selectedBackgroundColor:palette.accentDim,selectedTextColor:palette.accentBright},void 0,!1,void 0,this),previewIntent!==null?import_jsx_dev_runtime2.jsxDEV(CliPreviewLine,{intent:previewIntent},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var import_react18;var init_AgentPicker=__esm(async()=>{init_theme2();init_CliPreviewLine();init_jsx_dev_runtime();await init_react2();import_react18=__toESM(require_react_development(),1)});function ContextMenu({items,onAction,onClose,positionY=0}){let[selectedIndex,setSelectedIndex]=import_react20.useState(0),[inputMode,setInputMode]=import_react20.useState(!1),inputRef=import_react20.useRef(""),selectOptions=items.map((item)=>({name:`${item.label}${item.shortcut?` ${item.shortcut}`:""}`,description:"",value:item.action}));useKeyboard(import_react20.useCallback((key)=>{if(inputMode)return;if(key.name==="escape"){onClose();return}for(let item of items)if(item.shortcut&&key.name===item.shortcut.toLowerCase()){if(item.needsInput)setInputMode(!0),inputRef.current="",setSelectedIndex(items.indexOf(item));else onAction(item.action);return}},[inputMode,items,onAction,onClose]));let handleSelect=import_react20.useCallback((_index,option)=>{let value=option?.value;if(!value)return;if(items.find((i2)=>i2.action===value)?.needsInput){setInputMode(!0),inputRef.current="";return}onAction(value)},[items,onAction]),handleInputChange=import_react20.useCallback((v2)=>{inputRef.current=v2},[]),handleInputSubmit=import_react20.useCallback(()=>{let item=items[selectedIndex],value=inputRef.current.trim();if(item&&value)onAction(item.action,value);setInputMode(!1),inputRef.current=""},[items,selectedIndex,onAction]);if(items.length===0)return onClose(),null;return import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",onMouseDown:()=>onClose(),children:[positionY>0?import_jsx_dev_runtime2.jsxDEV("box",{height:positionY},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderStyle:"rounded",borderColor:palette.borderActive,backgroundColor:palette.bgRaised,width:"100%",height:inputMode?items.length+5:items.length+2,flexDirection:"column",onMouseDown:(e)=>e.stopPropagation?.(),children:[import_jsx_dev_runtime2.jsxDEV("select",{options:selectOptions,selectedIndex,onSelect:handleSelect,onChange:(index)=>setSelectedIndex(index),focused:!inputMode,height:items.length,showDescription:!1,selectedBackgroundColor:palette.accentDim,selectedTextColor:palette.accentBright},void 0,!1,void 0,this),inputMode?import_jsx_dev_runtime2.jsxDEV("box",{paddingX:1,height:3,flexDirection:"column",children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:[items[selectedIndex]?.label??"Input",":"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("input",{onChange:handleInputChange,onSubmit:handleInputSubmit,placeholder:"Type and press Enter...",focused:!0,width:28,backgroundColor:palette.bg,textColor:palette.text,placeholderColor:palette.textMuted},void 0,!1,void 0,this)]},void 0,!0,void 0,this):null]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var import_react20;var init_ContextMenu=__esm(async()=>{init_theme2();init_jsx_dev_runtime();await init_react2();import_react20=__toESM(require_react_development(),1)});function buildRows(sessions2){let rows=[];for(let session of sessions2){if(session.name===TUI_SESSION3)continue;rows.push({kind:"session",sessionName:session.name,label:`${session.name} (new window)`});for(let win of session.windows){let windowLabel=win.name?` ${win.name}`:"";rows.push({kind:"window",sessionName:session.name,windowIndex:win.index,label:` ${session.name}:${win.index}${windowLabel}`})}}return rows}function pickFromRow(row2){if(row2.kind==="session")return{kind:"session",sessionName:row2.sessionName};return{kind:"window",sessionName:row2.sessionName,windowIndex:row2.windowIndex}}function picksEqual(a,b3){if(a.kind==="session"&&b3.kind==="session")return a.sessionName===b3.sessionName;if(a.kind==="window"&&b3.kind==="window")return a.sessionName===b3.sessionName&&a.windowIndex===b3.windowIndex;return!1}function pickExists(pick,sessions2){let session=sessions2.find((s2)=>s2.name===pick.sessionName);if(!session)return!1;if(pick.kind==="session")return!0;return session.windows.some((w2)=>w2.index===pick.windowIndex)}function pickToIntent(agentName,pick){if(!pick)return{kind:"spawn-agent",name:agentName};if(pick.kind==="session")return{kind:"spawn-agent",name:agentName,session:pick.sessionName,newWindow:!0};return{kind:"spawn-agent",name:agentName,window:`${pick.sessionName}:${pick.windowIndex}`}}function pickLabel(pick){if(pick.kind==="session")return pick.sessionName;return`${pick.sessionName}:${pick.windowIndex}`}function SpawnTargetPicker({agentName,sessions:sessions2,onConfirm,onCancel}){let rows=import_react22.useMemo(()=>buildRows(sessions2),[sessions2]),[pick,setPick]=import_react22.useState(()=>rows[0]?pickFromRow(rows[0]):null),[staleError,setStaleError]=import_react22.useState(null);if(pick===null&&rows[0])setPick(pickFromRow(rows[0]));let selectedIndex=import_react22.useMemo(()=>{if(!pick)return-1;return rows.findIndex((r)=>picksEqual(pick,r))},[pick,rows]),movePick=import_react22.useCallback((delta)=>{if(rows.length===0)return;let next=((selectedIndex<0?0:selectedIndex)+delta+rows.length)%rows.length;setPick(pickFromRow(rows[next])),setStaleError(null)},[rows,selectedIndex]),handleEnter=import_react22.useCallback(()=>{if(!pick)return;if(!pickExists(pick,sessions2)){setStaleError(`Target "${pickLabel(pick)}" no longer exists \u2014 pick another.`);return}onConfirm(pickToIntent(agentName,pick))},[pick,sessions2,agentName,onConfirm]);useKeyboard(import_react22.useCallback((key)=>{let n=key.name;if(n==="escape"){onCancel();return}if(n==="enter"||n==="return"){handleEnter();return}if(n==="up"||n==="k")movePick(-1);else if(n==="down"||n==="j")movePick(1)},[onCancel,handleEnter,movePick]));let intent=import_react22.useMemo(()=>pickToIntent(agentName,pick),[agentName,pick]);return import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderStyle:"rounded",borderColor:palette.borderActive,backgroundColor:palette.bgRaised,paddingX:2,paddingY:1,flexDirection:"column",width:"100%",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:`Spawn "${agentName}" into\u2026`},void 0,!1,void 0,this)},void 0,!1,void 0,this),rows.length===0?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"No tmux sessions available. Press Esc to cancel."},void 0,!1,void 0,this)},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV("select",{options:rows.map((row2,i2)=>({name:row2.label,description:"",value:`${row2.kind}:${row2.sessionName}:${row2.kind==="window"?row2.windowIndex:""}:${i2}`})),selectedIndex,showDescription:!1,focused:!1,height:Math.min(rows.length,12),selectedBackgroundColor:palette.accentDim,selectedTextColor:palette.accentBright},void 0,!1,void 0,this),staleError?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:`\u26A0 ${staleError}`},void 0,!1,void 0,this)},void 0,!1,void 0,this):null,import_jsx_dev_runtime2.jsxDEV(CliPreviewLine,{intent},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var import_react22,TUI_SESSION3="genie-tui";var init_SpawnTargetPicker=__esm(async()=>{init_theme2();init_CliPreviewLine();init_jsx_dev_runtime();await init_react2();import_react22=__toESM(require_react_development(),1)});var require_package=__commonJS((exports,module2)=>{module2.exports={name:"systeminformation",version:"5.31.5",description:"Advanced, lightweight system and OS information library",license:"MIT",author:"Sebastian Hildebrandt <hildebrandt@plus-innovations.com> (https://plus-innovations.com)",homepage:"https://systeminformation.io",main:"./lib/index.js",type:"commonjs",bin:{systeminformation:"lib/cli.js"},types:"./lib/index.d.ts",scripts:{test:"node ./test/test.js",testDeno:"deno run -A ./test/test.js"},files:["lib/"],keywords:["system information","sysinfo","monitor","monitoring","os","linux","osx","windows","freebsd","openbsd","netbsd","cpu","cpuload","physical cores","logical cores","processor","cores","threads","socket type","memory","file system","fsstats","diskio","block devices","netstats","network","network interfaces","network connections","network stats","iface","printer","processes","users","internet","battery","docker","docker stats","docker processes","graphics","graphic card","graphic controller","gpu","display","smart","disk layout","usb","audio","bluetooth","wifi","wifinetworks","virtual box","virtualbox","vm","backend","hardware","BIOS","chassis"],repository:{type:"git",url:"git+https://github.com/sebhildebrandt/systeminformation.git"},funding:{type:"Buy me a coffee",url:"https://www.buymeacoffee.com/systeminfo"},os:["darwin","linux","win32","freebsd","openbsd","netbsd","sunos","android"],engines:{node:">=8.0.0"}}});var require_util3=__commonJS((exports)=>{var os4=__require("os"),fs3=__require("fs"),path6=__require("path"),spawn5=__require("child_process").spawn,exec3=__require("child_process").exec,execSync18=__require("child_process").execSync,util4=__require("util"),_platform=process.platform,_linux=_platform==="linux"||_platform==="android",_darwin=_platform==="darwin",_windows=_platform==="win32",_freebsd=_platform==="freebsd",_openbsd=_platform==="openbsd",_netbsd=_platform==="netbsd",_cores=0,codepage="",_smartMonToolsInstalled=null,_rpi_cpuinfo=null,WINDIR=process.env.WINDIR||"C:\\Windows",_psChild,_psResult="",_psCmds=[],_psPersistent=!1,_powerShell="",_psToUTF8="$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ",_psCmdStart="--###START###--",_psError="--ERROR--",_psCmdSeperator="--###ENDCMD###--",_psIdSeperator="--##ID##--",execOptsWin={windowsHide:!0,maxBuffer:104857600,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})},execOptsLinux={maxBuffer:104857600,encoding:"UTF-8",stdio:["pipe","pipe","ignore"]};function toInt(value){let result2=parseInt(value,10);if(isNaN(result2))result2=0;return result2}function splitByNumber(str5){let numberStarted=!1,num="",cpart="";for(let c of str5)if(c>="0"&&c<="9"||numberStarted)numberStarted=!0,num+=c;else cpart+=c;return[cpart,num]}var stringObj=new String,stringReplace=new String().replace,stringToLower=new String().toLowerCase,stringToString=new String().toString,stringSubstr=new String().substr,stringSubstring=new String().substring,stringTrim=new String().trim,stringStartWith=new String().startsWith,mathMin=Math.min;function isFunction(functionToCheck){return functionToCheck&&{}.toString.call(functionToCheck)==="[object Function]"}function unique(obj){let uniques=[],stringify2={};for(let i2=0;i2<obj.length;i2++){let keys=Object.keys(obj[i2]);keys.sort((a,b3)=>{return a-b3});let str5="";for(let j2=0;j2<keys.length;j2++)str5+=JSON.stringify(keys[j2]),str5+=JSON.stringify(obj[i2][keys[j2]]);if(!{}.hasOwnProperty.call(stringify2,str5))uniques.push(obj[i2]),stringify2[str5]=!0}return uniques}function sortByKey(array,keys){return array.sort((a,b3)=>{let x2="",y2="";return keys.forEach((key)=>{x2=x2+a[key],y2=y2+b3[key]}),x2<y2?-1:x2>y2?1:0})}function cores(){if(_cores===0)_cores=os4.cpus().length;return _cores}function getValue(lines,property,separator,trimmed,lineMatch){separator=separator||":",property=property.toLowerCase(),trimmed=trimmed||!1,lineMatch=lineMatch||!1;let result2="";return lines.some((line)=>{let lineLower=line.toLowerCase().replace(/\t/g,"");if(trimmed)lineLower=lineLower.trim();if(lineLower.startsWith(property)&&(lineMatch?lineLower.match(property+separator)||lineLower.match(property+" "+separator):!0)){let parts=trimmed?line.trim().split(separator):line.split(separator);if(parts.length>=2)return parts.shift(),result2=parts.join(separator).trim(),!0}return!1}),result2}function decodeEscapeSequence(str5,base){return base=base||16,str5.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],base))})}function detectSplit(str5){let seperator="",part=0;return str5.split("").forEach((element)=>{if(element>="0"&&element<="9"){if(part===1)part++}else{if(part===0)part++;if(part===1)seperator+=element}}),seperator}function parseTime(t2,pmDesignator){pmDesignator=pmDesignator||"",t2=t2.toUpperCase();let hour=0,min=0,splitter=detectSplit(t2),parts=t2.split(splitter);if(parts.length>=2){if(parts[2])parts[1]+=parts[2];let isPM=parts[1]&&parts[1].toLowerCase().indexOf("pm")>-1||parts[1].toLowerCase().indexOf("p.m.")>-1||parts[1].toLowerCase().indexOf("p. m.")>-1||parts[1].toLowerCase().indexOf("n")>-1||parts[1].toLowerCase().indexOf("ch")>-1||parts[1].toLowerCase().indexOf("\xF6s")>-1||pmDesignator&&parts[1].toLowerCase().indexOf(pmDesignator)>-1;return hour=parseInt(parts[0],10),min=parseInt(parts[1],10),hour=isPM&&hour<12?hour+12:hour,("0"+hour).substr(-2)+":"+("0"+min).substr(-2)}}function parseDateTime(dt,culture){let result2={date:"",time:""};culture=culture||{};let dateFormat=(culture.dateFormat||"").toLowerCase(),pmDesignator=culture.pmDesignator||"",parts=dt.split(" ");if(parts[0]){if(parts[0].indexOf("/")>=0){let dtparts=parts[0].split("/");if(dtparts.length===3)if(dtparts[0].length===4)result2.date=dtparts[0]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[2]).substr(-2);else if(dtparts[2].length===2)if(dateFormat.indexOf("/d/")>-1||dateFormat.indexOf("/dd/")>-1)result2.date="20"+dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2);else result2.date="20"+dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2);else if((dt.toLowerCase().indexOf("pm")>-1||dt.toLowerCase().indexOf("p.m.")>-1||dt.toLowerCase().indexOf("p. m.")>-1||dt.toLowerCase().indexOf("am")>-1||dt.toLowerCase().indexOf("a.m.")>-1||dt.toLowerCase().indexOf("a. m.")>-1||dateFormat.indexOf("/d/")>-1||dateFormat.indexOf("/dd/")>-1)&&dateFormat.indexOf("dd/")!==0)result2.date=dtparts[2]+"-"+("0"+dtparts[0]).substr(-2)+"-"+("0"+dtparts[1]).substr(-2);else result2.date=dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2)}if(parts[0].indexOf(".")>=0){let dtparts=parts[0].split(".");if(dtparts.length===3)if(dateFormat.indexOf(".d.")>-1||dateFormat.indexOf(".dd.")>-1)result2.date=dtparts[2]+"-"+("0"+dtparts[0]).substr(-2)+"-"+("0"+dtparts[1]).substr(-2);else result2.date=dtparts[2]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[0]).substr(-2)}if(parts[0].indexOf("-")>=0){let dtparts=parts[0].split("-");if(dtparts.length===3)result2.date=dtparts[0]+"-"+("0"+dtparts[1]).substr(-2)+"-"+("0"+dtparts[2]).substr(-2)}}if(parts[1]){parts.shift();let time=parts.join(" ");result2.time=parseTime(time,pmDesignator)}return result2}function parseHead(head,rights){let space=rights>0,count=1,from=0,to=0,result2=[];for(let i2=0;i2<head.length;i2++)if(count<=rights){if(/\s/.test(head[i2])&&!space)to=i2-1,result2.push({from,to:to+1,cap:head.substring(from,to+1)}),from=to+2,count++;space=head[i2]===" "}else{if(!/\s/.test(head[i2])&&space){if(to=i2-1,from<to)result2.push({from,to,cap:head.substring(from,to)});from=to+1,count++}space=head[i2]===" "}to=5000,result2.push({from,to,cap:head.substring(from,to)});let len=result2.length;for(let i2=0;i2<len;i2++)if(result2[i2].cap.replace(/\s/g,"").length===0){if(i2+1<len)result2[i2].to=result2[i2+1].to,result2[i2].cap=result2[i2].cap+result2[i2+1].cap,result2.splice(i2+1,1),len=len-1}return result2}function findObjectByKey(array,key,value){for(let i2=0;i2<array.length;i2++)if(array[i2][key]===value)return i2;return-1}function getPowershell(){if(_powerShell="powershell.exe",_windows){let defaultPath=`${WINDIR}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;if(fs3.existsSync(defaultPath))_powerShell=defaultPath}}function getVboxmanage(){return _windows?`"${process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"`:"vboxmanage"}function powerShellProceedResults(data){let id="",parts,res="";if(data.indexOf(_psCmdStart)>=0){parts=data.split(_psCmdStart);let parts2=parts[1].split(_psIdSeperator);if(id=parts2[0],parts2.length>1)data=parts2.slice(1).join(_psIdSeperator)}if(data.indexOf(_psCmdSeperator)>=0)parts=data.split(_psCmdSeperator),res=parts[0];let remove=-1;for(let i2=0;i2<_psCmds.length;i2++)if(_psCmds[i2].id===id)remove=i2,_psCmds[i2].callback(res);if(remove>=0)_psCmds.splice(remove,1)}function powerShellStart(){if(!_psChild){if(_psChild=spawn5(_powerShell,["-NoProfile","-NoLogo","-InputFormat","Text","-NoExit","-Command","-"],{stdio:"pipe",windowsHide:!0,maxBuffer:104857600,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})}),_psChild&&_psChild.pid)_psPersistent=!0,_psChild.stdout.on("data",(data)=>{if(_psResult=_psResult+data.toString("utf8"),data.indexOf(_psCmdSeperator)>=0)powerShellProceedResults(_psResult),_psResult=""}),_psChild.stderr.on("data",()=>{powerShellProceedResults(_psResult+_psError)}),_psChild.on("error",()=>{powerShellProceedResults(_psResult+_psError)}),_psChild.on("close",()=>{if(_psChild)_psChild.kill()})}}function powerShellRelease(){try{if(_psChild)_psChild.stdin.write("exit"+os4.EOL),_psChild.stdin.end()}catch{if(_psChild)_psChild.kill()}_psPersistent=!1,_psChild=null}function powerShell(cmd){if(_psPersistent){let id=Math.random().toString(36).substring(2,12);return new Promise((resolve21)=>{process.nextTick(()=>{function callback(data){resolve21(data)}_psCmds.push({id,cmd,callback,start:new Date});try{if(_psChild&&_psChild.pid)_psChild.stdin.write(_psToUTF8+"echo "+_psCmdStart+id+_psIdSeperator+"; "+os4.EOL+cmd+os4.EOL+"echo "+_psCmdSeperator+os4.EOL)}catch{resolve21("")}})})}else{let result2="";return new Promise((resolve21)=>{process.nextTick(()=>{try{let osVersion=os4.release().split(".").map(Number),spanOptions=osVersion[0]<10?["-NoProfile","-NoLogo","-InputFormat","Text","-NoExit","-ExecutionPolicy","Unrestricted","-Command","-"]:["-NoProfile","-NoLogo","-InputFormat","Text","-ExecutionPolicy","Unrestricted","-Command",_psToUTF8+cmd],child=spawn5(_powerShell,spanOptions,{stdio:"pipe",windowsHide:!0,maxBuffer:104857600,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})});if(child&&!child.pid)child.on("error",()=>{resolve21(result2)});if(child&&child.pid){if(child.stdout.on("data",(data)=>{result2=result2+data.toString("utf8")}),child.stderr.on("data",()=>{child.kill(),resolve21(result2)}),child.on("close",()=>{child.kill(),resolve21(result2)}),child.on("error",()=>{child.kill(),resolve21(result2)}),osVersion[0]<10)try{child.stdin.write(_psToUTF8+cmd+os4.EOL),child.stdin.write("exit"+os4.EOL),child.stdin.end()}catch{child.kill(),resolve21(result2)}}else resolve21(result2)}catch{resolve21(result2)}})})}}function execSafe(cmd,args,options){let result2="";return options=options||{},new Promise((resolve21)=>{process.nextTick(()=>{try{let child=spawn5(cmd,args,options);if(child&&!child.pid)child.on("error",()=>{resolve21(result2)});if(child&&child.pid)child.stdout.on("data",(data)=>{result2+=data.toString()}),child.on("close",()=>{child.kill(),resolve21(result2)}),child.on("error",()=>{child.kill(),resolve21(result2)});else resolve21(result2)}catch{resolve21(result2)}})})}function getCodepage(){if(_windows){if(!codepage)try{let parts=execSync18("chcp",execOptsWin).toString().split(`\r
|
|
3577
3580
|
`)[0].split(":");codepage=parts.length>1?parts[1].replace(".","").trim():""}catch{codepage="437"}return codepage}if(_linux||_darwin||_freebsd||_openbsd||_netbsd){if(!codepage)try{let parts=execSync18("echo $LANG",execOptsLinux).toString().split(`\r
|
|
3578
3581
|
`)[0].split(".");if(codepage=parts.length>1?parts[1].trim():"",!codepage)codepage="UTF-8"}catch{codepage="UTF-8"}return codepage}}function smartMonToolsInstalled(){if(_smartMonToolsInstalled!==null)return _smartMonToolsInstalled;if(_smartMonToolsInstalled=!1,_windows)try{let pathArray=execSync18("WHERE smartctl 2>nul",execOptsWin).toString().split(`\r
|
|
3579
3582
|
`);if(pathArray&&pathArray.length)_smartMonToolsInstalled=pathArray[0].indexOf(":\\")>=0;else _smartMonToolsInstalled=!1}catch{_smartMonToolsInstalled=!1}if(_linux||_darwin||_freebsd||_openbsd||_netbsd)try{_smartMonToolsInstalled=execSync18("which smartctl 2>/dev/null",execOptsLinux).toString().split(`\r
|
|
@@ -3958,9 +3961,9 @@ Bus `);for(let i2=1;i2<parts.length;i2++){let usb2=parseLinuxUsb(parts[i2]);resu
|
|
|
3958
3961
|
`);if(util4.getValue(lines,"class",":",!0).toLowerCase().indexOf("audio")>=0){let audio2=parseLinuxAudioPciMM(lines,audioPCI);result2.push(audio2)}})}if(callback)callback(result2);resolve21(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);resolve21(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(`
|
|
3959
3962
|
`);if(util4.getValue(lines,"name",":"))result2.push(parseWindowsAudio(lines))});if(callback)callback(result2);resolve21(result2)});if(_sunos)resolve21(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,execSync18=__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((resolve21)=>{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(`
|
|
3960
3963
|
`);result2.push(parseLinuxBluetoothInfo(infoFile,macAddr1,macAddr2))}});try{let hdicon=execSync18("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);resolve21(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);resolve21(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(`
|
|
3961
|
-
`),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);resolve21(result2)});if(_freebsd||_netbsd||_openbsd||_sunos)resolve21(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((resolve21)=>{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);resolve21(data)})})})}function getDynamicData(srv,iface,callback){if(util4.isFunction(iface))callback=iface,iface="";if(util4.isFunction(srv))callback=srv,srv="";return new Promise((resolve21)=>{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);resolve21(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((resolve21)=>{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);resolve21(data)})})})})}function get3(valueObject,callback){return new Promise((resolve21)=>{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);resolve21(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>90)return palette.error;if(percent>70)return palette.warning;return palette.accent}function SystemStatsView({stats:stats2}){if(!stats2)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgRaised,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.accent,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}=stats2,hotStr=cpu.hotCores.map((c)=>`#${c.id} ${c.load}%`).join(" ");return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgRaised,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.accent,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)}function SystemStats(){let[stats2,setStats]=import_react23.useState(null),mountedRef=import_react23.useRef(!0);return import_react23.useEffect(()=>{mountedRef.current=!0;async function refresh(){try{let[cpu,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=cpu.cpus.map((c,i2)=>({id:i2,load:Math.round(c.load)})).sort((a,b3)=>b3.load-a.load);setStats({cpu:{combined:Math.round(cpu.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)}},[]),import_jsx_dev_runtime2.jsxDEV(SystemStatsView,{stats:stats2},void 0,!1,void 0,this)}var import_react23,import_systeminformation;var init_SystemStats=__esm(()=>{init_version();init_theme2();init_jsx_dev_runtime();import_react23=__toESM(require_react_development(),1),import_systeminformation=__toESM(require_lib5(),1)});function validateName(name){if(name.length===0)return null;try{return validateBranchName(name),null}catch(err){return err instanceof Error?err.message:String(err)}}function TeamCreate({availableAgents,workspaceRoot,onConfirm,onCancel}){let[step,setStep]=import_react25.useState("name"),[teamName,setTeamName]=import_react25.useState(""),[selected,setSelected]=import_react25.useState(()=>new Set),[memberCursor,setMemberCursor]=import_react25.useState(0),nameError=import_react25.useMemo(()=>validateName(teamName),[teamName]),nameValid=teamName.length>0&&nameError===null,intent=import_react25.useMemo(()=>({kind:"create-team",name:teamName.length>0?teamName:"TEAM_NAME",repo:workspaceRoot}),[teamName,workspaceRoot]),handleNameChange=import_react25.useCallback((value)=>{setTeamName(value)},[]),advanceFromName=import_react25.useCallback(()=>{if(!nameValid)return;setStep("members")},[nameValid]),toggleMember=import_react25.useCallback((name)=>{setSelected((prev)=>{let next=new Set(prev);if(next.has(name))next.delete(name);else next.add(name);return next})},[]),confirmMembers=import_react25.useCallback(()=>{onConfirm({teamName,members:Array.from(selected)})},[onConfirm,teamName,selected]);return useKeyboard((key)=>{if(step==="name"){handleNameStepKey(key,{onCancel,nameValid,advanceFromName});return}handleMembersStepKey(key,{availableAgents,memberCursor,setStep,setMemberCursor,toggleMember,confirmMembers})}),import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderColor:palette.borderActive,backgroundColor:palette.bgRaised,paddingX:3,paddingY:1,flexDirection:"column",width:"100%",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:"New team"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:step==="name"?" \u2014 step 1 of 2":" \u2014 step 2 of 2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),step==="name"?import_jsx_dev_runtime2.jsxDEV(NameStep,{value:teamName,onChange:handleNameChange,onSubmit:advanceFromName,errorMessage:nameError},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV(MembersStep,{agents:availableAgents,selected,cursor:memberCursor},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV(CliPreviewLine,{intent,hint:step==="name"?"Enter: next \xB7 Esc: cancel":"Space: toggle \xB7 Enter: create \xB7 Esc: back"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function NameStep({value,onChange,onSubmit,errorMessage}){return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"Team name (git-branch-safe):"},void 0,!1,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("input",{value,onInput:onChange,onChange,onSubmit,focused:!0,placeholder:"feat/auth-bug",backgroundColor:palette.bg,textColor:palette.text,placeholderColor:palette.textMuted},void 0,!1,void 0,this),errorMessage!==null?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:`\u26A0 ${errorMessage}`},void 0,!1,void 0,this)},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)}function MembersStep({agents,selected,cursor}){if(agents.length===0)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"No agents registered"},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.textMuted,children:"Members can be hired later via `genie team hire`."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"Select members (space to toggle):"},void 0,!1,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",children:agents.map((name,idx)=>{let isSelected=selected.has(name),isCursor=idx===cursor,tick=isSelected?"[x]":"[ ]",prefix=isCursor?"\u25B6 ":" ";return import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:isCursor?palette.accent:palette.textMuted,children:prefix},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:isSelected?palette.success:palette.textDim,children:tick},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:` ${name}`},void 0,!1,void 0,this)]},name,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function isEnter(key){return key.name==="enter"||key.name==="return"}function handleNameStepKey(key,opts){if(key.name==="escape"){opts.onCancel();return}if(isEnter(key)&&opts.nameValid)opts.advanceFromName()}function handleMembersStepKey(key,opts){if(key.name==="escape"){opts.setStep("name");return}if(opts.availableAgents.length===0){if(isEnter(key))opts.confirmMembers();return}if(key.name==="up"||key.name==="k"){opts.setMemberCursor((prev)=>prev<=0?opts.availableAgents.length-1:prev-1);return}if(key.name==="down"||key.name==="j"){opts.setMemberCursor((prev)=>prev>=opts.availableAgents.length-1?0:prev+1);return}if(key.name==="space"){let name=opts.availableAgents[opts.memberCursor];if(name)opts.toggleMember(name);return}if(isEnter(key))opts.confirmMembers()}var import_react25;var init_TeamCreate=__esm(async()=>{init_team_manager();init_theme2();init_CliPreviewLine();init_jsx_dev_runtime();await init_react2();import_react25=__toESM(require_react_development(),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.workState){case"in_flight":return"\u25C6";case"paused":return"\u25D0";case"done":return"\u2714";case"stuck":return"\u2718";default:break}switch(node.wsAgentState){case"running":return"\u25CF";case"stopped":return"\u25CC";case"error":return"\u2298";case"spawning":return"\u231B";default:return"\u25CC"}}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.isClaudeLike)return"\u25C6";return"\u25CB"}function getNodeColor(node){if(node.type==="agent")return getAgentColor(node);switch(node.type){case"session":return node.data.attached?palette.success:palette.textDim;case"window":return node.data.active?palette.info:palette.text;case"pane":return getPaneColor(node);default:return palette.text}}function getAgentColor(node){switch(node.workState){case"in_flight":return palette.accentBright;case"paused":return palette.textDim;case"done":return palette.info;case"stuck":return palette.error;default:break}switch(node.wsAgentState){case"running":return palette.success;case"stopped":return palette.text;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.info;if(node.agentState==="permission")return palette.warning;if(node.agentState==="error")return palette.error;if(node.agentState==="idle")return palette.textDim;if(node.data.isClaudeLike)return palette.info;return palette.textDim}function getAgentSuffix(node){if(node.workState==="stuck")return" [stuck \u2014 press R to retry]";if(node.workState==="paused")return" [paused \u2014 auto-resume off]";if(node.workState==="done")return" [done]";if(node.wsAgentState==="spawning"&&node.activePanes===0)return" [stuck \u2014 press R to retry]";if(node.wsAgentState==="stopped")return" [Enter to start]";let wc=node.data.windowCount;if(wc>1)return` (${wc} windows)`;if(wc===1)return" (1 window)";return""}function getNodeSuffix(node){if(node.type==="agent")return getAgentSuffix(node);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.info;case"idle":return palette.textDim;case"permission":return palette.warning;case"error":return palette.error;default:return palette.textMuted}}var import_react26,TreeNodeRow;var init_TreeNode=__esm(()=>{init_theme2();init_jsx_dev_runtime();import_react26=__toESM(require_react_development(),1),TreeNodeRow=import_react26.memo(function({node,selected,onSelect,onToggle,onContextMenu}){let indent2=" ".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),labelColor=selected?palette.accentBright:node.type==="agent"&&node.kind==="subagent"?palette.textDim:palette.text;return import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",backgroundColor:selected?palette.accentDim: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:[indent2,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:labelColor,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,process.env.GENIE_TUI_DEBUG==="1"?import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:` [${node.type}]`},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)},void 0,!1,void 0,this)})});function useDiagnosticsRefresh(setDiagnostics,setRequestedInitialAgent){import_react28.useEffect(()=>{let active=!0,lastErrorMessage=null,lastErrorLoggedAt=0;async function refresh(){try{let snap=await collectDiagnostics();if(!active)return;setDiagnostics(snap),lastErrorMessage=null;let signaledAgent=consumeInitialAgentSignal();if(signaledAgent)setRequestedInitialAgent(signaledAgent)}catch(err){let message=err instanceof Error?err.message:String(err),now=Date.now();if(message!==lastErrorMessage||now-lastErrorLoggedAt>30000)console.error("TUI: diagnostics failed:",message),lastErrorMessage=message,lastErrorLoggedAt=now}}refresh();let timer2=setInterval(refresh,2000);return()=>{active=!1,clearInterval(timer2)}},[setDiagnostics,setRequestedInitialAgent])}function useSessionTreeBuilder(diagnostics,workspaceRoot,setSessionTree){import_react28.useEffect(()=>{if(!diagnostics)return;let newTree;if(workspaceRoot){let agentNames=scanAgents(workspaceRoot);newTree=buildWorkspaceTree({agentNames,sessions:diagnostics.sessions,executors:diagnostics.executors,workStates:diagnostics.workStates})}else newTree=buildSessionTree(diagnostics);setSessionTree((prev)=>mergeExpandedState(prev,newTree))},[diagnostics,workspaceRoot,setSessionTree])}function useStableSelection(flatNodes,selectedIndex,setSelectedIndex,selectedNodeId){import_react28.useEffect(()=>{let node=flatNodes[selectedIndex]?.node;if(node)selectedNodeId.current=node.id},[selectedIndex,flatNodes,selectedNodeId]),import_react28.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&¤tAtIndex.id===selectedNodeId.current)return;let restored=flatNodes.findIndex((n)=>n.node.id===selectedNodeId.current);if(restored>=0)setSelectedIndex(restored)},[flatNodes])}function useInitialAgentSelection(requestedInitialAgent,flatNodes,setSelectedIndex,setRequestedInitialAgent,onTmuxSessionSelect){import_react28.useEffect(()=>{if(!requestedInitialAgent||flatNodes.length===0)return;let idx=flatNodes.findIndex((n)=>n.node.id===`agent:${requestedInitialAgent}`);if(idx<0)return;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,setSelectedIndex,setRequestedInitialAgent])}function useAutoAttach(flatNodes,selectedIndex,lastTarget,onTmuxSessionSelect){import_react28.useEffect(()=>{let current=flatNodes[selectedIndex]?.node;if(!current)return;let target=getSessionTarget(current);if(!target)return;if(current.type==="agent"&¤t.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,lastTarget])}function useNavKeyboard(opts){useKeyboard((key)=>{if(opts.keyboardDisabled)return;if(opts.spawnIntoAgent!==null||opts.spawnPickerTarget!==null)return;if(tryOpenTeamCreate(key,{workspaceRoot:opts.workspaceRoot,showTeamCreate:opts.showTeamCreate,contextMenuNodeId:opts.contextMenuNodeId,handleOpenTeamCreate:opts.handleOpenTeamCreate}))return;if(opts.showTeamCreate)return;handleKeyboardInput(key,opts)})}function renderAlertBadge(alertCount){if(alertCount<=0)return null;return import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:[" ","\u25CF ",alertCount," alert",alertCount===1?"":"s"]},void 0,!0,void 0,this)}function countAgents(nodes,predicate){let count=0;for(let n of nodes){if(n.type==="agent"&&predicate(n))count++;if(n.children.length>0)count+=countAgents(n.children,predicate)}return count}function computeNavCounts(workspaceRoot,sessionTree,diagnostics){if(workspaceRoot){let agentCount=countAgents(sessionTree,()=>!0);if(agentCount>0)return{agentCount,runningCount:countAgents(sessionTree,(n)=>n.wsAgentState==="running")}}let paneSum=diagnostics?.sessions.reduce((sum,s2)=>sum+s2.windows.reduce((ws,w2)=>ws+w2.panes.length,0),0)??0;return{agentCount:diagnostics?.sessions.length??0,runningCount:paneSum}}function Nav({onTmuxSessionSelect,onNewAgentWindow,workspaceRoot,initialAgent,keyboardDisabled=!1}){let[diagnostics,setDiagnostics]=import_react28.useState(null),[sessionTree,setSessionTree]=import_react28.useState([]),[selectedIndex,setSelectedIndex]=import_react28.useState(0),[requestedInitialAgent,setRequestedInitialAgent]=import_react28.useState(initialAgent),[contextMenuNodeId,setContextMenuNodeId]=import_react28.useState(null),[spawnIntoAgent,setSpawnIntoAgent]=import_react28.useState(null),[spawnPickerTarget,setSpawnPickerTarget]=import_react28.useState(null),lastTarget=import_react28.useRef(null),selectedNodeId=import_react28.useRef(null);useDiagnosticsRefresh(setDiagnostics,setRequestedInitialAgent),useSessionTreeBuilder(diagnostics,workspaceRoot,setSessionTree);let flatNodes=import_react28.useMemo(()=>flattenTree(sessionTree),[sessionTree]);useStableSelection(flatNodes,selectedIndex,setSelectedIndex,selectedNodeId),useInitialAgentSelection(requestedInitialAgent,flatNodes,setSelectedIndex,setRequestedInitialAgent,onTmuxSessionSelect),useAutoAttach(flatNodes,selectedIndex,lastTarget,onTmuxSessionSelect);let handleSelect=import_react28.useCallback((id)=>{let idx=flatNodes.findIndex((n)=>n.node.id===id);if(idx>=0)setSelectedIndex(idx)},[flatNodes]),handleToggle=import_react28.useCallback((id)=>{setSessionTree((prev)=>toggleNode(prev,id))},[]),handleVerticalNav=import_react28.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_react28.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_react28.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_react28.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_react28.useCallback((nodeId)=>{let flat=flatNodes.find((n)=>n.node.id===nodeId);if(flat&&buildMenuItems(flat.node).length>0)setContextMenuNodeId(nodeId)},[flatNodes]),handleContextMenuAction=import_react28.useCallback((action,payload)=>{let node=flatNodes.find((n)=>n.node.id===contextMenuNodeId)?.node;if(!node)return;if(setContextMenuNodeId(null),action==="spawn-here"){let target=resolveSpawnHereTarget(node);if(target)setSpawnPickerTarget(target);return}dispatchContextMenuAction(action,node,payload,{sessionTree,onTmuxSessionSelect,onNewAgentWindow,openSpawnInto:setSpawnIntoAgent})},[flatNodes,contextMenuNodeId,sessionTree,onTmuxSessionSelect,onNewAgentWindow]),handleSpawnIntoConfirm=import_react28.useCallback((intent)=>{executeSpawnIntent(intent),setSpawnIntoAgent(null)},[]),handleSpawnIntoCancel=import_react28.useCallback(()=>{setSpawnIntoAgent(null)},[]),handleSpawnPickerConfirm=import_react28.useCallback((intent)=>{setSpawnPickerTarget(null),executeSpawnIntent(intent)},[]),handleSpawnPickerCancel=import_react28.useCallback(()=>{setSpawnPickerTarget(null)},[]),_menuDisabled=keyboardDisabled||contextMenuNodeId!==null,{showTeamCreate,handleOpenTeamCreate,handleTeamCreateConfirm,handleTeamCreateCancel}=useTeamCreateControls({workspaceRoot,diagnostics,onTmuxSessionSelect});useNavKeyboard({keyboardDisabled,spawnIntoAgent,spawnPickerTarget,workspaceRoot,showTeamCreate,contextMenuNodeId,handleOpenTeamCreate,flatNodes,selectedIndex,setContextMenuNodeId,handleVerticalNav,handleExpandCollapse,handleEnter,handleRetry,onNewAgentWindow});let{agentCount,runningCount}=computeNavCounts(workspaceRoot,sessionTree,diagnostics),headerLabel=workspaceRoot?"Agents":"Sessions",alertCount=diagnostics?.alertCount??0;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.bgRaised,children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,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,renderAlertBadge(alertCount)]},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",flexDirection:"column",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("ascii-font",{text:"GENIE",font:"tiny",color:palette.accent},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("text",{fg:palette.textDim,children:"Collecting..."},void 0,!1,void 0,this)]},void 0,!0,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,spawnIntoAgent!==null?import_jsx_dev_runtime2.jsxDEV(SpawnTargetPicker,{agentName:spawnIntoAgent,sessions:diagnostics?.sessions??[],onConfirm:handleSpawnIntoConfirm,onCancel:handleSpawnIntoCancel},void 0,!1,void 0,this):null,spawnPickerTarget!==null?import_jsx_dev_runtime2.jsxDEV(AgentPicker,{target:spawnPickerTarget,onConfirm:handleSpawnPickerConfirm,onCancel:handleSpawnPickerCancel},void 0,!1,void 0,this):null,showTeamCreate?import_jsx_dev_runtime2.jsxDEV(TeamCreate,{availableAgents:workspaceRoot?scanAgents(workspaceRoot):[],workspaceRoot,onConfirm:handleTeamCreateConfirm,onCancel:handleTeamCreateCancel},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.bgRaised,children:import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:buildFooterHint(workspaceRoot)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function useTeamCreateControls(opts){let{workspaceRoot,diagnostics,onTmuxSessionSelect}=opts,[showTeamCreate,setShowTeamCreate]=import_react28.useState(!1),pendingTeamNameRef=import_react28.useRef(null),handleOpenTeamCreate=import_react28.useCallback(()=>{if(!workspaceRoot)return;setShowTeamCreate(!0)},[workspaceRoot]),handleTeamCreateConfirm=import_react28.useCallback((result2)=>{setShowTeamCreate(!1),runTeamCreation(result2,workspaceRoot),pendingTeamNameRef.current=result2.teamName},[workspaceRoot]),handleTeamCreateCancel=import_react28.useCallback(()=>{setShowTeamCreate(!1)},[]);return import_react28.useEffect(()=>{let pending=pendingTeamNameRef.current;if(!pending||!diagnostics)return;let session=diagnostics.sessions.find((s2)=>s2.name===pending);if(!session)return;pendingTeamNameRef.current=null,onTmuxSessionSelect(session.name,resolvePreferredWindowIndex(session,pending))},[diagnostics,onTmuxSessionSelect]),{showTeamCreate,handleOpenTeamCreate,handleTeamCreateConfirm,handleTeamCreateCancel}}function handleEnterAgent(node,onTmuxSessionSelect,spawn5=spawnAgent){if(node.wsAgentState!=="running"&&node.wsAgentState!=="spawning")spawn5(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(action==="spawn-into"&&node.type==="agent"&&deps.openSpawnInto){deps.openSpawnInto(agentNameFromNode(node));return}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 buildFooterHint(workspaceRoot){return`\u2191\u2193:nav \u2190\u2192:expand Enter:${workspaceRoot?"spawn/attach":"attach"} ^T:new${workspaceRoot?" ^N:team":""} R:retry .:menu`}function tryOpenTeamCreate(key,opts){if(!key.ctrl||key.name!=="n")return!1;if(!opts.workspaceRoot||opts.showTeamCreate||opts.contextMenuNodeId)return!1;return opts.handleOpenTeamCreate(),!0}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,handlers,agentAction){let n=key.name;if(n==="up"||n==="k"||n==="down"||n==="j")handlers.handleVerticalNav(n);else if(n==="right"||n==="l"||n==="left"||n==="h")handlers.handleExpandCollapse(n);else if(n==="enter"||n==="return")handlers.handleEnter();else if(n==="r")handlers.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:join93,resolve:resolve21}=__require("path"),{existsSync:existsSync76,mkdirSync:mkdirSync34,openSync:openSync6}=__require("fs"),{homedir:homedir50}=__require("os"),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=resolve21(join93(wsRoot,"agents",parentName));if(existsSync76(agentDir))cwd=agentDir}let{GENIE_TUI_PANE:_a,GENIE_TUI_RIGHT:_b,GENIE_TUI_WORKSPACE:_c,GENIE_IS_DAEMON:_d,...cleanEnv}=process.env,logDir=join93(homedir50(),".genie","logs","tui-spawn");try{mkdirSync34(logDir,{recursive:!0})}catch{}let logPath=join93(logDir,`${sessionName}-${Date.now()}.log`),logFd;try{logFd=openSync6(logPath,"a")}catch{logFd=void 0}let spawnOpts=logFd!==void 0?{detached:!0,stdio:["ignore",logFd,logFd],cwd,env:cleanEnv}:{detached:!0,stdio:"ignore",cwd,env:cleanEnv},child=genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,"spawn",name,"--session",sessionName,"--new-window"],spawnOpts):spawn5("genie",["spawn",name,"--session",sessionName,"--new-window"],spawnOpts);if(child.on("exit",(code)=>{if(code&&code!==0)console.error(`TUI: spawn "${name}" exited ${code}. See ${logPath}`)}),child.on("error",(err)=>{console.error(`TUI: spawn "${name}" error: ${err.message}. See ${logPath}`)}),child.unref(),onTmuxSessionSelect)attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect)}catch(err){console.error(`TUI: spawn failed for ${name}:`,err instanceof Error?err.message:err)}}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 executeGenieAwaited(args){return new Promise((resolve21,reject)=>{try{let{spawn:spawn5}=__require("child_process"),bunPath=process.execPath||"bun",genieBin=process.argv[1],child=genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,...args],{stdio:"ignore"}):spawn5("genie",args,{stdio:"ignore"});child.on("exit",(code)=>resolve21(code)),child.on("error",reject)}catch(err){reject(err instanceof Error?err:Error(String(err)))}})}function resolveSpawnHereTarget(node){if(node.type==="session"){let sess=node.id.split(":").slice(1).join(":");if(sess.length===0)return null;return{session:sess}}if(node.type==="window"){let idParts=node.id.split(":");if(idParts.length<3)return null;return{session:idParts[1],window:`${idParts[1]}:${idParts[2]}`}}return null}function executeSpawnIntent(intent){try{let{argv}=buildSpawnInvocation(intent);executeGenie(argv)}catch(err){console.error("TUI: spawn-intent execution failed:",err instanceof Error?err.message:err)}}async function runTeamCreation(result2,workspaceRoot){let argv;try{({argv}=buildSpawnInvocation({kind:"create-team",name:result2.teamName,repo:workspaceRoot}))}catch(err){console.error("TUI: team create intent build failed:",err instanceof Error?err.message:err);return}let createExit=null;try{createExit=await executeGenieAwaited(argv)}catch(err){console.error("TUI: team create spawn failed:",err instanceof Error?err.message:err);return}if(createExit!==0){console.error(`TUI: team create exited ${createExit} \u2014 skipping member hires for "${result2.teamName}"`);return}for(let member of result2.members)try{let code=await executeGenieAwaited(["team","hire",member,"--team",result2.teamName]);if(code!==0)console.error(`TUI: team hire "${member}" exited ${code} \u2014 continuing with remaining members`)}catch(err){console.error(`TUI: team hire "${member}" failed:`,err instanceof Error?err.message:err)}}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_react28;var init_Nav=__esm(async()=>{init_spawn_invocation();init_workspace();init_diagnostics();init_initial_agent();init_session_tree();init_theme2();init_SystemStats();init_TreeNode();init_jsx_dev_runtime();await __promiseAll([init_react2(),init_AgentPicker(),init_ContextMenu(),init_SpawnTargetPicker(),init_TeamCreate()]);import_react28=__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:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderColor:palette.borderActive,backgroundColor:palette.bgRaised,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.accent,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_react2()});import{execSync as execSync18}from"child_process";import{readFileSync as readFileSync49}from"fs";function App({rightPane,workspaceRoot,initialAgent}){let renderer=useRenderer(),[showQuit,setShowQuit]=import_react32.useState(!1),[showHelp,setShowHelp]=import_react32.useState(!1),[activeSession,setActiveSession]=import_react32.useState(null);import_react32.useEffect(()=>{let title=activeSession?`${BASE_TERMINAL_TITLE} \u2014 ${activeSession}`:BASE_TERMINAL_TITLE;try{renderer.setTerminalTitle(title)}catch{}},[renderer,activeSession]);let handleQuit=import_react32.useCallback(()=>{try{let genieHome6=process.env.GENIE_HOME??`${process.env.HOME}/.genie`,pid=readFileSync49(`${genieHome6}/serve.pid`,"utf-8").trim();process.kill(Number.parseInt(pid,10),"SIGTERM")}catch{}try{execSync18("tmux -L genie-tui kill-server",{stdio:"ignore"})}catch{}},[]);useBindings(()=>({commands:[{name:"app.quit",title:"Quit",desc:"Show quit confirmation; press again to quit",category:"app",run(){if(showQuit)handleQuit();else setShowQuit(!0)}},{name:"app.help.toggle",title:"Toggle help overlay",desc:"Show/hide the keyboard shortcut overlay",category:"app",run(){setShowHelp((prev)=>!prev)}},{name:"app.console.toggle",title:"Toggle console overlay",desc:"Show/hide the OpenTUI console (logs)",category:"app",run(){renderer.console.toggle()}}],bindings:[{key:"ctrl+q",cmd:"app.quit"},{key:"f1",cmd:"app.help.toggle"},{key:"`",cmd:"app.console.toggle"}]}),[renderer,showQuit,handleQuit]);let handleTmuxSessionSelect=import_react32.useCallback((sessionName,windowIndex)=>{if(setActiveSession(sessionName),!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||showHelp},void 0,!1,void 0,this),showHelp?import_jsx_dev_runtime2.jsxDEV(HelpOverlay,{onClose:()=>setShowHelp(!1)},void 0,!1,void 0,this):null,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_react32,BASE_TERMINAL_TITLE="genie tui";var init_app=__esm(async()=>{init_react();init_tmux2();init_jsx_dev_runtime();await __promiseAll([init_react2(),init_HelpOverlay(),init_Nav(),init_QuitDialog()]);import_react32=__toESM(require_react_development(),1)});function getFocusedTargetIfAvailable(host){if(host.isDestroyed)return null;return host.getFocusedTarget()}function forEachActivationTarget(host,focused,visit){let current=focused??host.rootTarget,isFocusedTarget=focused!==null;while(current){if(visit(current,isFocusedTarget)===!1)return;current=host.getParentTarget(current),isFocusedTarget=!1}}function getActivationPath(host,focused){let path6=new Set;return forEachActivationTarget(host,focused,(current)=>{path6.add(current)}),path6}function getActiveLayersForFocused(state,host,focused){if(state.activeLayersCacheVersion===state.activeLayersVersion&&state.activeLayersCacheFocused===focused)return state.activeLayersCache;let activeLayers=[],activationPath=getActivationPath(host,focused);for(let layer of state.sortedLayers)if(isLayerActiveForFocused(host,layer,focused,activationPath))activeLayers.push(layer);return state.activeLayersCacheVersion=state.activeLayersVersion,state.activeLayersCacheFocused=focused,state.activeLayersCache=activeLayers,activeLayers}function invalidateCachedActiveLayers(state){state.activeLayersCacheVersion=-1,state.activeLayersCacheFocused=void 0,state.activeLayersCache=[]}function isLayerActiveForFocused(host,layer,focused,activationPath=getActivationPath(host,focused)){let target=layer.target;if(!target)return!0;if(host.isTargetDestroyed(target))return!1;if(layer.targetMode==="focus")return target===focused;return activationPath.has(target)}function normalizeBindingTokenName(token){let normalized=token.trim().toLowerCase();if(!normalized)throw Error("Invalid keymap token: token cannot be empty");return normalized}function normalizeKeyName(name){let normalized=name.trim().toLowerCase();if(!normalized)throw Error("Invalid key name: key name cannot be empty");return normalized}function normalizeKeyStroke(input){return{name:normalizeKeyName(input.name),ctrl:input.ctrl??!1,shift:input.shift??!1,meta:input.meta??!1,super:input.super??!1,hyper:input.hyper||void 0}}function cloneKeyStroke(stroke){return{name:stroke.name,ctrl:stroke.ctrl,shift:stroke.shift,meta:stroke.meta,super:stroke.super,hyper:stroke.hyper||void 0}}function createKeySequencePart(input,options){let stroke=cloneKeyStroke(normalizeKeyStroke(input));return{stroke,display:options?.display??stringifyCanonicalStroke(stroke),match:options?.match??createKeyMatch(stroke),tokenName:options?.tokenName?normalizeBindingTokenName(options.tokenName):void 0}}function cloneKeySequencePart(part){return{stroke:cloneKeyStroke(part.stroke),display:part.display,match:part.match,tokenName:part.tokenName}}function cloneKeySequence(parts){return parts.map((part)=>cloneKeySequencePart(part))}function resolveKeyMatch(input){if("match"in input)return input.match;if("stroke"in input)return createKeyMatch(input.stroke);return createKeyMatch(input)}function createKeyMatch(input){return`key:${buildKeyMatchId(normalizeKeyStroke(input))}`}function createTextKeyMatch(id){let normalized=id.trim();if(!normalized)throw Error("Invalid keymap match id: id cannot be empty");return`text:${normalized}`}function stringifyKeyStroke(input,options){if("stroke"in input){if(options?.preferDisplay&&input.display)return input.display;return stringifyCanonicalStroke(input.stroke)}return stringifyCanonicalStroke(normalizeKeyStroke(input))}function stringifyKeySequence(input,options){return input.map((part)=>stringifyKeyStroke(part,options)).join("")}function stringifyCanonicalStroke(stroke){let parts=[];if(stroke.ctrl)parts.push("ctrl");if(stroke.shift)parts.push("shift");if(stroke.meta)parts.push("meta");if(stroke.super)parts.push("super");if(stroke.hyper)parts.push("hyper");return parts.push(stroke.name==="return"?"enter":stroke.name),parts.join("+")}function buildKeyMatchId(stroke){return`${stroke.name}:${stroke.ctrl?1:0}:${stroke.shift?1:0}:${stroke.meta?1:0}:${stroke.super?1:0}:${stroke.hyper?1:0}`}function getLiveHost(host){if(host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");return host}function isSamePendingSequence(current,next){if(current===next)return!0;if(!current||!next)return!1;if(current.captures.length!==next.captures.length)return!1;for(let index=0;index<current.captures.length;index+=1){let left=current.captures[index],right=next.captures[index];if(!left||!right||left.layer!==right.layer||left.node!==right.node)return!1}return!0}class ActivationService{state;host;hooks;notify;conditions;catalog;options;constructor(state,host,hooks,notify,conditions,catalog,options={}){this.state=state,this.host=host,this.hooks=hooks,this.notify=notify,this.conditions=conditions,this.catalog=catalog,this.options=options}getFocusedTarget(){return getLiveHost(this.host).getFocusedTarget()}getFocusedTargetIfAvailable(){return getFocusedTargetIfAvailable(this.host)}setPendingSequence(next){let previous=this.state.projection.pendingSequence;if(isSamePendingSequence(previous,next))return;this.state.projection.pendingSequence=next,this.options.onPendingSequenceChanged?.(previous,next),this.invalidateCaches(),this.notifyPendingSequenceChange(),this.notify.queueStateChange()}ensureValidPendingSequence(){let pending=this.state.projection.pendingSequence;if(!pending)return;let focused=this.getFocusedTarget(),captures=pending.captures.filter((capture2)=>{return this.state.layers.layers.has(capture2.layer)&&this.isLayerActiveForFocused(capture2.layer,focused)&&this.conditions.layerMatchesRuntimeState(capture2.layer)&&this.nodeHasReachableBindings(capture2.node,focused)});if(captures.length===0){this.setPendingSequence(null);return}if(captures.length!==pending.captures.length)this.setPendingSequence({captures});return this.state.projection.pendingSequence??void 0}revalidatePendingSequenceIfNeeded(){if(this.host.isDestroyed||!this.state.projection.pendingSequence)return;this.ensureValidPendingSequence()}hasPendingSequenceState(){return!this.host.isDestroyed&&this.state.projection.pendingSequence!==null}getPendingSequence(){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion;if(projections.pendingSequenceCacheVersion===derivedStateVersion)return projections.pendingSequenceCache;let pending=this.ensureValidPendingSequence(),canUseCache=!pending||pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)),sequence=pending?this.collectSequencePartsFromPending(pending):[];if(canUseCache)projections.pendingSequenceCacheVersion=derivedStateVersion,projections.pendingSequenceCache=sequence;return sequence}popPendingSequence(){let pending=this.ensureValidPendingSequence();if(!pending)return!1;let firstCapture=pending.captures[0];if(!firstCapture||firstCapture.node.depth<=1)return this.setPendingSequence(null),!0;let nextCaptures=[];for(let capture2 of pending.captures){let parent=capture2.node.parent;if(!parent||!parent.stroke)continue;nextCaptures.push({layer:capture2.layer,node:parent})}if(nextCaptures.length===0)return this.setPendingSequence(null),!0;return this.setPendingSequence({captures:nextCaptures}),!0}getActiveKeys(options){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion,includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0;if(includeBindings){if(includeMetadata){if(projections.activeKeysBindingsAndMetadataCacheVersion===derivedStateVersion)return projections.activeKeysBindingsAndMetadataCache}else if(projections.activeKeysBindingsCacheVersion===derivedStateVersion)return projections.activeKeysBindingsCache}else if(includeMetadata){if(projections.activeKeysMetadataCacheVersion===derivedStateVersion)return projections.activeKeysMetadataCache}else if(projections.activeKeysPlainCacheVersion===derivedStateVersion)return projections.activeKeysPlainCache;let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),pending=this.ensureValidPendingSequence(),activeLayers=pending?[]:this.getActiveLayers(focused),canUseCache=pending?pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)):this.activeLayersCanCacheActiveKeys(activeLayers),activeKeys=pending?this.collectActiveKeysFromPending(pending.captures,includeBindings,includeMetadata,focused,activeView):this.collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView);if(!canUseCache)return activeKeys;if(includeBindings)if(includeMetadata)projections.activeKeysBindingsAndMetadataCacheVersion=derivedStateVersion,projections.activeKeysBindingsAndMetadataCache=activeKeys;else projections.activeKeysBindingsCacheVersion=derivedStateVersion,projections.activeKeysBindingsCache=activeKeys;else if(includeMetadata)projections.activeKeysMetadataCacheVersion=derivedStateVersion,projections.activeKeysMetadataCache=activeKeys;else projections.activeKeysPlainCacheVersion=derivedStateVersion,projections.activeKeysPlainCache=activeKeys;return activeKeys}getActiveKeysForCaptures(captures,options){let includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0,focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused);return this.collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView)}nodeHasReachableBindings(node,focused){return this.hasMatchingBindings(node.reachableBindings,focused,this.catalog.getActiveCommandView(focused))}getActiveLayers(focused){return getActiveLayersForFocused(this.state.layers,this.host,focused)}refreshActiveLayers(focused=this.getFocusedTargetIfAvailable()){getActiveLayersForFocused(this.state.layers,this.host,focused)}invalidateActiveLayers(){invalidateCachedActiveLayers(this.state.layers)}isLayerActiveForFocused(layer,focused){return isLayerActiveForFocused(this.host,layer,focused)}layerCanCacheActiveKeys(layer){return!layer.hasUnkeyedMatchers&&!layer.hasUnkeyedCommands&&!layer.hasUnkeyedBindings}activeLayersCanCacheActiveKeys(activeLayers){for(let layer of activeLayers)if(!this.layerCanCacheActiveKeys(layer))return!1;return!0}collectNodesFromNode(node){let nodes=[],current=node;while(current&¤t.stroke)nodes.push(current),current=current.parent;return nodes.reverse(),nodes}collectSequencePartsFromPending(pending){let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),paths=pending.captures.map((capture2)=>this.collectNodesFromNode(capture2.node)),firstPath=paths[0];if(!firstPath||firstPath.length===0)return[];let parts=[];for(let index=0;index<firstPath.length;index+=1){let firstNode=firstPath[index];if(!firstNode?.stroke||firstNode.match===null)continue;let display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let path6 of paths){let node=path6[index];if(!node)continue;let presentation=this.getNodePresentation(node,focused,activeView);if(display===void 0){display=presentation.display,tokenName=presentation.tokenName;continue}if(!hasDisplayConflict&&display!==presentation.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==presentation.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke(firstNode.stroke);if(hasTokenConflict)tokenName=void 0;parts.push(createKeySequencePart(firstNode.stroke,{display,match:firstNode.match,tokenName}))}return parts}collectMatchingBindings(bindings,focused,activeView){let matches=[];for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))matches.push(binding);return matches}hasMatchingBindings(bindings,focused,activeView){for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))return!0;return!1}getNodePresentation(node,focused,activeView,reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView)){if(!node.stroke)return{display:""};let partIndex=node.depth-1,display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let binding of reachableBindings){let part=binding.sequence[partIndex];if(!part)continue;if(display===void 0){display=part.display,tokenName=part.tokenName;continue}if(!hasDisplayConflict&&display!==part.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==part.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke(node.stroke);if(hasTokenConflict)tokenName=void 0;return{display,tokenName}}toActiveBinding(binding,focused,activeView){return{sequence:binding.sequence,command:binding.command,commandAttrs:this.catalog.getBindingCommandAttrs(binding,focused,activeView),attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough}}collectActiveBindings(bindings,focused,activeView){return bindings.map((binding)=>this.toActiveBinding(binding,focused,activeView))}collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set,hasLayerConditions=this.state.layers.layersWithConditions>0;for(let layer of activeLayers){if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let[bindingKey,child]of layer.root.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set;for(let capture2 of captures)for(let[bindingKey,child]of capture2.node.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}selectActiveKey(node,includeBindings,focused,activeView){return node.children.size>0?this.selectPrefixActiveKey(node,includeBindings,focused,activeView):this.selectExactActiveKey(node,includeBindings,focused,activeView)}selectPrefixActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView);if(reachableBindings.length===0)return;let prefixBindings=this.selectActiveBindings(node.bindings,focused,activeView);return{...this.getNodePresentation(node,focused,activeView,reachableBindings),continues:!0,firstBinding:prefixBindings?.bindings[0],commandBinding:prefixBindings?.commandBinding,bindings:includeBindings&&prefixBindings&&prefixBindings.bindings.length>0?[...prefixBindings.bindings]:void 0,stop:!0}}selectExactActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let selected=this.selectActiveBindings(node.bindings,focused,activeView);if(!selected)return;let display,tokenName;if(selected.bindings.length===1){let part=selected.bindings[0]?.sequence[node.depth-1];display=part?.display??stringifyKeyStroke(node.stroke),tokenName=part?.tokenName}else{let presentation=this.getNodePresentation(node,focused,activeView,selected.bindings);display=presentation.display,tokenName=presentation.tokenName}return{display,tokenName,continues:!1,firstBinding:selected.bindings[0],commandBinding:selected.commandBinding,bindings:includeBindings?[...selected.bindings]:void 0,stop:selected.stop}}selectActiveBindings(bindings,focused,activeView){let selected=[],commandBinding;for(let binding of bindings){if(!this.conditions.matchesConditions(binding)||!this.catalog.isBindingVisible(binding,focused,activeView))continue;if(selected.push(binding),binding.command===void 0)continue;if(commandBinding??=binding,!binding.fallthrough)return{bindings:selected,commandBinding,stop:!0}}if(selected.length===0)return;return{bindings:selected,commandBinding,stop:!1}}createActiveKeyState(stroke,selection,includeBindings){return{stroke,display:selection.display,tokenName:selection.tokenName,continues:selection.continues,firstBinding:selection.firstBinding,commandBinding:selection.commandBinding,bindings:includeBindings&&selection.bindings?[...selection.bindings]:void 0}}updateActiveKeyState(state,selection,includeBindings){if(!state.firstBinding&&selection.firstBinding)state.firstBinding=selection.firstBinding;if(!state.commandBinding&&selection.commandBinding)state.commandBinding=selection.commandBinding;if(selection.continues)state.continues=!0;if(!includeBindings||!selection.bindings||selection.bindings.length===0)return;if(!state.bindings){state.bindings=[...selection.bindings];return}state.bindings.push(...selection.bindings)}materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView){if(!state.commandBinding&&!state.continues)return;let activeKey={stroke:cloneKeyStroke(state.stroke),display:state.display,continues:state.continues};if(state.tokenName)activeKey.tokenName=state.tokenName;if(state.commandBinding)activeKey.command=state.commandBinding.command;if(includeBindings&&state.bindings&&state.bindings.length>0)activeKey.bindings=state.bindings.length===1?[this.toActiveBinding(state.bindings[0],focused,activeView)]:this.collectActiveBindings(state.bindings,focused,activeView);if(includeMetadata){if(state.firstBinding?.attrs)activeKey.bindingAttrs=state.firstBinding.attrs;let commandAttrs=state.commandBinding?this.catalog.getBindingCommandAttrs(state.commandBinding,focused,activeView):void 0;if(commandAttrs)activeKey.commandAttrs=commandAttrs}return activeKey}invalidateCaches(){this.state.projection.pendingSequenceCacheVersion=-1,this.state.projection.activeKeysPlainCacheVersion=-1,this.state.projection.activeKeysBindingsCacheVersion=-1,this.state.projection.activeKeysMetadataCacheVersion=-1,this.state.projection.activeKeysBindingsAndMetadataCacheVersion=-1}notifyPendingSequenceChange(){if(!this.hooks.has("pendingSequence"))return;this.hooks.emit("pendingSequence",this.state.projection.pendingSequence?this.collectSequencePartsFromPending(this.state.projection.pendingSequence):[])}}function mergeRequirement(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap requirement for "${name}" from ${source}`);target[name]=value}function mergeAttribute(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap attribute for "${name}" from ${source}`);target[name]=value}function isPlainObject2(value){let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function getErrorMessage(error2,fallback){if(error2 instanceof Error&&error2.message)return error2.message;return fallback}function isPromiseLike(value){if(!value)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return typeof value.then==="function"}function snapshotDataValue(value,options){let deep=options?.deep===!0,freeze=options?.freeze===!0,preserveNonPlainObjects=options?.preserveNonPlainObjects===!0;if(Array.isArray(value)){let cloned=deep?value.map((entry2)=>snapshotDataValue(entry2,options)):[...value];return freeze?Object.freeze(cloned):cloned}if(value&&typeof value==="object"){if(preserveNonPlainObjects&&!isPlainObject2(value))return value;let cloned={};for(let[key,entry2]of Object.entries(value))cloned[key]=deep?snapshotDataValue(entry2,options):entry2;return freeze?Object.freeze(cloned):cloned}return value}function createCommandChainCacheState(){return{resolvedWithoutRecordChains:new Map,resolvedWithRecordChains:new Map,fallbackWithoutRecord:new Map,fallbackWithRecord:new Map,fallbackWithoutRecordErrors:new Set,fallbackWithRecordErrors:new Set}}function normalizeBindingCommand(command){if(command===void 0||typeof command==="function")return command;let trimmed=command.trim();if(!trimmed)throw Error("Invalid keymap command: command cannot be empty");return trimmed}function normalizeCommandName(name){let trimmed=name.trim();if(!trimmed)throw Error("Invalid keymap command name: name cannot be empty");if(/\s/.test(trimmed))throw Error(`Invalid keymap command name "${name}": command names cannot contain whitespace`);return trimmed}class CommandCatalogService{state;host;notify;conditions;options;constructor(state,host,notify,conditions,options){this.state=state,this.host=host,this.notify=notify,this.conditions=conditions,this.options=options}normalizeCommands(commands){return normalizeRegisteredCommands({commands,commandFields:this.state.environment.commandFields,conditions:this.conditions,onError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}prependCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.prepend(resolver),resolver)}appendCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.append(resolver),resolver)}clearCommandResolvers(){if(!this.state.commands.commandResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.commands.commandResolvers.clear(),this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}getCommands(query2){return this.getFilteredCommandEntries(query2).map((entry2)=>getRegisteredCommandRecord(entry2.command))}getCommandEntries(query2){let context=this.getCommandQueryContext(query2),filteredEntries=this.getFilteredCommandEntries(query2,context);if(filteredEntries.length===0)return[];let grouped=filteredEntries.map((entry2)=>({entry:entry2,command:getRegisteredCommandRecord(entry2.command),bindings:[]})),indexesByName=new Map;for(let[index,item]of grouped.entries()){let existing=indexesByName.get(item.command.name);if(existing)existing.push(index);else indexesByName.set(item.command.name,[index])}if(indexesByName.size>0)this.collectCommandEntryBindings(grouped,indexesByName,context);return grouped.map((item)=>({command:item.command,bindings:item.bindings}))}getResolvedCommandChain(command,focused,includeRecord){let view=this.getActiveCommandView(focused),entries=this.getResolvedCommandChainFromView(view,command,focused,includeRecord,"active",view.chainsByName.get(command)),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{entries,hadError}}getRegisteredResolvedEntries(command,includeRecord){let view=this.getRegisteredCommandView(),cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let chain=view.chainsByName.get(command);if(!chain||chain.length===0){cache.set(command,[]);return}let resolved=[];for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand(entry2.command,{includeRecord})});return cache.set(command,resolved),resolved}getRegisteredResolverFallback(command,includeRecord){let view=this.getRegisteredCommandView(),fallback=this.getFallbackResolvedCommand(view,command,null,includeRecord,"registered"),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{resolved:fallback?.resolved,hadError}}getCommandAttrs(command,focused){return this.getTopResolvedCommand(command,focused,!1)?.resolved.attrs}getTopCommandRecord(command,focused){return this.getTopResolvedCommand(command,focused,!0)?.resolved.record}getTopRegisteredCommandRecord(command){let top=this.getTopRegisteredCommand(command);return top?getRegisteredCommandRecord(top.command):void 0}getDispatchUnavailableCommandState(command,focused,includeRecord){let chain=this.getRegisteredCommandView().chainsByName.get(command);if(!chain||chain.length===0)return;let inactiveEntry,disabledEntry;for(let entry2 of chain){if(!isLayerActiveForFocused(this.host,entry2.layer,focused)){inactiveEntry??=entry2;continue}if(!this.conditions.layerMatchesRuntimeState(entry2.layer)||!this.conditions.matchesConditions(entry2.command))disabledEntry??=entry2}let unavailableEntry=disabledEntry??inactiveEntry;if(!unavailableEntry)return;return{reason:disabledEntry?"disabled":"inactive",command:includeRecord?getRegisteredCommandRecord(unavailableEntry.command):void 0}}getActiveCommandView(focused){let currentFocused=getFocusedTargetIfAvailable(this.host),derivedStateVersion=this.state.notify.derivedStateVersion;if(focused===currentFocused&&this.state.commands.activeCommandViewVersion===derivedStateVersion&&this.state.commands.activeCommandView?.cacheable)return this.state.commands.activeCommandView;let entries=[],reachable=[],reachableByName=new Map,chainsByName=new Map,cacheable=!0;if(this.state.layers.layersWithCommands>0)for(let layer of getActiveLayersForFocused(this.state.layers,this.host,focused)){if(layer.commands.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;if(layer.hasUnkeyedMatchers)cacheable=!1;for(let command of layer.commands){if(command.hasUnkeyedMatchers)cacheable=!1;if(!this.conditions.matchesConditions(command))continue;let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2]);if(!reachableByName.has(command.name))reachableByName.set(command.name,entry2),reachable.push(entry2)}}let view={cacheable,entries,reachable,reachableByName,chainsByName,...createCommandChainCacheState()};if(focused===currentFocused&&view.cacheable)this.state.commands.activeCommandViewVersion=derivedStateVersion,this.state.commands.activeCommandView=view;return view}getRegisteredCommandView(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandViewVersion===cacheVersion&&this.state.commands.registeredCommandView)return this.state.commands.registeredCommandView;let entries=[],chainsByName=new Map;for(let layer of this.state.layers.sortedLayers){if(layer.commands.length===0)continue;for(let command of layer.commands){let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2])}}let view={entries,chainsByName,...createCommandChainCacheState()};return this.state.commands.registeredCommandViewVersion=cacheVersion,this.state.commands.registeredCommandView=view,view}isBindingVisible(binding,focused,activeView){if(binding.command===void 0||binding.run)return!0;if(typeof binding.command!=="string")return!1;if(activeView.reachableByName.has(binding.command))return!0;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")!==void 0}getBindingCommandAttrs(binding,focused,activeView){if(typeof binding.command!=="string")return;let active=activeView.reachableByName.get(binding.command);if(active)return active.command.attrs;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")?.resolved.attrs}getCommandResolutionStatus(command,layerCommands){if(layerCommands?.has(command)||this.state.commands.registeredNames.has(command))return"resolved";let lookup=this.resolveCommandWithResolvers(command,getFocusedTargetIfAvailable(this.host));if(lookup.resolved||lookup.hadError)return lookup.resolved?"resolved":"error";return"unresolved"}mutateCommandResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let off=register2();return this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange(),()=>{this.notify.runWithStateChangeBatch(()=>{if(off(),this.state.commands.commandResolvers.values().includes(resolver))return;this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}})}getTopResolvedCommand(command,focused,includeRecord){let activeView=this.getActiveCommandView(focused),active=activeView.reachableByName.get(command);if(active)return{target:active.layer.target,resolved:resolveRegisteredCommand(active.command,{includeRecord})};return this.getFallbackResolvedCommand(activeView,command,focused,includeRecord,"active")}getTopRegisteredCommand(command){return this.getRegisteredCommandView().chainsByName.get(command)?.[0]}getFallbackResolvedCommand(view,command,focused,includeRecord,mode){let cache=includeRecord?view.fallbackWithRecord:view.fallbackWithoutRecord,errorCache=includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors;if(cache.has(command)){let cached=cache.get(command);return cached?{resolved:cached}:void 0}let lookup=this.resolveCommandWithResolvers(command,focused,{includeRecord,mode});if(cache.set(command,lookup.resolved??null),lookup.hadError)errorCache.add(command);if(!lookup.resolved)return;return{resolved:lookup.resolved}}getResolvedCommandChainFromView(view,command,focused,includeRecord,mode,activeChain){let cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let resolved=[],chain=activeChain;if(chain)for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand(entry2.command,{includeRecord})});let fallback=this.getFallbackResolvedCommand(view,command,focused,includeRecord,mode);if(fallback)resolved.push(fallback);return cache.set(command,resolved),resolved.length>0?resolved:void 0}getRegisteredLayerCommandEntries(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandEntriesCacheVersion===cacheVersion)return this.state.commands.registeredCommandEntriesCache;let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);let entries=[];for(let layer of layers)for(let command of layer.commands)entries.push({layer,command});return this.state.commands.registeredCommandEntriesCacheVersion=cacheVersion,this.state.commands.registeredCommandEntriesCache=entries,entries}getCommandQueryContext(query2){let visibility=query2?.visibility??"reachable",focused=query2&&Object.prototype.hasOwnProperty.call(query2,"focused")?query2.focused??null:getFocusedTargetIfAvailable(this.host);if(visibility==="registered")return{visibility,focused};return{visibility,focused,activeView:this.getActiveCommandView(focused)}}getFilteredCommandEntries(query2,context=this.getCommandQueryContext(query2)){let entries;if(context.visibility==="registered")entries=this.getRegisteredLayerCommandEntries();else if(context.visibility==="active")entries=context.activeView?.entries??[];else entries=context.activeView?.reachable??[];return queryLayerCommandEntries({entries,query:query2,getCommandRecord:(command)=>getRegisteredCommandRecord(command),onFilterError:(error2)=>{this.notify.emitError("command-query-filter-error",error2,"[Keymap] Error in command query filter:")}})}collectCommandEntryBindings(grouped,indexesByName,context){if(context.visibility==="registered"){let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);for(let layer of layers)for(let binding of layer.compiledBindings)this.collectBindingForCommandEntries(grouped,indexesByName,binding);return}let activeView=context.activeView;if(!activeView)return;for(let layer of getActiveLayersForFocused(this.state.layers,this.host,context.focused)){if(layer.compiledBindings.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;for(let binding of layer.compiledBindings){if(!this.conditions.matchesConditions(binding)||!this.isBindingVisible(binding,context.focused,activeView))continue;this.collectBindingForCommandEntries(grouped,indexesByName,binding)}}}collectBindingForCommandEntries(grouped,indexesByName,binding){if(typeof binding.command!=="string")return;let indexes=indexesByName.get(binding.command);if(!indexes||indexes.length===0)return;for(let index of indexes){let item=grouped[index];if(!item)continue;item.bindings.push({sequence:binding.sequence,command:binding.command,commandAttrs:item.command.attrs,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough})}}resolveCommandWithResolvers(command,focused,options){let includeRecord=options?.includeRecord===!0,context=this.createCommandResolverContext(includeRecord,focused,options?.mode??"active");return resolveCommandWithResolvers(command,this.state.commands.commandResolvers.values(),context,(error2)=>{this.notify.emitError("command-resolver-error",error2,`[Keymap] Error in command resolver for "${command}":`)})}createCommandResolverContext(includeRecord,focused,mode){return{getCommandAttrs:(name)=>{if(mode==="registered")return this.getTopRegisteredCommand(name)?.command.attrs;return this.getCommandAttrs(name,focused)},getCommandRecord:(name)=>{if(!includeRecord)return;if(mode==="registered")return this.getTopRegisteredCommandRecord(name);return this.getTopCommandRecord(name,focused)}}}}function getRegisteredCommandRecord(command){if(command.record)return command.record;let fields=EMPTY_COMMAND_FIELDS;if(command.fields!==EMPTY_COMMAND_FIELDS&&Object.keys(command.fields).length>0)fields=snapshotDataValue(command.fields,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS);let record=command.attrs?Object.freeze({name:command.name,fields,attrs:snapshotDataValue(command.attrs,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS)}):Object.freeze({name:command.name,fields});return command.record=record,record}function resolveRegisteredCommand(command,options){if(options?.includeRecord===!0){let existing2=command.resolvedWithRecord;if(existing2)return existing2;let resolved2={run:createRegisteredCommandRunner(command)};if(command.attrs)resolved2.attrs=command.attrs;return resolved2.record=getRegisteredCommandRecord(command),command.resolvedWithRecord=resolved2,resolved2}let existing=command.resolved;if(existing)return existing;let resolved={run:createRegisteredCommandRunner(command)};if(command.attrs)resolved.attrs=command.attrs;return command.resolved=resolved,resolved}function normalizeRegisteredCommands(options){let normalizedCommands=[],seen=new Set;for(let command of options.commands){let normalizedCommand;try{let mergedAttrs={},mergedFields={},mergedRequires={},matchers=[],conditionKeys=new Set,hasUnkeyedMatchers=!1,normalizedName=normalizeCommandName(command.name);if(seen.has(normalizedName)){options.onError("duplicate-command",{command:normalizedName},`Duplicate keymap command "${normalizedName}" in the same layer`);continue}for(let[fieldName,value]of Object.entries(command)){if(RESERVED_COMMAND_FIELDS.has(fieldName)||value===void 0)continue;mergedFields[fieldName]=snapshotDataValue(value,SNAPSHOT_COMMAND_METADATA_OPTIONS);let compiler=options.commandFields.get(fieldName);if(!compiler)continue;compiler(value,createCommandFieldContext(mergedAttrs,mergedRequires,conditionKeys,matchers,options.conditions,fieldName,{onUnkeyedMatcher(){hasUnkeyedMatchers=!0}}))}let attrs=Object.keys(mergedAttrs).length===0?void 0:Object.freeze(mergedAttrs),fields=Object.keys(mergedFields).length===0?EMPTY_COMMAND_FIELDS:Object.freeze(mergedFields);if(normalizedCommand={name:normalizedName,fields,run:command.run,requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,matchCacheDirty:!0},attrs)normalizedCommand.attrs=attrs}catch(error2){options.onError("register-command-failed",error2,getErrorMessage(error2,`Failed to register keymap command "${String(command.name)}"`));continue}seen.add(normalizedCommand.name),normalizedCommands.push(normalizedCommand)}return normalizedCommands}function createCommandFieldContext(mergedAttrs,mergedRequires,conditionKeys,matchers,conditions,fieldName,options){return{require(name,requiredValue){mergeRequirement(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},attr(name,attributeValue){mergeAttribute(mergedAttrs,name,snapshotDataValue(attributeValue,SNAPSHOT_COMMAND_METADATA_OPTIONS),`field ${fieldName}`)},activeWhen(matcher){let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)options.onUnkeyedMatcher();matchers.push(runtimeMatcher)}}}function createRegisteredCommandRunner(command){if(command.runner)return command.runner;let runner=(ctx)=>{return command.run({...ctx,command:getRegisteredCommandRecord(command)})};return command.runner=runner,runner}function resolveCommandWithResolvers(command,resolvers,context,onResolverError){if(resolvers.length===0)return{hadError:!1};let hadError=!1;for(let resolver of resolvers){let resolved;try{resolved=resolver(command,context)}catch(error2){hadError=!0,onResolverError(error2);continue}if(resolved)return{hadError,resolved}}return{hadError}}function queryLayerCommandEntries(options){let namespace=options.query?.namespace,normalizedSearch=options.query?.search?.trim().toLowerCase()??"",searchKeys=DEFAULT_COMMAND_SEARCH_FIELDS;if(options.query?.searchIn&&options.query.searchIn.length>0)searchKeys=options.query.searchIn;let filter=options.query?.filter,filterEntries2,filterPredicate;if(typeof filter==="function")filterPredicate=filter;else if(filter)filterEntries2=Object.entries(filter);let results=[];for(let entry2 of options.entries){let command=entry2.command;if(!commandMatchesNamespace(command,namespace))continue;if(!commandMatchesSearch(command,normalizedSearch,searchKeys))continue;if(!commandMatchesFilters(command,filterEntries2,options))continue;let record=options.getCommandRecord(command);if(filterPredicate){let matches=!1;try{matches=filterPredicate(record)}catch(error2){options.onFilterError(error2);continue}if(!matches)continue}results.push(entry2)}return results}function commandMatchesSearch(command,search,searchKeys){if(!search)return!0;for(let key of searchKeys)if(commandKeyMatchesSearch(command,key,search))return!0;return!1}function commandMatchesNamespace(command,namespace){if(namespace===void 0)return!0;if(!Object.prototype.hasOwnProperty.call(command.fields,"namespace"))return!1;return commandValueMatchesFilter(command.fields.namespace,namespace)}function commandMatchesFilters(command,filters,options){if(!filters)return!0;for(let[key,matcher]of filters)if(!commandKeyMatchesQuery(command,key,matcher,options))return!1;return!0}function commandKeyMatchesSearch(command,key,search){if(key==="name"&&commandValueMatchesSearch(command.name,search))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesSearch(command.fields[key],search))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesSearch(command.attrs[key],search);return!1}function commandKeyMatchesQuery(command,key,matcher,options){if(typeof matcher==="function"){let record,getRecord=()=>{if(!record)record=options.getCommandRecord(command);return record},foundValue=!1;if(key==="name"){foundValue=!0;try{if(matcher(command.name,getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(Object.prototype.hasOwnProperty.call(command.fields,key)){foundValue=!0;try{if(matcher(command.fields[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key)){foundValue=!0;try{if(matcher(command.attrs[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(!foundValue)try{return matcher(void 0,getRecord())}catch(error2){return options.onFilterError(error2),!1}return!1}return commandKeyMatchesExact(command,key,matcher)}function commandKeyMatchesExact(command,key,matcher){if(key==="name"&&commandValueMatchesFilter(command.name,matcher))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesFilter(command.fields[key],matcher))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesFilter(command.attrs[key],matcher);return!1}function commandValueMatchesFilter(value,matcher){if(Array.isArray(matcher)){for(let expected of matcher)if(commandValueMatchesExact(value,expected))return!0;return!1}return commandValueMatchesExact(value,matcher)}function commandValueMatchesExact(value,expected){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesExact(entry2,expected))return!0;return!1}return Object.is(value,expected)}function commandValueMatchesSearch(value,search){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesSearch(entry2,search))return!0;return!1}if(typeof value==="string")return value.toLowerCase().includes(search);if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return String(value).toLowerCase().includes(search);return!1}class CommandExecutorService{notify;runtime;activation;catalog;options;constructor(notify,runtime,activation,catalog,options){this.notify=notify,this.runtime=runtime,this.activation=activation,this.catalog=catalog,this.options=options}runCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chain=this.catalog.getRegisteredResolvedEntries(normalized,includeRecord),rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}let fallback=this.catalog.getRegisteredResolverFallback(normalized,includeRecord);if(fallback.resolved){let execution=this.executeResolvedCommand(normalized,fallback.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(fallback.hadError)return{ok:!1,reason:"error"};return rejectedResult??{ok:!1,reason:"not-found"}}dispatchCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chainLookup=this.catalog.getResolvedCommandChain(normalized,focused,includeRecord),chain=chainLookup.entries,rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(chainLookup.hadError)return{ok:!1,reason:"error"};let unavailable=this.catalog.getDispatchUnavailableCommandState(normalized,focused,includeRecord);if(unavailable)return unavailable.command?{ok:!1,reason:unavailable.reason,command:unavailable.command}:{ok:!1,reason:unavailable.reason};return rejectedResult??{ok:!1,reason:"not-found"}}runBinding(bindingLayer,binding,event,focused){let data=this.runtime.getReadonlyData();if(binding.run){if(this.executeResolvedCommand(typeof binding.command==="string"?binding.command:"<function>",{run:binding.run},{keymap:this.options.keymap,event,focused,target:bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects(binding,event),!0}if(typeof binding.command!=="string")return!1;let chain=this.catalog.getResolvedCommandChain(binding.command,focused,!1).entries;if(chain?.length===1){let[entry2]=chain;if(entry2){if(this.executeResolvedCommand(binding.command,entry2.resolved,{keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects(binding,event),!0}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data};if(this.executeResolvedCommand(binding.command,entry2.resolved,context).status==="rejected")continue;return applyBindingEventEffects(binding,event),!0}return!1}executeResolvedCommand(commandName,resolved,context){let command=resolved.record,result2;try{result2=resolved.run(context)}catch(error2){return this.notify.emitError("command-execution-error",error2,`[Keymap] Error running command "${commandName}":`),{status:"error",result:{ok:!1,reason:"error",command}}}if(isPromiseLike(result2))return result2.catch((error2)=>{this.notify.emitError("async-command-error",error2,`[Keymap] Async error in command "${commandName}":`)}),{status:"handled",result:{ok:!0,command}};if(result2===!1){if(resolved.rejectedResult)return{status:"rejected",result:resolved.rejectedResult};return{status:"rejected",result:{ok:!1,reason:"rejected",command}}}return{status:"handled",result:{ok:!0,command}}}}function applyBindingEventEffects(binding,event){if(!binding.preventDefault)return;event.preventDefault(),event.stopPropagation()}function normalizeBindingInputs(bindings){if(Array.isArray(bindings))return bindings;let normalized=[];for(let[key,cmd]of Object.entries(bindings)){if(typeof cmd!=="string"&&typeof cmd!=="function")throw Error(`Invalid keymap binding for "${key}": shorthand bindings must map to string or function commands`);normalized.push({key,cmd})}return normalized}function snapshotBindingInputs(bindings){return normalizeBindingInputs(bindings).map((binding)=>({...binding,key:typeof binding.key==="string"?binding.key:{...binding.key}}))}function snapshotParsedBindingInput(binding){return{...binding,sequence:cloneKeySequence(binding.sequence)}}function createSequenceNode(parent,stroke,match){return{parent,depth:parent?parent.depth+1:0,stroke,match,children:new Map,bindings:[],reachableBindings:[]}}function snapshotAttributes(attrs){if(Object.keys(attrs).length===0)return;return snapshotDataValue(attrs,{freeze:!0})}class CompilerService{state;notify;conditions;options;constructor(state,notify,conditions,options){this.state=state,this.notify=notify,this.conditions=conditions,this.options=options}parseTokenKey(key){return parseSingleKeyPartWithParsers(key,this.state.environment.bindingParsers.values(),{tokens:this.state.environment.tokens,layer:EMPTY_COMPILE_FIELDS,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})}compileBindings(bindings,tokens2,sourceTarget,sourceLayerOrder,compileFields){let root=createSequenceNode(null,null,null),compiledBindings=[],hasTokenBindings=!1,bindingExpanders=this.state.environment.bindingExpanders.values(),bindingParsers=this.state.environment.bindingParsers.values(),bindingFieldCompilers=this.state.environment.bindingFields,allowExactPrefixAmbiguity=this.state.dispatch.disambiguationResolvers.has(),warnUnknownField=this.options.warnUnknownField,warnUnknownToken=this.options.warnUnknownToken,conditions=this.conditions;for(let[bindingIndex,binding]of bindings.entries()){let expandedBindingKeys;try{expandedBindingKeys=expandBindingInputWithExpanders(binding.key,bindingExpanders,{layer:compileFields})}catch(error2){this.notify.emitError("binding-expand-error",error2,getErrorMessage(error2,"Failed to expand keymap binding"));continue}for(let expandedBindingKey of expandedBindingKeys){let parsed;try{parsed=typeof expandedBindingKey==="string"?parseBindingSequenceWithParsers(expandedBindingKey,bindingParsers,{tokens:tokens2,layer:compileFields,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)}):{parts:[this.parseObjectKeyPart(expandedBindingKey)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1}}catch(error2){this.notify.emitError("binding-parse-error",error2,getErrorMessage(error2,"Failed to parse keymap binding"));continue}let sequence=parsed.parts;hasTokenBindings||=parsed.hasTokenBindings;for(let tokenName of parsed.unknownTokens)warnUnknownToken(tokenName,typeof expandedBindingKey==="string"?expandedBindingKey:String(expandedBindingKey.name));for(let compiledInput of this.applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields))try{let event=this.normalizeBindingEvent(compiledInput.event),compiledSequence=compiledInput.sequence,mergedRequires,mergedAttrs,matchers,conditionKeys,hasUnkeyedMatchers=!1;for(let fieldName in compiledInput){if(fieldName==="sequence")continue;if(RESERVED_BINDING_FIELDS.has(fieldName))continue;let value=compiledInput[fieldName];if(value===void 0)continue;let compiler=bindingFieldCompilers.get(fieldName);if(!compiler){warnUnknownField("binding",fieldName);continue}compiler(value,{require(name,requiredValue){if(!mergedRequires)mergedRequires={};if(mergeRequirement(mergedRequires,name,requiredValue,`field ${fieldName}`),!conditionKeys)conditionKeys=new Set;conditionKeys.add(name)},attr(name,attributeValue){if(!mergedAttrs)mergedAttrs={};mergeAttribute(mergedAttrs,name,attributeValue,`field ${fieldName}`)},activeWhen:(matcher)=>{let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;if(!matchers)matchers=[];matchers.push(runtimeMatcher)}})}let attrs=mergedAttrs?snapshotAttributes(mergedAttrs):void 0,command=normalizeBindingCommand(compiledInput.cmd),compiledBinding={sequence:compiledSequence,command,event,sourceBinding:snapshotParsedBindingInput(compiledInput),sourceTarget,sourceLayerOrder,sourceBindingIndex:bindingIndex,requires:mergedRequires?Object.entries(mergedRequires):EMPTY_REQUIRES,matchers:matchers??EMPTY_MATCHERS,conditionKeys:conditionKeys?[...conditionKeys]:EMPTY_CONDITION_KEYS,hasUnkeyedMatchers,matchCacheDirty:!0,preventDefault:compiledInput.preventDefault!==!1,fallthrough:compiledInput.fallthrough??!1};if(attrs)compiledBinding.attrs=attrs;if(typeof command==="function")compiledBinding.run=command;if(compiledSequence.length===0)continue;if(event==="release"&&compiledSequence.length>1)throw Error("Keymap release bindings only support a single key stroke");if(event==="press")this.insertBinding(root,compiledBinding,allowExactPrefixAmbiguity);compiledBindings.push(compiledBinding)}catch(error2){this.notify.emitError("binding-compile-error",error2,getErrorMessage(error2,"Failed to compile keymap binding"))}}}return{root,bindings:compiledBindings,hasTokenBindings}}parseObjectKeyPart(key,options){return createKeySequencePart(key,options)}normalizeBindingEvent(event){if(event===void 0||event==="press")return"press";if(event==="release")return"release";throw Error(`Invalid keymap binding event "${String(event)}": expected "press" or "release"`)}applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields){let bindingTransformers=this.state.environment.bindingTransformers.values();if(bindingTransformers.length===0)return[{...binding,sequence:cloneKeySequence(sequence)}];let parsedBinding={...binding,sequence:cloneKeySequence(sequence)},extraBindings=[],keepOriginal=!0,layer=compileFields??EMPTY_COMPILE_FIELDS;for(let transformer of bindingTransformers)try{transformer(parsedBinding,{layer,parseKey:(key)=>{return parseSingleKeyPartWithParsers(key,bindingParsers,{tokens:tokens2,layer,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})},add:(nextBinding)=>{extraBindings.push(snapshotParsedBindingInput(nextBinding))},skipOriginal:()=>{keepOriginal=!1}})}catch(error2){this.notify.emitError("binding-transformer-error",error2,"[Keymap] Error in binding transformer:")}if(!keepOriginal)return extraBindings;if(extraBindings.length===0)return[parsedBinding];return[parsedBinding,...extraBindings]}insertBinding(root,binding,allowExactPrefixAmbiguity){let node=root,touchedNodes=[],createdNodes=[];try{for(let part of binding.sequence){if(!allowExactPrefixAmbiguity&&node.bindings.some((candidate)=>candidate.command!==void 0))throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");let bindingKey=part.match,child=node.children.get(bindingKey);if(!child)child=createSequenceNode(node,cloneKeySequencePart(part).stroke,part.match),node.children.set(bindingKey,child),createdNodes.push({parent:node,key:bindingKey});child.reachableBindings.push(binding),touchedNodes.push(child),node=child}if(!allowExactPrefixAmbiguity&&binding.command!==void 0&&node.children.size>0)throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");node.bindings=[...node.bindings,binding]}catch(error2){for(let index=touchedNodes.length-1;index>=0;index-=1){let touchedNode=touchedNodes[index];if(!touchedNode)continue;if(touchedNode.reachableBindings.at(-1)===binding){touchedNode.reachableBindings.pop();continue}touchedNode.reachableBindings=touchedNode.reachableBindings.filter((candidate)=>candidate!==binding)}for(let index=createdNodes.length-1;index>=0;index-=1){let createdNode=createdNodes[index];if(!createdNode)continue;let child=createdNode.parent.children.get(createdNode.key);if(!child)continue;if(child.children.size>0||child.reachableBindings.length>0||child.bindings.length>0)continue;createdNode.parent.children.delete(createdNode.key)}throw error2}}}function expandBindingInputWithExpanders(key,expanders,options){if(typeof key!=="string"||expanders.length===0)return[key];let layer=options?.layer??EMPTY_COMPILE_FIELDS,candidates=[key];for(let expander of expanders){let nextCandidates=[];for(let input of candidates){let result2=expander({input,layer});if(!result2){nextCandidates.push(input);continue}if(result2.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${input}"`);for(let expandedInput of result2){if(typeof expandedInput!=="string")throw Error(`Keymap binding expander must return string key sequences for "${input}"`);nextCandidates.push(expandedInput)}}candidates=nextCandidates}return candidates}function parseBindingSequenceWithParsers(key,parsers2,options){if(key.length===0)throw Error("Invalid key sequence: sequence cannot be empty");if(parsers2.length===0)throw Error("No keymap binding parsers are registered");let tokens2=options.tokens??new Map,layer=options.layer??EMPTY_COMPILE_FIELDS,parseObjectKey=options.parseObjectKey,parts=[],usedTokens=new Set,unknownTokens=new Set,index=0;while(index<key.length){let matched=!1;for(let parser of parsers2){let result2=parser({input:key,index,layer,tokens:tokens2,normalizeTokenName:normalizeBindingTokenName,createMatch:createTextKeyMatch,parseObjectKey});if(!result2)continue;if(result2.nextIndex<=index||result2.nextIndex>key.length)throw Error(`Keymap binding parser must advance the input for "${key}" at index ${index}`);parts.push(...result2.parts);for(let tokenName of result2.usedTokens??[])usedTokens.add(tokenName);for(let tokenName of result2.unknownTokens??[])unknownTokens.add(tokenName);index=result2.nextIndex,matched=!0;break}if(!matched)throw Error(`No keymap binding parser handled input at index ${index} in "${key}"`)}return{parts,usedTokens:[...usedTokens],unknownTokens:[...unknownTokens],hasTokenBindings:usedTokens.size>0||unknownTokens.size>0}}function parseSingleKeyPartWithParsers(key,parsers2,options){if(typeof key!=="string")return options.parseObjectKey(key);let{parts}=parseBindingSequenceWithParsers(key,parsers2,options),[part]=parts;if(!part||parts.length!==1)throw Error(`Invalid key "${String(key)}": expected a single key stroke`);return part}function isReactiveMatcher(value){if(!value||typeof value!=="object")return!1;let candidate=value;return typeof candidate.get==="function"&&typeof candidate.subscribe==="function"}class ConditionService{state;notify;constructor(state,notify){this.state=state,this.notify=notify}buildRuntimeMatcher(matcher,source){if(typeof matcher==="function")return{source,match:matcher,cacheable:!1};if(isReactiveMatcher(matcher))return{source,match:()=>matcher.get(),cacheable:!0,subscribe:(onChange)=>matcher.subscribe(onChange)};throw Error(`Keymap ${source} expected a function or a reactive matcher`)}hasNoConditions(target){return target.requires.length===0&&target.matchers.length===0}indexRuntimeMatchable(target){if(target.conditionKeys.length>0)for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(dependents){dependents.add(target);continue}this.state.conditions.runtimeKeyDependents.set(key,new Set([target]))}if(!target.hasUnkeyedMatchers)target.matchCacheDirty=!0}unindexRuntimeMatchable(target){if(target.conditionKeys.length===0)return;for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(!dependents)continue;if(dependents.delete(target),dependents.size===0)this.state.conditions.runtimeKeyDependents.delete(key)}}invalidateRuntimeConditionKey(name){let dependents=this.state.conditions.runtimeKeyDependents.get(name);if(!dependents)return;for(let target of dependents)target.matchCacheDirty=!0}matchesConditions(target){if(this.hasNoConditions(target))return!0;if(this.hasFreshConditionCache(target))return target.matchCache===!0;let matched=this.matchRequirements(target.requires)&&this.matchesRuntimeMatchers(target);return this.updateConditionCache(target,matched),matched}layerMatchesRuntimeState(layer){if(this.state.layers.layersWithConditions===0||this.hasNoConditions(layer))return!0;return this.matchesConditions(layer)}matchRequirements(requires){if(requires.length===0)return!0;for(let[name,value]of requires)if(!Object.is(this.state.runtime.data[name],value))return!1;return!0}hasFreshConditionCache(target){if(target.hasUnkeyedMatchers)return!1;return target.matchCacheDirty!==!0&&target.matchCache!==void 0}updateConditionCache(target,matched){if(target.hasUnkeyedMatchers)return;target.matchCacheDirty=!1,target.matchCache=matched}matchesRuntimeMatcher(matcher){try{return matcher.match()}catch(error2){return this.notify.emitError("runtime-matcher-error",error2,`[Keymap] Error evaluating runtime matcher from ${matcher.source}:`),!1}}matchesRuntimeMatchers(target){if(target.matchers.length===0)return!0;if(target.matchers.length===1){let[matcher]=target.matchers;return matcher?this.matchesRuntimeMatcher(matcher):!0}for(let matcher of target.matchers)if(!this.matchesRuntimeMatcher(matcher))return!1;return!0}}function createSyncDecision(action,handler){return{[KEY_DISAMBIGUATION_DECISION]:!0,action,handler}}function createDeferredDecision(action){return{[KEY_DEFERRED_DISAMBIGUATION_DECISION]:!0,action}}function isSyncDecision(value){return!!value&&typeof value==="object"&&value[KEY_DISAMBIGUATION_DECISION]===!0}function isDeferredDecision(value){return!!value&&typeof value==="object"&&value[KEY_DEFERRED_DISAMBIGUATION_DECISION]===!0}class DispatchService{state;notify;runtime;activation;conditions;executor;compiler;catalog;layers;eventMatchResolverContext;pendingDisambiguation=null;nextPendingDisambiguationId=0;constructor(state,notify,runtime,activation,conditions,executor,compiler,catalog,layers){this.state=state,this.notify=notify,this.runtime=runtime,this.activation=activation,this.conditions=conditions,this.executor=executor,this.compiler=compiler,this.catalog=catalog,this.layers=layers,this.eventMatchResolverContext={resolveKey:(key)=>{return this.compiler.parseTokenKey(key).match}}}intercept(name,fn,options){if(name==="key"){let keyOptions=options;return this.state.dispatch.keyHooks.register(fn,{priority:keyOptions?.priority??0,release:keyOptions?.release??!1})}let rawOptions=options;return this.state.dispatch.rawHooks.register(fn,{priority:rawOptions?.priority??0})}prependEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.prepend(resolver)}appendEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.append(resolver)}clearEventMatchResolvers(){this.state.dispatch.eventMatchResolvers.clear()}prependDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.prepend(resolver),resolver)}appendDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.append(resolver),resolver)}clearDisambiguationResolvers(){if(!this.state.dispatch.disambiguationResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.dispatch.disambiguationResolvers.clear(),this.layers.recompileBindings()})}handlePendingSequenceChange(_previous,_next){if(!this.pendingDisambiguation)return;this.cancelPendingDisambiguation()}handleRawSequence(sequence){let hooks=this.state.dispatch.rawHooks.entries();if(hooks.length===0)return!1;let stopped=!1,context={sequence,stop(){stopped=!0}};for(let hook of hooks){try{hook.listener(context)}catch(error2){this.notify.emitError("raw-intercept-error",error2,"[Keymap] Error in raw intercept listener:")}if(stopped)return!0}return!1}handleKeyEvent(event,release){if(!release)this.cancelPendingDisambiguation();let hooks=this.state.dispatch.keyHooks.entries(),context={event,setData:(name,value)=>{this.runtime.setData(name,value)},getData:(name)=>{return this.runtime.getData(name)},consume:(options)=>{let shouldPreventDefault=options?.preventDefault??!0,shouldStopPropagation=options?.stopPropagation??!0;if(shouldPreventDefault)event.preventDefault();if(shouldStopPropagation)event.stopPropagation()}};for(let hook of hooks){if(hook.release!==release)continue;try{hook.listener(context)}catch(error2){this.notify.emitError("key-intercept-error",error2,"[Keymap] Error in key intercept listener:")}if(event.propagationStopped)return}if(release){this.dispatchReleaseLayers(event);return}this.dispatchLayers(event)}mutateDisambiguationResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let hadResolvers=this.state.dispatch.disambiguationResolvers.has(),off=register2();if(!hadResolvers&&this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings();return()=>{this.notify.runWithStateChangeBatch(()=>{let hadBeforeRemoval=this.state.dispatch.disambiguationResolvers.has();if(off(),this.state.dispatch.disambiguationResolvers.values().includes(resolver))return;if(hadBeforeRemoval&&!this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings()})}})}dispatchReleaseLayers(event){let focused=this.activation.getFocusedTarget(),activeLayers=this.activation.getActiveLayers(focused),hasLayerConditions=this.state.layers.layersWithConditions>0,matchKeys=this.resolveEventMatchKeys(event);layerLoop:for(let layer of activeLayers){if(layer.compiledBindings.length===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let strokeKey of matchKeys){let result2=this.runReleaseBindings(layer,strokeKey,event,focused);if(!result2.handled)continue;if(result2.stop)return;continue layerLoop}}}dispatchLayers(event){let focused=this.activation.getFocusedTarget(),pending=this.activation.ensureValidPendingSequence(),matchKeys=this.resolveEventMatchKeys(event);if(pending){this.dispatchPendingSequence(pending,matchKeys,event,focused);return}let activeLayers=this.activation.getActiveLayers(focused);this.dispatchFromRoot(activeLayers,matchKeys,event,focused)}dispatchPendingSequence(pending,matchKeys,event,focused){let advancedCaptures=[];for(let capture2 of pending.captures){let nextNode=this.getReachableChild(capture2.node,matchKeys,focused);if(!nextNode)continue;advancedCaptures.push({layer:capture2.layer,node:nextNode})}if(advancedCaptures.length===0){this.activation.setPendingSequence(null);return}this.dispatchPendingCapturesFromIndex(advancedCaptures,0,!1,event,focused)}dispatchPendingCapturesFromIndex(advancedCaptures,startIndex,handledExact,event,focused){let hasHandledExact=handledExact;for(let index=startIndex;index<advancedCaptures.length;index+=1){let capture2=advancedCaptures[index];if(!capture2)continue;if(capture2.node.children.size>0){if(hasHandledExact)continue;let continuationCaptures=this.collectPendingCapturesFromAdvanced(advancedCaptures,index);if(this.tryResolvePendingAmbiguity(advancedCaptures,index,continuationCaptures,capture2,event,focused,hasHandledExact))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(!result2.handled)continue;if(hasHandledExact=!0,result2.stop){this.activation.setPendingSequence(null);return}}this.activation.setPendingSequence(null)}dispatchFromRoot(activeLayers,matchKeys,event,focused){this.dispatchFromRootAtIndex(activeLayers,0,matchKeys,event,focused)}dispatchFromRootAtIndex(activeLayers,startIndex,matchKeys,event,focused){let hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer)continue;if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode)continue;if(nextNode.children.size>0){let continuationCaptures=this.collectPendingCapturesFromRoot(activeLayers,index,matchKeys,focused);if(this.tryResolveRootAmbiguity(activeLayers,index,matchKeys,continuationCaptures,layer,nextNode,event,focused))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(layer,nextNode.bindings,event,focused);if(!result2.handled)continue;if(result2.stop)return}}tryResolveRootAmbiguity(activeLayers,layerIndex,matchKeys,continuationCaptures,layer,node,event,focused){let applyExact=()=>{if(this.activation.setPendingSequence(null),!this.runBindings(layer,node.bindings,event,focused).stop)this.dispatchFromRootAtIndex(activeLayers,layerIndex+1,matchKeys,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:node.bindings,runExact:applyExact})}tryResolvePendingAmbiguity(advancedCaptures,captureIndex,continuationCaptures,capture2,event,focused,handledExact){let applyExact=()=>{this.activation.setPendingSequence(null);let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(result2.stop)return;this.dispatchPendingCapturesFromIndex(advancedCaptures,captureIndex+1,handledExact||result2.handled,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:capture2.node.bindings,runExact:applyExact})}tryResolveAmbiguity(options){let{event,focused,continuationCaptures,exactBindingsSource,runExact}=options;if(!this.state.dispatch.disambiguationResolvers.has()||continuationCaptures.length===0)return!1;let activeView=this.catalog.getActiveCommandView(focused),exactBindings=this.activation.collectMatchingBindings(exactBindingsSource,focused,activeView);if(!exactBindings.some((binding)=>binding.command!==void 0))return!1;let continueSequence=()=>{this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation()},clear=()=>{this.activation.setPendingSequence(null),event.preventDefault(),event.stopPropagation()},sequence,getSequence=()=>{return sequence??=this.activation.collectSequencePartsFromPending({captures:continuationCaptures}),sequence},decision=this.resolveDisambiguation({event,focused,getSequence,exactBindings,continuationCaptures,activeView});if(!decision)return this.warnUnresolvedAmbiguity(getSequence()),continueSequence(),!0;return this.applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence)}applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence){if(decision.action==="run-exact")return runExact(),!0;if(decision.action==="continue-sequence")return continueSequence(),!0;if(decision.action==="clear")return clear(),!0;return continueSequence(),this.scheduleDeferredDisambiguation(continuationCaptures,decision.handler,focused,getSequence(),(nextDecision)=>{if(!nextDecision)return;if(nextDecision.action==="run-exact"){runExact();return}if(nextDecision.action==="continue-sequence"){continueSequence();return}clear()}),!0}resolveDisambiguation(options){let activation=this.activation,runtime=this.runtime,sequence,exact,continuations,strokePart,ctx={event:options.event,focused:options.focused,get sequence(){return sequence??=cloneKeySequence(options.getSequence()),sequence},get stroke(){let stroke=options.getSequence().at(-1);if(!stroke)throw Error("Disambiguation context expected a non-empty sequence");return strokePart??={...stroke,stroke:cloneKeyStroke(stroke.stroke)},strokePart},get exact(){return exact??=activation.collectActiveBindings(options.exactBindings,options.focused,options.activeView).map((binding)=>({...binding,sequence:cloneKeySequence(binding.sequence)})),exact},get continuations(){return continuations??=activation.getActiveKeysForCaptures(options.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),continuations},getData:(name)=>{return runtime.getData(name)},setData:(name,value)=>{runtime.setData(name,value)},runExact:()=>createSyncDecision("run-exact"),continueSequence:()=>createSyncDecision("continue-sequence"),clear:()=>createSyncDecision("clear"),defer:(run)=>createSyncDecision("defer",run)};for(let resolver of this.state.dispatch.disambiguationResolvers.values()){let result2;try{result2=resolver(ctx)}catch(error2){this.notify.emitError("disambiguation-resolver-error",error2,"[Keymap] Error in disambiguation resolver:");continue}if(result2===void 0)continue;if(isPromiseLike(result2)){this.notify.emitError("invalid-disambiguation-resolver-return",result2,"[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling");continue}if(!isSyncDecision(result2)){this.notify.emitError("invalid-disambiguation-decision",result2,"[Keymap] Invalid disambiguation decision returned by resolver:");continue}return result2}return}scheduleDeferredDisambiguation(captures,handler,focused,sequence,apply){this.cancelPendingDisambiguation();let controller=new AbortController,pending={id:this.nextPendingDisambiguationId++,controller,captures,apply};this.pendingDisambiguation=pending,queueMicrotask(()=>{this.executeDeferredDisambiguation(pending,handler,focused,sequence)})}executeDeferredDisambiguation(pending,handler,focused,sequence){if(!this.isPendingDisambiguationCurrent(pending))return;let ctx={signal:pending.controller.signal,sequence:cloneKeySequence(sequence),focused,sleep:(ms)=>{return this.sleepWithSignal(ms,pending.controller.signal)},runExact:()=>createDeferredDecision("run-exact"),continueSequence:()=>createDeferredDecision("continue-sequence"),clear:()=>createDeferredDecision("clear")},result2;try{result2=handler(ctx)}catch(error2){if(this.isPendingDisambiguationCurrent(pending))this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending);return}if(isPromiseLike(result2)){result2.then((resolved)=>{this.applyDeferredDisambiguationResult(pending,resolved)}).catch((error2)=>{if(!this.isPendingDisambiguationCurrent(pending))return;this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending)});return}this.applyDeferredDisambiguationResult(pending,result2)}applyDeferredDisambiguationResult(pending,result2){if(!this.isPendingDisambiguationCurrent(pending))return;if(result2!==void 0&&!isDeferredDecision(result2)){this.notify.emitError("invalid-deferred-disambiguation-decision",result2,"[Keymap] Invalid deferred disambiguation decision returned by handler:"),this.finishPendingDisambiguation(pending);return}this.finishPendingDisambiguation(pending),pending.apply(result2)}finishPendingDisambiguation(pending){if(!this.isPendingDisambiguationCurrent(pending))return;this.pendingDisambiguation=null}cancelPendingDisambiguation(){let pending=this.pendingDisambiguation;if(!pending)return;this.pendingDisambiguation=null,pending.controller.abort()}isPendingDisambiguationCurrent(pending){return this.pendingDisambiguation===pending}sleepWithSignal(ms,signal){if(signal.aborted)return Promise.resolve(!1);return new Promise((resolve21)=>{let timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve21(!0)},Math.max(0,ms)),onAbort=()=>{clearTimeout(timeout),signal.removeEventListener("abort",onAbort),resolve21(!1)};signal.addEventListener("abort",onAbort,{once:!0})})}warnUnresolvedAmbiguity(sequence){let display=stringifyKeySequence(sequence,{preferDisplay:!0});this.notify.warnOnce(`unresolved-disambiguation:${display}`,"unresolved-disambiguation",{sequence:display},`[Keymap] Ambiguous exact/prefix sequence "${display}" fell back to prefix handling because no disambiguation resolver resolved it`)}collectPendingCapturesFromRoot(activeLayers,startIndex,matchKeys,focused){let captures=[],hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer||layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode||nextNode.children.size===0)continue;captures.push({layer,node:nextNode})}return captures}collectPendingCapturesFromAdvanced(advancedCaptures,startIndex){return advancedCaptures.filter((candidate,candidateIndex)=>{return candidateIndex>=startIndex&&candidate.node.children.size>0})}resolveEventMatchKeys(event){let resolvers=this.state.dispatch.eventMatchResolvers.values();if(resolvers.length===0)return[];if(resolvers.length===1)return resolveSingleEventMatchKeys(resolvers[0],event,this.eventMatchResolverContext,this.notify);let keys=[],seen=new Set;for(let resolver of resolvers){let resolved;try{resolved=resolver(event,this.eventMatchResolverContext)}catch(error2){this.notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:");continue}if(!resolved||resolved.length===0)continue;for(let candidate of resolved){if(typeof candidate!=="string"){this.notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}}return keys}runReleaseBindings(layer,strokeKey,event,focused){let handled=!1;for(let binding of layer.compiledBindings){if(binding.event!=="release")continue;let firstPart=binding.sequence[0];if(!firstPart||firstPart.match!==strokeKey)continue;if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}getReachableChild(node,matchKeys,focused){for(let strokeKey of matchKeys){let child=node.children.get(strokeKey);if(!child||!this.activation.nodeHasReachableBindings(child,focused))continue;return child}return}runBindings(layer,bindings,event,focused){let handled=!1;for(let binding of bindings){if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}}function resolveSingleEventMatchKeys(resolver,event,ctx,notify){let resolved;try{resolved=resolver(event,ctx)}catch(error2){return notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:"),[]}if(!resolved||resolved.length===0)return[];if(resolved.length===1){let[candidate]=resolved;if(typeof candidate!=="string")return notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:"),[];return[candidate]}let keys=[],seen=new Set;for(let candidate of resolved){if(typeof candidate!=="string"){notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}return keys}function registerFieldCompilers(fields,options){let{kind,reservedFields,registeredFields,emitError}=options,entries=Object.entries(fields),registered=[];for(let[name]of entries){if(reservedFields.has(name)){emitError(`reserved-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is reserved`);continue}if(registeredFields.has(name))emitError(`duplicate-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is already registered`)}for(let[name,compiler]of entries){if(reservedFields.has(name)||registeredFields.has(name))continue;registeredFields.set(name,compiler),registered.push([name,compiler])}return()=>{for(let[name,compiler]of registered)if(registeredFields.get(name)===compiler)registeredFields.delete(name)}}class EnvironmentService{state;notify;compiler;layers;constructor(state,notify,compiler,layers){this.state=state,this.notify=notify,this.compiler=compiler,this.layers=layers}prependBindingTransformer(transformer){return this.state.environment.bindingTransformers.prepend(transformer)}appendBindingTransformer(transformer){return this.state.environment.bindingTransformers.append(transformer)}clearBindingTransformers(){this.state.environment.bindingTransformers.clear()}prependBindingParser(parser){return this.state.environment.bindingParsers.prepend(parser)}appendBindingParser(parser){return this.state.environment.bindingParsers.append(parser)}clearBindingParsers(){this.state.environment.bindingParsers.clear()}registerToken(token){let normalizedToken;try{normalizedToken=normalizeBindingTokenName(token.name)}catch(error2){return this.notify.emitError("token-name-normalize-error",error2,getErrorMessage(error2,"Failed to register keymap token")),NOOP}if(this.state.environment.tokens.has(normalizedToken))return this.notify.emitError("duplicate-token",{token:normalizedToken},`Keymap token "${normalizedToken}" is already registered`),NOOP;let parsedToken;try{parsedToken=this.compiler.parseTokenKey(token.key)}catch(error2){return this.notify.emitError("token-parse-error",error2,getErrorMessage(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP}let registeredToken={stroke:parsedToken.stroke,match:parsedToken.match},nextTokens=new Map(this.state.environment.tokens);nextTokens.set(normalizedToken,registeredToken);try{this.layers.applyTokenState(nextTokens)}catch(error2){return this.notify.emitError("token-register-error",error2,getErrorMessage(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP}return()=>{if(this.state.environment.tokens.get(normalizedToken)!==registeredToken)return;let nextTokens2=new Map(this.state.environment.tokens);nextTokens2.delete(normalizedToken);try{this.layers.applyTokenState(nextTokens2)}catch(error2){this.notify.emitError("token-unregister-error",error2,getErrorMessage(error2,`Failed to unregister keymap token "${normalizedToken}"`))}}}prependBindingExpander(expander){return this.state.environment.bindingExpanders.prepend(expander)}appendBindingExpander(expander){return this.state.environment.bindingExpanders.append(expander)}clearBindingExpanders(){this.state.environment.bindingExpanders.clear()}registerLayerFields(fields){return registerFieldCompilers(fields,{kind:"layer",reservedFields:RESERVED_LAYER_FIELDS,registeredFields:this.state.environment.layerFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerBindingFields(fields){return registerFieldCompilers(fields,{kind:"binding",reservedFields:RESERVED_BINDING_FIELDS,registeredFields:this.state.environment.bindingFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerCommandFields(fields){return registerFieldCompilers(fields,{kind:"command",reservedFields:RESERVED_COMMAND_FIELDS,registeredFields:this.state.environment.commandFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}}function sortLayers(layers){return[...layers].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return right.order-left.order})}function createCommandLookup(commands){if(commands.length===0)return;let lookup=new Map;for(let command of commands)lookup.set(command.name,command);return lookup}function addRegisteredCommandNames(target,commands){for(let command of commands)target.set(command.name,(target.get(command.name)??0)+1)}function removeRegisteredCommandNames(target,commands){for(let command of commands){let count=target.get(command.name);if(!count||count<=1){target.delete(command.name);continue}target.set(command.name,count-1)}}function getSequenceNode(root,sequence){let node=root;for(let part of sequence)if(node=node.children.get(part.match),!node)return;return node}function buildLayerBindingAnalyses(root,compiledBindings){return compiledBindings.map((binding)=>{let node=binding.event==="press"?getSequenceNode(root,binding.sequence):void 0;return{sequence:cloneKeySequence(binding.sequence),command:binding.command,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough,sourceBinding:snapshotParsedBindingInput(binding.sourceBinding),sourceTarget:binding.sourceTarget,sourceLayerOrder:binding.sourceLayerOrder,sourceBindingIndex:binding.sourceBindingIndex,hasCommandAtSequence:node?node.bindings.some((candidate)=>candidate.command!==void 0):!1,hasContinuations:node?node.children.size>0:!1}})}class LayerService{state;notify;conditions;activation;options;constructor(state,notify,conditions,activation,options){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation,this.options=options}registerLayer(layer){return this.notify.runWithStateChangeBatch(()=>{let target=layer.target;if(target&&this.options.host.isTargetDestroyed(target))return this.notify.emitError("destroyed-layer-target",{target},"Cannot register a keymap layer for a destroyed keymap target"),NOOP2;let bindingInputs,requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields,commands,commandLookup,targetMode;try{targetMode=this.normalizeTargetMode(layer),bindingInputs=snapshotBindingInputs(layer.bindings??[]),commands=!layer.commands||layer.commands.length===0?[]:this.options.commands.normalizeCommands(layer.commands),commandLookup=createCommandLookup(commands),{requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields}=this.compileLayerRuntimeState(layer)}catch(error2){return this.notify.emitError("register-layer-failed",error2,getErrorMessage(error2,"Failed to register keymap layer")),NOOP2}let order=this.state.core.order++,compiledBindings=this.options.compiler.compileBindings(bindingInputs,this.state.environment.tokens,target,order,compileFields);if(compiledBindings.bindings.length===0&&!compiledBindings.hasTokenBindings&&commands.length===0)return NOOP2;this.runLayerAnalyzers({target,order,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,root:compiledBindings.root,hasTokenBindings:compiledBindings.hasTokenBindings});let registeredLayer={order,target,targetMode,priority:layer.priority??0,requires,matchers,conditionKeys,hasUnkeyedMatchers,matchCacheDirty:!0,compileFields,commands,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,hasUnkeyedCommands:commands.some((command)=>command.hasUnkeyedMatchers),hasUnkeyedBindings:compiledBindings.bindings.some((binding)=>binding.hasUnkeyedMatchers),hasTokenBindings:compiledBindings.hasTokenBindings,root:compiledBindings.root};if(this.state.layers.layers.add(registeredLayer),registeredLayer.commands.length>0)this.state.layers.layersWithCommands+=1,this.state.commands.commandMetadataVersion+=1,addRegisteredCommandNames(this.state.commands.registeredNames,registeredLayer.commands);if(registeredLayer.requires.length>0||registeredLayer.matchers.length>0)this.state.layers.layersWithConditions+=1;this.connectRuntimeMatchable(registeredLayer);for(let command of registeredLayer.commands)this.connectRuntimeMatchable(command);for(let binding of registeredLayer.compiledBindings)this.connectRuntimeMatchable(binding);if(this.indexLayer(registeredLayer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),target){let onTargetDestroy=()=>{this.unregisterLayer(registeredLayer)};registeredLayer.offTargetDestroy=this.options.host.onTargetDestroy(target,onTargetDestroy)}if(registeredLayer.commands.length>0)this.activation.ensureValidPendingSequence();return this.notify.queueStateChange(),()=>{this.unregisterLayer(registeredLayer)}})}applyTokenState(nextTokens){this.notify.runWithStateChangeBatch(()=>{let nextCompilations=new Map;for(let layer of this.state.layers.layers){if(!layer.hasTokenBindings)continue;nextCompilations.set(layer,this.compileLayerBindings(layer,nextTokens))}this.state.environment.tokens=nextTokens;let shouldClearPending=!1;for(let[layer,compilation]of nextCompilations)if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;if(shouldClearPending)this.activation.setPendingSequence(null);if(nextCompilations.size>0)this.notify.queueStateChange()})}recompileBindings(){this.notify.runWithStateChangeBatch(()=>{let recompiledLayers=0,shouldClearPending=!1;for(let layer of this.state.layers.layers){if(layer.bindingInputs.length===0)continue;let compilation=this.compileLayerBindings(layer,this.state.environment.tokens);if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;recompiledLayers+=1}if(shouldClearPending)this.activation.setPendingSequence(null);if(recompiledLayers>0)this.notify.queueStateChange()})}prependLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.prepend(analyzer)}appendLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.append(analyzer)}clearLayerAnalyzers(){this.state.layers.layerAnalyzers.clear()}cleanup(){for(let layer of this.state.layers.layers){this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0}}normalizeTargetMode(layer){if(layer.targetMode){if(!layer.target)throw Error(`Keymap targetMode "${layer.targetMode}" requires a target`);return layer.targetMode}return layer.target?"focus-within":void 0}runLayerAnalyzers(options){let analyzers=this.state.layers.layerAnalyzers.values();if(analyzers.length===0)return;let bindings=buildLayerBindingAnalyses(options.root,options.compiledBindings),ctx={target:options.target,order:options.order,bindingInputs:options.bindingInputs,bindings,hasTokenBindings:options.hasTokenBindings,checkCommandResolution:(command)=>{return this.options.commands.getCommandResolutionStatus(command,options.commandLookup)},warn:(code,warning,message)=>{this.notify.emitWarning(code,warning,message)},warnOnce:(key,code,warning,message)=>{this.notify.warnOnce(key,code,warning,message)},error:(code,error2,message)=>{this.notify.emitError(code,error2,message)}};for(let analyzer of analyzers)try{analyzer(ctx)}catch(error2){this.notify.emitError("layer-analyzer-error",error2,"[Keymap] Error in layer analyzer:")}}compileLayerRuntimeState(layer){let mergedRequires={},matchers=[],compileFields=Object.create(null),conditionKeys=new Set,hasUnkeyedMatchers=!1;for(let[fieldName,value]of Object.entries(layer)){if(RESERVED_LAYER_FIELDS.has(fieldName))continue;if(value===void 0)continue;compileFields[fieldName]=snapshotDataValue(value);let compiler=this.state.environment.layerFields.get(fieldName);if(!compiler){this.options.warnUnknownField("layer",fieldName);continue}compiler(value,{require:(name,requiredValue)=>{mergeRequirement(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},activeWhen:(matcher)=>{let runtimeMatcher=this.conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;matchers.push(runtimeMatcher)}})}return{requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,compileFields:Object.keys(compileFields).length>0?Object.freeze(compileFields):void 0}}compileLayerBindings(layer,tokens2){return this.options.compiler.compileBindings(layer.bindingInputs,tokens2,layer.target,layer.order,layer.compileFields)}applyCompiledBindings(layer,compilation){this.runLayerAnalyzers({target:layer.target,order:layer.order,commandLookup:layer.commandLookup,bindingInputs:layer.bindingInputs,compiledBindings:compilation.bindings,root:compilation.root,hasTokenBindings:compilation.hasTokenBindings});for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.root=compilation.root,layer.compiledBindings=compilation.bindings,layer.hasUnkeyedBindings=compilation.bindings.some((binding)=>binding.hasUnkeyedMatchers),layer.hasTokenBindings=compilation.hasTokenBindings;for(let binding of layer.compiledBindings)this.connectRuntimeMatchable(binding);return this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer)??!1}indexLayer(layer){this.state.layers.sortedLayers=sortLayers([...this.state.layers.sortedLayers,layer]),this.state.layers.activeLayersVersion+=1}removeLayerFromIndex(layer){this.state.layers.sortedLayers=this.state.layers.sortedLayers.filter((candidate)=>candidate!==layer),this.state.layers.activeLayersVersion+=1}unregisterLayer(layer){this.notify.runWithStateChangeBatch(()=>{if(!this.state.layers.layers.delete(layer))return;if(layer.requires.length>0||layer.matchers.length>0)this.state.layers.layersWithConditions-=1;if(layer.commands.length>0)this.state.layers.layersWithCommands-=1,this.state.commands.commandMetadataVersion+=1,removeRegisteredCommandNames(this.state.commands.registeredNames,layer.commands);this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);if(this.removeLayerFromIndex(layer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0,this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer))this.activation.setPendingSequence(null);else if(layer.commands.length>0&&!this.options.host.isDestroyed)this.activation.ensureValidPendingSequence();this.notify.queueStateChange()})}connectRuntimeMatchable(target){this.attachReactiveMatchers(target),this.conditions.indexRuntimeMatchable(target)}disconnectRuntimeMatchable(target){this.detachReactiveMatchers(target),this.conditions.unindexRuntimeMatchable(target)}attachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.subscribe)continue;try{matcher.dispose=matcher.subscribe(()=>{if(target.matchCacheDirty=!0,!this.activation.hasPendingSequenceState()){this.notify.queueStateChange();return}this.notify.runWithStateChangeBatch(()=>{this.activation.revalidatePendingSequenceIfNeeded(),this.notify.queueStateChange()})})}catch(error2){this.notify.emitError("reactive-matcher-subscribe-error",error2,getErrorMessage(error2,`Failed to subscribe to reactive matcher from ${matcher.source}`))}}}detachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.dispose)continue;try{matcher.dispose()}catch(error2){this.notify.emitError("reactive-matcher-dispose-error",error2,getErrorMessage(error2,`Failed to dispose reactive matcher from ${matcher.source}`))}matcher.dispose=void 0}}}class Emitter2{onError;listeners=Object.create(null);constructor(onError){this.onError=onError}hook(name,listener){let current=this.listeners[name]??[];return this.listeners[name]=[...current,listener],()=>{let current2=this.listeners[name];if(!current2||current2.length===0)return;let next=current2.filter((candidate)=>candidate!==listener);if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}}has(name){return(this.listeners[name]?.length??0)>0}off(name,listener){let current=this.listeners[name];if(!current||current.length===0)return;let next=current.filter((candidate)=>candidate!==listener);if(next.length===current.length)return;if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}clear(){this.listeners=Object.create(null)}emit(name,...args){let listeners2=this.listeners[name];if(!listeners2||listeners2.length===0)return;for(let listener of listeners2)try{if(args.length===0)listener();else listener(args[0])}catch(error2){this.onError(name,error2)}}}class NotificationService{state;events;hooks;constructor(state,events,hooks){this.state=state,this.events=events,this.hooks=hooks}runWithStateChangeBatch(fn){this.state.notify.stateChangeDepth+=1;try{return fn()}finally{if(this.state.notify.stateChangeDepth-=1,this.state.notify.stateChangeDepth===0)this.flushStateChange()}}queueStateChange(){if(this.state.notify.derivedStateVersion+=1,!this.hooks.has("state"))return;if(this.state.notify.stateChangePending=!0,this.state.notify.stateChangeDepth===0&&!this.state.notify.flushingStateChange)this.flushStateChange()}emitWarning(code,warning,message){if(!this.events.has("warning")){let consoleMessage=`[${code}] ${message}`;if(warning instanceof Error)console.warn(consoleMessage,warning);else console.warn(consoleMessage);return}this.events.emit("warning",{code,message,warning})}emitError(code,error2,message){if(!this.events.has("error")){let consoleMessage=`[${code}] ${message}`;if(error2 instanceof Error)console.error(consoleMessage,error2);else console.error(consoleMessage);return}this.events.emit("error",{code,message,error:error2})}reportListenerError(name,error2){if(name==="state"){this.emitError("state-listener-error",error2,"[Keymap] Error in state listener:");return}if(name==="pendingSequence"){this.emitError("pending-sequence-listener-error",error2,"[Keymap] Error in pending sequence listener:");return}}warnOnce(key,code,warning,message){if(this.state.notify.usedWarningKeys.has(key))return;this.state.notify.usedWarningKeys.add(key),this.emitWarning(code,warning,message)}flushStateChange(){if(!this.state.notify.stateChangePending||this.state.notify.stateChangeDepth>0||this.state.notify.flushingStateChange)return;this.state.notify.flushingStateChange=!0;try{let iterations=0;while(this.state.notify.stateChangePending&&this.state.notify.stateChangeDepth===0){if(iterations>=MAX_STATE_CHANGE_FLUSH_ITERATIONS){this.state.notify.stateChangePending=!1,this.emitError("state-change-feedback-loop",{iterations:MAX_STATE_CHANGE_FLUSH_ITERATIONS},`[Keymap] Possible infinite state listener feedback loop detected after ${MAX_STATE_CHANGE_FLUSH_ITERATIONS} iterations; pending state notifications were dropped`);break}iterations+=1,this.state.notify.stateChangePending=!1,this.hooks.emit("state")}}finally{this.state.notify.flushingStateChange=!1}}}class RuntimeService{state;notify;conditions;activation;constructor(state,notify,conditions,activation){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation}getData(name){return this.state.runtime.data[name]}setData(name,value){this.notify.runWithStateChangeBatch(()=>{if(value===void 0){if(!(name in this.state.runtime.data))return;delete this.state.runtime.data[name],this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange();return}if(Object.is(this.state.runtime.data[name],value))return;this.state.runtime.data[name]=value,this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange()})}getReadonlyData(){if(this.state.runtime.readonlyDataVersion===this.state.runtime.dataVersion)return this.state.runtime.readonlyData;return this.state.runtime.readonlyData=Object.freeze({...this.state.runtime.data}),this.state.runtime.readonlyDataVersion=this.state.runtime.dataVersion,this.state.runtime.readonlyData}}class CopyOnWriteRegistry{items=[];getItems(){return this.items}setItems(items){this.items=items}removeItem(value){let current=this.items;if(current.length===0)return!1;let next=current.filter((candidate)=>candidate!==value);if(next.length===current.length)return!1;return this.items=next,!0}has(){return this.items.length>0}clear(){this.items=[]}}function createKeymapState(){return{core:{order:0},environment:{tokens:new Map,layerFields:new Map,bindingExpanders:new OrderedRegistry,bindingParsers:new OrderedRegistry,bindingTransformers:new OrderedRegistry,bindingFields:new Map,commandFields:new Map},dispatch:{eventMatchResolvers:new OrderedRegistry,disambiguationResolvers:new OrderedRegistry,keyHooks:new PriorityRegistry,rawHooks:new PriorityRegistry},layers:{layers:new Set,sortedLayers:[],activeLayersVersion:0,activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],layersWithConditions:0,layersWithCommands:0,layerAnalyzers:new OrderedRegistry},commands:{commandMetadataVersion:0,registeredNames:new Map,commandResolvers:new OrderedRegistry,activeCommandViewVersion:-1,activeCommandView:void 0,registeredCommandViewVersion:-1,registeredCommandView:void 0,registeredCommandEntriesCacheVersion:-1,registeredCommandEntriesCache:[]},projection:{pendingSequence:null,pendingSequenceCacheVersion:-1,pendingSequenceCache:[],activeKeysPlainCacheVersion:-1,activeKeysPlainCache:[],activeKeysBindingsCacheVersion:-1,activeKeysBindingsCache:[],activeKeysMetadataCacheVersion:-1,activeKeysMetadataCache:[],activeKeysBindingsAndMetadataCacheVersion:-1,activeKeysBindingsAndMetadataCache:[]},conditions:{runtimeKeyDependents:new Map},runtime:{data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:EMPTY_DATA},notify:{derivedStateVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}}function getKeyMatchKey(input){return resolveKeyMatch(input)}class Keymap{host;state=createKeymapState();cleanedUp=!1;resources=new Map;cleanupListeners=[];events=new Emitter2(()=>{});hooks;notify;activation;runtime;conditions;catalog;executor;compiler;dispatch;layers;environment;keypressListener;keyreleaseListener;rawListener;focusedTargetListener;constructor(host){if(this.host=host,host.isDestroyed)throw Error("Cannot create a keymap for a destroyed host");if(this.hooks=new Emitter2((name,error2)=>{this.notify.reportListenerError(name,error2)}),this.notify=new NotificationService(this.state,this.events,this.hooks),this.conditions=new ConditionService(this.state,this.notify),this.catalog=new CommandCatalogService(this.state,this.host,this.notify,this.conditions,{onCommandResolversChanged:()=>{this.activation.ensureValidPendingSequence()}}),this.activation=new ActivationService(this.state,this.host,this.hooks,this.notify,this.conditions,this.catalog,{onPendingSequenceChanged:(previous,next)=>{this.dispatch?.handlePendingSequenceChange(previous,next)}}),this.runtime=new RuntimeService(this.state,this.notify,this.conditions,this.activation),this.executor=new CommandExecutorService(this.notify,this.runtime,this.activation,this.catalog,{keymap:this,createCommandEvent:()=>this.host.createCommandEvent()}),this.compiler=new CompilerService(this.state,this.notify,this.conditions,{warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)},warnUnknownToken:(token,sequence)=>{this.warnUnknownToken(token,sequence)}}),this.layers=new LayerService(this.state,this.notify,this.conditions,this.activation,{compiler:this.compiler,commands:this.catalog,host:this.host,warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)}}),this.environment=new EnvironmentService(this.state,this.notify,this.compiler,this.layers),this.dispatch=new DispatchService(this.state,this.notify,this.runtime,this.activation,this.conditions,this.executor,this.compiler,this.catalog,this.layers),this.keypressListener=(event)=>{this.dispatch.handleKeyEvent(event,!1)},this.keyreleaseListener=(event)=>{this.dispatch.handleKeyEvent(event,!0)},this.rawListener=(sequence)=>{return this.dispatch.handleRawSequence(sequence)},this.focusedTargetListener=(focused)=>{this.handleFocusedTargetChange(focused)},this.cleanupListeners.push(this.host.onKeyPress(this.keypressListener)),this.cleanupListeners.push(this.host.onKeyRelease(this.keyreleaseListener)),this.host.onRawInput)this.cleanupListeners.push(this.host.onRawInput(this.rawListener));if(this.cleanupListeners.push(this.host.onFocusChange(this.focusedTargetListener)),this.host.onDestroy)this.cleanupListeners.push(this.host.onDestroy(()=>{this.cleanup()}))}cleanup(){if(this.cleanedUp)return;this.cleanedUp=!0,this.activation.setPendingSequence(null);for(let resource of this.resources.values())resource.dispose();this.resources.clear(),this.layers.cleanup();for(let cleanupListener of this.cleanupListeners.splice(0))cleanupListener()}setData(name,value){this.runtime.setData(name,value)}getData(name){return this.runtime.getData(name)}hasPendingSequence(){return this.activation.ensureValidPendingSequence()!==void 0}getPendingSequence(){return this.activation.getPendingSequence()}createKeyMatcher(key){let match=this.compiler.parseTokenKey(key).match;return(input)=>{if(!input)return!1;return getKeyMatchKey(input)===match}}clearPendingSequence(){this.activation.setPendingSequence(null)}popPendingSequence(){return this.activation.popPendingSequence()}getActiveKeys(options){return this.activation.getActiveKeys(options)}getCommands(query2){return this.catalog.getCommands(query2)}getCommandEntries(query2){return this.catalog.getCommandEntries(query2)}normalizeCommandName(name){return normalizeCommandName(name)}normalizeBindings(bindings){return normalizeBindingInputs(bindings)}acquireResource(key,setup){if(this.cleanedUp||this.host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");let existing=this.resources.get(key);if(existing)return existing.count+=1,()=>{this.releaseResource(key,existing)};let resource={count:1,dispose:setup()};return this.resources.set(key,resource),()=>{this.releaseResource(key,resource)}}runCommand(cmd,options){return this.executor.runCommand(cmd,options)}dispatchCommand(cmd,options){return this.executor.dispatchCommand(cmd,options)}on(name,fn){if(name==="warning")return this.events.hook(name,fn);if(name==="error")return this.events.hook(name,fn);return this.hooks.hook(name,fn)}intercept(name,fn,options){if(name==="key")return this.dispatch.intercept(name,fn,options);return this.dispatch.intercept(name,fn,options)}registerLayer(layer){return this.layers.registerLayer(layer)}registerLayerFields(fields){return this.environment.registerLayerFields(fields)}prependBindingTransformer(transformer){return this.environment.prependBindingTransformer(transformer)}appendBindingTransformer(transformer){return this.environment.appendBindingTransformer(transformer)}clearBindingTransformers(){this.environment.clearBindingTransformers()}prependBindingParser(parser){return this.environment.prependBindingParser(parser)}appendBindingParser(parser){return this.environment.appendBindingParser(parser)}clearBindingParsers(){this.environment.clearBindingParsers()}registerToken(token){return this.environment.registerToken(token)}prependBindingExpander(expander){return this.environment.prependBindingExpander(expander)}appendBindingExpander(expander){return this.environment.appendBindingExpander(expander)}clearBindingExpanders(){this.environment.clearBindingExpanders()}registerBindingFields(fields){return this.environment.registerBindingFields(fields)}registerCommandFields(fields){return this.environment.registerCommandFields(fields)}prependCommandResolver(resolver){return this.catalog.prependCommandResolver(resolver)}appendCommandResolver(resolver){return this.catalog.appendCommandResolver(resolver)}clearCommandResolvers(){this.catalog.clearCommandResolvers()}prependLayerAnalyzer(analyzer){return this.layers.prependLayerAnalyzer(analyzer)}appendLayerAnalyzer(analyzer){return this.layers.appendLayerAnalyzer(analyzer)}clearLayerAnalyzers(){this.layers.clearLayerAnalyzers()}prependEventMatchResolver(resolver){return this.dispatch.prependEventMatchResolver(resolver)}appendEventMatchResolver(resolver){return this.dispatch.appendEventMatchResolver(resolver)}clearEventMatchResolvers(){this.dispatch.clearEventMatchResolvers()}prependDisambiguationResolver(resolver){return this.dispatch.prependDisambiguationResolver(resolver)}appendDisambiguationResolver(resolver){return this.dispatch.appendDisambiguationResolver(resolver)}clearDisambiguationResolvers(){this.dispatch.clearDisambiguationResolvers()}handleFocusedTargetChange(_focused){this.notify.runWithStateChangeBatch(()=>{this.activation.setPendingSequence(null),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(_focused),this.notify.queueStateChange()})}warnUnknownField(kind,fieldName){this.notify.warnOnce(`${kind}:${fieldName}`,`unknown-${kind}-field`,{field:fieldName,kind},`[Keymap] Unknown ${kind} field "${fieldName}" was ignored`)}warnUnknownToken(token,sequence){this.notify.warnOnce(`token:${token}`,"unknown-token",{token,sequence},`[Keymap] Unknown token "${token}" in key sequence "${sequence}" was ignored`)}releaseResource(key,resource){if(this.resources.get(key)!==resource)return;if(resource.count-=1,resource.count>0)return;resource.dispose(),this.resources.delete(key)}}function registerEscapeClearsPendingSequence(keymap,options){let shouldPreventDefault=options?.preventDefault??!0;return keymap.intercept("key",({event,consume})=>{if(event.name!=="escape")return;if(!keymap.hasPendingSequence())return;if(keymap.clearPendingSequence(),shouldPreventDefault)consume()},{priority:options?.priority??0})}function registerLeader(keymap,options){return keymap.registerToken({name:options.name??"<leader>",key:options.trigger})}var RESERVED_COMMAND_FIELDS,RESERVED_BINDING_FIELDS,RESERVED_LAYER_FIELDS,DEFAULT_COMMAND_SEARCH_FIELDS,SNAPSHOT_COMMAND_METADATA_OPTIONS,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS,EMPTY_COMMAND_FIELDS,EMPTY_COMPILE_FIELDS,EMPTY_REQUIRES,EMPTY_MATCHERS,EMPTY_CONDITION_KEYS,KEY_DISAMBIGUATION_DECISION,KEY_DEFERRED_DISAMBIGUATION_DECISION,NOOP=()=>{},NOOP2=()=>{},MAX_STATE_CHANGE_FLUSH_ITERATIONS=1000,OrderedRegistry,PriorityRegistry,EMPTY_DATA,EMPTY_FIELDS;var init_addons=__esm(()=>{RESERVED_COMMAND_FIELDS=new Set(["name","run"]),RESERVED_BINDING_FIELDS=new Set(["key","cmd","event","preventDefault","fallthrough"]),RESERVED_LAYER_FIELDS=new Set(["target","targetMode","priority","bindings","commands"]);DEFAULT_COMMAND_SEARCH_FIELDS=["name"],SNAPSHOT_COMMAND_METADATA_OPTIONS=Object.freeze({deep:!0,preserveNonPlainObjects:!0}),SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS=Object.freeze({deep:!0,freeze:!0,preserveNonPlainObjects:!0}),EMPTY_COMMAND_FIELDS=Object.freeze({});EMPTY_COMPILE_FIELDS=Object.freeze({}),EMPTY_REQUIRES=[],EMPTY_MATCHERS=[],EMPTY_CONDITION_KEYS=[];KEY_DISAMBIGUATION_DECISION=Symbol("keymap-disambiguation-decision"),KEY_DEFERRED_DISAMBIGUATION_DECISION=Symbol("keymap-deferred-disambiguation-decision");OrderedRegistry=class OrderedRegistry extends CopyOnWriteRegistry{append(value){return this.setItems([...this.getItems(),value]),()=>{this.remove(value)}}prepend(value){return this.setItems([value,...this.getItems()]),()=>{this.remove(value)}}remove(value){return this.removeItem(value)}values(){return this.getItems()}};PriorityRegistry=class PriorityRegistry extends CopyOnWriteRegistry{order=0;register(listener,options){let registered={...options,listener,order:this.order++};return this.setItems([...this.getItems(),registered].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return left.order-right.order})),()=>{this.removeItem(registered)}}entries(){return this.getItems()}};EMPTY_DATA=Object.freeze({});EMPTY_FIELDS=Object.freeze({})});function getFocusedTargetIfAvailable2(host){if(host.isDestroyed)return null;return host.getFocusedTarget()}function forEachActivationTarget2(host,focused,visit){let current=focused??host.rootTarget,isFocusedTarget=focused!==null;while(current){if(visit(current,isFocusedTarget)===!1)return;current=host.getParentTarget(current),isFocusedTarget=!1}}function getActivationPath2(host,focused){let path6=new Set;return forEachActivationTarget2(host,focused,(current)=>{path6.add(current)}),path6}function getActiveLayersForFocused2(state,host,focused){if(state.activeLayersCacheVersion===state.activeLayersVersion&&state.activeLayersCacheFocused===focused)return state.activeLayersCache;let activeLayers=[],activationPath=getActivationPath2(host,focused);for(let layer of state.sortedLayers)if(isLayerActiveForFocused2(host,layer,focused,activationPath))activeLayers.push(layer);return state.activeLayersCacheVersion=state.activeLayersVersion,state.activeLayersCacheFocused=focused,state.activeLayersCache=activeLayers,activeLayers}function invalidateCachedActiveLayers2(state){state.activeLayersCacheVersion=-1,state.activeLayersCacheFocused=void 0,state.activeLayersCache=[]}function isLayerActiveForFocused2(host,layer,focused,activationPath=getActivationPath2(host,focused)){let target=layer.target;if(!target)return!0;if(host.isTargetDestroyed(target))return!1;if(layer.targetMode==="focus")return target===focused;return activationPath.has(target)}function normalizeBindingTokenName2(token){let normalized=token.trim().toLowerCase();if(!normalized)throw Error("Invalid keymap token: token cannot be empty");return normalized}function normalizeKeyName2(name){let normalized=name.trim().toLowerCase();if(!normalized)throw Error("Invalid key name: key name cannot be empty");return normalized}function normalizeKeyStroke2(input){return{name:normalizeKeyName2(input.name),ctrl:input.ctrl??!1,shift:input.shift??!1,meta:input.meta??!1,super:input.super??!1,hyper:input.hyper||void 0}}function cloneKeyStroke2(stroke){return{name:stroke.name,ctrl:stroke.ctrl,shift:stroke.shift,meta:stroke.meta,super:stroke.super,hyper:stroke.hyper||void 0}}function createKeySequencePart2(input,options){let stroke=cloneKeyStroke2(normalizeKeyStroke2(input));return{stroke,display:options?.display??stringifyCanonicalStroke2(stroke),match:options?.match??createKeyMatch2(stroke),tokenName:options?.tokenName?normalizeBindingTokenName2(options.tokenName):void 0}}function cloneKeySequencePart2(part){return{stroke:cloneKeyStroke2(part.stroke),display:part.display,match:part.match,tokenName:part.tokenName}}function cloneKeySequence2(parts){return parts.map((part)=>cloneKeySequencePart2(part))}function resolveKeyMatch2(input){if("match"in input)return input.match;if("stroke"in input)return createKeyMatch2(input.stroke);return createKeyMatch2(input)}function createKeyMatch2(input){return`key:${buildKeyMatchId2(normalizeKeyStroke2(input))}`}function createTextKeyMatch2(id){let normalized=id.trim();if(!normalized)throw Error("Invalid keymap match id: id cannot be empty");return`text:${normalized}`}function stringifyKeyStroke2(input,options){if("stroke"in input){if(options?.preferDisplay&&input.display)return input.display;return stringifyCanonicalStroke2(input.stroke)}return stringifyCanonicalStroke2(normalizeKeyStroke2(input))}function stringifyKeySequence2(input,options){return input.map((part)=>stringifyKeyStroke2(part,options)).join("")}function stringifyCanonicalStroke2(stroke){let parts=[];if(stroke.ctrl)parts.push("ctrl");if(stroke.shift)parts.push("shift");if(stroke.meta)parts.push("meta");if(stroke.super)parts.push("super");if(stroke.hyper)parts.push("hyper");return parts.push(stroke.name==="return"?"enter":stroke.name),parts.join("+")}function buildKeyMatchId2(stroke){return`${stroke.name}:${stroke.ctrl?1:0}:${stroke.shift?1:0}:${stroke.meta?1:0}:${stroke.super?1:0}:${stroke.hyper?1:0}`}function getLiveHost2(host){if(host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");return host}function isSamePendingSequence2(current,next){if(current===next)return!0;if(!current||!next)return!1;if(current.captures.length!==next.captures.length)return!1;for(let index=0;index<current.captures.length;index+=1){let left=current.captures[index],right=next.captures[index];if(!left||!right||left.layer!==right.layer||left.node!==right.node)return!1}return!0}class ActivationService2{state;host;hooks;notify;conditions;catalog;options;constructor(state,host,hooks,notify,conditions,catalog,options={}){this.state=state,this.host=host,this.hooks=hooks,this.notify=notify,this.conditions=conditions,this.catalog=catalog,this.options=options}getFocusedTarget(){return getLiveHost2(this.host).getFocusedTarget()}getFocusedTargetIfAvailable(){return getFocusedTargetIfAvailable2(this.host)}setPendingSequence(next){let previous=this.state.projection.pendingSequence;if(isSamePendingSequence2(previous,next))return;this.state.projection.pendingSequence=next,this.options.onPendingSequenceChanged?.(previous,next),this.invalidateCaches(),this.notifyPendingSequenceChange(),this.notify.queueStateChange()}ensureValidPendingSequence(){let pending=this.state.projection.pendingSequence;if(!pending)return;let focused=this.getFocusedTarget(),captures=pending.captures.filter((capture2)=>{return this.state.layers.layers.has(capture2.layer)&&this.isLayerActiveForFocused(capture2.layer,focused)&&this.conditions.layerMatchesRuntimeState(capture2.layer)&&this.nodeHasReachableBindings(capture2.node,focused)});if(captures.length===0){this.setPendingSequence(null);return}if(captures.length!==pending.captures.length)this.setPendingSequence({captures});return this.state.projection.pendingSequence??void 0}revalidatePendingSequenceIfNeeded(){if(this.host.isDestroyed||!this.state.projection.pendingSequence)return;this.ensureValidPendingSequence()}hasPendingSequenceState(){return!this.host.isDestroyed&&this.state.projection.pendingSequence!==null}getPendingSequence(){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion;if(projections.pendingSequenceCacheVersion===derivedStateVersion)return projections.pendingSequenceCache;let pending=this.ensureValidPendingSequence(),canUseCache=!pending||pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)),sequence=pending?this.collectSequencePartsFromPending(pending):[];if(canUseCache)projections.pendingSequenceCacheVersion=derivedStateVersion,projections.pendingSequenceCache=sequence;return sequence}popPendingSequence(){let pending=this.ensureValidPendingSequence();if(!pending)return!1;let firstCapture=pending.captures[0];if(!firstCapture||firstCapture.node.depth<=1)return this.setPendingSequence(null),!0;let nextCaptures=[];for(let capture2 of pending.captures){let parent=capture2.node.parent;if(!parent||!parent.stroke)continue;nextCaptures.push({layer:capture2.layer,node:parent})}if(nextCaptures.length===0)return this.setPendingSequence(null),!0;return this.setPendingSequence({captures:nextCaptures}),!0}getActiveKeys(options){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion,includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0;if(includeBindings){if(includeMetadata){if(projections.activeKeysBindingsAndMetadataCacheVersion===derivedStateVersion)return projections.activeKeysBindingsAndMetadataCache}else if(projections.activeKeysBindingsCacheVersion===derivedStateVersion)return projections.activeKeysBindingsCache}else if(includeMetadata){if(projections.activeKeysMetadataCacheVersion===derivedStateVersion)return projections.activeKeysMetadataCache}else if(projections.activeKeysPlainCacheVersion===derivedStateVersion)return projections.activeKeysPlainCache;let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),pending=this.ensureValidPendingSequence(),activeLayers=pending?[]:this.getActiveLayers(focused),canUseCache=pending?pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)):this.activeLayersCanCacheActiveKeys(activeLayers),activeKeys=pending?this.collectActiveKeysFromPending(pending.captures,includeBindings,includeMetadata,focused,activeView):this.collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView);if(!canUseCache)return activeKeys;if(includeBindings)if(includeMetadata)projections.activeKeysBindingsAndMetadataCacheVersion=derivedStateVersion,projections.activeKeysBindingsAndMetadataCache=activeKeys;else projections.activeKeysBindingsCacheVersion=derivedStateVersion,projections.activeKeysBindingsCache=activeKeys;else if(includeMetadata)projections.activeKeysMetadataCacheVersion=derivedStateVersion,projections.activeKeysMetadataCache=activeKeys;else projections.activeKeysPlainCacheVersion=derivedStateVersion,projections.activeKeysPlainCache=activeKeys;return activeKeys}getActiveKeysForCaptures(captures,options){let includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0,focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused);return this.collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView)}nodeHasReachableBindings(node,focused){return this.hasMatchingBindings(node.reachableBindings,focused,this.catalog.getActiveCommandView(focused))}getActiveLayers(focused){return getActiveLayersForFocused2(this.state.layers,this.host,focused)}refreshActiveLayers(focused=this.getFocusedTargetIfAvailable()){getActiveLayersForFocused2(this.state.layers,this.host,focused)}invalidateActiveLayers(){invalidateCachedActiveLayers2(this.state.layers)}isLayerActiveForFocused(layer,focused){return isLayerActiveForFocused2(this.host,layer,focused)}layerCanCacheActiveKeys(layer){return!layer.hasUnkeyedMatchers&&!layer.hasUnkeyedCommands&&!layer.hasUnkeyedBindings}activeLayersCanCacheActiveKeys(activeLayers){for(let layer of activeLayers)if(!this.layerCanCacheActiveKeys(layer))return!1;return!0}collectNodesFromNode(node){let nodes=[],current=node;while(current&¤t.stroke)nodes.push(current),current=current.parent;return nodes.reverse(),nodes}collectSequencePartsFromPending(pending){let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),paths=pending.captures.map((capture2)=>this.collectNodesFromNode(capture2.node)),firstPath=paths[0];if(!firstPath||firstPath.length===0)return[];let parts=[];for(let index=0;index<firstPath.length;index+=1){let firstNode=firstPath[index];if(!firstNode?.stroke||firstNode.match===null)continue;let display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let path6 of paths){let node=path6[index];if(!node)continue;let presentation=this.getNodePresentation(node,focused,activeView);if(display===void 0){display=presentation.display,tokenName=presentation.tokenName;continue}if(!hasDisplayConflict&&display!==presentation.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==presentation.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke2(firstNode.stroke);if(hasTokenConflict)tokenName=void 0;parts.push(createKeySequencePart2(firstNode.stroke,{display,match:firstNode.match,tokenName}))}return parts}collectMatchingBindings(bindings,focused,activeView){let matches=[];for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))matches.push(binding);return matches}hasMatchingBindings(bindings,focused,activeView){for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))return!0;return!1}getNodePresentation(node,focused,activeView,reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView)){if(!node.stroke)return{display:""};let partIndex=node.depth-1,display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let binding of reachableBindings){let part=binding.sequence[partIndex];if(!part)continue;if(display===void 0){display=part.display,tokenName=part.tokenName;continue}if(!hasDisplayConflict&&display!==part.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==part.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke2(node.stroke);if(hasTokenConflict)tokenName=void 0;return{display,tokenName}}toActiveBinding(binding,focused,activeView){return{sequence:binding.sequence,command:binding.command,commandAttrs:this.catalog.getBindingCommandAttrs(binding,focused,activeView),attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough}}collectActiveBindings(bindings,focused,activeView){return bindings.map((binding)=>this.toActiveBinding(binding,focused,activeView))}collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set,hasLayerConditions=this.state.layers.layersWithConditions>0;for(let layer of activeLayers){if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let[bindingKey,child]of layer.root.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set;for(let capture2 of captures)for(let[bindingKey,child]of capture2.node.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}selectActiveKey(node,includeBindings,focused,activeView){return node.children.size>0?this.selectPrefixActiveKey(node,includeBindings,focused,activeView):this.selectExactActiveKey(node,includeBindings,focused,activeView)}selectPrefixActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView);if(reachableBindings.length===0)return;let prefixBindings=this.selectActiveBindings(node.bindings,focused,activeView);return{...this.getNodePresentation(node,focused,activeView,reachableBindings),continues:!0,firstBinding:prefixBindings?.bindings[0],commandBinding:prefixBindings?.commandBinding,bindings:includeBindings&&prefixBindings&&prefixBindings.bindings.length>0?[...prefixBindings.bindings]:void 0,stop:!0}}selectExactActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let selected=this.selectActiveBindings(node.bindings,focused,activeView);if(!selected)return;let display,tokenName;if(selected.bindings.length===1){let part=selected.bindings[0]?.sequence[node.depth-1];display=part?.display??stringifyKeyStroke2(node.stroke),tokenName=part?.tokenName}else{let presentation=this.getNodePresentation(node,focused,activeView,selected.bindings);display=presentation.display,tokenName=presentation.tokenName}return{display,tokenName,continues:!1,firstBinding:selected.bindings[0],commandBinding:selected.commandBinding,bindings:includeBindings?[...selected.bindings]:void 0,stop:selected.stop}}selectActiveBindings(bindings,focused,activeView){let selected=[],commandBinding;for(let binding of bindings){if(!this.conditions.matchesConditions(binding)||!this.catalog.isBindingVisible(binding,focused,activeView))continue;if(selected.push(binding),binding.command===void 0)continue;if(commandBinding??=binding,!binding.fallthrough)return{bindings:selected,commandBinding,stop:!0}}if(selected.length===0)return;return{bindings:selected,commandBinding,stop:!1}}createActiveKeyState(stroke,selection,includeBindings){return{stroke,display:selection.display,tokenName:selection.tokenName,continues:selection.continues,firstBinding:selection.firstBinding,commandBinding:selection.commandBinding,bindings:includeBindings&&selection.bindings?[...selection.bindings]:void 0}}updateActiveKeyState(state,selection,includeBindings){if(!state.firstBinding&&selection.firstBinding)state.firstBinding=selection.firstBinding;if(!state.commandBinding&&selection.commandBinding)state.commandBinding=selection.commandBinding;if(selection.continues)state.continues=!0;if(!includeBindings||!selection.bindings||selection.bindings.length===0)return;if(!state.bindings){state.bindings=[...selection.bindings];return}state.bindings.push(...selection.bindings)}materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView){if(!state.commandBinding&&!state.continues)return;let activeKey={stroke:cloneKeyStroke2(state.stroke),display:state.display,continues:state.continues};if(state.tokenName)activeKey.tokenName=state.tokenName;if(state.commandBinding)activeKey.command=state.commandBinding.command;if(includeBindings&&state.bindings&&state.bindings.length>0)activeKey.bindings=state.bindings.length===1?[this.toActiveBinding(state.bindings[0],focused,activeView)]:this.collectActiveBindings(state.bindings,focused,activeView);if(includeMetadata){if(state.firstBinding?.attrs)activeKey.bindingAttrs=state.firstBinding.attrs;let commandAttrs=state.commandBinding?this.catalog.getBindingCommandAttrs(state.commandBinding,focused,activeView):void 0;if(commandAttrs)activeKey.commandAttrs=commandAttrs}return activeKey}invalidateCaches(){this.state.projection.pendingSequenceCacheVersion=-1,this.state.projection.activeKeysPlainCacheVersion=-1,this.state.projection.activeKeysBindingsCacheVersion=-1,this.state.projection.activeKeysMetadataCacheVersion=-1,this.state.projection.activeKeysBindingsAndMetadataCacheVersion=-1}notifyPendingSequenceChange(){if(!this.hooks.has("pendingSequence"))return;this.hooks.emit("pendingSequence",this.state.projection.pendingSequence?this.collectSequencePartsFromPending(this.state.projection.pendingSequence):[])}}function mergeRequirement2(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap requirement for "${name}" from ${source}`);target[name]=value}function mergeAttribute2(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap attribute for "${name}" from ${source}`);target[name]=value}function isPlainObject3(value){let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function getErrorMessage2(error2,fallback){if(error2 instanceof Error&&error2.message)return error2.message;return fallback}function isPromiseLike2(value){if(!value)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return typeof value.then==="function"}function snapshotDataValue2(value,options){let deep=options?.deep===!0,freeze=options?.freeze===!0,preserveNonPlainObjects=options?.preserveNonPlainObjects===!0;if(Array.isArray(value)){let cloned=deep?value.map((entry2)=>snapshotDataValue2(entry2,options)):[...value];return freeze?Object.freeze(cloned):cloned}if(value&&typeof value==="object"){if(preserveNonPlainObjects&&!isPlainObject3(value))return value;let cloned={};for(let[key,entry2]of Object.entries(value))cloned[key]=deep?snapshotDataValue2(entry2,options):entry2;return freeze?Object.freeze(cloned):cloned}return value}function createCommandChainCacheState2(){return{resolvedWithoutRecordChains:new Map,resolvedWithRecordChains:new Map,fallbackWithoutRecord:new Map,fallbackWithRecord:new Map,fallbackWithoutRecordErrors:new Set,fallbackWithRecordErrors:new Set}}function normalizeBindingCommand2(command){if(command===void 0||typeof command==="function")return command;let trimmed=command.trim();if(!trimmed)throw Error("Invalid keymap command: command cannot be empty");return trimmed}function normalizeCommandName2(name){let trimmed=name.trim();if(!trimmed)throw Error("Invalid keymap command name: name cannot be empty");if(/\s/.test(trimmed))throw Error(`Invalid keymap command name "${name}": command names cannot contain whitespace`);return trimmed}class CommandCatalogService2{state;host;notify;conditions;options;constructor(state,host,notify,conditions,options){this.state=state,this.host=host,this.notify=notify,this.conditions=conditions,this.options=options}normalizeCommands(commands){return normalizeRegisteredCommands2({commands,commandFields:this.state.environment.commandFields,conditions:this.conditions,onError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}prependCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.prepend(resolver),resolver)}appendCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.append(resolver),resolver)}clearCommandResolvers(){if(!this.state.commands.commandResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.commands.commandResolvers.clear(),this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}getCommands(query2){return this.getFilteredCommandEntries(query2).map((entry2)=>getRegisteredCommandRecord2(entry2.command))}getCommandEntries(query2){let context=this.getCommandQueryContext(query2),filteredEntries=this.getFilteredCommandEntries(query2,context);if(filteredEntries.length===0)return[];let grouped=filteredEntries.map((entry2)=>({entry:entry2,command:getRegisteredCommandRecord2(entry2.command),bindings:[]})),indexesByName=new Map;for(let[index,item]of grouped.entries()){let existing=indexesByName.get(item.command.name);if(existing)existing.push(index);else indexesByName.set(item.command.name,[index])}if(indexesByName.size>0)this.collectCommandEntryBindings(grouped,indexesByName,context);return grouped.map((item)=>({command:item.command,bindings:item.bindings}))}getResolvedCommandChain(command,focused,includeRecord){let view=this.getActiveCommandView(focused),entries=this.getResolvedCommandChainFromView(view,command,focused,includeRecord,"active",view.chainsByName.get(command)),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{entries,hadError}}getRegisteredResolvedEntries(command,includeRecord){let view=this.getRegisteredCommandView(),cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let chain=view.chainsByName.get(command);if(!chain||chain.length===0){cache.set(command,[]);return}let resolved=[];for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand2(entry2.command,{includeRecord})});return cache.set(command,resolved),resolved}getRegisteredResolverFallback(command,includeRecord){let view=this.getRegisteredCommandView(),fallback=this.getFallbackResolvedCommand(view,command,null,includeRecord,"registered"),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{resolved:fallback?.resolved,hadError}}getCommandAttrs(command,focused){return this.getTopResolvedCommand(command,focused,!1)?.resolved.attrs}getTopCommandRecord(command,focused){return this.getTopResolvedCommand(command,focused,!0)?.resolved.record}getTopRegisteredCommandRecord(command){let top=this.getTopRegisteredCommand(command);return top?getRegisteredCommandRecord2(top.command):void 0}getDispatchUnavailableCommandState(command,focused,includeRecord){let chain=this.getRegisteredCommandView().chainsByName.get(command);if(!chain||chain.length===0)return;let inactiveEntry,disabledEntry;for(let entry2 of chain){if(!isLayerActiveForFocused2(this.host,entry2.layer,focused)){inactiveEntry??=entry2;continue}if(!this.conditions.layerMatchesRuntimeState(entry2.layer)||!this.conditions.matchesConditions(entry2.command))disabledEntry??=entry2}let unavailableEntry=disabledEntry??inactiveEntry;if(!unavailableEntry)return;return{reason:disabledEntry?"disabled":"inactive",command:includeRecord?getRegisteredCommandRecord2(unavailableEntry.command):void 0}}getActiveCommandView(focused){let currentFocused=getFocusedTargetIfAvailable2(this.host),derivedStateVersion=this.state.notify.derivedStateVersion;if(focused===currentFocused&&this.state.commands.activeCommandViewVersion===derivedStateVersion&&this.state.commands.activeCommandView?.cacheable)return this.state.commands.activeCommandView;let entries=[],reachable=[],reachableByName=new Map,chainsByName=new Map,cacheable=!0;if(this.state.layers.layersWithCommands>0)for(let layer of getActiveLayersForFocused2(this.state.layers,this.host,focused)){if(layer.commands.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;if(layer.hasUnkeyedMatchers)cacheable=!1;for(let command of layer.commands){if(command.hasUnkeyedMatchers)cacheable=!1;if(!this.conditions.matchesConditions(command))continue;let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2]);if(!reachableByName.has(command.name))reachableByName.set(command.name,entry2),reachable.push(entry2)}}let view={cacheable,entries,reachable,reachableByName,chainsByName,...createCommandChainCacheState2()};if(focused===currentFocused&&view.cacheable)this.state.commands.activeCommandViewVersion=derivedStateVersion,this.state.commands.activeCommandView=view;return view}getRegisteredCommandView(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandViewVersion===cacheVersion&&this.state.commands.registeredCommandView)return this.state.commands.registeredCommandView;let entries=[],chainsByName=new Map;for(let layer of this.state.layers.sortedLayers){if(layer.commands.length===0)continue;for(let command of layer.commands){let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2])}}let view={entries,chainsByName,...createCommandChainCacheState2()};return this.state.commands.registeredCommandViewVersion=cacheVersion,this.state.commands.registeredCommandView=view,view}isBindingVisible(binding,focused,activeView){if(binding.command===void 0||binding.run)return!0;if(typeof binding.command!=="string")return!1;if(activeView.reachableByName.has(binding.command))return!0;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")!==void 0}getBindingCommandAttrs(binding,focused,activeView){if(typeof binding.command!=="string")return;let active=activeView.reachableByName.get(binding.command);if(active)return active.command.attrs;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")?.resolved.attrs}getCommandResolutionStatus(command,layerCommands){if(layerCommands?.has(command)||this.state.commands.registeredNames.has(command))return"resolved";let lookup=this.resolveCommandWithResolvers(command,getFocusedTargetIfAvailable2(this.host));if(lookup.resolved||lookup.hadError)return lookup.resolved?"resolved":"error";return"unresolved"}mutateCommandResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let off=register2();return this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange(),()=>{this.notify.runWithStateChangeBatch(()=>{if(off(),this.state.commands.commandResolvers.values().includes(resolver))return;this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}})}getTopResolvedCommand(command,focused,includeRecord){let activeView=this.getActiveCommandView(focused),active=activeView.reachableByName.get(command);if(active)return{target:active.layer.target,resolved:resolveRegisteredCommand2(active.command,{includeRecord})};return this.getFallbackResolvedCommand(activeView,command,focused,includeRecord,"active")}getTopRegisteredCommand(command){return this.getRegisteredCommandView().chainsByName.get(command)?.[0]}getFallbackResolvedCommand(view,command,focused,includeRecord,mode){let cache=includeRecord?view.fallbackWithRecord:view.fallbackWithoutRecord,errorCache=includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors;if(cache.has(command)){let cached=cache.get(command);return cached?{resolved:cached}:void 0}let lookup=this.resolveCommandWithResolvers(command,focused,{includeRecord,mode});if(cache.set(command,lookup.resolved??null),lookup.hadError)errorCache.add(command);if(!lookup.resolved)return;return{resolved:lookup.resolved}}getResolvedCommandChainFromView(view,command,focused,includeRecord,mode,activeChain){let cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let resolved=[],chain=activeChain;if(chain)for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand2(entry2.command,{includeRecord})});let fallback=this.getFallbackResolvedCommand(view,command,focused,includeRecord,mode);if(fallback)resolved.push(fallback);return cache.set(command,resolved),resolved.length>0?resolved:void 0}getRegisteredLayerCommandEntries(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandEntriesCacheVersion===cacheVersion)return this.state.commands.registeredCommandEntriesCache;let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);let entries=[];for(let layer of layers)for(let command of layer.commands)entries.push({layer,command});return this.state.commands.registeredCommandEntriesCacheVersion=cacheVersion,this.state.commands.registeredCommandEntriesCache=entries,entries}getCommandQueryContext(query2){let visibility=query2?.visibility??"reachable",focused=query2&&Object.prototype.hasOwnProperty.call(query2,"focused")?query2.focused??null:getFocusedTargetIfAvailable2(this.host);if(visibility==="registered")return{visibility,focused};return{visibility,focused,activeView:this.getActiveCommandView(focused)}}getFilteredCommandEntries(query2,context=this.getCommandQueryContext(query2)){let entries;if(context.visibility==="registered")entries=this.getRegisteredLayerCommandEntries();else if(context.visibility==="active")entries=context.activeView?.entries??[];else entries=context.activeView?.reachable??[];return queryLayerCommandEntries2({entries,query:query2,getCommandRecord:(command)=>getRegisteredCommandRecord2(command),onFilterError:(error2)=>{this.notify.emitError("command-query-filter-error",error2,"[Keymap] Error in command query filter:")}})}collectCommandEntryBindings(grouped,indexesByName,context){if(context.visibility==="registered"){let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);for(let layer of layers)for(let binding of layer.compiledBindings)this.collectBindingForCommandEntries(grouped,indexesByName,binding);return}let activeView=context.activeView;if(!activeView)return;for(let layer of getActiveLayersForFocused2(this.state.layers,this.host,context.focused)){if(layer.compiledBindings.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;for(let binding of layer.compiledBindings){if(!this.conditions.matchesConditions(binding)||!this.isBindingVisible(binding,context.focused,activeView))continue;this.collectBindingForCommandEntries(grouped,indexesByName,binding)}}}collectBindingForCommandEntries(grouped,indexesByName,binding){if(typeof binding.command!=="string")return;let indexes=indexesByName.get(binding.command);if(!indexes||indexes.length===0)return;for(let index of indexes){let item=grouped[index];if(!item)continue;item.bindings.push({sequence:binding.sequence,command:binding.command,commandAttrs:item.command.attrs,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough})}}resolveCommandWithResolvers(command,focused,options){let includeRecord=options?.includeRecord===!0,context=this.createCommandResolverContext(includeRecord,focused,options?.mode??"active");return resolveCommandWithResolvers2(command,this.state.commands.commandResolvers.values(),context,(error2)=>{this.notify.emitError("command-resolver-error",error2,`[Keymap] Error in command resolver for "${command}":`)})}createCommandResolverContext(includeRecord,focused,mode){return{getCommandAttrs:(name)=>{if(mode==="registered")return this.getTopRegisteredCommand(name)?.command.attrs;return this.getCommandAttrs(name,focused)},getCommandRecord:(name)=>{if(!includeRecord)return;if(mode==="registered")return this.getTopRegisteredCommandRecord(name);return this.getTopCommandRecord(name,focused)}}}}function getRegisteredCommandRecord2(command){if(command.record)return command.record;let fields=EMPTY_COMMAND_FIELDS2;if(command.fields!==EMPTY_COMMAND_FIELDS2&&Object.keys(command.fields).length>0)fields=snapshotDataValue2(command.fields,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2);let record=command.attrs?Object.freeze({name:command.name,fields,attrs:snapshotDataValue2(command.attrs,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2)}):Object.freeze({name:command.name,fields});return command.record=record,record}function resolveRegisteredCommand2(command,options){if(options?.includeRecord===!0){let existing2=command.resolvedWithRecord;if(existing2)return existing2;let resolved2={run:createRegisteredCommandRunner2(command)};if(command.attrs)resolved2.attrs=command.attrs;return resolved2.record=getRegisteredCommandRecord2(command),command.resolvedWithRecord=resolved2,resolved2}let existing=command.resolved;if(existing)return existing;let resolved={run:createRegisteredCommandRunner2(command)};if(command.attrs)resolved.attrs=command.attrs;return command.resolved=resolved,resolved}function normalizeRegisteredCommands2(options){let normalizedCommands=[],seen=new Set;for(let command of options.commands){let normalizedCommand;try{let mergedAttrs={},mergedFields={},mergedRequires={},matchers=[],conditionKeys=new Set,hasUnkeyedMatchers=!1,normalizedName=normalizeCommandName2(command.name);if(seen.has(normalizedName)){options.onError("duplicate-command",{command:normalizedName},`Duplicate keymap command "${normalizedName}" in the same layer`);continue}for(let[fieldName,value]of Object.entries(command)){if(RESERVED_COMMAND_FIELDS2.has(fieldName)||value===void 0)continue;mergedFields[fieldName]=snapshotDataValue2(value,SNAPSHOT_COMMAND_METADATA_OPTIONS2);let compiler=options.commandFields.get(fieldName);if(!compiler)continue;compiler(value,createCommandFieldContext2(mergedAttrs,mergedRequires,conditionKeys,matchers,options.conditions,fieldName,{onUnkeyedMatcher(){hasUnkeyedMatchers=!0}}))}let attrs=Object.keys(mergedAttrs).length===0?void 0:Object.freeze(mergedAttrs),fields=Object.keys(mergedFields).length===0?EMPTY_COMMAND_FIELDS2:Object.freeze(mergedFields);if(normalizedCommand={name:normalizedName,fields,run:command.run,requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,matchCacheDirty:!0},attrs)normalizedCommand.attrs=attrs}catch(error2){options.onError("register-command-failed",error2,getErrorMessage2(error2,`Failed to register keymap command "${String(command.name)}"`));continue}seen.add(normalizedCommand.name),normalizedCommands.push(normalizedCommand)}return normalizedCommands}function createCommandFieldContext2(mergedAttrs,mergedRequires,conditionKeys,matchers,conditions,fieldName,options){return{require(name,requiredValue){mergeRequirement2(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},attr(name,attributeValue){mergeAttribute2(mergedAttrs,name,snapshotDataValue2(attributeValue,SNAPSHOT_COMMAND_METADATA_OPTIONS2),`field ${fieldName}`)},activeWhen(matcher){let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)options.onUnkeyedMatcher();matchers.push(runtimeMatcher)}}}function createRegisteredCommandRunner2(command){if(command.runner)return command.runner;let runner=(ctx)=>{return command.run({...ctx,command:getRegisteredCommandRecord2(command)})};return command.runner=runner,runner}function resolveCommandWithResolvers2(command,resolvers,context,onResolverError){if(resolvers.length===0)return{hadError:!1};let hadError=!1;for(let resolver of resolvers){let resolved;try{resolved=resolver(command,context)}catch(error2){hadError=!0,onResolverError(error2);continue}if(resolved)return{hadError,resolved}}return{hadError}}function queryLayerCommandEntries2(options){let namespace=options.query?.namespace,normalizedSearch=options.query?.search?.trim().toLowerCase()??"",searchKeys=DEFAULT_COMMAND_SEARCH_FIELDS2;if(options.query?.searchIn&&options.query.searchIn.length>0)searchKeys=options.query.searchIn;let filter=options.query?.filter,filterEntries2,filterPredicate;if(typeof filter==="function")filterPredicate=filter;else if(filter)filterEntries2=Object.entries(filter);let results=[];for(let entry2 of options.entries){let command=entry2.command;if(!commandMatchesNamespace2(command,namespace))continue;if(!commandMatchesSearch2(command,normalizedSearch,searchKeys))continue;if(!commandMatchesFilters2(command,filterEntries2,options))continue;let record=options.getCommandRecord(command);if(filterPredicate){let matches=!1;try{matches=filterPredicate(record)}catch(error2){options.onFilterError(error2);continue}if(!matches)continue}results.push(entry2)}return results}function commandMatchesSearch2(command,search,searchKeys){if(!search)return!0;for(let key of searchKeys)if(commandKeyMatchesSearch2(command,key,search))return!0;return!1}function commandMatchesNamespace2(command,namespace){if(namespace===void 0)return!0;if(!Object.prototype.hasOwnProperty.call(command.fields,"namespace"))return!1;return commandValueMatchesFilter2(command.fields.namespace,namespace)}function commandMatchesFilters2(command,filters,options){if(!filters)return!0;for(let[key,matcher]of filters)if(!commandKeyMatchesQuery2(command,key,matcher,options))return!1;return!0}function commandKeyMatchesSearch2(command,key,search){if(key==="name"&&commandValueMatchesSearch2(command.name,search))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesSearch2(command.fields[key],search))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesSearch2(command.attrs[key],search);return!1}function commandKeyMatchesQuery2(command,key,matcher,options){if(typeof matcher==="function"){let record,getRecord=()=>{if(!record)record=options.getCommandRecord(command);return record},foundValue=!1;if(key==="name"){foundValue=!0;try{if(matcher(command.name,getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(Object.prototype.hasOwnProperty.call(command.fields,key)){foundValue=!0;try{if(matcher(command.fields[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key)){foundValue=!0;try{if(matcher(command.attrs[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(!foundValue)try{return matcher(void 0,getRecord())}catch(error2){return options.onFilterError(error2),!1}return!1}return commandKeyMatchesExact2(command,key,matcher)}function commandKeyMatchesExact2(command,key,matcher){if(key==="name"&&commandValueMatchesFilter2(command.name,matcher))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesFilter2(command.fields[key],matcher))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesFilter2(command.attrs[key],matcher);return!1}function commandValueMatchesFilter2(value,matcher){if(Array.isArray(matcher)){for(let expected of matcher)if(commandValueMatchesExact2(value,expected))return!0;return!1}return commandValueMatchesExact2(value,matcher)}function commandValueMatchesExact2(value,expected){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesExact2(entry2,expected))return!0;return!1}return Object.is(value,expected)}function commandValueMatchesSearch2(value,search){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesSearch2(entry2,search))return!0;return!1}if(typeof value==="string")return value.toLowerCase().includes(search);if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return String(value).toLowerCase().includes(search);return!1}class CommandExecutorService2{notify;runtime;activation;catalog;options;constructor(notify,runtime,activation,catalog,options){this.notify=notify,this.runtime=runtime,this.activation=activation,this.catalog=catalog,this.options=options}runCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand2(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chain=this.catalog.getRegisteredResolvedEntries(normalized,includeRecord),rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}let fallback=this.catalog.getRegisteredResolverFallback(normalized,includeRecord);if(fallback.resolved){let execution=this.executeResolvedCommand(normalized,fallback.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(fallback.hadError)return{ok:!1,reason:"error"};return rejectedResult??{ok:!1,reason:"not-found"}}dispatchCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand2(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chainLookup=this.catalog.getResolvedCommandChain(normalized,focused,includeRecord),chain=chainLookup.entries,rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(chainLookup.hadError)return{ok:!1,reason:"error"};let unavailable=this.catalog.getDispatchUnavailableCommandState(normalized,focused,includeRecord);if(unavailable)return unavailable.command?{ok:!1,reason:unavailable.reason,command:unavailable.command}:{ok:!1,reason:unavailable.reason};return rejectedResult??{ok:!1,reason:"not-found"}}runBinding(bindingLayer,binding,event,focused){let data=this.runtime.getReadonlyData();if(binding.run){if(this.executeResolvedCommand(typeof binding.command==="string"?binding.command:"<function>",{run:binding.run},{keymap:this.options.keymap,event,focused,target:bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects2(binding,event),!0}if(typeof binding.command!=="string")return!1;let chain=this.catalog.getResolvedCommandChain(binding.command,focused,!1).entries;if(chain?.length===1){let[entry2]=chain;if(entry2){if(this.executeResolvedCommand(binding.command,entry2.resolved,{keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects2(binding,event),!0}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data};if(this.executeResolvedCommand(binding.command,entry2.resolved,context).status==="rejected")continue;return applyBindingEventEffects2(binding,event),!0}return!1}executeResolvedCommand(commandName,resolved,context){let command=resolved.record,result2;try{result2=resolved.run(context)}catch(error2){return this.notify.emitError("command-execution-error",error2,`[Keymap] Error running command "${commandName}":`),{status:"error",result:{ok:!1,reason:"error",command}}}if(isPromiseLike2(result2))return result2.catch((error2)=>{this.notify.emitError("async-command-error",error2,`[Keymap] Async error in command "${commandName}":`)}),{status:"handled",result:{ok:!0,command}};if(result2===!1){if(resolved.rejectedResult)return{status:"rejected",result:resolved.rejectedResult};return{status:"rejected",result:{ok:!1,reason:"rejected",command}}}return{status:"handled",result:{ok:!0,command}}}}function applyBindingEventEffects2(binding,event){if(!binding.preventDefault)return;event.preventDefault(),event.stopPropagation()}function normalizeBindingInputs2(bindings){if(Array.isArray(bindings))return bindings;let normalized=[];for(let[key,cmd]of Object.entries(bindings)){if(typeof cmd!=="string"&&typeof cmd!=="function")throw Error(`Invalid keymap binding for "${key}": shorthand bindings must map to string or function commands`);normalized.push({key,cmd})}return normalized}function snapshotBindingInputs2(bindings){return normalizeBindingInputs2(bindings).map((binding)=>({...binding,key:typeof binding.key==="string"?binding.key:{...binding.key}}))}function snapshotParsedBindingInput2(binding){return{...binding,sequence:cloneKeySequence2(binding.sequence)}}function createSequenceNode2(parent,stroke,match){return{parent,depth:parent?parent.depth+1:0,stroke,match,children:new Map,bindings:[],reachableBindings:[]}}function snapshotAttributes2(attrs){if(Object.keys(attrs).length===0)return;return snapshotDataValue2(attrs,{freeze:!0})}class CompilerService2{state;notify;conditions;options;constructor(state,notify,conditions,options){this.state=state,this.notify=notify,this.conditions=conditions,this.options=options}parseTokenKey(key){return parseSingleKeyPartWithParsers2(key,this.state.environment.bindingParsers.values(),{tokens:this.state.environment.tokens,layer:EMPTY_COMPILE_FIELDS2,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})}compileBindings(bindings,tokens2,sourceTarget,sourceLayerOrder,compileFields){let root=createSequenceNode2(null,null,null),compiledBindings=[],hasTokenBindings=!1,bindingExpanders=this.state.environment.bindingExpanders.values(),bindingParsers=this.state.environment.bindingParsers.values(),bindingFieldCompilers=this.state.environment.bindingFields,allowExactPrefixAmbiguity=this.state.dispatch.disambiguationResolvers.has(),warnUnknownField=this.options.warnUnknownField,warnUnknownToken=this.options.warnUnknownToken,conditions=this.conditions;for(let[bindingIndex,binding]of bindings.entries()){let expandedBindingKeys;try{expandedBindingKeys=expandBindingInputWithExpanders2(binding.key,bindingExpanders,{layer:compileFields})}catch(error2){this.notify.emitError("binding-expand-error",error2,getErrorMessage2(error2,"Failed to expand keymap binding"));continue}for(let expandedBindingKey of expandedBindingKeys){let parsed;try{parsed=typeof expandedBindingKey==="string"?parseBindingSequenceWithParsers2(expandedBindingKey,bindingParsers,{tokens:tokens2,layer:compileFields,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)}):{parts:[this.parseObjectKeyPart(expandedBindingKey)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1}}catch(error2){this.notify.emitError("binding-parse-error",error2,getErrorMessage2(error2,"Failed to parse keymap binding"));continue}let sequence=parsed.parts;hasTokenBindings||=parsed.hasTokenBindings;for(let tokenName of parsed.unknownTokens)warnUnknownToken(tokenName,typeof expandedBindingKey==="string"?expandedBindingKey:String(expandedBindingKey.name));for(let compiledInput of this.applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields))try{let event=this.normalizeBindingEvent(compiledInput.event),compiledSequence=compiledInput.sequence,mergedRequires,mergedAttrs,matchers,conditionKeys,hasUnkeyedMatchers=!1;for(let fieldName in compiledInput){if(fieldName==="sequence")continue;if(RESERVED_BINDING_FIELDS2.has(fieldName))continue;let value=compiledInput[fieldName];if(value===void 0)continue;let compiler=bindingFieldCompilers.get(fieldName);if(!compiler){warnUnknownField("binding",fieldName);continue}compiler(value,{require(name,requiredValue){if(!mergedRequires)mergedRequires={};if(mergeRequirement2(mergedRequires,name,requiredValue,`field ${fieldName}`),!conditionKeys)conditionKeys=new Set;conditionKeys.add(name)},attr(name,attributeValue){if(!mergedAttrs)mergedAttrs={};mergeAttribute2(mergedAttrs,name,attributeValue,`field ${fieldName}`)},activeWhen:(matcher)=>{let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;if(!matchers)matchers=[];matchers.push(runtimeMatcher)}})}let attrs=mergedAttrs?snapshotAttributes2(mergedAttrs):void 0,command=normalizeBindingCommand2(compiledInput.cmd),compiledBinding={sequence:compiledSequence,command,event,sourceBinding:snapshotParsedBindingInput2(compiledInput),sourceTarget,sourceLayerOrder,sourceBindingIndex:bindingIndex,requires:mergedRequires?Object.entries(mergedRequires):EMPTY_REQUIRES2,matchers:matchers??EMPTY_MATCHERS2,conditionKeys:conditionKeys?[...conditionKeys]:EMPTY_CONDITION_KEYS2,hasUnkeyedMatchers,matchCacheDirty:!0,preventDefault:compiledInput.preventDefault!==!1,fallthrough:compiledInput.fallthrough??!1};if(attrs)compiledBinding.attrs=attrs;if(typeof command==="function")compiledBinding.run=command;if(compiledSequence.length===0)continue;if(event==="release"&&compiledSequence.length>1)throw Error("Keymap release bindings only support a single key stroke");if(event==="press")this.insertBinding(root,compiledBinding,allowExactPrefixAmbiguity);compiledBindings.push(compiledBinding)}catch(error2){this.notify.emitError("binding-compile-error",error2,getErrorMessage2(error2,"Failed to compile keymap binding"))}}}return{root,bindings:compiledBindings,hasTokenBindings}}parseObjectKeyPart(key,options){return createKeySequencePart2(key,options)}normalizeBindingEvent(event){if(event===void 0||event==="press")return"press";if(event==="release")return"release";throw Error(`Invalid keymap binding event "${String(event)}": expected "press" or "release"`)}applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields){let bindingTransformers=this.state.environment.bindingTransformers.values();if(bindingTransformers.length===0)return[{...binding,sequence:cloneKeySequence2(sequence)}];let parsedBinding={...binding,sequence:cloneKeySequence2(sequence)},extraBindings=[],keepOriginal=!0,layer=compileFields??EMPTY_COMPILE_FIELDS2;for(let transformer of bindingTransformers)try{transformer(parsedBinding,{layer,parseKey:(key)=>{return parseSingleKeyPartWithParsers2(key,bindingParsers,{tokens:tokens2,layer,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})},add:(nextBinding)=>{extraBindings.push(snapshotParsedBindingInput2(nextBinding))},skipOriginal:()=>{keepOriginal=!1}})}catch(error2){this.notify.emitError("binding-transformer-error",error2,"[Keymap] Error in binding transformer:")}if(!keepOriginal)return extraBindings;if(extraBindings.length===0)return[parsedBinding];return[parsedBinding,...extraBindings]}insertBinding(root,binding,allowExactPrefixAmbiguity){let node=root,touchedNodes=[],createdNodes=[];try{for(let part of binding.sequence){if(!allowExactPrefixAmbiguity&&node.bindings.some((candidate)=>candidate.command!==void 0))throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");let bindingKey=part.match,child=node.children.get(bindingKey);if(!child)child=createSequenceNode2(node,cloneKeySequencePart2(part).stroke,part.match),node.children.set(bindingKey,child),createdNodes.push({parent:node,key:bindingKey});child.reachableBindings.push(binding),touchedNodes.push(child),node=child}if(!allowExactPrefixAmbiguity&&binding.command!==void 0&&node.children.size>0)throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");node.bindings=[...node.bindings,binding]}catch(error2){for(let index=touchedNodes.length-1;index>=0;index-=1){let touchedNode=touchedNodes[index];if(!touchedNode)continue;if(touchedNode.reachableBindings.at(-1)===binding){touchedNode.reachableBindings.pop();continue}touchedNode.reachableBindings=touchedNode.reachableBindings.filter((candidate)=>candidate!==binding)}for(let index=createdNodes.length-1;index>=0;index-=1){let createdNode=createdNodes[index];if(!createdNode)continue;let child=createdNode.parent.children.get(createdNode.key);if(!child)continue;if(child.children.size>0||child.reachableBindings.length>0||child.bindings.length>0)continue;createdNode.parent.children.delete(createdNode.key)}throw error2}}}function expandBindingInputWithExpanders2(key,expanders,options){if(typeof key!=="string"||expanders.length===0)return[key];let layer=options?.layer??EMPTY_COMPILE_FIELDS2,candidates=[key];for(let expander of expanders){let nextCandidates=[];for(let input of candidates){let result2=expander({input,layer});if(!result2){nextCandidates.push(input);continue}if(result2.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${input}"`);for(let expandedInput of result2){if(typeof expandedInput!=="string")throw Error(`Keymap binding expander must return string key sequences for "${input}"`);nextCandidates.push(expandedInput)}}candidates=nextCandidates}return candidates}function parseBindingSequenceWithParsers2(key,parsers2,options){if(key.length===0)throw Error("Invalid key sequence: sequence cannot be empty");if(parsers2.length===0)throw Error("No keymap binding parsers are registered");let tokens2=options.tokens??new Map,layer=options.layer??EMPTY_COMPILE_FIELDS2,parseObjectKey=options.parseObjectKey,parts=[],usedTokens=new Set,unknownTokens=new Set,index=0;while(index<key.length){let matched=!1;for(let parser of parsers2){let result2=parser({input:key,index,layer,tokens:tokens2,normalizeTokenName:normalizeBindingTokenName2,createMatch:createTextKeyMatch2,parseObjectKey});if(!result2)continue;if(result2.nextIndex<=index||result2.nextIndex>key.length)throw Error(`Keymap binding parser must advance the input for "${key}" at index ${index}`);parts.push(...result2.parts);for(let tokenName of result2.usedTokens??[])usedTokens.add(tokenName);for(let tokenName of result2.unknownTokens??[])unknownTokens.add(tokenName);index=result2.nextIndex,matched=!0;break}if(!matched)throw Error(`No keymap binding parser handled input at index ${index} in "${key}"`)}return{parts,usedTokens:[...usedTokens],unknownTokens:[...unknownTokens],hasTokenBindings:usedTokens.size>0||unknownTokens.size>0}}function parseSingleKeyPartWithParsers2(key,parsers2,options){if(typeof key!=="string")return options.parseObjectKey(key);let{parts}=parseBindingSequenceWithParsers2(key,parsers2,options),[part]=parts;if(!part||parts.length!==1)throw Error(`Invalid key "${String(key)}": expected a single key stroke`);return part}function isReactiveMatcher2(value){if(!value||typeof value!=="object")return!1;let candidate=value;return typeof candidate.get==="function"&&typeof candidate.subscribe==="function"}class ConditionService2{state;notify;constructor(state,notify){this.state=state,this.notify=notify}buildRuntimeMatcher(matcher,source){if(typeof matcher==="function")return{source,match:matcher,cacheable:!1};if(isReactiveMatcher2(matcher))return{source,match:()=>matcher.get(),cacheable:!0,subscribe:(onChange)=>matcher.subscribe(onChange)};throw Error(`Keymap ${source} expected a function or a reactive matcher`)}hasNoConditions(target){return target.requires.length===0&&target.matchers.length===0}indexRuntimeMatchable(target){if(target.conditionKeys.length>0)for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(dependents){dependents.add(target);continue}this.state.conditions.runtimeKeyDependents.set(key,new Set([target]))}if(!target.hasUnkeyedMatchers)target.matchCacheDirty=!0}unindexRuntimeMatchable(target){if(target.conditionKeys.length===0)return;for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(!dependents)continue;if(dependents.delete(target),dependents.size===0)this.state.conditions.runtimeKeyDependents.delete(key)}}invalidateRuntimeConditionKey(name){let dependents=this.state.conditions.runtimeKeyDependents.get(name);if(!dependents)return;for(let target of dependents)target.matchCacheDirty=!0}matchesConditions(target){if(this.hasNoConditions(target))return!0;if(this.hasFreshConditionCache(target))return target.matchCache===!0;let matched=this.matchRequirements(target.requires)&&this.matchesRuntimeMatchers(target);return this.updateConditionCache(target,matched),matched}layerMatchesRuntimeState(layer){if(this.state.layers.layersWithConditions===0||this.hasNoConditions(layer))return!0;return this.matchesConditions(layer)}matchRequirements(requires){if(requires.length===0)return!0;for(let[name,value]of requires)if(!Object.is(this.state.runtime.data[name],value))return!1;return!0}hasFreshConditionCache(target){if(target.hasUnkeyedMatchers)return!1;return target.matchCacheDirty!==!0&&target.matchCache!==void 0}updateConditionCache(target,matched){if(target.hasUnkeyedMatchers)return;target.matchCacheDirty=!1,target.matchCache=matched}matchesRuntimeMatcher(matcher){try{return matcher.match()}catch(error2){return this.notify.emitError("runtime-matcher-error",error2,`[Keymap] Error evaluating runtime matcher from ${matcher.source}:`),!1}}matchesRuntimeMatchers(target){if(target.matchers.length===0)return!0;if(target.matchers.length===1){let[matcher]=target.matchers;return matcher?this.matchesRuntimeMatcher(matcher):!0}for(let matcher of target.matchers)if(!this.matchesRuntimeMatcher(matcher))return!1;return!0}}function createSyncDecision2(action,handler){return{[KEY_DISAMBIGUATION_DECISION2]:!0,action,handler}}function createDeferredDecision2(action){return{[KEY_DEFERRED_DISAMBIGUATION_DECISION2]:!0,action}}function isSyncDecision2(value){return!!value&&typeof value==="object"&&value[KEY_DISAMBIGUATION_DECISION2]===!0}function isDeferredDecision2(value){return!!value&&typeof value==="object"&&value[KEY_DEFERRED_DISAMBIGUATION_DECISION2]===!0}class DispatchService2{state;notify;runtime;activation;conditions;executor;compiler;catalog;layers;eventMatchResolverContext;pendingDisambiguation=null;nextPendingDisambiguationId=0;constructor(state,notify,runtime,activation,conditions,executor,compiler,catalog,layers){this.state=state,this.notify=notify,this.runtime=runtime,this.activation=activation,this.conditions=conditions,this.executor=executor,this.compiler=compiler,this.catalog=catalog,this.layers=layers,this.eventMatchResolverContext={resolveKey:(key)=>{return this.compiler.parseTokenKey(key).match}}}intercept(name,fn,options){if(name==="key"){let keyOptions=options;return this.state.dispatch.keyHooks.register(fn,{priority:keyOptions?.priority??0,release:keyOptions?.release??!1})}let rawOptions=options;return this.state.dispatch.rawHooks.register(fn,{priority:rawOptions?.priority??0})}prependEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.prepend(resolver)}appendEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.append(resolver)}clearEventMatchResolvers(){this.state.dispatch.eventMatchResolvers.clear()}prependDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.prepend(resolver),resolver)}appendDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.append(resolver),resolver)}clearDisambiguationResolvers(){if(!this.state.dispatch.disambiguationResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.dispatch.disambiguationResolvers.clear(),this.layers.recompileBindings()})}handlePendingSequenceChange(_previous,_next){if(!this.pendingDisambiguation)return;this.cancelPendingDisambiguation()}handleRawSequence(sequence){let hooks=this.state.dispatch.rawHooks.entries();if(hooks.length===0)return!1;let stopped=!1,context={sequence,stop(){stopped=!0}};for(let hook of hooks){try{hook.listener(context)}catch(error2){this.notify.emitError("raw-intercept-error",error2,"[Keymap] Error in raw intercept listener:")}if(stopped)return!0}return!1}handleKeyEvent(event,release){if(!release)this.cancelPendingDisambiguation();let hooks=this.state.dispatch.keyHooks.entries(),context={event,setData:(name,value)=>{this.runtime.setData(name,value)},getData:(name)=>{return this.runtime.getData(name)},consume:(options)=>{let shouldPreventDefault=options?.preventDefault??!0,shouldStopPropagation=options?.stopPropagation??!0;if(shouldPreventDefault)event.preventDefault();if(shouldStopPropagation)event.stopPropagation()}};for(let hook of hooks){if(hook.release!==release)continue;try{hook.listener(context)}catch(error2){this.notify.emitError("key-intercept-error",error2,"[Keymap] Error in key intercept listener:")}if(event.propagationStopped)return}if(release){this.dispatchReleaseLayers(event);return}this.dispatchLayers(event)}mutateDisambiguationResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let hadResolvers=this.state.dispatch.disambiguationResolvers.has(),off=register2();if(!hadResolvers&&this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings();return()=>{this.notify.runWithStateChangeBatch(()=>{let hadBeforeRemoval=this.state.dispatch.disambiguationResolvers.has();if(off(),this.state.dispatch.disambiguationResolvers.values().includes(resolver))return;if(hadBeforeRemoval&&!this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings()})}})}dispatchReleaseLayers(event){let focused=this.activation.getFocusedTarget(),activeLayers=this.activation.getActiveLayers(focused),hasLayerConditions=this.state.layers.layersWithConditions>0,matchKeys=this.resolveEventMatchKeys(event);layerLoop:for(let layer of activeLayers){if(layer.compiledBindings.length===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let strokeKey of matchKeys){let result2=this.runReleaseBindings(layer,strokeKey,event,focused);if(!result2.handled)continue;if(result2.stop)return;continue layerLoop}}}dispatchLayers(event){let focused=this.activation.getFocusedTarget(),pending=this.activation.ensureValidPendingSequence(),matchKeys=this.resolveEventMatchKeys(event);if(pending){this.dispatchPendingSequence(pending,matchKeys,event,focused);return}let activeLayers=this.activation.getActiveLayers(focused);this.dispatchFromRoot(activeLayers,matchKeys,event,focused)}dispatchPendingSequence(pending,matchKeys,event,focused){let advancedCaptures=[];for(let capture2 of pending.captures){let nextNode=this.getReachableChild(capture2.node,matchKeys,focused);if(!nextNode)continue;advancedCaptures.push({layer:capture2.layer,node:nextNode})}if(advancedCaptures.length===0){this.activation.setPendingSequence(null);return}this.dispatchPendingCapturesFromIndex(advancedCaptures,0,!1,event,focused)}dispatchPendingCapturesFromIndex(advancedCaptures,startIndex,handledExact,event,focused){let hasHandledExact=handledExact;for(let index=startIndex;index<advancedCaptures.length;index+=1){let capture2=advancedCaptures[index];if(!capture2)continue;if(capture2.node.children.size>0){if(hasHandledExact)continue;let continuationCaptures=this.collectPendingCapturesFromAdvanced(advancedCaptures,index);if(this.tryResolvePendingAmbiguity(advancedCaptures,index,continuationCaptures,capture2,event,focused,hasHandledExact))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(!result2.handled)continue;if(hasHandledExact=!0,result2.stop){this.activation.setPendingSequence(null);return}}this.activation.setPendingSequence(null)}dispatchFromRoot(activeLayers,matchKeys,event,focused){this.dispatchFromRootAtIndex(activeLayers,0,matchKeys,event,focused)}dispatchFromRootAtIndex(activeLayers,startIndex,matchKeys,event,focused){let hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer)continue;if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode)continue;if(nextNode.children.size>0){let continuationCaptures=this.collectPendingCapturesFromRoot(activeLayers,index,matchKeys,focused);if(this.tryResolveRootAmbiguity(activeLayers,index,matchKeys,continuationCaptures,layer,nextNode,event,focused))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(layer,nextNode.bindings,event,focused);if(!result2.handled)continue;if(result2.stop)return}}tryResolveRootAmbiguity(activeLayers,layerIndex,matchKeys,continuationCaptures,layer,node,event,focused){let applyExact=()=>{if(this.activation.setPendingSequence(null),!this.runBindings(layer,node.bindings,event,focused).stop)this.dispatchFromRootAtIndex(activeLayers,layerIndex+1,matchKeys,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:node.bindings,runExact:applyExact})}tryResolvePendingAmbiguity(advancedCaptures,captureIndex,continuationCaptures,capture2,event,focused,handledExact){let applyExact=()=>{this.activation.setPendingSequence(null);let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(result2.stop)return;this.dispatchPendingCapturesFromIndex(advancedCaptures,captureIndex+1,handledExact||result2.handled,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:capture2.node.bindings,runExact:applyExact})}tryResolveAmbiguity(options){let{event,focused,continuationCaptures,exactBindingsSource,runExact}=options;if(!this.state.dispatch.disambiguationResolvers.has()||continuationCaptures.length===0)return!1;let activeView=this.catalog.getActiveCommandView(focused),exactBindings=this.activation.collectMatchingBindings(exactBindingsSource,focused,activeView);if(!exactBindings.some((binding)=>binding.command!==void 0))return!1;let continueSequence=()=>{this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation()},clear=()=>{this.activation.setPendingSequence(null),event.preventDefault(),event.stopPropagation()},sequence,getSequence=()=>{return sequence??=this.activation.collectSequencePartsFromPending({captures:continuationCaptures}),sequence},decision=this.resolveDisambiguation({event,focused,getSequence,exactBindings,continuationCaptures,activeView});if(!decision)return this.warnUnresolvedAmbiguity(getSequence()),continueSequence(),!0;return this.applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence)}applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence){if(decision.action==="run-exact")return runExact(),!0;if(decision.action==="continue-sequence")return continueSequence(),!0;if(decision.action==="clear")return clear(),!0;return continueSequence(),this.scheduleDeferredDisambiguation(continuationCaptures,decision.handler,focused,getSequence(),(nextDecision)=>{if(!nextDecision)return;if(nextDecision.action==="run-exact"){runExact();return}if(nextDecision.action==="continue-sequence"){continueSequence();return}clear()}),!0}resolveDisambiguation(options){let activation=this.activation,runtime=this.runtime,sequence,exact,continuations,strokePart,ctx={event:options.event,focused:options.focused,get sequence(){return sequence??=cloneKeySequence2(options.getSequence()),sequence},get stroke(){let stroke=options.getSequence().at(-1);if(!stroke)throw Error("Disambiguation context expected a non-empty sequence");return strokePart??={...stroke,stroke:cloneKeyStroke2(stroke.stroke)},strokePart},get exact(){return exact??=activation.collectActiveBindings(options.exactBindings,options.focused,options.activeView).map((binding)=>({...binding,sequence:cloneKeySequence2(binding.sequence)})),exact},get continuations(){return continuations??=activation.getActiveKeysForCaptures(options.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),continuations},getData:(name)=>{return runtime.getData(name)},setData:(name,value)=>{runtime.setData(name,value)},runExact:()=>createSyncDecision2("run-exact"),continueSequence:()=>createSyncDecision2("continue-sequence"),clear:()=>createSyncDecision2("clear"),defer:(run)=>createSyncDecision2("defer",run)};for(let resolver of this.state.dispatch.disambiguationResolvers.values()){let result2;try{result2=resolver(ctx)}catch(error2){this.notify.emitError("disambiguation-resolver-error",error2,"[Keymap] Error in disambiguation resolver:");continue}if(result2===void 0)continue;if(isPromiseLike2(result2)){this.notify.emitError("invalid-disambiguation-resolver-return",result2,"[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling");continue}if(!isSyncDecision2(result2)){this.notify.emitError("invalid-disambiguation-decision",result2,"[Keymap] Invalid disambiguation decision returned by resolver:");continue}return result2}return}scheduleDeferredDisambiguation(captures,handler,focused,sequence,apply){this.cancelPendingDisambiguation();let controller=new AbortController,pending={id:this.nextPendingDisambiguationId++,controller,captures,apply};this.pendingDisambiguation=pending,queueMicrotask(()=>{this.executeDeferredDisambiguation(pending,handler,focused,sequence)})}executeDeferredDisambiguation(pending,handler,focused,sequence){if(!this.isPendingDisambiguationCurrent(pending))return;let ctx={signal:pending.controller.signal,sequence:cloneKeySequence2(sequence),focused,sleep:(ms)=>{return this.sleepWithSignal(ms,pending.controller.signal)},runExact:()=>createDeferredDecision2("run-exact"),continueSequence:()=>createDeferredDecision2("continue-sequence"),clear:()=>createDeferredDecision2("clear")},result2;try{result2=handler(ctx)}catch(error2){if(this.isPendingDisambiguationCurrent(pending))this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending);return}if(isPromiseLike2(result2)){result2.then((resolved)=>{this.applyDeferredDisambiguationResult(pending,resolved)}).catch((error2)=>{if(!this.isPendingDisambiguationCurrent(pending))return;this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending)});return}this.applyDeferredDisambiguationResult(pending,result2)}applyDeferredDisambiguationResult(pending,result2){if(!this.isPendingDisambiguationCurrent(pending))return;if(result2!==void 0&&!isDeferredDecision2(result2)){this.notify.emitError("invalid-deferred-disambiguation-decision",result2,"[Keymap] Invalid deferred disambiguation decision returned by handler:"),this.finishPendingDisambiguation(pending);return}this.finishPendingDisambiguation(pending),pending.apply(result2)}finishPendingDisambiguation(pending){if(!this.isPendingDisambiguationCurrent(pending))return;this.pendingDisambiguation=null}cancelPendingDisambiguation(){let pending=this.pendingDisambiguation;if(!pending)return;this.pendingDisambiguation=null,pending.controller.abort()}isPendingDisambiguationCurrent(pending){return this.pendingDisambiguation===pending}sleepWithSignal(ms,signal){if(signal.aborted)return Promise.resolve(!1);return new Promise((resolve21)=>{let timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve21(!0)},Math.max(0,ms)),onAbort=()=>{clearTimeout(timeout),signal.removeEventListener("abort",onAbort),resolve21(!1)};signal.addEventListener("abort",onAbort,{once:!0})})}warnUnresolvedAmbiguity(sequence){let display=stringifyKeySequence2(sequence,{preferDisplay:!0});this.notify.warnOnce(`unresolved-disambiguation:${display}`,"unresolved-disambiguation",{sequence:display},`[Keymap] Ambiguous exact/prefix sequence "${display}" fell back to prefix handling because no disambiguation resolver resolved it`)}collectPendingCapturesFromRoot(activeLayers,startIndex,matchKeys,focused){let captures=[],hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer||layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode||nextNode.children.size===0)continue;captures.push({layer,node:nextNode})}return captures}collectPendingCapturesFromAdvanced(advancedCaptures,startIndex){return advancedCaptures.filter((candidate,candidateIndex)=>{return candidateIndex>=startIndex&&candidate.node.children.size>0})}resolveEventMatchKeys(event){let resolvers=this.state.dispatch.eventMatchResolvers.values();if(resolvers.length===0)return[];if(resolvers.length===1)return resolveSingleEventMatchKeys2(resolvers[0],event,this.eventMatchResolverContext,this.notify);let keys=[],seen=new Set;for(let resolver of resolvers){let resolved;try{resolved=resolver(event,this.eventMatchResolverContext)}catch(error2){this.notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:");continue}if(!resolved||resolved.length===0)continue;for(let candidate of resolved){if(typeof candidate!=="string"){this.notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}}return keys}runReleaseBindings(layer,strokeKey,event,focused){let handled=!1;for(let binding of layer.compiledBindings){if(binding.event!=="release")continue;let firstPart=binding.sequence[0];if(!firstPart||firstPart.match!==strokeKey)continue;if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}getReachableChild(node,matchKeys,focused){for(let strokeKey of matchKeys){let child=node.children.get(strokeKey);if(!child||!this.activation.nodeHasReachableBindings(child,focused))continue;return child}return}runBindings(layer,bindings,event,focused){let handled=!1;for(let binding of bindings){if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}}function resolveSingleEventMatchKeys2(resolver,event,ctx,notify){let resolved;try{resolved=resolver(event,ctx)}catch(error2){return notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:"),[]}if(!resolved||resolved.length===0)return[];if(resolved.length===1){let[candidate]=resolved;if(typeof candidate!=="string")return notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:"),[];return[candidate]}let keys=[],seen=new Set;for(let candidate of resolved){if(typeof candidate!=="string"){notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}return keys}function registerFieldCompilers2(fields,options){let{kind,reservedFields,registeredFields,emitError}=options,entries=Object.entries(fields),registered=[];for(let[name]of entries){if(reservedFields.has(name)){emitError(`reserved-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is reserved`);continue}if(registeredFields.has(name))emitError(`duplicate-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is already registered`)}for(let[name,compiler]of entries){if(reservedFields.has(name)||registeredFields.has(name))continue;registeredFields.set(name,compiler),registered.push([name,compiler])}return()=>{for(let[name,compiler]of registered)if(registeredFields.get(name)===compiler)registeredFields.delete(name)}}class EnvironmentService2{state;notify;compiler;layers;constructor(state,notify,compiler,layers){this.state=state,this.notify=notify,this.compiler=compiler,this.layers=layers}prependBindingTransformer(transformer){return this.state.environment.bindingTransformers.prepend(transformer)}appendBindingTransformer(transformer){return this.state.environment.bindingTransformers.append(transformer)}clearBindingTransformers(){this.state.environment.bindingTransformers.clear()}prependBindingParser(parser){return this.state.environment.bindingParsers.prepend(parser)}appendBindingParser(parser){return this.state.environment.bindingParsers.append(parser)}clearBindingParsers(){this.state.environment.bindingParsers.clear()}registerToken(token){let normalizedToken;try{normalizedToken=normalizeBindingTokenName2(token.name)}catch(error2){return this.notify.emitError("token-name-normalize-error",error2,getErrorMessage2(error2,"Failed to register keymap token")),NOOP3}if(this.state.environment.tokens.has(normalizedToken))return this.notify.emitError("duplicate-token",{token:normalizedToken},`Keymap token "${normalizedToken}" is already registered`),NOOP3;let parsedToken;try{parsedToken=this.compiler.parseTokenKey(token.key)}catch(error2){return this.notify.emitError("token-parse-error",error2,getErrorMessage2(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP3}let registeredToken={stroke:parsedToken.stroke,match:parsedToken.match},nextTokens=new Map(this.state.environment.tokens);nextTokens.set(normalizedToken,registeredToken);try{this.layers.applyTokenState(nextTokens)}catch(error2){return this.notify.emitError("token-register-error",error2,getErrorMessage2(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP3}return()=>{if(this.state.environment.tokens.get(normalizedToken)!==registeredToken)return;let nextTokens2=new Map(this.state.environment.tokens);nextTokens2.delete(normalizedToken);try{this.layers.applyTokenState(nextTokens2)}catch(error2){this.notify.emitError("token-unregister-error",error2,getErrorMessage2(error2,`Failed to unregister keymap token "${normalizedToken}"`))}}}prependBindingExpander(expander){return this.state.environment.bindingExpanders.prepend(expander)}appendBindingExpander(expander){return this.state.environment.bindingExpanders.append(expander)}clearBindingExpanders(){this.state.environment.bindingExpanders.clear()}registerLayerFields(fields){return registerFieldCompilers2(fields,{kind:"layer",reservedFields:RESERVED_LAYER_FIELDS2,registeredFields:this.state.environment.layerFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerBindingFields(fields){return registerFieldCompilers2(fields,{kind:"binding",reservedFields:RESERVED_BINDING_FIELDS2,registeredFields:this.state.environment.bindingFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerCommandFields(fields){return registerFieldCompilers2(fields,{kind:"command",reservedFields:RESERVED_COMMAND_FIELDS2,registeredFields:this.state.environment.commandFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}}function sortLayers2(layers){return[...layers].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return right.order-left.order})}function createCommandLookup2(commands){if(commands.length===0)return;let lookup=new Map;for(let command of commands)lookup.set(command.name,command);return lookup}function addRegisteredCommandNames2(target,commands){for(let command of commands)target.set(command.name,(target.get(command.name)??0)+1)}function removeRegisteredCommandNames2(target,commands){for(let command of commands){let count=target.get(command.name);if(!count||count<=1){target.delete(command.name);continue}target.set(command.name,count-1)}}function getSequenceNode2(root,sequence){let node=root;for(let part of sequence)if(node=node.children.get(part.match),!node)return;return node}function buildLayerBindingAnalyses2(root,compiledBindings){return compiledBindings.map((binding)=>{let node=binding.event==="press"?getSequenceNode2(root,binding.sequence):void 0;return{sequence:cloneKeySequence2(binding.sequence),command:binding.command,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough,sourceBinding:snapshotParsedBindingInput2(binding.sourceBinding),sourceTarget:binding.sourceTarget,sourceLayerOrder:binding.sourceLayerOrder,sourceBindingIndex:binding.sourceBindingIndex,hasCommandAtSequence:node?node.bindings.some((candidate)=>candidate.command!==void 0):!1,hasContinuations:node?node.children.size>0:!1}})}class LayerService2{state;notify;conditions;activation;options;constructor(state,notify,conditions,activation,options){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation,this.options=options}registerLayer(layer){return this.notify.runWithStateChangeBatch(()=>{let target=layer.target;if(target&&this.options.host.isTargetDestroyed(target))return this.notify.emitError("destroyed-layer-target",{target},"Cannot register a keymap layer for a destroyed keymap target"),NOOP22;let bindingInputs,requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields,commands,commandLookup,targetMode;try{targetMode=this.normalizeTargetMode(layer),bindingInputs=snapshotBindingInputs2(layer.bindings??[]),commands=!layer.commands||layer.commands.length===0?[]:this.options.commands.normalizeCommands(layer.commands),commandLookup=createCommandLookup2(commands),{requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields}=this.compileLayerRuntimeState(layer)}catch(error2){return this.notify.emitError("register-layer-failed",error2,getErrorMessage2(error2,"Failed to register keymap layer")),NOOP22}let order=this.state.core.order++,compiledBindings=this.options.compiler.compileBindings(bindingInputs,this.state.environment.tokens,target,order,compileFields);if(compiledBindings.bindings.length===0&&!compiledBindings.hasTokenBindings&&commands.length===0)return NOOP22;this.runLayerAnalyzers({target,order,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,root:compiledBindings.root,hasTokenBindings:compiledBindings.hasTokenBindings});let registeredLayer={order,target,targetMode,priority:layer.priority??0,requires,matchers,conditionKeys,hasUnkeyedMatchers,matchCacheDirty:!0,compileFields,commands,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,hasUnkeyedCommands:commands.some((command)=>command.hasUnkeyedMatchers),hasUnkeyedBindings:compiledBindings.bindings.some((binding)=>binding.hasUnkeyedMatchers),hasTokenBindings:compiledBindings.hasTokenBindings,root:compiledBindings.root};if(this.state.layers.layers.add(registeredLayer),registeredLayer.commands.length>0)this.state.layers.layersWithCommands+=1,this.state.commands.commandMetadataVersion+=1,addRegisteredCommandNames2(this.state.commands.registeredNames,registeredLayer.commands);if(registeredLayer.requires.length>0||registeredLayer.matchers.length>0)this.state.layers.layersWithConditions+=1;this.connectRuntimeMatchable(registeredLayer);for(let command of registeredLayer.commands)this.connectRuntimeMatchable(command);for(let binding of registeredLayer.compiledBindings)this.connectRuntimeMatchable(binding);if(this.indexLayer(registeredLayer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),target){let onTargetDestroy=()=>{this.unregisterLayer(registeredLayer)};registeredLayer.offTargetDestroy=this.options.host.onTargetDestroy(target,onTargetDestroy)}if(registeredLayer.commands.length>0)this.activation.ensureValidPendingSequence();return this.notify.queueStateChange(),()=>{this.unregisterLayer(registeredLayer)}})}applyTokenState(nextTokens){this.notify.runWithStateChangeBatch(()=>{let nextCompilations=new Map;for(let layer of this.state.layers.layers){if(!layer.hasTokenBindings)continue;nextCompilations.set(layer,this.compileLayerBindings(layer,nextTokens))}this.state.environment.tokens=nextTokens;let shouldClearPending=!1;for(let[layer,compilation]of nextCompilations)if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;if(shouldClearPending)this.activation.setPendingSequence(null);if(nextCompilations.size>0)this.notify.queueStateChange()})}recompileBindings(){this.notify.runWithStateChangeBatch(()=>{let recompiledLayers=0,shouldClearPending=!1;for(let layer of this.state.layers.layers){if(layer.bindingInputs.length===0)continue;let compilation=this.compileLayerBindings(layer,this.state.environment.tokens);if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;recompiledLayers+=1}if(shouldClearPending)this.activation.setPendingSequence(null);if(recompiledLayers>0)this.notify.queueStateChange()})}prependLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.prepend(analyzer)}appendLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.append(analyzer)}clearLayerAnalyzers(){this.state.layers.layerAnalyzers.clear()}cleanup(){for(let layer of this.state.layers.layers){this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0}}normalizeTargetMode(layer){if(layer.targetMode){if(!layer.target)throw Error(`Keymap targetMode "${layer.targetMode}" requires a target`);return layer.targetMode}return layer.target?"focus-within":void 0}runLayerAnalyzers(options){let analyzers=this.state.layers.layerAnalyzers.values();if(analyzers.length===0)return;let bindings=buildLayerBindingAnalyses2(options.root,options.compiledBindings),ctx={target:options.target,order:options.order,bindingInputs:options.bindingInputs,bindings,hasTokenBindings:options.hasTokenBindings,checkCommandResolution:(command)=>{return this.options.commands.getCommandResolutionStatus(command,options.commandLookup)},warn:(code,warning,message)=>{this.notify.emitWarning(code,warning,message)},warnOnce:(key,code,warning,message)=>{this.notify.warnOnce(key,code,warning,message)},error:(code,error2,message)=>{this.notify.emitError(code,error2,message)}};for(let analyzer of analyzers)try{analyzer(ctx)}catch(error2){this.notify.emitError("layer-analyzer-error",error2,"[Keymap] Error in layer analyzer:")}}compileLayerRuntimeState(layer){let mergedRequires={},matchers=[],compileFields=Object.create(null),conditionKeys=new Set,hasUnkeyedMatchers=!1;for(let[fieldName,value]of Object.entries(layer)){if(RESERVED_LAYER_FIELDS2.has(fieldName))continue;if(value===void 0)continue;compileFields[fieldName]=snapshotDataValue2(value);let compiler=this.state.environment.layerFields.get(fieldName);if(!compiler){this.options.warnUnknownField("layer",fieldName);continue}compiler(value,{require:(name,requiredValue)=>{mergeRequirement2(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},activeWhen:(matcher)=>{let runtimeMatcher=this.conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;matchers.push(runtimeMatcher)}})}return{requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,compileFields:Object.keys(compileFields).length>0?Object.freeze(compileFields):void 0}}compileLayerBindings(layer,tokens2){return this.options.compiler.compileBindings(layer.bindingInputs,tokens2,layer.target,layer.order,layer.compileFields)}applyCompiledBindings(layer,compilation){this.runLayerAnalyzers({target:layer.target,order:layer.order,commandLookup:layer.commandLookup,bindingInputs:layer.bindingInputs,compiledBindings:compilation.bindings,root:compilation.root,hasTokenBindings:compilation.hasTokenBindings});for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.root=compilation.root,layer.compiledBindings=compilation.bindings,layer.hasUnkeyedBindings=compilation.bindings.some((binding)=>binding.hasUnkeyedMatchers),layer.hasTokenBindings=compilation.hasTokenBindings;for(let binding of layer.compiledBindings)this.connectRuntimeMatchable(binding);return this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer)??!1}indexLayer(layer){this.state.layers.sortedLayers=sortLayers2([...this.state.layers.sortedLayers,layer]),this.state.layers.activeLayersVersion+=1}removeLayerFromIndex(layer){this.state.layers.sortedLayers=this.state.layers.sortedLayers.filter((candidate)=>candidate!==layer),this.state.layers.activeLayersVersion+=1}unregisterLayer(layer){this.notify.runWithStateChangeBatch(()=>{if(!this.state.layers.layers.delete(layer))return;if(layer.requires.length>0||layer.matchers.length>0)this.state.layers.layersWithConditions-=1;if(layer.commands.length>0)this.state.layers.layersWithCommands-=1,this.state.commands.commandMetadataVersion+=1,removeRegisteredCommandNames2(this.state.commands.registeredNames,layer.commands);this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);if(this.removeLayerFromIndex(layer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0,this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer))this.activation.setPendingSequence(null);else if(layer.commands.length>0&&!this.options.host.isDestroyed)this.activation.ensureValidPendingSequence();this.notify.queueStateChange()})}connectRuntimeMatchable(target){this.attachReactiveMatchers(target),this.conditions.indexRuntimeMatchable(target)}disconnectRuntimeMatchable(target){this.detachReactiveMatchers(target),this.conditions.unindexRuntimeMatchable(target)}attachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.subscribe)continue;try{matcher.dispose=matcher.subscribe(()=>{if(target.matchCacheDirty=!0,!this.activation.hasPendingSequenceState()){this.notify.queueStateChange();return}this.notify.runWithStateChangeBatch(()=>{this.activation.revalidatePendingSequenceIfNeeded(),this.notify.queueStateChange()})})}catch(error2){this.notify.emitError("reactive-matcher-subscribe-error",error2,getErrorMessage2(error2,`Failed to subscribe to reactive matcher from ${matcher.source}`))}}}detachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.dispose)continue;try{matcher.dispose()}catch(error2){this.notify.emitError("reactive-matcher-dispose-error",error2,getErrorMessage2(error2,`Failed to dispose reactive matcher from ${matcher.source}`))}matcher.dispose=void 0}}}class Emitter3{onError;listeners=Object.create(null);constructor(onError){this.onError=onError}hook(name,listener){let current=this.listeners[name]??[];return this.listeners[name]=[...current,listener],()=>{let current2=this.listeners[name];if(!current2||current2.length===0)return;let next=current2.filter((candidate)=>candidate!==listener);if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}}has(name){return(this.listeners[name]?.length??0)>0}off(name,listener){let current=this.listeners[name];if(!current||current.length===0)return;let next=current.filter((candidate)=>candidate!==listener);if(next.length===current.length)return;if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}clear(){this.listeners=Object.create(null)}emit(name,...args){let listeners2=this.listeners[name];if(!listeners2||listeners2.length===0)return;for(let listener of listeners2)try{if(args.length===0)listener();else listener(args[0])}catch(error2){this.onError(name,error2)}}}class NotificationService2{state;events;hooks;constructor(state,events,hooks){this.state=state,this.events=events,this.hooks=hooks}runWithStateChangeBatch(fn){this.state.notify.stateChangeDepth+=1;try{return fn()}finally{if(this.state.notify.stateChangeDepth-=1,this.state.notify.stateChangeDepth===0)this.flushStateChange()}}queueStateChange(){if(this.state.notify.derivedStateVersion+=1,!this.hooks.has("state"))return;if(this.state.notify.stateChangePending=!0,this.state.notify.stateChangeDepth===0&&!this.state.notify.flushingStateChange)this.flushStateChange()}emitWarning(code,warning,message){if(!this.events.has("warning")){let consoleMessage=`[${code}] ${message}`;if(warning instanceof Error)console.warn(consoleMessage,warning);else console.warn(consoleMessage);return}this.events.emit("warning",{code,message,warning})}emitError(code,error2,message){if(!this.events.has("error")){let consoleMessage=`[${code}] ${message}`;if(error2 instanceof Error)console.error(consoleMessage,error2);else console.error(consoleMessage);return}this.events.emit("error",{code,message,error:error2})}reportListenerError(name,error2){if(name==="state"){this.emitError("state-listener-error",error2,"[Keymap] Error in state listener:");return}if(name==="pendingSequence"){this.emitError("pending-sequence-listener-error",error2,"[Keymap] Error in pending sequence listener:");return}}warnOnce(key,code,warning,message){if(this.state.notify.usedWarningKeys.has(key))return;this.state.notify.usedWarningKeys.add(key),this.emitWarning(code,warning,message)}flushStateChange(){if(!this.state.notify.stateChangePending||this.state.notify.stateChangeDepth>0||this.state.notify.flushingStateChange)return;this.state.notify.flushingStateChange=!0;try{let iterations=0;while(this.state.notify.stateChangePending&&this.state.notify.stateChangeDepth===0){if(iterations>=MAX_STATE_CHANGE_FLUSH_ITERATIONS2){this.state.notify.stateChangePending=!1,this.emitError("state-change-feedback-loop",{iterations:MAX_STATE_CHANGE_FLUSH_ITERATIONS2},`[Keymap] Possible infinite state listener feedback loop detected after ${MAX_STATE_CHANGE_FLUSH_ITERATIONS2} iterations; pending state notifications were dropped`);break}iterations+=1,this.state.notify.stateChangePending=!1,this.hooks.emit("state")}}finally{this.state.notify.flushingStateChange=!1}}}class RuntimeService2{state;notify;conditions;activation;constructor(state,notify,conditions,activation){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation}getData(name){return this.state.runtime.data[name]}setData(name,value){this.notify.runWithStateChangeBatch(()=>{if(value===void 0){if(!(name in this.state.runtime.data))return;delete this.state.runtime.data[name],this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange();return}if(Object.is(this.state.runtime.data[name],value))return;this.state.runtime.data[name]=value,this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange()})}getReadonlyData(){if(this.state.runtime.readonlyDataVersion===this.state.runtime.dataVersion)return this.state.runtime.readonlyData;return this.state.runtime.readonlyData=Object.freeze({...this.state.runtime.data}),this.state.runtime.readonlyDataVersion=this.state.runtime.dataVersion,this.state.runtime.readonlyData}}class CopyOnWriteRegistry2{items=[];getItems(){return this.items}setItems(items){this.items=items}removeItem(value){let current=this.items;if(current.length===0)return!1;let next=current.filter((candidate)=>candidate!==value);if(next.length===current.length)return!1;return this.items=next,!0}has(){return this.items.length>0}clear(){this.items=[]}}function createKeymapState2(){return{core:{order:0},environment:{tokens:new Map,layerFields:new Map,bindingExpanders:new OrderedRegistry2,bindingParsers:new OrderedRegistry2,bindingTransformers:new OrderedRegistry2,bindingFields:new Map,commandFields:new Map},dispatch:{eventMatchResolvers:new OrderedRegistry2,disambiguationResolvers:new OrderedRegistry2,keyHooks:new PriorityRegistry2,rawHooks:new PriorityRegistry2},layers:{layers:new Set,sortedLayers:[],activeLayersVersion:0,activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],layersWithConditions:0,layersWithCommands:0,layerAnalyzers:new OrderedRegistry2},commands:{commandMetadataVersion:0,registeredNames:new Map,commandResolvers:new OrderedRegistry2,activeCommandViewVersion:-1,activeCommandView:void 0,registeredCommandViewVersion:-1,registeredCommandView:void 0,registeredCommandEntriesCacheVersion:-1,registeredCommandEntriesCache:[]},projection:{pendingSequence:null,pendingSequenceCacheVersion:-1,pendingSequenceCache:[],activeKeysPlainCacheVersion:-1,activeKeysPlainCache:[],activeKeysBindingsCacheVersion:-1,activeKeysBindingsCache:[],activeKeysMetadataCacheVersion:-1,activeKeysMetadataCache:[],activeKeysBindingsAndMetadataCacheVersion:-1,activeKeysBindingsAndMetadataCache:[]},conditions:{runtimeKeyDependents:new Map},runtime:{data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:EMPTY_DATA2},notify:{derivedStateVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}}function getKeyMatchKey2(input){return resolveKeyMatch2(input)}class Keymap2{host;state=createKeymapState2();cleanedUp=!1;resources=new Map;cleanupListeners=[];events=new Emitter3(()=>{});hooks;notify;activation;runtime;conditions;catalog;executor;compiler;dispatch;layers;environment;keypressListener;keyreleaseListener;rawListener;focusedTargetListener;constructor(host){if(this.host=host,host.isDestroyed)throw Error("Cannot create a keymap for a destroyed host");if(this.hooks=new Emitter3((name,error2)=>{this.notify.reportListenerError(name,error2)}),this.notify=new NotificationService2(this.state,this.events,this.hooks),this.conditions=new ConditionService2(this.state,this.notify),this.catalog=new CommandCatalogService2(this.state,this.host,this.notify,this.conditions,{onCommandResolversChanged:()=>{this.activation.ensureValidPendingSequence()}}),this.activation=new ActivationService2(this.state,this.host,this.hooks,this.notify,this.conditions,this.catalog,{onPendingSequenceChanged:(previous,next)=>{this.dispatch?.handlePendingSequenceChange(previous,next)}}),this.runtime=new RuntimeService2(this.state,this.notify,this.conditions,this.activation),this.executor=new CommandExecutorService2(this.notify,this.runtime,this.activation,this.catalog,{keymap:this,createCommandEvent:()=>this.host.createCommandEvent()}),this.compiler=new CompilerService2(this.state,this.notify,this.conditions,{warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)},warnUnknownToken:(token,sequence)=>{this.warnUnknownToken(token,sequence)}}),this.layers=new LayerService2(this.state,this.notify,this.conditions,this.activation,{compiler:this.compiler,commands:this.catalog,host:this.host,warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)}}),this.environment=new EnvironmentService2(this.state,this.notify,this.compiler,this.layers),this.dispatch=new DispatchService2(this.state,this.notify,this.runtime,this.activation,this.conditions,this.executor,this.compiler,this.catalog,this.layers),this.keypressListener=(event)=>{this.dispatch.handleKeyEvent(event,!1)},this.keyreleaseListener=(event)=>{this.dispatch.handleKeyEvent(event,!0)},this.rawListener=(sequence)=>{return this.dispatch.handleRawSequence(sequence)},this.focusedTargetListener=(focused)=>{this.handleFocusedTargetChange(focused)},this.cleanupListeners.push(this.host.onKeyPress(this.keypressListener)),this.cleanupListeners.push(this.host.onKeyRelease(this.keyreleaseListener)),this.host.onRawInput)this.cleanupListeners.push(this.host.onRawInput(this.rawListener));if(this.cleanupListeners.push(this.host.onFocusChange(this.focusedTargetListener)),this.host.onDestroy)this.cleanupListeners.push(this.host.onDestroy(()=>{this.cleanup()}))}cleanup(){if(this.cleanedUp)return;this.cleanedUp=!0,this.activation.setPendingSequence(null);for(let resource of this.resources.values())resource.dispose();this.resources.clear(),this.layers.cleanup();for(let cleanupListener of this.cleanupListeners.splice(0))cleanupListener()}setData(name,value){this.runtime.setData(name,value)}getData(name){return this.runtime.getData(name)}hasPendingSequence(){return this.activation.ensureValidPendingSequence()!==void 0}getPendingSequence(){return this.activation.getPendingSequence()}createKeyMatcher(key){let match=this.compiler.parseTokenKey(key).match;return(input)=>{if(!input)return!1;return getKeyMatchKey2(input)===match}}clearPendingSequence(){this.activation.setPendingSequence(null)}popPendingSequence(){return this.activation.popPendingSequence()}getActiveKeys(options){return this.activation.getActiveKeys(options)}getCommands(query2){return this.catalog.getCommands(query2)}getCommandEntries(query2){return this.catalog.getCommandEntries(query2)}normalizeCommandName(name){return normalizeCommandName2(name)}normalizeBindings(bindings){return normalizeBindingInputs2(bindings)}acquireResource(key,setup){if(this.cleanedUp||this.host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");let existing=this.resources.get(key);if(existing)return existing.count+=1,()=>{this.releaseResource(key,existing)};let resource={count:1,dispose:setup()};return this.resources.set(key,resource),()=>{this.releaseResource(key,resource)}}runCommand(cmd,options){return this.executor.runCommand(cmd,options)}dispatchCommand(cmd,options){return this.executor.dispatchCommand(cmd,options)}on(name,fn){if(name==="warning")return this.events.hook(name,fn);if(name==="error")return this.events.hook(name,fn);return this.hooks.hook(name,fn)}intercept(name,fn,options){if(name==="key")return this.dispatch.intercept(name,fn,options);return this.dispatch.intercept(name,fn,options)}registerLayer(layer){return this.layers.registerLayer(layer)}registerLayerFields(fields){return this.environment.registerLayerFields(fields)}prependBindingTransformer(transformer){return this.environment.prependBindingTransformer(transformer)}appendBindingTransformer(transformer){return this.environment.appendBindingTransformer(transformer)}clearBindingTransformers(){this.environment.clearBindingTransformers()}prependBindingParser(parser){return this.environment.prependBindingParser(parser)}appendBindingParser(parser){return this.environment.appendBindingParser(parser)}clearBindingParsers(){this.environment.clearBindingParsers()}registerToken(token){return this.environment.registerToken(token)}prependBindingExpander(expander){return this.environment.prependBindingExpander(expander)}appendBindingExpander(expander){return this.environment.appendBindingExpander(expander)}clearBindingExpanders(){this.environment.clearBindingExpanders()}registerBindingFields(fields){return this.environment.registerBindingFields(fields)}registerCommandFields(fields){return this.environment.registerCommandFields(fields)}prependCommandResolver(resolver){return this.catalog.prependCommandResolver(resolver)}appendCommandResolver(resolver){return this.catalog.appendCommandResolver(resolver)}clearCommandResolvers(){this.catalog.clearCommandResolvers()}prependLayerAnalyzer(analyzer){return this.layers.prependLayerAnalyzer(analyzer)}appendLayerAnalyzer(analyzer){return this.layers.appendLayerAnalyzer(analyzer)}clearLayerAnalyzers(){this.layers.clearLayerAnalyzers()}prependEventMatchResolver(resolver){return this.dispatch.prependEventMatchResolver(resolver)}appendEventMatchResolver(resolver){return this.dispatch.appendEventMatchResolver(resolver)}clearEventMatchResolvers(){this.dispatch.clearEventMatchResolvers()}prependDisambiguationResolver(resolver){return this.dispatch.prependDisambiguationResolver(resolver)}appendDisambiguationResolver(resolver){return this.dispatch.appendDisambiguationResolver(resolver)}clearDisambiguationResolvers(){this.dispatch.clearDisambiguationResolvers()}handleFocusedTargetChange(_focused){this.notify.runWithStateChangeBatch(()=>{this.activation.setPendingSequence(null),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(_focused),this.notify.queueStateChange()})}warnUnknownField(kind,fieldName){this.notify.warnOnce(`${kind}:${fieldName}`,`unknown-${kind}-field`,{field:fieldName,kind},`[Keymap] Unknown ${kind} field "${fieldName}" was ignored`)}warnUnknownToken(token,sequence){this.notify.warnOnce(`token:${token}`,"unknown-token",{token,sequence},`[Keymap] Unknown token "${token}" in key sequence "${sequence}" was ignored`)}releaseResource(key,resource){if(this.resources.get(key)!==resource)return;if(resource.count-=1,resource.count>0)return;resource.dispose(),this.resources.delete(key)}}function parseObjectKeyInput(ctx,key,display,match,tokenName){return ctx.parseObjectKey(key,{display,match,tokenName})}function isNamedSingleStrokeKey(input,extraNames){let normalized=input.trim().toLowerCase();if(!normalized)return!1;if(namedSingleStrokeKeys.has(normalized))return!0;if(extraNames?.has(normalized))return!0;return/^f\d{1,2}$/i.test(normalized)}function isSingleStrokeString(input,tokens2,normalizeTokenName,extraNames){if(input===" "||input==="+")return!0;if(input.length===1)return!0;if(tokens2.has(normalizeTokenName(input)))return!0;if(input.includes("+"))return!0;return isNamedSingleStrokeKey(input,extraNames)}function parseStringKeyPart(input,ctx){if(input===" ")return ctx.parseObjectKey({name:"space"},{display:"space"});if(input==="+")return ctx.parseObjectKey({name:"+"},{display:"+"});let parts=input.split("+"),name="",displayName="",ctrl=!1,shift=!1,meta=!1,superKey=!1,hyper=!1;for(let rawPart of parts){let part=rawPart.trim();if(!part)continue;let lowered=part.toLowerCase();if(lowered==="ctrl"||lowered==="control"){ctrl=!0;continue}if(lowered==="shift"){shift=!0;continue}if(lowered==="meta"||lowered==="alt"||lowered==="option"){meta=!0;continue}if(lowered==="super"){superKey=!0;continue}if(lowered==="hyper"){hyper=!0;continue}if(name)throw Error(`Invalid key "${input}": multiple key names are not supported`);name=part,displayName=lowered}if(!name)throw Error(`Invalid key "${input}": missing key name`);let displayParts=[];if(ctrl)displayParts.push("ctrl");if(shift)displayParts.push("shift");if(meta)displayParts.push("meta");if(superKey)displayParts.push("super");if(hyper)displayParts.push("hyper");return displayParts.push(displayName),ctx.parseObjectKey({name,ctrl,shift,meta,super:superKey,hyper:hyper||void 0},{display:displayParts.join("+")})}function registerDefaultBindingParser(keymap){return keymap.appendBindingParser(defaultBindingParser)}function registerDefaultEventMatchResolver(keymap){return keymap.appendEventMatchResolver(defaultEventMatchResolver)}function registerDefaultKeys(keymap){let offParser=registerDefaultBindingParser(keymap),offResolver=registerDefaultEventMatchResolver(keymap);return()=>{offResolver(),offParser()}}function isReactiveMatcher22(value){if(!value||typeof value!=="object")return!1;let candidate=value;return typeof candidate.get==="function"&&typeof candidate.subscribe==="function"}function normalizeEnabledValue(fieldName,value){if(typeof value==="boolean")return value;if(typeof value==="function")return value;if(isReactiveMatcher22(value))return value;throw Error(`Keymap enabled field "${fieldName}" must be a boolean, a function, or a reactive matcher`)}function registerEnabledFields(keymap){let offLayerFields=keymap.registerLayerFields({enabled(value,ctx){let normalized=normalizeEnabledValue("enabled",value);if(normalized===!0)return;if(normalized===!1){ctx.activeWhen(()=>!1);return}ctx.activeWhen(normalized)}}),offCommandFields=keymap.registerCommandFields({enabled(value,ctx){let normalized=normalizeEnabledValue("enabled",value);if(normalized===!0)return;if(normalized===!1){ctx.activeWhen(()=>!1);return}ctx.activeWhen(normalized)}});return()=>{offCommandFields(),offLayerFields()}}function normalizeMetadataText(fieldName,value){if(typeof value!=="string")throw Error(`Keymap metadata field "${fieldName}" must be a string`);let trimmed=value.trim();if(!trimmed)throw Error(`Keymap metadata field "${fieldName}" cannot be empty`);return trimmed}function registerMetadataFields(keymap){let offBindingFields=keymap.registerBindingFields({desc(value,ctx){ctx.attr("desc",normalizeMetadataText("desc",value))},group(value,ctx){ctx.attr("group",normalizeMetadataText("group",value))}}),offCommandFields=keymap.registerCommandFields({desc(value,ctx){ctx.attr("desc",normalizeMetadataText("desc",value))},title(value,ctx){ctx.attr("title",normalizeMetadataText("title",value))},category(value,ctx){ctx.attr("category",normalizeMetadataText("category",value))}});return()=>{offCommandFields(),offBindingFields()}}function createSyntheticCommandEvent(){return new KeyEvent({name:"command",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:"",number:!1,raw:"",eventType:"press",source:"raw"})}function createOpenTuiKeymapHost(renderer){return{rootTarget:renderer.root,get isDestroyed(){return renderer.isDestroyed},getFocusedTarget(){let focused=renderer.currentFocusedRenderable;if(!focused||focused.isDestroyed||!focused.focused)return null;return focused},getParentTarget(target){return target.parent},isTargetDestroyed(target){return target.isDestroyed},onKeyPress(listener){return renderer.keyInput.prependListener("keypress",listener),()=>{renderer.keyInput.off("keypress",listener)}},onKeyRelease(listener){return renderer.keyInput.prependListener("keyrelease",listener),()=>{renderer.keyInput.off("keyrelease",listener)}},onFocusChange(listener){return renderer.on(CliRenderEvents.FOCUSED_RENDERABLE,listener),()=>{renderer.off(CliRenderEvents.FOCUSED_RENDERABLE,listener)}},onDestroy(listener){return renderer.once(CliRenderEvents.DESTROY,listener),()=>{renderer.off(CliRenderEvents.DESTROY,listener)}},onTargetDestroy(target,listener){return target.once(RenderableEvents.DESTROYED,listener),()=>{target.off(RenderableEvents.DESTROYED,listener)}},onRawInput(listener){return renderer.prependInputHandler(listener),()=>{renderer.removeInputHandler(listener)}},createCommandEvent(){return createSyntheticCommandEvent()}}}function createOpenTuiKeymap(renderer){if(renderer.isDestroyed)throw Error("Cannot create a keymap for a destroyed renderer");return new Keymap2(createOpenTuiKeymapHost(renderer))}function createDefaultOpenTuiKeymap(renderer){let keymap=createOpenTuiKeymap(renderer);return registerDefaultKeys(keymap),registerEnabledFields(keymap),registerMetadataFields(keymap),keymap}var RESERVED_COMMAND_FIELDS2,RESERVED_BINDING_FIELDS2,RESERVED_LAYER_FIELDS2,DEFAULT_COMMAND_SEARCH_FIELDS2,SNAPSHOT_COMMAND_METADATA_OPTIONS2,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2,EMPTY_COMMAND_FIELDS2,EMPTY_COMPILE_FIELDS2,EMPTY_REQUIRES2,EMPTY_MATCHERS2,EMPTY_CONDITION_KEYS2,KEY_DISAMBIGUATION_DECISION2,KEY_DEFERRED_DISAMBIGUATION_DECISION2,NOOP3=()=>{},NOOP22=()=>{},MAX_STATE_CHANGE_FLUSH_ITERATIONS2=1000,OrderedRegistry2,PriorityRegistry2,EMPTY_DATA2,namedSingleStrokeKeys,defaultBindingParser=(ctx)=>{let{input,index,tokens:tokens2,normalizeTokenName}=ctx;if(index===0&&isSingleStrokeString(input,tokens2,normalizeTokenName)){if(input===" "||input==="+")return{parts:[parseStringKeyPart(input,ctx)],nextIndex:input.length};let normalizedToken=normalizeTokenName(input),token=tokens2.get(normalizedToken);if(token)return{parts:[parseObjectKeyInput(ctx,token.stroke,normalizedToken,token.match,normalizedToken)],nextIndex:input.length,usedTokens:[normalizedToken]};return{parts:[parseStringKeyPart(input,ctx)],nextIndex:input.length}}let char=input[index];if(char===void 0)return;if(char==="<"){let end=input.indexOf(">",index);if(end===-1)throw Error(`Invalid key sequence "${input}": unterminated token`);let tokenName=normalizeTokenName(input.slice(index,end+1)),token=tokens2.get(tokenName);if(!token)return{parts:[],nextIndex:end+1,unknownTokens:[tokenName]};return{parts:[parseObjectKeyInput(ctx,token.stroke,tokenName,token.match,tokenName)],nextIndex:end+1,usedTokens:[tokenName]}}return{parts:[parseStringKeyPart(char,ctx)],nextIndex:index+1}},defaultEventMatchResolver=(event,ctx)=>{return[ctx.resolveKey({name:event.name,ctrl:event.ctrl,shift:event.shift,meta:event.meta,super:event.super??!1,hyper:event.hyper||void 0})]};var init_opentui=__esm(async()=>{await init_core();RESERVED_COMMAND_FIELDS2=new Set(["name","run"]),RESERVED_BINDING_FIELDS2=new Set(["key","cmd","event","preventDefault","fallthrough"]),RESERVED_LAYER_FIELDS2=new Set(["target","targetMode","priority","bindings","commands"]);DEFAULT_COMMAND_SEARCH_FIELDS2=["name"],SNAPSHOT_COMMAND_METADATA_OPTIONS2=Object.freeze({deep:!0,preserveNonPlainObjects:!0}),SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2=Object.freeze({deep:!0,freeze:!0,preserveNonPlainObjects:!0}),EMPTY_COMMAND_FIELDS2=Object.freeze({});EMPTY_COMPILE_FIELDS2=Object.freeze({}),EMPTY_REQUIRES2=[],EMPTY_MATCHERS2=[],EMPTY_CONDITION_KEYS2=[];KEY_DISAMBIGUATION_DECISION2=Symbol("keymap-disambiguation-decision"),KEY_DEFERRED_DISAMBIGUATION_DECISION2=Symbol("keymap-deferred-disambiguation-decision");OrderedRegistry2=class OrderedRegistry2 extends CopyOnWriteRegistry2{append(value){return this.setItems([...this.getItems(),value]),()=>{this.remove(value)}}prepend(value){return this.setItems([value,...this.getItems()]),()=>{this.remove(value)}}remove(value){return this.removeItem(value)}values(){return this.getItems()}};PriorityRegistry2=class PriorityRegistry2 extends CopyOnWriteRegistry2{order=0;register(listener,options){let registered={...options,listener,order:this.order++};return this.setItems([...this.getItems(),registered].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return left.order-right.order})),()=>{this.removeItem(registered)}}entries(){return this.getItems()}};EMPTY_DATA2=Object.freeze({});namedSingleStrokeKeys=new Set(["up","down","left","right","clear","escape","return","linefeed","enter","tab","backspace","delete","insert","home","end","pageup","pagedown","space","lt","gt","plus","minus","equal","comma","period","slash","backslash","semicolon","quote","backquote","leftbracket","rightbracket","capslock","numlock","scrolllock","printscreen","pause","menu","apps","kp0","kp1","kp2","kp3","kp4","kp5","kp6","kp7","kp8","kp9","kpdecimal","kpdivide","kpmultiply","kpminus","kpplus","kpenter","kpequal","kpseparator","kpleft","kpright","kpup","kpdown","kppageup","kppagedown","kphome","kpend","kpinsert","kpdelete","mediaplay","mediapause","mediaplaypause","mediareverse","mediastop","mediafastforward","mediarewind","medianext","mediaprev","mediarecord","volumedown","volumeup","mute","leftshift","leftctrl","leftalt","leftsuper","lefthyper","leftmeta","rightshift","rightctrl","rightalt","rightsuper","righthyper","rightmeta","iso_level3_shift","iso_level5_shift","option","alt","meta","super","hyper","control","ctrl","shift"])});function createTuiKeymap(renderer){let keymap=createDefaultOpenTuiKeymap(renderer);return registerLeader(keymap,{trigger:{name:"space"}}),registerEscapeClearsPendingSequence(keymap),keymap}var init_keymap=__esm(async()=>{init_addons();await init_opentui()});import{spawnSync as spawnSync10}from"child_process";import{existsSync as existsSync76}from"fs";function resolveTuiTmuxConf(){let tuiConf=`${process.env.GENIE_HOME??`${process.env.HOME}/.genie`}/tui-tmux.conf`;return existsSync76(tuiConf)?tuiConf:"/dev/null"}function safeHex(value,fallback){if(!value)return fallback;let trimmed=value.trim();return HEX_COLOR_RE.test(trimmed)?trimmed:fallback}function resolveThemePalette(snapshot){if(snapshot.mode==="dark")return{bg:palette.bg,bgRaised:palette.bgRaised,text:palette.text,textDim:palette.textDim,textMuted:palette.textMuted,border:palette.border,accent:palette.accent,accentDim:palette.accentDim,accentBright:palette.accentBright,warning:palette.warning,info:palette.info};return{...lightPalette,bg:safeHex(snapshot.terminalBackground,lightPalette.bg),text:safeHex(snapshot.terminalForeground,lightPalette.text)}}function flattenTmuxCommands(commands){let args=[];return commands.forEach((command,index)=>{if(index>0)args.push(";");args.push(...command)}),args}function buildTuiTmuxThemeCommands(snapshot){let theme=resolveThemePalette(snapshot),terminalForeground=safeHex(snapshot.terminalForeground,theme.text),terminalBackground=safeHex(snapshot.terminalBackground,theme.bg);return flattenTmuxCommands([["set-environment","-g","GENIE_TUI_THEME_MODE",snapshot.mode],["set-environment","-g","GENIE_TUI_TERMINAL_FG",terminalForeground],["set-environment","-g","GENIE_TUI_TERMINAL_BG",terminalBackground],["set-environment","-g","GENIE_TUI_TMUX_BG",theme.bg],["set-environment","-g","GENIE_TUI_TMUX_TEXT",theme.text],["set-environment","-g","GENIE_TUI_TMUX_ACCENT",theme.accent],["set-option","-g","pane-border-style",`fg=${theme.border}`],["set-option","-g","pane-active-border-style",`fg=${theme.accent}`],["set-option","-g","message-style",`bg=${theme.bgRaised},fg=${theme.info}`],["set-option","-g","message-command-style",`bg=${theme.bgRaised},fg=${theme.warning}`],["set-option","-g","status-style",`bg=${theme.bg},fg=${theme.text}`],["set-window-option","-g","mode-style",`bg=${theme.accent},fg=${theme.bg}`],["set-window-option","-g","clock-mode-colour",theme.accent]])}function syncTuiTmuxTheme(snapshot,deps={}){let run=deps.spawnSync??spawnSync10,tmux=deps.tmuxBin??tmuxBin(),socketName=deps.socketName??TUI_TMUX_SOCKET,configPath2=deps.configPath??resolveTuiTmuxConf(),timeoutMs=deps.timeoutMs??DEFAULT_TMUX_SYNC_TIMEOUT_MS;return run(tmux,["-L",socketName,"-f",configPath2,...buildTuiTmuxThemeCommands(snapshot)],{stdio:"ignore",timeout:timeoutMs}).status===0}var TUI_TMUX_SOCKET="genie-tui",DEFAULT_TMUX_SYNC_TIMEOUT_MS=300,HEX_COLOR_RE,lightPalette;var init_tmux_theme_sync=__esm(()=>{init_ensure_tmux();init_theme2();HEX_COLOR_RE=/^#[0-9a-f]{6}$/i,lightPalette={bg:"#f5efe4",bgRaised:"#ebe3d7",text:"#24323a",textDim:"#56656d",textMuted:"#718087",border:"#c8bdae",accent:"#2f7a62",accentDim:"#3e9277",accentBright:"#17694f",warning:"#9a651e",info:"#406f8b"}});function readBool(env2,name,fallback){let raw=env2[name];if(!raw)return fallback;let normalized=raw.trim().toLowerCase();if(TRUTHY3.has(normalized))return!0;if(FALSY.has(normalized))return!1;return fallback}function readPositiveInt(env2,name,fallback){let raw=env2[name];if(!raw)return fallback;let parsed=Number.parseInt(raw,10);return Number.isFinite(parsed)&&parsed>0?parsed:fallback}function inferThemeMode(background){if(!background||!/^#[0-9a-f]{6}$/i.test(background))return null;let r=Number.parseInt(background.slice(1,3),16),g2=Number.parseInt(background.slice(3,5),16),b3=Number.parseInt(background.slice(5,7),16);return(0.2126*r+0.7152*g2+0.0722*b3)/255>=0.5?"light":"dark"}function snapshotKey(snapshot){return[snapshot.mode,snapshot.terminalForeground??"",snapshot.terminalBackground??""].join("|")}function buildSnapshot(mode,colors8){let resolvedMode=mode??inferThemeMode(colors8?.defaultBackground);if(!resolvedMode)return null;return{mode:resolvedMode,terminalForeground:colors8?.defaultForeground,terminalBackground:colors8?.defaultBackground}}function installOpenTui20Bridge(renderer,options={}){let env2=options.env??process.env;if(!readBool(env2,"GENIE_TUI_TMUX_THEME_SYNC",!0))return()=>{};let syncTheme=options.syncTheme??syncTuiTmuxTheme,themeQueryTimeoutMs=readPositiveInt(env2,"GENIE_TUI_THEME_QUERY_TIMEOUT_MS",DEFAULT_THEME_QUERY_TIMEOUT_MS),tmuxApplyTimeoutMs=readPositiveInt(env2,"GENIE_TUI_TMUX_THEME_SYNC_TIMEOUT_MS",DEFAULT_TMUX_APPLY_TIMEOUT_MS),disposed=!1,lastSnapshot="",syncSnapshot=(snapshot)=>{if(disposed||!snapshot)return;let key=snapshotKey(snapshot);if(key===lastSnapshot)return;lastSnapshot=key;try{syncTheme(snapshot,{timeoutMs:tmuxApplyTimeoutMs})}catch{}},syncFromMode=(mode,colors8)=>{syncSnapshot(buildSnapshot(mode,colors8))},onThemeMode=(mode)=>syncFromMode(mode);renderer.on("theme_mode",onThemeMode),syncFromMode(renderer.themeMode),renderer.waitForThemeMode(themeQueryTimeoutMs).then((mode)=>syncFromMode(mode)).catch(()=>{});let paletteOptions={size:OPEN_TUI_02_PALETTE_SIZE,timeout:themeQueryTimeoutMs};return renderer.getPalette(paletteOptions).then((colors8)=>syncFromMode(renderer.themeMode,colors8)).catch(()=>{}),()=>{disposed=!0,renderer.off("theme_mode",onThemeMode)}}var TRUTHY3,FALSY,DEFAULT_THEME_QUERY_TIMEOUT_MS=700,DEFAULT_TMUX_APPLY_TIMEOUT_MS=300,OPEN_TUI_02_PALETTE_SIZE=16;var init_opentui_bridge=__esm(()=>{init_tmux_theme_sync();TRUTHY3=new Set(["1","true","yes","on"]),FALSY=new Set(["0","false","no","off"])});var exports_render={};__export(exports_render,{resolveTuiRendererConfig:()=>resolveTuiRendererConfig,renderNav:()=>renderNav});function readBool2(env2,name,fallback){let raw=env2[name];if(!raw)return fallback;let normalized=raw.trim().toLowerCase();if(TRUTHY4.has(normalized))return!0;if(FALSY2.has(normalized))return!1;return fallback}function readPositiveInt2(env2,name){let raw=env2[name];if(!raw)return;let parsed=Number.parseInt(raw,10);return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveTuiRendererConfig(env2=process.env,platform2=process.platform){let isDarwin=platform2==="darwin",targetFps=readPositiveInt2(env2,"GENIE_TUI_TARGET_FPS")??(isDarwin?8:30),configuredMaxFps=readPositiveInt2(env2,"GENIE_TUI_MAX_FPS")??(isDarwin?12:60),maxFps=Math.max(configuredMaxFps,targetFps),useMouse=readBool2(env2,"GENIE_TUI_MOUSE",!0),enableMouseMovement=useMouse&&readBool2(env2,"GENIE_TUI_MOUSE_MOVEMENT",!isDarwin),consoleEnabled=readBool2(env2,"GENIE_TUI_CONSOLE",!0),kittyKeyboardOptIn=readBool2(env2,"GENIE_TUI_KITTY_KEYBOARD",!isDarwin);return{exitOnCtrlC:!1,useThread:!isDarwin,targetFps,maxFps,useMouse,enableMouseMovement,useKittyKeyboard:kittyKeyboardOptIn?void 0:null,consoleMode:consoleEnabled?void 0:"disabled",openConsoleOnError:consoleEnabled&&!isDarwin}}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(resolveTuiRendererConfig()),disposeOpenTui20Bridge=installOpenTui20Bridge(renderer),keymap=createTuiKeymap(renderer);createRoot(renderer).render(import_jsx_dev_runtime2.jsxDEV(KeymapProvider,{keymap,children:import_jsx_dev_runtime2.jsxDEV(App,{rightPane,workspaceRoot,initialAgent},void 0,!1,void 0,this)},void 0,!1,void 0,this)),await new Promise((resolve21)=>{renderer.once("destroy",()=>{disposeOpenTui20Bridge(),resolve21()})})}var TRUTHY4,FALSY2;var init_render=__esm(async()=>{init_react();init_opentui_bridge();init_jsx_dev_runtime();await __promiseAll([init_core(),init_react2(),init_app(),init_keymap()]);TRUTHY4=new Set(["1","true","yes","on"]),FALSY2=new Set(["0","false","no","off"])});var exports_tui={};__export(exports_tui,{launchTui:()=>launchTui});import{appendFileSync as appendFileSync5,closeSync as closeSync6,mkdirSync as mkdirSync34,openSync as openSync6,readSync as readSync3,statSync as statSync15}from"fs";import{homedir as homedir50}from"os";import{join as join93}from"path";function genieHome6(){return process.env.GENIE_HOME??join93(homedir50(),".genie")}function extractPreviousRunCrashOutput(logPath){let fd=null;try{let size=statSync15(logPath).size;if(size===0)return"";let readSize=Math.min(size,TUI_CRASH_LOG_RECOVERY_MAX_BYTES);fd=openSync6(logPath,"r");let buffer2=Buffer.alloc(readSize);readSync3(fd,buffer2,0,readSize,size-readSize);let text=buffer2.toString("utf-8"),lastBannerIndex=text.lastIndexOf(TUI_CRASH_LOG_BANNER_PREFIX);if(lastBannerIndex<0)return"";let afterBannerNewline=text.indexOf(`
|
|
3964
|
+
`),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);resolve21(result2)});if(_freebsd||_netbsd||_openbsd||_sunos)resolve21(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((resolve21)=>{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);resolve21(data)})})})}function getDynamicData(srv,iface,callback){if(util4.isFunction(iface))callback=iface,iface="";if(util4.isFunction(srv))callback=srv,srv="";return new Promise((resolve21)=>{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);resolve21(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((resolve21)=>{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);resolve21(data)})})})})}function get3(valueObject,callback){return new Promise((resolve21)=>{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);resolve21(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>90)return palette.error;if(percent>70)return palette.warning;return palette.accent}function SystemStatsView({stats:stats2}){if(!stats2)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgRaised,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.accent,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}=stats2,hotStr=cpu.hotCores.map((c)=>`#${c.id} ${c.load}%`).join(" ");return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",paddingX:1,backgroundColor:palette.bgRaised,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.accent,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)}function SystemStats(){let[stats2,setStats]=import_react23.useState(null),mountedRef=import_react23.useRef(!0);return import_react23.useEffect(()=>{mountedRef.current=!0;async function refresh(){try{let[cpu,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=cpu.cpus.map((c,i2)=>({id:i2,load:Math.round(c.load)})).sort((a,b3)=>b3.load-a.load);setStats({cpu:{combined:Math.round(cpu.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)}},[]),import_jsx_dev_runtime2.jsxDEV(SystemStatsView,{stats:stats2},void 0,!1,void 0,this)}var import_react23,import_systeminformation;var init_SystemStats=__esm(()=>{init_version();init_theme2();init_jsx_dev_runtime();import_react23=__toESM(require_react_development(),1),import_systeminformation=__toESM(require_lib5(),1)});function validateName(name){if(name.length===0)return null;try{return validateBranchName(name),null}catch(err){return err instanceof Error?err.message:String(err)}}function TeamCreate({availableAgents,workspaceRoot,onConfirm,onCancel}){let[step,setStep]=import_react25.useState("name"),[teamName,setTeamName]=import_react25.useState(""),[selected,setSelected]=import_react25.useState(()=>new Set),[memberCursor,setMemberCursor]=import_react25.useState(0),nameError=import_react25.useMemo(()=>validateName(teamName),[teamName]),nameValid=teamName.length>0&&nameError===null,intent=import_react25.useMemo(()=>({kind:"create-team",name:teamName.length>0?teamName:"TEAM_NAME",repo:workspaceRoot}),[teamName,workspaceRoot]),handleNameChange=import_react25.useCallback((value)=>{setTeamName(value)},[]),advanceFromName=import_react25.useCallback(()=>{if(!nameValid)return;setStep("members")},[nameValid]),toggleMember=import_react25.useCallback((name)=>{setSelected((prev)=>{let next=new Set(prev);if(next.has(name))next.delete(name);else next.add(name);return next})},[]),confirmMembers=import_react25.useCallback(()=>{onConfirm({teamName,members:Array.from(selected)})},[onConfirm,teamName,selected]);return useKeyboard((key)=>{if(step==="name"){handleNameStepKey(key,{onCancel,nameValid,advanceFromName});return}handleMembersStepKey(key,{availableAgents,memberCursor,setStep,setMemberCursor,toggleMember,confirmMembers})}),import_jsx_dev_runtime2.jsxDEV("box",{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",backgroundColor:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderColor:palette.borderActive,backgroundColor:palette.bgRaised,paddingX:3,paddingY:1,flexDirection:"column",width:"100%",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,children:"New team"},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:step==="name"?" \u2014 step 1 of 2":" \u2014 step 2 of 2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),step==="name"?import_jsx_dev_runtime2.jsxDEV(NameStep,{value:teamName,onChange:handleNameChange,onSubmit:advanceFromName,errorMessage:nameError},void 0,!1,void 0,this):import_jsx_dev_runtime2.jsxDEV(MembersStep,{agents:availableAgents,selected,cursor:memberCursor},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV(CliPreviewLine,{intent,hint:step==="name"?"Enter: next \xB7 Esc: cancel":"Space: toggle \xB7 Enter: create \xB7 Esc: back"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function NameStep({value,onChange,onSubmit,errorMessage}){return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"Team name (git-branch-safe):"},void 0,!1,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("input",{value,onInput:onChange,onChange,onSubmit,focused:!0,placeholder:"feat/auth-bug",backgroundColor:palette.bg,textColor:palette.text,placeholderColor:palette.textMuted},void 0,!1,void 0,this),errorMessage!==null?import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:`\u26A0 ${errorMessage}`},void 0,!1,void 0,this)},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)}function MembersStep({agents,selected,cursor}){if(agents.length===0)return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"No agents registered"},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.textMuted,children:"Members can be hired later via `genie team hire`."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",children:[import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textDim,children:"Select members (space to toggle):"},void 0,!1,void 0,this)},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("box",{flexDirection:"column",children:agents.map((name,idx)=>{let isSelected=selected.has(name),isCursor=idx===cursor,tick=isSelected?"[x]":"[ ]",prefix=isCursor?"\u25B6 ":" ";return import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:isCursor?palette.accent:palette.textMuted,children:prefix},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:isSelected?palette.success:palette.textDim,children:tick},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.text,children:` ${name}`},void 0,!1,void 0,this)]},name,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function isEnter(key){return key.name==="enter"||key.name==="return"}function handleNameStepKey(key,opts){if(key.name==="escape"){opts.onCancel();return}if(isEnter(key)&&opts.nameValid)opts.advanceFromName()}function handleMembersStepKey(key,opts){if(key.name==="escape"){opts.setStep("name");return}if(opts.availableAgents.length===0){if(isEnter(key))opts.confirmMembers();return}if(key.name==="up"||key.name==="k"){opts.setMemberCursor((prev)=>prev<=0?opts.availableAgents.length-1:prev-1);return}if(key.name==="down"||key.name==="j"){opts.setMemberCursor((prev)=>prev>=opts.availableAgents.length-1?0:prev+1);return}if(key.name==="space"){let name=opts.availableAgents[opts.memberCursor];if(name)opts.toggleMember(name);return}if(isEnter(key))opts.confirmMembers()}var import_react25;var init_TeamCreate=__esm(async()=>{init_team_manager();init_theme2();init_CliPreviewLine();init_jsx_dev_runtime();await init_react2();import_react25=__toESM(require_react_development(),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.workState){case"in_flight":return"\u25C6";case"paused":return"\u25D0";case"done":return"\u2714";case"stuck":return"\u2718";default:break}switch(node.wsAgentState){case"running":return"\u25CF";case"stopped":return"\u25CC";case"error":return"\u2298";case"spawning":return"\u231B";default:return"\u25CC"}}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.isClaudeLike)return"\u25C6";return"\u25CB"}function getNodeColor(node){if(node.type==="agent")return getAgentColor(node);switch(node.type){case"session":return node.data.attached?palette.success:palette.textDim;case"window":return node.data.active?palette.info:palette.text;case"pane":return getPaneColor(node);default:return palette.text}}function getAgentColor(node){switch(node.workState){case"in_flight":return palette.accentBright;case"paused":return palette.textDim;case"done":return palette.info;case"stuck":return palette.error;default:break}switch(node.wsAgentState){case"running":return palette.success;case"stopped":return palette.text;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.info;if(node.agentState==="permission")return palette.warning;if(node.agentState==="error")return palette.error;if(node.agentState==="idle")return palette.textDim;if(node.data.isClaudeLike)return palette.info;return palette.textDim}function getAgentSuffix(node){if(node.workState==="stuck")return" [stuck \u2014 press R to retry]";if(node.workState==="paused")return" [paused \u2014 auto-resume off]";if(node.workState==="done")return" [done]";if(node.wsAgentState==="spawning"&&node.activePanes===0)return" [stuck \u2014 press R to retry]";if(node.wsAgentState==="stopped")return" [Enter to start]";let wc=node.data.windowCount;if(wc>1)return` (${wc} windows)`;if(wc===1)return" (1 window)";return""}function getNodeSuffix(node){if(node.type==="agent")return getAgentSuffix(node);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.info;case"idle":return palette.textDim;case"permission":return palette.warning;case"error":return palette.error;default:return palette.textMuted}}var import_react26,TreeNodeRow;var init_TreeNode=__esm(()=>{init_theme2();init_jsx_dev_runtime();import_react26=__toESM(require_react_development(),1),TreeNodeRow=import_react26.memo(function({node,selected,onSelect,onToggle,onContextMenu}){let indent2=" ".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),labelColor=selected?palette.accentBright:node.type==="agent"&&node.kind==="subagent"?palette.textDim:palette.text;return import_jsx_dev_runtime2.jsxDEV("box",{height:1,width:"100%",backgroundColor:selected?palette.accentDim: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:[indent2,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:labelColor,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,process.env.GENIE_TUI_DEBUG==="1"?import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:` [${node.type}]`},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)},void 0,!1,void 0,this)})});function useDiagnosticsRefresh(setDiagnostics,setRequestedInitialAgent){import_react28.useEffect(()=>{let active=!0,lastErrorMessage=null,lastErrorLoggedAt=0;async function refresh(){try{let snap=await collectDiagnostics();if(!active)return;setDiagnostics(snap),lastErrorMessage=null;let signaledAgent=consumeInitialAgentSignal();if(signaledAgent)setRequestedInitialAgent(signaledAgent)}catch(err){let message=err instanceof Error?err.message:String(err),now=Date.now();if(message!==lastErrorMessage||now-lastErrorLoggedAt>30000)console.error("TUI: diagnostics failed:",message),lastErrorMessage=message,lastErrorLoggedAt=now}}refresh();let timer2=setInterval(refresh,2000);return()=>{active=!1,clearInterval(timer2)}},[setDiagnostics,setRequestedInitialAgent])}function useSessionTreeBuilder(diagnostics,workspaceRoot,setSessionTree){import_react28.useEffect(()=>{if(!diagnostics)return;let newTree;if(workspaceRoot){let agentNames=scanAgents(workspaceRoot);newTree=buildWorkspaceTree({agentNames,sessions:diagnostics.sessions,executors:diagnostics.executors,workStates:diagnostics.workStates})}else newTree=buildSessionTree(diagnostics);setSessionTree((prev)=>mergeExpandedState(prev,newTree))},[diagnostics,workspaceRoot,setSessionTree])}function useStableSelection(flatNodes,selectedIndex,setSelectedIndex,selectedNodeId){import_react28.useEffect(()=>{let node=flatNodes[selectedIndex]?.node;if(node)selectedNodeId.current=node.id},[selectedIndex,flatNodes,selectedNodeId]),import_react28.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&¤tAtIndex.id===selectedNodeId.current)return;let restored=flatNodes.findIndex((n)=>n.node.id===selectedNodeId.current);if(restored>=0)setSelectedIndex(restored)},[flatNodes])}function useInitialAgentSelection(requestedInitialAgent,flatNodes,setSelectedIndex,setRequestedInitialAgent,onTmuxSessionSelect){import_react28.useEffect(()=>{if(!requestedInitialAgent||flatNodes.length===0)return;let idx=flatNodes.findIndex((n)=>n.node.id===`agent:${requestedInitialAgent}`);if(idx<0)return;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,setSelectedIndex,setRequestedInitialAgent])}function useAutoAttach(flatNodes,selectedIndex,lastTarget,onTmuxSessionSelect){import_react28.useEffect(()=>{let current=flatNodes[selectedIndex]?.node;if(!current)return;let target=getSessionTarget(current);if(!target)return;if(current.type==="agent"&¤t.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,lastTarget])}function useNavKeyboard(opts){useKeyboard((key)=>{if(opts.keyboardDisabled)return;if(opts.spawnIntoAgent!==null||opts.spawnPickerTarget!==null)return;if(tryOpenTeamCreate(key,{workspaceRoot:opts.workspaceRoot,showTeamCreate:opts.showTeamCreate,contextMenuNodeId:opts.contextMenuNodeId,handleOpenTeamCreate:opts.handleOpenTeamCreate}))return;if(opts.showTeamCreate)return;handleKeyboardInput(key,opts)})}function renderAlertBadge(alertCount){if(alertCount<=0)return null;return import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.error,children:[" ","\u25CF ",alertCount," alert",alertCount===1?"":"s"]},void 0,!0,void 0,this)}function countAgents(nodes,predicate){let count=0;for(let n of nodes){if(n.type==="agent"&&predicate(n))count++;if(n.children.length>0)count+=countAgents(n.children,predicate)}return count}function computeNavCounts(workspaceRoot,sessionTree,diagnostics){if(workspaceRoot){let agentCount=countAgents(sessionTree,()=>!0);if(agentCount>0)return{agentCount,runningCount:countAgents(sessionTree,(n)=>n.wsAgentState==="running")}}let paneSum=diagnostics?.sessions.reduce((sum,s2)=>sum+s2.windows.reduce((ws,w2)=>ws+w2.panes.length,0),0)??0;return{agentCount:diagnostics?.sessions.length??0,runningCount:paneSum}}function Nav({onTmuxSessionSelect,onNewAgentWindow,workspaceRoot,initialAgent,keyboardDisabled=!1}){let[diagnostics,setDiagnostics]=import_react28.useState(null),[sessionTree,setSessionTree]=import_react28.useState([]),[selectedIndex,setSelectedIndex]=import_react28.useState(0),[requestedInitialAgent,setRequestedInitialAgent]=import_react28.useState(initialAgent),[contextMenuNodeId,setContextMenuNodeId]=import_react28.useState(null),[spawnIntoAgent,setSpawnIntoAgent]=import_react28.useState(null),[spawnPickerTarget,setSpawnPickerTarget]=import_react28.useState(null),lastTarget=import_react28.useRef(null),selectedNodeId=import_react28.useRef(null);useDiagnosticsRefresh(setDiagnostics,setRequestedInitialAgent),useSessionTreeBuilder(diagnostics,workspaceRoot,setSessionTree);let flatNodes=import_react28.useMemo(()=>flattenTree(sessionTree),[sessionTree]);useStableSelection(flatNodes,selectedIndex,setSelectedIndex,selectedNodeId),useInitialAgentSelection(requestedInitialAgent,flatNodes,setSelectedIndex,setRequestedInitialAgent,onTmuxSessionSelect),useAutoAttach(flatNodes,selectedIndex,lastTarget,onTmuxSessionSelect);let handleSelect=import_react28.useCallback((id)=>{let idx=flatNodes.findIndex((n)=>n.node.id===id);if(idx>=0)setSelectedIndex(idx)},[flatNodes]),handleToggle=import_react28.useCallback((id)=>{setSessionTree((prev)=>toggleNode(prev,id))},[]),handleVerticalNav=import_react28.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_react28.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_react28.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_react28.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_react28.useCallback((nodeId)=>{let flat=flatNodes.find((n)=>n.node.id===nodeId);if(flat&&buildMenuItems(flat.node).length>0)setContextMenuNodeId(nodeId)},[flatNodes]),handleContextMenuAction=import_react28.useCallback((action,payload)=>{let node=flatNodes.find((n)=>n.node.id===contextMenuNodeId)?.node;if(!node)return;if(setContextMenuNodeId(null),action==="spawn-here"){let target=resolveSpawnHereTarget(node);if(target)setSpawnPickerTarget(target);return}dispatchContextMenuAction(action,node,payload,{sessionTree,onTmuxSessionSelect,onNewAgentWindow,openSpawnInto:setSpawnIntoAgent})},[flatNodes,contextMenuNodeId,sessionTree,onTmuxSessionSelect,onNewAgentWindow]),handleSpawnIntoConfirm=import_react28.useCallback((intent)=>{executeSpawnIntent(intent),setSpawnIntoAgent(null)},[]),handleSpawnIntoCancel=import_react28.useCallback(()=>{setSpawnIntoAgent(null)},[]),handleSpawnPickerConfirm=import_react28.useCallback((intent)=>{setSpawnPickerTarget(null),executeSpawnIntent(intent)},[]),handleSpawnPickerCancel=import_react28.useCallback(()=>{setSpawnPickerTarget(null)},[]),_menuDisabled=keyboardDisabled||contextMenuNodeId!==null,{showTeamCreate,handleOpenTeamCreate,handleTeamCreateConfirm,handleTeamCreateCancel}=useTeamCreateControls({workspaceRoot,diagnostics,onTmuxSessionSelect});useNavKeyboard({keyboardDisabled,spawnIntoAgent,spawnPickerTarget,workspaceRoot,showTeamCreate,contextMenuNodeId,handleOpenTeamCreate,flatNodes,selectedIndex,setContextMenuNodeId,handleVerticalNav,handleExpandCollapse,handleEnter,handleRetry,onNewAgentWindow});let{agentCount,runningCount}=computeNavCounts(workspaceRoot,sessionTree,diagnostics),headerLabel=workspaceRoot?"Agents":"Sessions",alertCount=diagnostics?.alertCount??0;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.bgRaised,children:import_jsx_dev_runtime2.jsxDEV("text",{children:[import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.accent,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,renderAlertBadge(alertCount)]},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",flexDirection:"column",gap:1,children:[import_jsx_dev_runtime2.jsxDEV("ascii-font",{text:"GENIE",font:"tiny",color:palette.accent},void 0,!1,void 0,this),import_jsx_dev_runtime2.jsxDEV("text",{fg:palette.textDim,children:"Collecting..."},void 0,!1,void 0,this)]},void 0,!0,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,spawnIntoAgent!==null?import_jsx_dev_runtime2.jsxDEV(SpawnTargetPicker,{agentName:spawnIntoAgent,sessions:diagnostics?.sessions??[],onConfirm:handleSpawnIntoConfirm,onCancel:handleSpawnIntoCancel},void 0,!1,void 0,this):null,spawnPickerTarget!==null?import_jsx_dev_runtime2.jsxDEV(AgentPicker,{target:spawnPickerTarget,onConfirm:handleSpawnPickerConfirm,onCancel:handleSpawnPickerCancel},void 0,!1,void 0,this):null,showTeamCreate?import_jsx_dev_runtime2.jsxDEV(TeamCreate,{availableAgents:workspaceRoot?scanAgents(workspaceRoot):[],workspaceRoot,onConfirm:handleTeamCreateConfirm,onCancel:handleTeamCreateCancel},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.bgRaised,children:import_jsx_dev_runtime2.jsxDEV("text",{children:import_jsx_dev_runtime2.jsxDEV("span",{fg:palette.textMuted,children:buildFooterHint(workspaceRoot)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function useTeamCreateControls(opts){let{workspaceRoot,diagnostics,onTmuxSessionSelect}=opts,[showTeamCreate,setShowTeamCreate]=import_react28.useState(!1),pendingTeamNameRef=import_react28.useRef(null),handleOpenTeamCreate=import_react28.useCallback(()=>{if(!workspaceRoot)return;setShowTeamCreate(!0)},[workspaceRoot]),handleTeamCreateConfirm=import_react28.useCallback((result2)=>{setShowTeamCreate(!1),runTeamCreation(result2,workspaceRoot),pendingTeamNameRef.current=result2.teamName},[workspaceRoot]),handleTeamCreateCancel=import_react28.useCallback(()=>{setShowTeamCreate(!1)},[]);return import_react28.useEffect(()=>{let pending=pendingTeamNameRef.current;if(!pending||!diagnostics)return;let session=diagnostics.sessions.find((s2)=>s2.name===pending);if(!session)return;pendingTeamNameRef.current=null,onTmuxSessionSelect(session.name,resolvePreferredWindowIndex(session,pending))},[diagnostics,onTmuxSessionSelect]),{showTeamCreate,handleOpenTeamCreate,handleTeamCreateConfirm,handleTeamCreateCancel}}function handleEnterAgent(node,onTmuxSessionSelect,spawn5=spawnAgent){if(node.wsAgentState!=="running"&&node.wsAgentState!=="spawning")spawn5(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(action==="spawn-into"&&node.type==="agent"&&deps.openSpawnInto){deps.openSpawnInto(agentNameFromNode(node));return}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 buildFooterHint(workspaceRoot){return`\u2191\u2193:nav \u2190\u2192:expand Enter:${workspaceRoot?"spawn/attach":"attach"} ^T:new${workspaceRoot?" ^N:team":""} R:retry .:menu`}function tryOpenTeamCreate(key,opts){if(!key.ctrl||key.name!=="n")return!1;if(!opts.workspaceRoot||opts.showTeamCreate||opts.contextMenuNodeId)return!1;return opts.handleOpenTeamCreate(),!0}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,handlers,agentAction){let n=key.name;if(n==="up"||n==="k"||n==="down"||n==="j")handlers.handleVerticalNav(n);else if(n==="right"||n==="l"||n==="left"||n==="h")handlers.handleExpandCollapse(n);else if(n==="enter"||n==="return")handlers.handleEnter();else if(n==="r")handlers.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:join93,resolve:resolve21}=__require("path"),{existsSync:existsSync76,mkdirSync:mkdirSync35,openSync:openSync6}=__require("fs"),{homedir:homedir51}=__require("os"),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=resolve21(join93(wsRoot,"agents",parentName));if(existsSync76(agentDir))cwd=agentDir}let{GENIE_TUI_PANE:_a,GENIE_TUI_RIGHT:_b,GENIE_TUI_WORKSPACE:_c,GENIE_IS_DAEMON:_d,...cleanEnv}=process.env,logDir=join93(homedir51(),".genie","logs","tui-spawn");try{mkdirSync35(logDir,{recursive:!0})}catch{}let logPath=join93(logDir,`${sessionName}-${Date.now()}.log`),logFd;try{logFd=openSync6(logPath,"a")}catch{logFd=void 0}let spawnOpts=logFd!==void 0?{detached:!0,stdio:["ignore",logFd,logFd],cwd,env:cleanEnv}:{detached:!0,stdio:"ignore",cwd,env:cleanEnv},child=genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,"spawn",name,"--session",sessionName,"--new-window"],spawnOpts):spawn5("genie",["spawn",name,"--session",sessionName,"--new-window"],spawnOpts);if(child.on("exit",(code)=>{if(code&&code!==0)console.error(`TUI: spawn "${name}" exited ${code}. See ${logPath}`)}),child.on("error",(err)=>{console.error(`TUI: spawn "${name}" error: ${err.message}. See ${logPath}`)}),child.unref(),onTmuxSessionSelect)attachSpawnedAgentWhenReady(sessionName,onTmuxSessionSelect)}catch(err){console.error(`TUI: spawn failed for ${name}:`,err instanceof Error?err.message:err)}}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 executeGenieAwaited(args){return new Promise((resolve21,reject)=>{try{let{spawn:spawn5}=__require("child_process"),bunPath=process.execPath||"bun",genieBin=process.argv[1],child=genieBin&&genieBin!=="genie"?spawn5(bunPath,[genieBin,...args],{stdio:"ignore"}):spawn5("genie",args,{stdio:"ignore"});child.on("exit",(code)=>resolve21(code)),child.on("error",reject)}catch(err){reject(err instanceof Error?err:Error(String(err)))}})}function resolveSpawnHereTarget(node){if(node.type==="session"){let sess=node.id.split(":").slice(1).join(":");if(sess.length===0)return null;return{session:sess}}if(node.type==="window"){let idParts=node.id.split(":");if(idParts.length<3)return null;return{session:idParts[1],window:`${idParts[1]}:${idParts[2]}`}}return null}function executeSpawnIntent(intent){try{let{argv}=buildSpawnInvocation(intent);executeGenie(argv)}catch(err){console.error("TUI: spawn-intent execution failed:",err instanceof Error?err.message:err)}}async function runTeamCreation(result2,workspaceRoot){let argv;try{({argv}=buildSpawnInvocation({kind:"create-team",name:result2.teamName,repo:workspaceRoot}))}catch(err){console.error("TUI: team create intent build failed:",err instanceof Error?err.message:err);return}let createExit=null;try{createExit=await executeGenieAwaited(argv)}catch(err){console.error("TUI: team create spawn failed:",err instanceof Error?err.message:err);return}if(createExit!==0){console.error(`TUI: team create exited ${createExit} \u2014 skipping member hires for "${result2.teamName}"`);return}for(let member of result2.members)try{let code=await executeGenieAwaited(["team","hire",member,"--team",result2.teamName]);if(code!==0)console.error(`TUI: team hire "${member}" exited ${code} \u2014 continuing with remaining members`)}catch(err){console.error(`TUI: team hire "${member}" failed:`,err instanceof Error?err.message:err)}}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_react28;var init_Nav=__esm(async()=>{init_spawn_invocation();init_workspace();init_diagnostics();init_initial_agent();init_session_tree();init_theme2();init_SystemStats();init_TreeNode();init_jsx_dev_runtime();await __promiseAll([init_react2(),init_AgentPicker(),init_ContextMenu(),init_SpawnTargetPicker(),init_TeamCreate()]);import_react28=__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:palette.bgOverlay,children:import_jsx_dev_runtime2.jsxDEV("box",{border:!0,borderColor:palette.borderActive,backgroundColor:palette.bgRaised,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.accent,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_react2()});import{execSync as execSync18}from"child_process";import{readFileSync as readFileSync49}from"fs";function App({rightPane,workspaceRoot,initialAgent}){let renderer=useRenderer(),[showQuit,setShowQuit]=import_react32.useState(!1),[showHelp,setShowHelp]=import_react32.useState(!1),[activeSession,setActiveSession]=import_react32.useState(null);import_react32.useEffect(()=>{let title=activeSession?`${BASE_TERMINAL_TITLE} \u2014 ${activeSession}`:BASE_TERMINAL_TITLE;try{renderer.setTerminalTitle(title)}catch{}},[renderer,activeSession]);let handleQuit=import_react32.useCallback(()=>{try{let genieHome6=process.env.GENIE_HOME??`${process.env.HOME}/.genie`,pid=readFileSync49(`${genieHome6}/serve.pid`,"utf-8").trim();process.kill(Number.parseInt(pid,10),"SIGTERM")}catch{}try{execSync18("tmux -L genie-tui kill-server",{stdio:"ignore"})}catch{}},[]);useBindings(()=>({commands:[{name:"app.quit",title:"Quit",desc:"Show quit confirmation; press again to quit",category:"app",run(){if(showQuit)handleQuit();else setShowQuit(!0)}},{name:"app.help.toggle",title:"Toggle help overlay",desc:"Show/hide the keyboard shortcut overlay",category:"app",run(){setShowHelp((prev)=>!prev)}},{name:"app.console.toggle",title:"Toggle console overlay",desc:"Show/hide the OpenTUI console (logs)",category:"app",run(){renderer.console.toggle()}}],bindings:[{key:"ctrl+q",cmd:"app.quit"},{key:"f1",cmd:"app.help.toggle"},{key:"`",cmd:"app.console.toggle"}]}),[renderer,showQuit,handleQuit]);let handleTmuxSessionSelect=import_react32.useCallback((sessionName,windowIndex)=>{if(setActiveSession(sessionName),!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||showHelp},void 0,!1,void 0,this),showHelp?import_jsx_dev_runtime2.jsxDEV(HelpOverlay,{onClose:()=>setShowHelp(!1)},void 0,!1,void 0,this):null,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_react32,BASE_TERMINAL_TITLE="genie tui";var init_app=__esm(async()=>{init_react();init_tmux2();init_jsx_dev_runtime();await __promiseAll([init_react2(),init_HelpOverlay(),init_Nav(),init_QuitDialog()]);import_react32=__toESM(require_react_development(),1)});function getFocusedTargetIfAvailable(host){if(host.isDestroyed)return null;return host.getFocusedTarget()}function forEachActivationTarget(host,focused,visit){let current=focused??host.rootTarget,isFocusedTarget=focused!==null;while(current){if(visit(current,isFocusedTarget)===!1)return;current=host.getParentTarget(current),isFocusedTarget=!1}}function getActivationPath(host,focused){let path6=new Set;return forEachActivationTarget(host,focused,(current)=>{path6.add(current)}),path6}function getActiveLayersForFocused(state,host,focused){if(state.activeLayersCacheVersion===state.activeLayersVersion&&state.activeLayersCacheFocused===focused)return state.activeLayersCache;let activeLayers=[],activationPath=getActivationPath(host,focused);for(let layer of state.sortedLayers)if(isLayerActiveForFocused(host,layer,focused,activationPath))activeLayers.push(layer);return state.activeLayersCacheVersion=state.activeLayersVersion,state.activeLayersCacheFocused=focused,state.activeLayersCache=activeLayers,activeLayers}function invalidateCachedActiveLayers(state){state.activeLayersCacheVersion=-1,state.activeLayersCacheFocused=void 0,state.activeLayersCache=[]}function isLayerActiveForFocused(host,layer,focused,activationPath=getActivationPath(host,focused)){let target=layer.target;if(!target)return!0;if(host.isTargetDestroyed(target))return!1;if(layer.targetMode==="focus")return target===focused;return activationPath.has(target)}function normalizeBindingTokenName(token){let normalized=token.trim().toLowerCase();if(!normalized)throw Error("Invalid keymap token: token cannot be empty");return normalized}function normalizeKeyName(name){let normalized=name.trim().toLowerCase();if(!normalized)throw Error("Invalid key name: key name cannot be empty");return normalized}function normalizeKeyStroke(input){return{name:normalizeKeyName(input.name),ctrl:input.ctrl??!1,shift:input.shift??!1,meta:input.meta??!1,super:input.super??!1,hyper:input.hyper||void 0}}function cloneKeyStroke(stroke){return{name:stroke.name,ctrl:stroke.ctrl,shift:stroke.shift,meta:stroke.meta,super:stroke.super,hyper:stroke.hyper||void 0}}function createKeySequencePart(input,options){let stroke=cloneKeyStroke(normalizeKeyStroke(input));return{stroke,display:options?.display??stringifyCanonicalStroke(stroke),match:options?.match??createKeyMatch(stroke),tokenName:options?.tokenName?normalizeBindingTokenName(options.tokenName):void 0}}function cloneKeySequencePart(part){return{stroke:cloneKeyStroke(part.stroke),display:part.display,match:part.match,tokenName:part.tokenName}}function cloneKeySequence(parts){return parts.map((part)=>cloneKeySequencePart(part))}function resolveKeyMatch(input){if("match"in input)return input.match;if("stroke"in input)return createKeyMatch(input.stroke);return createKeyMatch(input)}function createKeyMatch(input){return`key:${buildKeyMatchId(normalizeKeyStroke(input))}`}function createTextKeyMatch(id){let normalized=id.trim();if(!normalized)throw Error("Invalid keymap match id: id cannot be empty");return`text:${normalized}`}function stringifyKeyStroke(input,options){if("stroke"in input){if(options?.preferDisplay&&input.display)return input.display;return stringifyCanonicalStroke(input.stroke)}return stringifyCanonicalStroke(normalizeKeyStroke(input))}function stringifyKeySequence(input,options){return input.map((part)=>stringifyKeyStroke(part,options)).join("")}function stringifyCanonicalStroke(stroke){let parts=[];if(stroke.ctrl)parts.push("ctrl");if(stroke.shift)parts.push("shift");if(stroke.meta)parts.push("meta");if(stroke.super)parts.push("super");if(stroke.hyper)parts.push("hyper");return parts.push(stroke.name==="return"?"enter":stroke.name),parts.join("+")}function buildKeyMatchId(stroke){return`${stroke.name}:${stroke.ctrl?1:0}:${stroke.shift?1:0}:${stroke.meta?1:0}:${stroke.super?1:0}:${stroke.hyper?1:0}`}function getLiveHost(host){if(host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");return host}function isSamePendingSequence(current,next){if(current===next)return!0;if(!current||!next)return!1;if(current.captures.length!==next.captures.length)return!1;for(let index=0;index<current.captures.length;index+=1){let left=current.captures[index],right=next.captures[index];if(!left||!right||left.layer!==right.layer||left.node!==right.node)return!1}return!0}class ActivationService{state;host;hooks;notify;conditions;catalog;options;constructor(state,host,hooks,notify,conditions,catalog,options={}){this.state=state,this.host=host,this.hooks=hooks,this.notify=notify,this.conditions=conditions,this.catalog=catalog,this.options=options}getFocusedTarget(){return getLiveHost(this.host).getFocusedTarget()}getFocusedTargetIfAvailable(){return getFocusedTargetIfAvailable(this.host)}setPendingSequence(next){let previous=this.state.projection.pendingSequence;if(isSamePendingSequence(previous,next))return;this.state.projection.pendingSequence=next,this.options.onPendingSequenceChanged?.(previous,next),this.invalidateCaches(),this.notifyPendingSequenceChange(),this.notify.queueStateChange()}ensureValidPendingSequence(){let pending=this.state.projection.pendingSequence;if(!pending)return;let focused=this.getFocusedTarget(),captures=pending.captures.filter((capture2)=>{return this.state.layers.layers.has(capture2.layer)&&this.isLayerActiveForFocused(capture2.layer,focused)&&this.conditions.layerMatchesRuntimeState(capture2.layer)&&this.nodeHasReachableBindings(capture2.node,focused)});if(captures.length===0){this.setPendingSequence(null);return}if(captures.length!==pending.captures.length)this.setPendingSequence({captures});return this.state.projection.pendingSequence??void 0}revalidatePendingSequenceIfNeeded(){if(this.host.isDestroyed||!this.state.projection.pendingSequence)return;this.ensureValidPendingSequence()}hasPendingSequenceState(){return!this.host.isDestroyed&&this.state.projection.pendingSequence!==null}getPendingSequence(){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion;if(projections.pendingSequenceCacheVersion===derivedStateVersion)return projections.pendingSequenceCache;let pending=this.ensureValidPendingSequence(),canUseCache=!pending||pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)),sequence=pending?this.collectSequencePartsFromPending(pending):[];if(canUseCache)projections.pendingSequenceCacheVersion=derivedStateVersion,projections.pendingSequenceCache=sequence;return sequence}popPendingSequence(){let pending=this.ensureValidPendingSequence();if(!pending)return!1;let firstCapture=pending.captures[0];if(!firstCapture||firstCapture.node.depth<=1)return this.setPendingSequence(null),!0;let nextCaptures=[];for(let capture2 of pending.captures){let parent=capture2.node.parent;if(!parent||!parent.stroke)continue;nextCaptures.push({layer:capture2.layer,node:parent})}if(nextCaptures.length===0)return this.setPendingSequence(null),!0;return this.setPendingSequence({captures:nextCaptures}),!0}getActiveKeys(options){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion,includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0;if(includeBindings){if(includeMetadata){if(projections.activeKeysBindingsAndMetadataCacheVersion===derivedStateVersion)return projections.activeKeysBindingsAndMetadataCache}else if(projections.activeKeysBindingsCacheVersion===derivedStateVersion)return projections.activeKeysBindingsCache}else if(includeMetadata){if(projections.activeKeysMetadataCacheVersion===derivedStateVersion)return projections.activeKeysMetadataCache}else if(projections.activeKeysPlainCacheVersion===derivedStateVersion)return projections.activeKeysPlainCache;let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),pending=this.ensureValidPendingSequence(),activeLayers=pending?[]:this.getActiveLayers(focused),canUseCache=pending?pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)):this.activeLayersCanCacheActiveKeys(activeLayers),activeKeys=pending?this.collectActiveKeysFromPending(pending.captures,includeBindings,includeMetadata,focused,activeView):this.collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView);if(!canUseCache)return activeKeys;if(includeBindings)if(includeMetadata)projections.activeKeysBindingsAndMetadataCacheVersion=derivedStateVersion,projections.activeKeysBindingsAndMetadataCache=activeKeys;else projections.activeKeysBindingsCacheVersion=derivedStateVersion,projections.activeKeysBindingsCache=activeKeys;else if(includeMetadata)projections.activeKeysMetadataCacheVersion=derivedStateVersion,projections.activeKeysMetadataCache=activeKeys;else projections.activeKeysPlainCacheVersion=derivedStateVersion,projections.activeKeysPlainCache=activeKeys;return activeKeys}getActiveKeysForCaptures(captures,options){let includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0,focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused);return this.collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView)}nodeHasReachableBindings(node,focused){return this.hasMatchingBindings(node.reachableBindings,focused,this.catalog.getActiveCommandView(focused))}getActiveLayers(focused){return getActiveLayersForFocused(this.state.layers,this.host,focused)}refreshActiveLayers(focused=this.getFocusedTargetIfAvailable()){getActiveLayersForFocused(this.state.layers,this.host,focused)}invalidateActiveLayers(){invalidateCachedActiveLayers(this.state.layers)}isLayerActiveForFocused(layer,focused){return isLayerActiveForFocused(this.host,layer,focused)}layerCanCacheActiveKeys(layer){return!layer.hasUnkeyedMatchers&&!layer.hasUnkeyedCommands&&!layer.hasUnkeyedBindings}activeLayersCanCacheActiveKeys(activeLayers){for(let layer of activeLayers)if(!this.layerCanCacheActiveKeys(layer))return!1;return!0}collectNodesFromNode(node){let nodes=[],current=node;while(current&¤t.stroke)nodes.push(current),current=current.parent;return nodes.reverse(),nodes}collectSequencePartsFromPending(pending){let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),paths=pending.captures.map((capture2)=>this.collectNodesFromNode(capture2.node)),firstPath=paths[0];if(!firstPath||firstPath.length===0)return[];let parts=[];for(let index=0;index<firstPath.length;index+=1){let firstNode=firstPath[index];if(!firstNode?.stroke||firstNode.match===null)continue;let display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let path6 of paths){let node=path6[index];if(!node)continue;let presentation=this.getNodePresentation(node,focused,activeView);if(display===void 0){display=presentation.display,tokenName=presentation.tokenName;continue}if(!hasDisplayConflict&&display!==presentation.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==presentation.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke(firstNode.stroke);if(hasTokenConflict)tokenName=void 0;parts.push(createKeySequencePart(firstNode.stroke,{display,match:firstNode.match,tokenName}))}return parts}collectMatchingBindings(bindings,focused,activeView){let matches=[];for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))matches.push(binding);return matches}hasMatchingBindings(bindings,focused,activeView){for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))return!0;return!1}getNodePresentation(node,focused,activeView,reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView)){if(!node.stroke)return{display:""};let partIndex=node.depth-1,display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let binding of reachableBindings){let part=binding.sequence[partIndex];if(!part)continue;if(display===void 0){display=part.display,tokenName=part.tokenName;continue}if(!hasDisplayConflict&&display!==part.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==part.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke(node.stroke);if(hasTokenConflict)tokenName=void 0;return{display,tokenName}}toActiveBinding(binding,focused,activeView){return{sequence:binding.sequence,command:binding.command,commandAttrs:this.catalog.getBindingCommandAttrs(binding,focused,activeView),attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough}}collectActiveBindings(bindings,focused,activeView){return bindings.map((binding)=>this.toActiveBinding(binding,focused,activeView))}collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set,hasLayerConditions=this.state.layers.layersWithConditions>0;for(let layer of activeLayers){if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let[bindingKey,child]of layer.root.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set;for(let capture2 of captures)for(let[bindingKey,child]of capture2.node.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}selectActiveKey(node,includeBindings,focused,activeView){return node.children.size>0?this.selectPrefixActiveKey(node,includeBindings,focused,activeView):this.selectExactActiveKey(node,includeBindings,focused,activeView)}selectPrefixActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView);if(reachableBindings.length===0)return;let prefixBindings=this.selectActiveBindings(node.bindings,focused,activeView);return{...this.getNodePresentation(node,focused,activeView,reachableBindings),continues:!0,firstBinding:prefixBindings?.bindings[0],commandBinding:prefixBindings?.commandBinding,bindings:includeBindings&&prefixBindings&&prefixBindings.bindings.length>0?[...prefixBindings.bindings]:void 0,stop:!0}}selectExactActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let selected=this.selectActiveBindings(node.bindings,focused,activeView);if(!selected)return;let display,tokenName;if(selected.bindings.length===1){let part=selected.bindings[0]?.sequence[node.depth-1];display=part?.display??stringifyKeyStroke(node.stroke),tokenName=part?.tokenName}else{let presentation=this.getNodePresentation(node,focused,activeView,selected.bindings);display=presentation.display,tokenName=presentation.tokenName}return{display,tokenName,continues:!1,firstBinding:selected.bindings[0],commandBinding:selected.commandBinding,bindings:includeBindings?[...selected.bindings]:void 0,stop:selected.stop}}selectActiveBindings(bindings,focused,activeView){let selected=[],commandBinding;for(let binding of bindings){if(!this.conditions.matchesConditions(binding)||!this.catalog.isBindingVisible(binding,focused,activeView))continue;if(selected.push(binding),binding.command===void 0)continue;if(commandBinding??=binding,!binding.fallthrough)return{bindings:selected,commandBinding,stop:!0}}if(selected.length===0)return;return{bindings:selected,commandBinding,stop:!1}}createActiveKeyState(stroke,selection,includeBindings){return{stroke,display:selection.display,tokenName:selection.tokenName,continues:selection.continues,firstBinding:selection.firstBinding,commandBinding:selection.commandBinding,bindings:includeBindings&&selection.bindings?[...selection.bindings]:void 0}}updateActiveKeyState(state,selection,includeBindings){if(!state.firstBinding&&selection.firstBinding)state.firstBinding=selection.firstBinding;if(!state.commandBinding&&selection.commandBinding)state.commandBinding=selection.commandBinding;if(selection.continues)state.continues=!0;if(!includeBindings||!selection.bindings||selection.bindings.length===0)return;if(!state.bindings){state.bindings=[...selection.bindings];return}state.bindings.push(...selection.bindings)}materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView){if(!state.commandBinding&&!state.continues)return;let activeKey={stroke:cloneKeyStroke(state.stroke),display:state.display,continues:state.continues};if(state.tokenName)activeKey.tokenName=state.tokenName;if(state.commandBinding)activeKey.command=state.commandBinding.command;if(includeBindings&&state.bindings&&state.bindings.length>0)activeKey.bindings=state.bindings.length===1?[this.toActiveBinding(state.bindings[0],focused,activeView)]:this.collectActiveBindings(state.bindings,focused,activeView);if(includeMetadata){if(state.firstBinding?.attrs)activeKey.bindingAttrs=state.firstBinding.attrs;let commandAttrs=state.commandBinding?this.catalog.getBindingCommandAttrs(state.commandBinding,focused,activeView):void 0;if(commandAttrs)activeKey.commandAttrs=commandAttrs}return activeKey}invalidateCaches(){this.state.projection.pendingSequenceCacheVersion=-1,this.state.projection.activeKeysPlainCacheVersion=-1,this.state.projection.activeKeysBindingsCacheVersion=-1,this.state.projection.activeKeysMetadataCacheVersion=-1,this.state.projection.activeKeysBindingsAndMetadataCacheVersion=-1}notifyPendingSequenceChange(){if(!this.hooks.has("pendingSequence"))return;this.hooks.emit("pendingSequence",this.state.projection.pendingSequence?this.collectSequencePartsFromPending(this.state.projection.pendingSequence):[])}}function mergeRequirement(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap requirement for "${name}" from ${source}`);target[name]=value}function mergeAttribute(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap attribute for "${name}" from ${source}`);target[name]=value}function isPlainObject2(value){let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function getErrorMessage(error2,fallback){if(error2 instanceof Error&&error2.message)return error2.message;return fallback}function isPromiseLike(value){if(!value)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return typeof value.then==="function"}function snapshotDataValue(value,options){let deep=options?.deep===!0,freeze=options?.freeze===!0,preserveNonPlainObjects=options?.preserveNonPlainObjects===!0;if(Array.isArray(value)){let cloned=deep?value.map((entry2)=>snapshotDataValue(entry2,options)):[...value];return freeze?Object.freeze(cloned):cloned}if(value&&typeof value==="object"){if(preserveNonPlainObjects&&!isPlainObject2(value))return value;let cloned={};for(let[key,entry2]of Object.entries(value))cloned[key]=deep?snapshotDataValue(entry2,options):entry2;return freeze?Object.freeze(cloned):cloned}return value}function createCommandChainCacheState(){return{resolvedWithoutRecordChains:new Map,resolvedWithRecordChains:new Map,fallbackWithoutRecord:new Map,fallbackWithRecord:new Map,fallbackWithoutRecordErrors:new Set,fallbackWithRecordErrors:new Set}}function normalizeBindingCommand(command){if(command===void 0||typeof command==="function")return command;let trimmed=command.trim();if(!trimmed)throw Error("Invalid keymap command: command cannot be empty");return trimmed}function normalizeCommandName(name){let trimmed=name.trim();if(!trimmed)throw Error("Invalid keymap command name: name cannot be empty");if(/\s/.test(trimmed))throw Error(`Invalid keymap command name "${name}": command names cannot contain whitespace`);return trimmed}class CommandCatalogService{state;host;notify;conditions;options;constructor(state,host,notify,conditions,options){this.state=state,this.host=host,this.notify=notify,this.conditions=conditions,this.options=options}normalizeCommands(commands){return normalizeRegisteredCommands({commands,commandFields:this.state.environment.commandFields,conditions:this.conditions,onError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}prependCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.prepend(resolver),resolver)}appendCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.append(resolver),resolver)}clearCommandResolvers(){if(!this.state.commands.commandResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.commands.commandResolvers.clear(),this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}getCommands(query2){return this.getFilteredCommandEntries(query2).map((entry2)=>getRegisteredCommandRecord(entry2.command))}getCommandEntries(query2){let context=this.getCommandQueryContext(query2),filteredEntries=this.getFilteredCommandEntries(query2,context);if(filteredEntries.length===0)return[];let grouped=filteredEntries.map((entry2)=>({entry:entry2,command:getRegisteredCommandRecord(entry2.command),bindings:[]})),indexesByName=new Map;for(let[index,item]of grouped.entries()){let existing=indexesByName.get(item.command.name);if(existing)existing.push(index);else indexesByName.set(item.command.name,[index])}if(indexesByName.size>0)this.collectCommandEntryBindings(grouped,indexesByName,context);return grouped.map((item)=>({command:item.command,bindings:item.bindings}))}getResolvedCommandChain(command,focused,includeRecord){let view=this.getActiveCommandView(focused),entries=this.getResolvedCommandChainFromView(view,command,focused,includeRecord,"active",view.chainsByName.get(command)),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{entries,hadError}}getRegisteredResolvedEntries(command,includeRecord){let view=this.getRegisteredCommandView(),cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let chain=view.chainsByName.get(command);if(!chain||chain.length===0){cache.set(command,[]);return}let resolved=[];for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand(entry2.command,{includeRecord})});return cache.set(command,resolved),resolved}getRegisteredResolverFallback(command,includeRecord){let view=this.getRegisteredCommandView(),fallback=this.getFallbackResolvedCommand(view,command,null,includeRecord,"registered"),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{resolved:fallback?.resolved,hadError}}getCommandAttrs(command,focused){return this.getTopResolvedCommand(command,focused,!1)?.resolved.attrs}getTopCommandRecord(command,focused){return this.getTopResolvedCommand(command,focused,!0)?.resolved.record}getTopRegisteredCommandRecord(command){let top=this.getTopRegisteredCommand(command);return top?getRegisteredCommandRecord(top.command):void 0}getDispatchUnavailableCommandState(command,focused,includeRecord){let chain=this.getRegisteredCommandView().chainsByName.get(command);if(!chain||chain.length===0)return;let inactiveEntry,disabledEntry;for(let entry2 of chain){if(!isLayerActiveForFocused(this.host,entry2.layer,focused)){inactiveEntry??=entry2;continue}if(!this.conditions.layerMatchesRuntimeState(entry2.layer)||!this.conditions.matchesConditions(entry2.command))disabledEntry??=entry2}let unavailableEntry=disabledEntry??inactiveEntry;if(!unavailableEntry)return;return{reason:disabledEntry?"disabled":"inactive",command:includeRecord?getRegisteredCommandRecord(unavailableEntry.command):void 0}}getActiveCommandView(focused){let currentFocused=getFocusedTargetIfAvailable(this.host),derivedStateVersion=this.state.notify.derivedStateVersion;if(focused===currentFocused&&this.state.commands.activeCommandViewVersion===derivedStateVersion&&this.state.commands.activeCommandView?.cacheable)return this.state.commands.activeCommandView;let entries=[],reachable=[],reachableByName=new Map,chainsByName=new Map,cacheable=!0;if(this.state.layers.layersWithCommands>0)for(let layer of getActiveLayersForFocused(this.state.layers,this.host,focused)){if(layer.commands.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;if(layer.hasUnkeyedMatchers)cacheable=!1;for(let command of layer.commands){if(command.hasUnkeyedMatchers)cacheable=!1;if(!this.conditions.matchesConditions(command))continue;let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2]);if(!reachableByName.has(command.name))reachableByName.set(command.name,entry2),reachable.push(entry2)}}let view={cacheable,entries,reachable,reachableByName,chainsByName,...createCommandChainCacheState()};if(focused===currentFocused&&view.cacheable)this.state.commands.activeCommandViewVersion=derivedStateVersion,this.state.commands.activeCommandView=view;return view}getRegisteredCommandView(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandViewVersion===cacheVersion&&this.state.commands.registeredCommandView)return this.state.commands.registeredCommandView;let entries=[],chainsByName=new Map;for(let layer of this.state.layers.sortedLayers){if(layer.commands.length===0)continue;for(let command of layer.commands){let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2])}}let view={entries,chainsByName,...createCommandChainCacheState()};return this.state.commands.registeredCommandViewVersion=cacheVersion,this.state.commands.registeredCommandView=view,view}isBindingVisible(binding,focused,activeView){if(binding.command===void 0||binding.run)return!0;if(typeof binding.command!=="string")return!1;if(activeView.reachableByName.has(binding.command))return!0;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")!==void 0}getBindingCommandAttrs(binding,focused,activeView){if(typeof binding.command!=="string")return;let active=activeView.reachableByName.get(binding.command);if(active)return active.command.attrs;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")?.resolved.attrs}getCommandResolutionStatus(command,layerCommands){if(layerCommands?.has(command)||this.state.commands.registeredNames.has(command))return"resolved";let lookup=this.resolveCommandWithResolvers(command,getFocusedTargetIfAvailable(this.host));if(lookup.resolved||lookup.hadError)return lookup.resolved?"resolved":"error";return"unresolved"}mutateCommandResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let off=register2();return this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange(),()=>{this.notify.runWithStateChangeBatch(()=>{if(off(),this.state.commands.commandResolvers.values().includes(resolver))return;this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}})}getTopResolvedCommand(command,focused,includeRecord){let activeView=this.getActiveCommandView(focused),active=activeView.reachableByName.get(command);if(active)return{target:active.layer.target,resolved:resolveRegisteredCommand(active.command,{includeRecord})};return this.getFallbackResolvedCommand(activeView,command,focused,includeRecord,"active")}getTopRegisteredCommand(command){return this.getRegisteredCommandView().chainsByName.get(command)?.[0]}getFallbackResolvedCommand(view,command,focused,includeRecord,mode){let cache=includeRecord?view.fallbackWithRecord:view.fallbackWithoutRecord,errorCache=includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors;if(cache.has(command)){let cached=cache.get(command);return cached?{resolved:cached}:void 0}let lookup=this.resolveCommandWithResolvers(command,focused,{includeRecord,mode});if(cache.set(command,lookup.resolved??null),lookup.hadError)errorCache.add(command);if(!lookup.resolved)return;return{resolved:lookup.resolved}}getResolvedCommandChainFromView(view,command,focused,includeRecord,mode,activeChain){let cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let resolved=[],chain=activeChain;if(chain)for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand(entry2.command,{includeRecord})});let fallback=this.getFallbackResolvedCommand(view,command,focused,includeRecord,mode);if(fallback)resolved.push(fallback);return cache.set(command,resolved),resolved.length>0?resolved:void 0}getRegisteredLayerCommandEntries(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandEntriesCacheVersion===cacheVersion)return this.state.commands.registeredCommandEntriesCache;let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);let entries=[];for(let layer of layers)for(let command of layer.commands)entries.push({layer,command});return this.state.commands.registeredCommandEntriesCacheVersion=cacheVersion,this.state.commands.registeredCommandEntriesCache=entries,entries}getCommandQueryContext(query2){let visibility=query2?.visibility??"reachable",focused=query2&&Object.prototype.hasOwnProperty.call(query2,"focused")?query2.focused??null:getFocusedTargetIfAvailable(this.host);if(visibility==="registered")return{visibility,focused};return{visibility,focused,activeView:this.getActiveCommandView(focused)}}getFilteredCommandEntries(query2,context=this.getCommandQueryContext(query2)){let entries;if(context.visibility==="registered")entries=this.getRegisteredLayerCommandEntries();else if(context.visibility==="active")entries=context.activeView?.entries??[];else entries=context.activeView?.reachable??[];return queryLayerCommandEntries({entries,query:query2,getCommandRecord:(command)=>getRegisteredCommandRecord(command),onFilterError:(error2)=>{this.notify.emitError("command-query-filter-error",error2,"[Keymap] Error in command query filter:")}})}collectCommandEntryBindings(grouped,indexesByName,context){if(context.visibility==="registered"){let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);for(let layer of layers)for(let binding of layer.compiledBindings)this.collectBindingForCommandEntries(grouped,indexesByName,binding);return}let activeView=context.activeView;if(!activeView)return;for(let layer of getActiveLayersForFocused(this.state.layers,this.host,context.focused)){if(layer.compiledBindings.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;for(let binding of layer.compiledBindings){if(!this.conditions.matchesConditions(binding)||!this.isBindingVisible(binding,context.focused,activeView))continue;this.collectBindingForCommandEntries(grouped,indexesByName,binding)}}}collectBindingForCommandEntries(grouped,indexesByName,binding){if(typeof binding.command!=="string")return;let indexes=indexesByName.get(binding.command);if(!indexes||indexes.length===0)return;for(let index of indexes){let item=grouped[index];if(!item)continue;item.bindings.push({sequence:binding.sequence,command:binding.command,commandAttrs:item.command.attrs,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough})}}resolveCommandWithResolvers(command,focused,options){let includeRecord=options?.includeRecord===!0,context=this.createCommandResolverContext(includeRecord,focused,options?.mode??"active");return resolveCommandWithResolvers(command,this.state.commands.commandResolvers.values(),context,(error2)=>{this.notify.emitError("command-resolver-error",error2,`[Keymap] Error in command resolver for "${command}":`)})}createCommandResolverContext(includeRecord,focused,mode){return{getCommandAttrs:(name)=>{if(mode==="registered")return this.getTopRegisteredCommand(name)?.command.attrs;return this.getCommandAttrs(name,focused)},getCommandRecord:(name)=>{if(!includeRecord)return;if(mode==="registered")return this.getTopRegisteredCommandRecord(name);return this.getTopCommandRecord(name,focused)}}}}function getRegisteredCommandRecord(command){if(command.record)return command.record;let fields=EMPTY_COMMAND_FIELDS;if(command.fields!==EMPTY_COMMAND_FIELDS&&Object.keys(command.fields).length>0)fields=snapshotDataValue(command.fields,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS);let record=command.attrs?Object.freeze({name:command.name,fields,attrs:snapshotDataValue(command.attrs,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS)}):Object.freeze({name:command.name,fields});return command.record=record,record}function resolveRegisteredCommand(command,options){if(options?.includeRecord===!0){let existing2=command.resolvedWithRecord;if(existing2)return existing2;let resolved2={run:createRegisteredCommandRunner(command)};if(command.attrs)resolved2.attrs=command.attrs;return resolved2.record=getRegisteredCommandRecord(command),command.resolvedWithRecord=resolved2,resolved2}let existing=command.resolved;if(existing)return existing;let resolved={run:createRegisteredCommandRunner(command)};if(command.attrs)resolved.attrs=command.attrs;return command.resolved=resolved,resolved}function normalizeRegisteredCommands(options){let normalizedCommands=[],seen=new Set;for(let command of options.commands){let normalizedCommand;try{let mergedAttrs={},mergedFields={},mergedRequires={},matchers=[],conditionKeys=new Set,hasUnkeyedMatchers=!1,normalizedName=normalizeCommandName(command.name);if(seen.has(normalizedName)){options.onError("duplicate-command",{command:normalizedName},`Duplicate keymap command "${normalizedName}" in the same layer`);continue}for(let[fieldName,value]of Object.entries(command)){if(RESERVED_COMMAND_FIELDS.has(fieldName)||value===void 0)continue;mergedFields[fieldName]=snapshotDataValue(value,SNAPSHOT_COMMAND_METADATA_OPTIONS);let compiler=options.commandFields.get(fieldName);if(!compiler)continue;compiler(value,createCommandFieldContext(mergedAttrs,mergedRequires,conditionKeys,matchers,options.conditions,fieldName,{onUnkeyedMatcher(){hasUnkeyedMatchers=!0}}))}let attrs=Object.keys(mergedAttrs).length===0?void 0:Object.freeze(mergedAttrs),fields=Object.keys(mergedFields).length===0?EMPTY_COMMAND_FIELDS:Object.freeze(mergedFields);if(normalizedCommand={name:normalizedName,fields,run:command.run,requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,matchCacheDirty:!0},attrs)normalizedCommand.attrs=attrs}catch(error2){options.onError("register-command-failed",error2,getErrorMessage(error2,`Failed to register keymap command "${String(command.name)}"`));continue}seen.add(normalizedCommand.name),normalizedCommands.push(normalizedCommand)}return normalizedCommands}function createCommandFieldContext(mergedAttrs,mergedRequires,conditionKeys,matchers,conditions,fieldName,options){return{require(name,requiredValue){mergeRequirement(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},attr(name,attributeValue){mergeAttribute(mergedAttrs,name,snapshotDataValue(attributeValue,SNAPSHOT_COMMAND_METADATA_OPTIONS),`field ${fieldName}`)},activeWhen(matcher){let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)options.onUnkeyedMatcher();matchers.push(runtimeMatcher)}}}function createRegisteredCommandRunner(command){if(command.runner)return command.runner;let runner=(ctx)=>{return command.run({...ctx,command:getRegisteredCommandRecord(command)})};return command.runner=runner,runner}function resolveCommandWithResolvers(command,resolvers,context,onResolverError){if(resolvers.length===0)return{hadError:!1};let hadError=!1;for(let resolver of resolvers){let resolved;try{resolved=resolver(command,context)}catch(error2){hadError=!0,onResolverError(error2);continue}if(resolved)return{hadError,resolved}}return{hadError}}function queryLayerCommandEntries(options){let namespace=options.query?.namespace,normalizedSearch=options.query?.search?.trim().toLowerCase()??"",searchKeys=DEFAULT_COMMAND_SEARCH_FIELDS;if(options.query?.searchIn&&options.query.searchIn.length>0)searchKeys=options.query.searchIn;let filter=options.query?.filter,filterEntries2,filterPredicate;if(typeof filter==="function")filterPredicate=filter;else if(filter)filterEntries2=Object.entries(filter);let results=[];for(let entry2 of options.entries){let command=entry2.command;if(!commandMatchesNamespace(command,namespace))continue;if(!commandMatchesSearch(command,normalizedSearch,searchKeys))continue;if(!commandMatchesFilters(command,filterEntries2,options))continue;let record=options.getCommandRecord(command);if(filterPredicate){let matches=!1;try{matches=filterPredicate(record)}catch(error2){options.onFilterError(error2);continue}if(!matches)continue}results.push(entry2)}return results}function commandMatchesSearch(command,search,searchKeys){if(!search)return!0;for(let key of searchKeys)if(commandKeyMatchesSearch(command,key,search))return!0;return!1}function commandMatchesNamespace(command,namespace){if(namespace===void 0)return!0;if(!Object.prototype.hasOwnProperty.call(command.fields,"namespace"))return!1;return commandValueMatchesFilter(command.fields.namespace,namespace)}function commandMatchesFilters(command,filters,options){if(!filters)return!0;for(let[key,matcher]of filters)if(!commandKeyMatchesQuery(command,key,matcher,options))return!1;return!0}function commandKeyMatchesSearch(command,key,search){if(key==="name"&&commandValueMatchesSearch(command.name,search))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesSearch(command.fields[key],search))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesSearch(command.attrs[key],search);return!1}function commandKeyMatchesQuery(command,key,matcher,options){if(typeof matcher==="function"){let record,getRecord=()=>{if(!record)record=options.getCommandRecord(command);return record},foundValue=!1;if(key==="name"){foundValue=!0;try{if(matcher(command.name,getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(Object.prototype.hasOwnProperty.call(command.fields,key)){foundValue=!0;try{if(matcher(command.fields[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key)){foundValue=!0;try{if(matcher(command.attrs[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(!foundValue)try{return matcher(void 0,getRecord())}catch(error2){return options.onFilterError(error2),!1}return!1}return commandKeyMatchesExact(command,key,matcher)}function commandKeyMatchesExact(command,key,matcher){if(key==="name"&&commandValueMatchesFilter(command.name,matcher))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesFilter(command.fields[key],matcher))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesFilter(command.attrs[key],matcher);return!1}function commandValueMatchesFilter(value,matcher){if(Array.isArray(matcher)){for(let expected of matcher)if(commandValueMatchesExact(value,expected))return!0;return!1}return commandValueMatchesExact(value,matcher)}function commandValueMatchesExact(value,expected){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesExact(entry2,expected))return!0;return!1}return Object.is(value,expected)}function commandValueMatchesSearch(value,search){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesSearch(entry2,search))return!0;return!1}if(typeof value==="string")return value.toLowerCase().includes(search);if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return String(value).toLowerCase().includes(search);return!1}class CommandExecutorService{notify;runtime;activation;catalog;options;constructor(notify,runtime,activation,catalog,options){this.notify=notify,this.runtime=runtime,this.activation=activation,this.catalog=catalog,this.options=options}runCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chain=this.catalog.getRegisteredResolvedEntries(normalized,includeRecord),rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}let fallback=this.catalog.getRegisteredResolverFallback(normalized,includeRecord);if(fallback.resolved){let execution=this.executeResolvedCommand(normalized,fallback.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(fallback.hadError)return{ok:!1,reason:"error"};return rejectedResult??{ok:!1,reason:"not-found"}}dispatchCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chainLookup=this.catalog.getResolvedCommandChain(normalized,focused,includeRecord),chain=chainLookup.entries,rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(chainLookup.hadError)return{ok:!1,reason:"error"};let unavailable=this.catalog.getDispatchUnavailableCommandState(normalized,focused,includeRecord);if(unavailable)return unavailable.command?{ok:!1,reason:unavailable.reason,command:unavailable.command}:{ok:!1,reason:unavailable.reason};return rejectedResult??{ok:!1,reason:"not-found"}}runBinding(bindingLayer,binding,event,focused){let data=this.runtime.getReadonlyData();if(binding.run){if(this.executeResolvedCommand(typeof binding.command==="string"?binding.command:"<function>",{run:binding.run},{keymap:this.options.keymap,event,focused,target:bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects(binding,event),!0}if(typeof binding.command!=="string")return!1;let chain=this.catalog.getResolvedCommandChain(binding.command,focused,!1).entries;if(chain?.length===1){let[entry2]=chain;if(entry2){if(this.executeResolvedCommand(binding.command,entry2.resolved,{keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects(binding,event),!0}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data};if(this.executeResolvedCommand(binding.command,entry2.resolved,context).status==="rejected")continue;return applyBindingEventEffects(binding,event),!0}return!1}executeResolvedCommand(commandName,resolved,context){let command=resolved.record,result2;try{result2=resolved.run(context)}catch(error2){return this.notify.emitError("command-execution-error",error2,`[Keymap] Error running command "${commandName}":`),{status:"error",result:{ok:!1,reason:"error",command}}}if(isPromiseLike(result2))return result2.catch((error2)=>{this.notify.emitError("async-command-error",error2,`[Keymap] Async error in command "${commandName}":`)}),{status:"handled",result:{ok:!0,command}};if(result2===!1){if(resolved.rejectedResult)return{status:"rejected",result:resolved.rejectedResult};return{status:"rejected",result:{ok:!1,reason:"rejected",command}}}return{status:"handled",result:{ok:!0,command}}}}function applyBindingEventEffects(binding,event){if(!binding.preventDefault)return;event.preventDefault(),event.stopPropagation()}function normalizeBindingInputs(bindings){if(Array.isArray(bindings))return bindings;let normalized=[];for(let[key,cmd]of Object.entries(bindings)){if(typeof cmd!=="string"&&typeof cmd!=="function")throw Error(`Invalid keymap binding for "${key}": shorthand bindings must map to string or function commands`);normalized.push({key,cmd})}return normalized}function snapshotBindingInputs(bindings){return normalizeBindingInputs(bindings).map((binding)=>({...binding,key:typeof binding.key==="string"?binding.key:{...binding.key}}))}function snapshotParsedBindingInput(binding){return{...binding,sequence:cloneKeySequence(binding.sequence)}}function createSequenceNode(parent,stroke,match){return{parent,depth:parent?parent.depth+1:0,stroke,match,children:new Map,bindings:[],reachableBindings:[]}}function snapshotAttributes(attrs){if(Object.keys(attrs).length===0)return;return snapshotDataValue(attrs,{freeze:!0})}class CompilerService{state;notify;conditions;options;constructor(state,notify,conditions,options){this.state=state,this.notify=notify,this.conditions=conditions,this.options=options}parseTokenKey(key){return parseSingleKeyPartWithParsers(key,this.state.environment.bindingParsers.values(),{tokens:this.state.environment.tokens,layer:EMPTY_COMPILE_FIELDS,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})}compileBindings(bindings,tokens2,sourceTarget,sourceLayerOrder,compileFields){let root=createSequenceNode(null,null,null),compiledBindings=[],hasTokenBindings=!1,bindingExpanders=this.state.environment.bindingExpanders.values(),bindingParsers=this.state.environment.bindingParsers.values(),bindingFieldCompilers=this.state.environment.bindingFields,allowExactPrefixAmbiguity=this.state.dispatch.disambiguationResolvers.has(),warnUnknownField=this.options.warnUnknownField,warnUnknownToken=this.options.warnUnknownToken,conditions=this.conditions;for(let[bindingIndex,binding]of bindings.entries()){let expandedBindingKeys;try{expandedBindingKeys=expandBindingInputWithExpanders(binding.key,bindingExpanders,{layer:compileFields})}catch(error2){this.notify.emitError("binding-expand-error",error2,getErrorMessage(error2,"Failed to expand keymap binding"));continue}for(let expandedBindingKey of expandedBindingKeys){let parsed;try{parsed=typeof expandedBindingKey==="string"?parseBindingSequenceWithParsers(expandedBindingKey,bindingParsers,{tokens:tokens2,layer:compileFields,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)}):{parts:[this.parseObjectKeyPart(expandedBindingKey)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1}}catch(error2){this.notify.emitError("binding-parse-error",error2,getErrorMessage(error2,"Failed to parse keymap binding"));continue}let sequence=parsed.parts;hasTokenBindings||=parsed.hasTokenBindings;for(let tokenName of parsed.unknownTokens)warnUnknownToken(tokenName,typeof expandedBindingKey==="string"?expandedBindingKey:String(expandedBindingKey.name));for(let compiledInput of this.applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields))try{let event=this.normalizeBindingEvent(compiledInput.event),compiledSequence=compiledInput.sequence,mergedRequires,mergedAttrs,matchers,conditionKeys,hasUnkeyedMatchers=!1;for(let fieldName in compiledInput){if(fieldName==="sequence")continue;if(RESERVED_BINDING_FIELDS.has(fieldName))continue;let value=compiledInput[fieldName];if(value===void 0)continue;let compiler=bindingFieldCompilers.get(fieldName);if(!compiler){warnUnknownField("binding",fieldName);continue}compiler(value,{require(name,requiredValue){if(!mergedRequires)mergedRequires={};if(mergeRequirement(mergedRequires,name,requiredValue,`field ${fieldName}`),!conditionKeys)conditionKeys=new Set;conditionKeys.add(name)},attr(name,attributeValue){if(!mergedAttrs)mergedAttrs={};mergeAttribute(mergedAttrs,name,attributeValue,`field ${fieldName}`)},activeWhen:(matcher)=>{let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;if(!matchers)matchers=[];matchers.push(runtimeMatcher)}})}let attrs=mergedAttrs?snapshotAttributes(mergedAttrs):void 0,command=normalizeBindingCommand(compiledInput.cmd),compiledBinding={sequence:compiledSequence,command,event,sourceBinding:snapshotParsedBindingInput(compiledInput),sourceTarget,sourceLayerOrder,sourceBindingIndex:bindingIndex,requires:mergedRequires?Object.entries(mergedRequires):EMPTY_REQUIRES,matchers:matchers??EMPTY_MATCHERS,conditionKeys:conditionKeys?[...conditionKeys]:EMPTY_CONDITION_KEYS,hasUnkeyedMatchers,matchCacheDirty:!0,preventDefault:compiledInput.preventDefault!==!1,fallthrough:compiledInput.fallthrough??!1};if(attrs)compiledBinding.attrs=attrs;if(typeof command==="function")compiledBinding.run=command;if(compiledSequence.length===0)continue;if(event==="release"&&compiledSequence.length>1)throw Error("Keymap release bindings only support a single key stroke");if(event==="press")this.insertBinding(root,compiledBinding,allowExactPrefixAmbiguity);compiledBindings.push(compiledBinding)}catch(error2){this.notify.emitError("binding-compile-error",error2,getErrorMessage(error2,"Failed to compile keymap binding"))}}}return{root,bindings:compiledBindings,hasTokenBindings}}parseObjectKeyPart(key,options){return createKeySequencePart(key,options)}normalizeBindingEvent(event){if(event===void 0||event==="press")return"press";if(event==="release")return"release";throw Error(`Invalid keymap binding event "${String(event)}": expected "press" or "release"`)}applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields){let bindingTransformers=this.state.environment.bindingTransformers.values();if(bindingTransformers.length===0)return[{...binding,sequence:cloneKeySequence(sequence)}];let parsedBinding={...binding,sequence:cloneKeySequence(sequence)},extraBindings=[],keepOriginal=!0,layer=compileFields??EMPTY_COMPILE_FIELDS;for(let transformer of bindingTransformers)try{transformer(parsedBinding,{layer,parseKey:(key)=>{return parseSingleKeyPartWithParsers(key,bindingParsers,{tokens:tokens2,layer,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})},add:(nextBinding)=>{extraBindings.push(snapshotParsedBindingInput(nextBinding))},skipOriginal:()=>{keepOriginal=!1}})}catch(error2){this.notify.emitError("binding-transformer-error",error2,"[Keymap] Error in binding transformer:")}if(!keepOriginal)return extraBindings;if(extraBindings.length===0)return[parsedBinding];return[parsedBinding,...extraBindings]}insertBinding(root,binding,allowExactPrefixAmbiguity){let node=root,touchedNodes=[],createdNodes=[];try{for(let part of binding.sequence){if(!allowExactPrefixAmbiguity&&node.bindings.some((candidate)=>candidate.command!==void 0))throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");let bindingKey=part.match,child=node.children.get(bindingKey);if(!child)child=createSequenceNode(node,cloneKeySequencePart(part).stroke,part.match),node.children.set(bindingKey,child),createdNodes.push({parent:node,key:bindingKey});child.reachableBindings.push(binding),touchedNodes.push(child),node=child}if(!allowExactPrefixAmbiguity&&binding.command!==void 0&&node.children.size>0)throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");node.bindings=[...node.bindings,binding]}catch(error2){for(let index=touchedNodes.length-1;index>=0;index-=1){let touchedNode=touchedNodes[index];if(!touchedNode)continue;if(touchedNode.reachableBindings.at(-1)===binding){touchedNode.reachableBindings.pop();continue}touchedNode.reachableBindings=touchedNode.reachableBindings.filter((candidate)=>candidate!==binding)}for(let index=createdNodes.length-1;index>=0;index-=1){let createdNode=createdNodes[index];if(!createdNode)continue;let child=createdNode.parent.children.get(createdNode.key);if(!child)continue;if(child.children.size>0||child.reachableBindings.length>0||child.bindings.length>0)continue;createdNode.parent.children.delete(createdNode.key)}throw error2}}}function expandBindingInputWithExpanders(key,expanders,options){if(typeof key!=="string"||expanders.length===0)return[key];let layer=options?.layer??EMPTY_COMPILE_FIELDS,candidates=[key];for(let expander of expanders){let nextCandidates=[];for(let input of candidates){let result2=expander({input,layer});if(!result2){nextCandidates.push(input);continue}if(result2.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${input}"`);for(let expandedInput of result2){if(typeof expandedInput!=="string")throw Error(`Keymap binding expander must return string key sequences for "${input}"`);nextCandidates.push(expandedInput)}}candidates=nextCandidates}return candidates}function parseBindingSequenceWithParsers(key,parsers2,options){if(key.length===0)throw Error("Invalid key sequence: sequence cannot be empty");if(parsers2.length===0)throw Error("No keymap binding parsers are registered");let tokens2=options.tokens??new Map,layer=options.layer??EMPTY_COMPILE_FIELDS,parseObjectKey=options.parseObjectKey,parts=[],usedTokens=new Set,unknownTokens=new Set,index=0;while(index<key.length){let matched=!1;for(let parser of parsers2){let result2=parser({input:key,index,layer,tokens:tokens2,normalizeTokenName:normalizeBindingTokenName,createMatch:createTextKeyMatch,parseObjectKey});if(!result2)continue;if(result2.nextIndex<=index||result2.nextIndex>key.length)throw Error(`Keymap binding parser must advance the input for "${key}" at index ${index}`);parts.push(...result2.parts);for(let tokenName of result2.usedTokens??[])usedTokens.add(tokenName);for(let tokenName of result2.unknownTokens??[])unknownTokens.add(tokenName);index=result2.nextIndex,matched=!0;break}if(!matched)throw Error(`No keymap binding parser handled input at index ${index} in "${key}"`)}return{parts,usedTokens:[...usedTokens],unknownTokens:[...unknownTokens],hasTokenBindings:usedTokens.size>0||unknownTokens.size>0}}function parseSingleKeyPartWithParsers(key,parsers2,options){if(typeof key!=="string")return options.parseObjectKey(key);let{parts}=parseBindingSequenceWithParsers(key,parsers2,options),[part]=parts;if(!part||parts.length!==1)throw Error(`Invalid key "${String(key)}": expected a single key stroke`);return part}function isReactiveMatcher(value){if(!value||typeof value!=="object")return!1;let candidate=value;return typeof candidate.get==="function"&&typeof candidate.subscribe==="function"}class ConditionService{state;notify;constructor(state,notify){this.state=state,this.notify=notify}buildRuntimeMatcher(matcher,source){if(typeof matcher==="function")return{source,match:matcher,cacheable:!1};if(isReactiveMatcher(matcher))return{source,match:()=>matcher.get(),cacheable:!0,subscribe:(onChange)=>matcher.subscribe(onChange)};throw Error(`Keymap ${source} expected a function or a reactive matcher`)}hasNoConditions(target){return target.requires.length===0&&target.matchers.length===0}indexRuntimeMatchable(target){if(target.conditionKeys.length>0)for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(dependents){dependents.add(target);continue}this.state.conditions.runtimeKeyDependents.set(key,new Set([target]))}if(!target.hasUnkeyedMatchers)target.matchCacheDirty=!0}unindexRuntimeMatchable(target){if(target.conditionKeys.length===0)return;for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(!dependents)continue;if(dependents.delete(target),dependents.size===0)this.state.conditions.runtimeKeyDependents.delete(key)}}invalidateRuntimeConditionKey(name){let dependents=this.state.conditions.runtimeKeyDependents.get(name);if(!dependents)return;for(let target of dependents)target.matchCacheDirty=!0}matchesConditions(target){if(this.hasNoConditions(target))return!0;if(this.hasFreshConditionCache(target))return target.matchCache===!0;let matched=this.matchRequirements(target.requires)&&this.matchesRuntimeMatchers(target);return this.updateConditionCache(target,matched),matched}layerMatchesRuntimeState(layer){if(this.state.layers.layersWithConditions===0||this.hasNoConditions(layer))return!0;return this.matchesConditions(layer)}matchRequirements(requires){if(requires.length===0)return!0;for(let[name,value]of requires)if(!Object.is(this.state.runtime.data[name],value))return!1;return!0}hasFreshConditionCache(target){if(target.hasUnkeyedMatchers)return!1;return target.matchCacheDirty!==!0&&target.matchCache!==void 0}updateConditionCache(target,matched){if(target.hasUnkeyedMatchers)return;target.matchCacheDirty=!1,target.matchCache=matched}matchesRuntimeMatcher(matcher){try{return matcher.match()}catch(error2){return this.notify.emitError("runtime-matcher-error",error2,`[Keymap] Error evaluating runtime matcher from ${matcher.source}:`),!1}}matchesRuntimeMatchers(target){if(target.matchers.length===0)return!0;if(target.matchers.length===1){let[matcher]=target.matchers;return matcher?this.matchesRuntimeMatcher(matcher):!0}for(let matcher of target.matchers)if(!this.matchesRuntimeMatcher(matcher))return!1;return!0}}function createSyncDecision(action,handler){return{[KEY_DISAMBIGUATION_DECISION]:!0,action,handler}}function createDeferredDecision(action){return{[KEY_DEFERRED_DISAMBIGUATION_DECISION]:!0,action}}function isSyncDecision(value){return!!value&&typeof value==="object"&&value[KEY_DISAMBIGUATION_DECISION]===!0}function isDeferredDecision(value){return!!value&&typeof value==="object"&&value[KEY_DEFERRED_DISAMBIGUATION_DECISION]===!0}class DispatchService{state;notify;runtime;activation;conditions;executor;compiler;catalog;layers;eventMatchResolverContext;pendingDisambiguation=null;nextPendingDisambiguationId=0;constructor(state,notify,runtime,activation,conditions,executor,compiler,catalog,layers){this.state=state,this.notify=notify,this.runtime=runtime,this.activation=activation,this.conditions=conditions,this.executor=executor,this.compiler=compiler,this.catalog=catalog,this.layers=layers,this.eventMatchResolverContext={resolveKey:(key)=>{return this.compiler.parseTokenKey(key).match}}}intercept(name,fn,options){if(name==="key"){let keyOptions=options;return this.state.dispatch.keyHooks.register(fn,{priority:keyOptions?.priority??0,release:keyOptions?.release??!1})}let rawOptions=options;return this.state.dispatch.rawHooks.register(fn,{priority:rawOptions?.priority??0})}prependEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.prepend(resolver)}appendEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.append(resolver)}clearEventMatchResolvers(){this.state.dispatch.eventMatchResolvers.clear()}prependDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.prepend(resolver),resolver)}appendDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.append(resolver),resolver)}clearDisambiguationResolvers(){if(!this.state.dispatch.disambiguationResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.dispatch.disambiguationResolvers.clear(),this.layers.recompileBindings()})}handlePendingSequenceChange(_previous,_next){if(!this.pendingDisambiguation)return;this.cancelPendingDisambiguation()}handleRawSequence(sequence){let hooks=this.state.dispatch.rawHooks.entries();if(hooks.length===0)return!1;let stopped=!1,context={sequence,stop(){stopped=!0}};for(let hook of hooks){try{hook.listener(context)}catch(error2){this.notify.emitError("raw-intercept-error",error2,"[Keymap] Error in raw intercept listener:")}if(stopped)return!0}return!1}handleKeyEvent(event,release){if(!release)this.cancelPendingDisambiguation();let hooks=this.state.dispatch.keyHooks.entries(),context={event,setData:(name,value)=>{this.runtime.setData(name,value)},getData:(name)=>{return this.runtime.getData(name)},consume:(options)=>{let shouldPreventDefault=options?.preventDefault??!0,shouldStopPropagation=options?.stopPropagation??!0;if(shouldPreventDefault)event.preventDefault();if(shouldStopPropagation)event.stopPropagation()}};for(let hook of hooks){if(hook.release!==release)continue;try{hook.listener(context)}catch(error2){this.notify.emitError("key-intercept-error",error2,"[Keymap] Error in key intercept listener:")}if(event.propagationStopped)return}if(release){this.dispatchReleaseLayers(event);return}this.dispatchLayers(event)}mutateDisambiguationResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let hadResolvers=this.state.dispatch.disambiguationResolvers.has(),off=register2();if(!hadResolvers&&this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings();return()=>{this.notify.runWithStateChangeBatch(()=>{let hadBeforeRemoval=this.state.dispatch.disambiguationResolvers.has();if(off(),this.state.dispatch.disambiguationResolvers.values().includes(resolver))return;if(hadBeforeRemoval&&!this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings()})}})}dispatchReleaseLayers(event){let focused=this.activation.getFocusedTarget(),activeLayers=this.activation.getActiveLayers(focused),hasLayerConditions=this.state.layers.layersWithConditions>0,matchKeys=this.resolveEventMatchKeys(event);layerLoop:for(let layer of activeLayers){if(layer.compiledBindings.length===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let strokeKey of matchKeys){let result2=this.runReleaseBindings(layer,strokeKey,event,focused);if(!result2.handled)continue;if(result2.stop)return;continue layerLoop}}}dispatchLayers(event){let focused=this.activation.getFocusedTarget(),pending=this.activation.ensureValidPendingSequence(),matchKeys=this.resolveEventMatchKeys(event);if(pending){this.dispatchPendingSequence(pending,matchKeys,event,focused);return}let activeLayers=this.activation.getActiveLayers(focused);this.dispatchFromRoot(activeLayers,matchKeys,event,focused)}dispatchPendingSequence(pending,matchKeys,event,focused){let advancedCaptures=[];for(let capture2 of pending.captures){let nextNode=this.getReachableChild(capture2.node,matchKeys,focused);if(!nextNode)continue;advancedCaptures.push({layer:capture2.layer,node:nextNode})}if(advancedCaptures.length===0){this.activation.setPendingSequence(null);return}this.dispatchPendingCapturesFromIndex(advancedCaptures,0,!1,event,focused)}dispatchPendingCapturesFromIndex(advancedCaptures,startIndex,handledExact,event,focused){let hasHandledExact=handledExact;for(let index=startIndex;index<advancedCaptures.length;index+=1){let capture2=advancedCaptures[index];if(!capture2)continue;if(capture2.node.children.size>0){if(hasHandledExact)continue;let continuationCaptures=this.collectPendingCapturesFromAdvanced(advancedCaptures,index);if(this.tryResolvePendingAmbiguity(advancedCaptures,index,continuationCaptures,capture2,event,focused,hasHandledExact))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(!result2.handled)continue;if(hasHandledExact=!0,result2.stop){this.activation.setPendingSequence(null);return}}this.activation.setPendingSequence(null)}dispatchFromRoot(activeLayers,matchKeys,event,focused){this.dispatchFromRootAtIndex(activeLayers,0,matchKeys,event,focused)}dispatchFromRootAtIndex(activeLayers,startIndex,matchKeys,event,focused){let hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer)continue;if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode)continue;if(nextNode.children.size>0){let continuationCaptures=this.collectPendingCapturesFromRoot(activeLayers,index,matchKeys,focused);if(this.tryResolveRootAmbiguity(activeLayers,index,matchKeys,continuationCaptures,layer,nextNode,event,focused))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(layer,nextNode.bindings,event,focused);if(!result2.handled)continue;if(result2.stop)return}}tryResolveRootAmbiguity(activeLayers,layerIndex,matchKeys,continuationCaptures,layer,node,event,focused){let applyExact=()=>{if(this.activation.setPendingSequence(null),!this.runBindings(layer,node.bindings,event,focused).stop)this.dispatchFromRootAtIndex(activeLayers,layerIndex+1,matchKeys,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:node.bindings,runExact:applyExact})}tryResolvePendingAmbiguity(advancedCaptures,captureIndex,continuationCaptures,capture2,event,focused,handledExact){let applyExact=()=>{this.activation.setPendingSequence(null);let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(result2.stop)return;this.dispatchPendingCapturesFromIndex(advancedCaptures,captureIndex+1,handledExact||result2.handled,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:capture2.node.bindings,runExact:applyExact})}tryResolveAmbiguity(options){let{event,focused,continuationCaptures,exactBindingsSource,runExact}=options;if(!this.state.dispatch.disambiguationResolvers.has()||continuationCaptures.length===0)return!1;let activeView=this.catalog.getActiveCommandView(focused),exactBindings=this.activation.collectMatchingBindings(exactBindingsSource,focused,activeView);if(!exactBindings.some((binding)=>binding.command!==void 0))return!1;let continueSequence=()=>{this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation()},clear=()=>{this.activation.setPendingSequence(null),event.preventDefault(),event.stopPropagation()},sequence,getSequence=()=>{return sequence??=this.activation.collectSequencePartsFromPending({captures:continuationCaptures}),sequence},decision=this.resolveDisambiguation({event,focused,getSequence,exactBindings,continuationCaptures,activeView});if(!decision)return this.warnUnresolvedAmbiguity(getSequence()),continueSequence(),!0;return this.applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence)}applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence){if(decision.action==="run-exact")return runExact(),!0;if(decision.action==="continue-sequence")return continueSequence(),!0;if(decision.action==="clear")return clear(),!0;return continueSequence(),this.scheduleDeferredDisambiguation(continuationCaptures,decision.handler,focused,getSequence(),(nextDecision)=>{if(!nextDecision)return;if(nextDecision.action==="run-exact"){runExact();return}if(nextDecision.action==="continue-sequence"){continueSequence();return}clear()}),!0}resolveDisambiguation(options){let activation=this.activation,runtime=this.runtime,sequence,exact,continuations,strokePart,ctx={event:options.event,focused:options.focused,get sequence(){return sequence??=cloneKeySequence(options.getSequence()),sequence},get stroke(){let stroke=options.getSequence().at(-1);if(!stroke)throw Error("Disambiguation context expected a non-empty sequence");return strokePart??={...stroke,stroke:cloneKeyStroke(stroke.stroke)},strokePart},get exact(){return exact??=activation.collectActiveBindings(options.exactBindings,options.focused,options.activeView).map((binding)=>({...binding,sequence:cloneKeySequence(binding.sequence)})),exact},get continuations(){return continuations??=activation.getActiveKeysForCaptures(options.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),continuations},getData:(name)=>{return runtime.getData(name)},setData:(name,value)=>{runtime.setData(name,value)},runExact:()=>createSyncDecision("run-exact"),continueSequence:()=>createSyncDecision("continue-sequence"),clear:()=>createSyncDecision("clear"),defer:(run)=>createSyncDecision("defer",run)};for(let resolver of this.state.dispatch.disambiguationResolvers.values()){let result2;try{result2=resolver(ctx)}catch(error2){this.notify.emitError("disambiguation-resolver-error",error2,"[Keymap] Error in disambiguation resolver:");continue}if(result2===void 0)continue;if(isPromiseLike(result2)){this.notify.emitError("invalid-disambiguation-resolver-return",result2,"[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling");continue}if(!isSyncDecision(result2)){this.notify.emitError("invalid-disambiguation-decision",result2,"[Keymap] Invalid disambiguation decision returned by resolver:");continue}return result2}return}scheduleDeferredDisambiguation(captures,handler,focused,sequence,apply){this.cancelPendingDisambiguation();let controller=new AbortController,pending={id:this.nextPendingDisambiguationId++,controller,captures,apply};this.pendingDisambiguation=pending,queueMicrotask(()=>{this.executeDeferredDisambiguation(pending,handler,focused,sequence)})}executeDeferredDisambiguation(pending,handler,focused,sequence){if(!this.isPendingDisambiguationCurrent(pending))return;let ctx={signal:pending.controller.signal,sequence:cloneKeySequence(sequence),focused,sleep:(ms)=>{return this.sleepWithSignal(ms,pending.controller.signal)},runExact:()=>createDeferredDecision("run-exact"),continueSequence:()=>createDeferredDecision("continue-sequence"),clear:()=>createDeferredDecision("clear")},result2;try{result2=handler(ctx)}catch(error2){if(this.isPendingDisambiguationCurrent(pending))this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending);return}if(isPromiseLike(result2)){result2.then((resolved)=>{this.applyDeferredDisambiguationResult(pending,resolved)}).catch((error2)=>{if(!this.isPendingDisambiguationCurrent(pending))return;this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending)});return}this.applyDeferredDisambiguationResult(pending,result2)}applyDeferredDisambiguationResult(pending,result2){if(!this.isPendingDisambiguationCurrent(pending))return;if(result2!==void 0&&!isDeferredDecision(result2)){this.notify.emitError("invalid-deferred-disambiguation-decision",result2,"[Keymap] Invalid deferred disambiguation decision returned by handler:"),this.finishPendingDisambiguation(pending);return}this.finishPendingDisambiguation(pending),pending.apply(result2)}finishPendingDisambiguation(pending){if(!this.isPendingDisambiguationCurrent(pending))return;this.pendingDisambiguation=null}cancelPendingDisambiguation(){let pending=this.pendingDisambiguation;if(!pending)return;this.pendingDisambiguation=null,pending.controller.abort()}isPendingDisambiguationCurrent(pending){return this.pendingDisambiguation===pending}sleepWithSignal(ms,signal){if(signal.aborted)return Promise.resolve(!1);return new Promise((resolve21)=>{let timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve21(!0)},Math.max(0,ms)),onAbort=()=>{clearTimeout(timeout),signal.removeEventListener("abort",onAbort),resolve21(!1)};signal.addEventListener("abort",onAbort,{once:!0})})}warnUnresolvedAmbiguity(sequence){let display=stringifyKeySequence(sequence,{preferDisplay:!0});this.notify.warnOnce(`unresolved-disambiguation:${display}`,"unresolved-disambiguation",{sequence:display},`[Keymap] Ambiguous exact/prefix sequence "${display}" fell back to prefix handling because no disambiguation resolver resolved it`)}collectPendingCapturesFromRoot(activeLayers,startIndex,matchKeys,focused){let captures=[],hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer||layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode||nextNode.children.size===0)continue;captures.push({layer,node:nextNode})}return captures}collectPendingCapturesFromAdvanced(advancedCaptures,startIndex){return advancedCaptures.filter((candidate,candidateIndex)=>{return candidateIndex>=startIndex&&candidate.node.children.size>0})}resolveEventMatchKeys(event){let resolvers=this.state.dispatch.eventMatchResolvers.values();if(resolvers.length===0)return[];if(resolvers.length===1)return resolveSingleEventMatchKeys(resolvers[0],event,this.eventMatchResolverContext,this.notify);let keys=[],seen=new Set;for(let resolver of resolvers){let resolved;try{resolved=resolver(event,this.eventMatchResolverContext)}catch(error2){this.notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:");continue}if(!resolved||resolved.length===0)continue;for(let candidate of resolved){if(typeof candidate!=="string"){this.notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}}return keys}runReleaseBindings(layer,strokeKey,event,focused){let handled=!1;for(let binding of layer.compiledBindings){if(binding.event!=="release")continue;let firstPart=binding.sequence[0];if(!firstPart||firstPart.match!==strokeKey)continue;if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}getReachableChild(node,matchKeys,focused){for(let strokeKey of matchKeys){let child=node.children.get(strokeKey);if(!child||!this.activation.nodeHasReachableBindings(child,focused))continue;return child}return}runBindings(layer,bindings,event,focused){let handled=!1;for(let binding of bindings){if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}}function resolveSingleEventMatchKeys(resolver,event,ctx,notify){let resolved;try{resolved=resolver(event,ctx)}catch(error2){return notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:"),[]}if(!resolved||resolved.length===0)return[];if(resolved.length===1){let[candidate]=resolved;if(typeof candidate!=="string")return notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:"),[];return[candidate]}let keys=[],seen=new Set;for(let candidate of resolved){if(typeof candidate!=="string"){notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}return keys}function registerFieldCompilers(fields,options){let{kind,reservedFields,registeredFields,emitError}=options,entries=Object.entries(fields),registered=[];for(let[name]of entries){if(reservedFields.has(name)){emitError(`reserved-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is reserved`);continue}if(registeredFields.has(name))emitError(`duplicate-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is already registered`)}for(let[name,compiler]of entries){if(reservedFields.has(name)||registeredFields.has(name))continue;registeredFields.set(name,compiler),registered.push([name,compiler])}return()=>{for(let[name,compiler]of registered)if(registeredFields.get(name)===compiler)registeredFields.delete(name)}}class EnvironmentService{state;notify;compiler;layers;constructor(state,notify,compiler,layers){this.state=state,this.notify=notify,this.compiler=compiler,this.layers=layers}prependBindingTransformer(transformer){return this.state.environment.bindingTransformers.prepend(transformer)}appendBindingTransformer(transformer){return this.state.environment.bindingTransformers.append(transformer)}clearBindingTransformers(){this.state.environment.bindingTransformers.clear()}prependBindingParser(parser){return this.state.environment.bindingParsers.prepend(parser)}appendBindingParser(parser){return this.state.environment.bindingParsers.append(parser)}clearBindingParsers(){this.state.environment.bindingParsers.clear()}registerToken(token){let normalizedToken;try{normalizedToken=normalizeBindingTokenName(token.name)}catch(error2){return this.notify.emitError("token-name-normalize-error",error2,getErrorMessage(error2,"Failed to register keymap token")),NOOP}if(this.state.environment.tokens.has(normalizedToken))return this.notify.emitError("duplicate-token",{token:normalizedToken},`Keymap token "${normalizedToken}" is already registered`),NOOP;let parsedToken;try{parsedToken=this.compiler.parseTokenKey(token.key)}catch(error2){return this.notify.emitError("token-parse-error",error2,getErrorMessage(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP}let registeredToken={stroke:parsedToken.stroke,match:parsedToken.match},nextTokens=new Map(this.state.environment.tokens);nextTokens.set(normalizedToken,registeredToken);try{this.layers.applyTokenState(nextTokens)}catch(error2){return this.notify.emitError("token-register-error",error2,getErrorMessage(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP}return()=>{if(this.state.environment.tokens.get(normalizedToken)!==registeredToken)return;let nextTokens2=new Map(this.state.environment.tokens);nextTokens2.delete(normalizedToken);try{this.layers.applyTokenState(nextTokens2)}catch(error2){this.notify.emitError("token-unregister-error",error2,getErrorMessage(error2,`Failed to unregister keymap token "${normalizedToken}"`))}}}prependBindingExpander(expander){return this.state.environment.bindingExpanders.prepend(expander)}appendBindingExpander(expander){return this.state.environment.bindingExpanders.append(expander)}clearBindingExpanders(){this.state.environment.bindingExpanders.clear()}registerLayerFields(fields){return registerFieldCompilers(fields,{kind:"layer",reservedFields:RESERVED_LAYER_FIELDS,registeredFields:this.state.environment.layerFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerBindingFields(fields){return registerFieldCompilers(fields,{kind:"binding",reservedFields:RESERVED_BINDING_FIELDS,registeredFields:this.state.environment.bindingFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerCommandFields(fields){return registerFieldCompilers(fields,{kind:"command",reservedFields:RESERVED_COMMAND_FIELDS,registeredFields:this.state.environment.commandFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}}function sortLayers(layers){return[...layers].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return right.order-left.order})}function createCommandLookup(commands){if(commands.length===0)return;let lookup=new Map;for(let command of commands)lookup.set(command.name,command);return lookup}function addRegisteredCommandNames(target,commands){for(let command of commands)target.set(command.name,(target.get(command.name)??0)+1)}function removeRegisteredCommandNames(target,commands){for(let command of commands){let count=target.get(command.name);if(!count||count<=1){target.delete(command.name);continue}target.set(command.name,count-1)}}function getSequenceNode(root,sequence){let node=root;for(let part of sequence)if(node=node.children.get(part.match),!node)return;return node}function buildLayerBindingAnalyses(root,compiledBindings){return compiledBindings.map((binding)=>{let node=binding.event==="press"?getSequenceNode(root,binding.sequence):void 0;return{sequence:cloneKeySequence(binding.sequence),command:binding.command,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough,sourceBinding:snapshotParsedBindingInput(binding.sourceBinding),sourceTarget:binding.sourceTarget,sourceLayerOrder:binding.sourceLayerOrder,sourceBindingIndex:binding.sourceBindingIndex,hasCommandAtSequence:node?node.bindings.some((candidate)=>candidate.command!==void 0):!1,hasContinuations:node?node.children.size>0:!1}})}class LayerService{state;notify;conditions;activation;options;constructor(state,notify,conditions,activation,options){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation,this.options=options}registerLayer(layer){return this.notify.runWithStateChangeBatch(()=>{let target=layer.target;if(target&&this.options.host.isTargetDestroyed(target))return this.notify.emitError("destroyed-layer-target",{target},"Cannot register a keymap layer for a destroyed keymap target"),NOOP2;let bindingInputs,requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields,commands,commandLookup,targetMode;try{targetMode=this.normalizeTargetMode(layer),bindingInputs=snapshotBindingInputs(layer.bindings??[]),commands=!layer.commands||layer.commands.length===0?[]:this.options.commands.normalizeCommands(layer.commands),commandLookup=createCommandLookup(commands),{requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields}=this.compileLayerRuntimeState(layer)}catch(error2){return this.notify.emitError("register-layer-failed",error2,getErrorMessage(error2,"Failed to register keymap layer")),NOOP2}let order=this.state.core.order++,compiledBindings=this.options.compiler.compileBindings(bindingInputs,this.state.environment.tokens,target,order,compileFields);if(compiledBindings.bindings.length===0&&!compiledBindings.hasTokenBindings&&commands.length===0)return NOOP2;this.runLayerAnalyzers({target,order,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,root:compiledBindings.root,hasTokenBindings:compiledBindings.hasTokenBindings});let registeredLayer={order,target,targetMode,priority:layer.priority??0,requires,matchers,conditionKeys,hasUnkeyedMatchers,matchCacheDirty:!0,compileFields,commands,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,hasUnkeyedCommands:commands.some((command)=>command.hasUnkeyedMatchers),hasUnkeyedBindings:compiledBindings.bindings.some((binding)=>binding.hasUnkeyedMatchers),hasTokenBindings:compiledBindings.hasTokenBindings,root:compiledBindings.root};if(this.state.layers.layers.add(registeredLayer),registeredLayer.commands.length>0)this.state.layers.layersWithCommands+=1,this.state.commands.commandMetadataVersion+=1,addRegisteredCommandNames(this.state.commands.registeredNames,registeredLayer.commands);if(registeredLayer.requires.length>0||registeredLayer.matchers.length>0)this.state.layers.layersWithConditions+=1;this.connectRuntimeMatchable(registeredLayer);for(let command of registeredLayer.commands)this.connectRuntimeMatchable(command);for(let binding of registeredLayer.compiledBindings)this.connectRuntimeMatchable(binding);if(this.indexLayer(registeredLayer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),target){let onTargetDestroy=()=>{this.unregisterLayer(registeredLayer)};registeredLayer.offTargetDestroy=this.options.host.onTargetDestroy(target,onTargetDestroy)}if(registeredLayer.commands.length>0)this.activation.ensureValidPendingSequence();return this.notify.queueStateChange(),()=>{this.unregisterLayer(registeredLayer)}})}applyTokenState(nextTokens){this.notify.runWithStateChangeBatch(()=>{let nextCompilations=new Map;for(let layer of this.state.layers.layers){if(!layer.hasTokenBindings)continue;nextCompilations.set(layer,this.compileLayerBindings(layer,nextTokens))}this.state.environment.tokens=nextTokens;let shouldClearPending=!1;for(let[layer,compilation]of nextCompilations)if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;if(shouldClearPending)this.activation.setPendingSequence(null);if(nextCompilations.size>0)this.notify.queueStateChange()})}recompileBindings(){this.notify.runWithStateChangeBatch(()=>{let recompiledLayers=0,shouldClearPending=!1;for(let layer of this.state.layers.layers){if(layer.bindingInputs.length===0)continue;let compilation=this.compileLayerBindings(layer,this.state.environment.tokens);if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;recompiledLayers+=1}if(shouldClearPending)this.activation.setPendingSequence(null);if(recompiledLayers>0)this.notify.queueStateChange()})}prependLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.prepend(analyzer)}appendLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.append(analyzer)}clearLayerAnalyzers(){this.state.layers.layerAnalyzers.clear()}cleanup(){for(let layer of this.state.layers.layers){this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0}}normalizeTargetMode(layer){if(layer.targetMode){if(!layer.target)throw Error(`Keymap targetMode "${layer.targetMode}" requires a target`);return layer.targetMode}return layer.target?"focus-within":void 0}runLayerAnalyzers(options){let analyzers=this.state.layers.layerAnalyzers.values();if(analyzers.length===0)return;let bindings=buildLayerBindingAnalyses(options.root,options.compiledBindings),ctx={target:options.target,order:options.order,bindingInputs:options.bindingInputs,bindings,hasTokenBindings:options.hasTokenBindings,checkCommandResolution:(command)=>{return this.options.commands.getCommandResolutionStatus(command,options.commandLookup)},warn:(code,warning,message)=>{this.notify.emitWarning(code,warning,message)},warnOnce:(key,code,warning,message)=>{this.notify.warnOnce(key,code,warning,message)},error:(code,error2,message)=>{this.notify.emitError(code,error2,message)}};for(let analyzer of analyzers)try{analyzer(ctx)}catch(error2){this.notify.emitError("layer-analyzer-error",error2,"[Keymap] Error in layer analyzer:")}}compileLayerRuntimeState(layer){let mergedRequires={},matchers=[],compileFields=Object.create(null),conditionKeys=new Set,hasUnkeyedMatchers=!1;for(let[fieldName,value]of Object.entries(layer)){if(RESERVED_LAYER_FIELDS.has(fieldName))continue;if(value===void 0)continue;compileFields[fieldName]=snapshotDataValue(value);let compiler=this.state.environment.layerFields.get(fieldName);if(!compiler){this.options.warnUnknownField("layer",fieldName);continue}compiler(value,{require:(name,requiredValue)=>{mergeRequirement(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},activeWhen:(matcher)=>{let runtimeMatcher=this.conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;matchers.push(runtimeMatcher)}})}return{requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,compileFields:Object.keys(compileFields).length>0?Object.freeze(compileFields):void 0}}compileLayerBindings(layer,tokens2){return this.options.compiler.compileBindings(layer.bindingInputs,tokens2,layer.target,layer.order,layer.compileFields)}applyCompiledBindings(layer,compilation){this.runLayerAnalyzers({target:layer.target,order:layer.order,commandLookup:layer.commandLookup,bindingInputs:layer.bindingInputs,compiledBindings:compilation.bindings,root:compilation.root,hasTokenBindings:compilation.hasTokenBindings});for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.root=compilation.root,layer.compiledBindings=compilation.bindings,layer.hasUnkeyedBindings=compilation.bindings.some((binding)=>binding.hasUnkeyedMatchers),layer.hasTokenBindings=compilation.hasTokenBindings;for(let binding of layer.compiledBindings)this.connectRuntimeMatchable(binding);return this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer)??!1}indexLayer(layer){this.state.layers.sortedLayers=sortLayers([...this.state.layers.sortedLayers,layer]),this.state.layers.activeLayersVersion+=1}removeLayerFromIndex(layer){this.state.layers.sortedLayers=this.state.layers.sortedLayers.filter((candidate)=>candidate!==layer),this.state.layers.activeLayersVersion+=1}unregisterLayer(layer){this.notify.runWithStateChangeBatch(()=>{if(!this.state.layers.layers.delete(layer))return;if(layer.requires.length>0||layer.matchers.length>0)this.state.layers.layersWithConditions-=1;if(layer.commands.length>0)this.state.layers.layersWithCommands-=1,this.state.commands.commandMetadataVersion+=1,removeRegisteredCommandNames(this.state.commands.registeredNames,layer.commands);this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);if(this.removeLayerFromIndex(layer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0,this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer))this.activation.setPendingSequence(null);else if(layer.commands.length>0&&!this.options.host.isDestroyed)this.activation.ensureValidPendingSequence();this.notify.queueStateChange()})}connectRuntimeMatchable(target){this.attachReactiveMatchers(target),this.conditions.indexRuntimeMatchable(target)}disconnectRuntimeMatchable(target){this.detachReactiveMatchers(target),this.conditions.unindexRuntimeMatchable(target)}attachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.subscribe)continue;try{matcher.dispose=matcher.subscribe(()=>{if(target.matchCacheDirty=!0,!this.activation.hasPendingSequenceState()){this.notify.queueStateChange();return}this.notify.runWithStateChangeBatch(()=>{this.activation.revalidatePendingSequenceIfNeeded(),this.notify.queueStateChange()})})}catch(error2){this.notify.emitError("reactive-matcher-subscribe-error",error2,getErrorMessage(error2,`Failed to subscribe to reactive matcher from ${matcher.source}`))}}}detachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.dispose)continue;try{matcher.dispose()}catch(error2){this.notify.emitError("reactive-matcher-dispose-error",error2,getErrorMessage(error2,`Failed to dispose reactive matcher from ${matcher.source}`))}matcher.dispose=void 0}}}class Emitter2{onError;listeners=Object.create(null);constructor(onError){this.onError=onError}hook(name,listener){let current=this.listeners[name]??[];return this.listeners[name]=[...current,listener],()=>{let current2=this.listeners[name];if(!current2||current2.length===0)return;let next=current2.filter((candidate)=>candidate!==listener);if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}}has(name){return(this.listeners[name]?.length??0)>0}off(name,listener){let current=this.listeners[name];if(!current||current.length===0)return;let next=current.filter((candidate)=>candidate!==listener);if(next.length===current.length)return;if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}clear(){this.listeners=Object.create(null)}emit(name,...args){let listeners2=this.listeners[name];if(!listeners2||listeners2.length===0)return;for(let listener of listeners2)try{if(args.length===0)listener();else listener(args[0])}catch(error2){this.onError(name,error2)}}}class NotificationService{state;events;hooks;constructor(state,events,hooks){this.state=state,this.events=events,this.hooks=hooks}runWithStateChangeBatch(fn){this.state.notify.stateChangeDepth+=1;try{return fn()}finally{if(this.state.notify.stateChangeDepth-=1,this.state.notify.stateChangeDepth===0)this.flushStateChange()}}queueStateChange(){if(this.state.notify.derivedStateVersion+=1,!this.hooks.has("state"))return;if(this.state.notify.stateChangePending=!0,this.state.notify.stateChangeDepth===0&&!this.state.notify.flushingStateChange)this.flushStateChange()}emitWarning(code,warning,message){if(!this.events.has("warning")){let consoleMessage=`[${code}] ${message}`;if(warning instanceof Error)console.warn(consoleMessage,warning);else console.warn(consoleMessage);return}this.events.emit("warning",{code,message,warning})}emitError(code,error2,message){if(!this.events.has("error")){let consoleMessage=`[${code}] ${message}`;if(error2 instanceof Error)console.error(consoleMessage,error2);else console.error(consoleMessage);return}this.events.emit("error",{code,message,error:error2})}reportListenerError(name,error2){if(name==="state"){this.emitError("state-listener-error",error2,"[Keymap] Error in state listener:");return}if(name==="pendingSequence"){this.emitError("pending-sequence-listener-error",error2,"[Keymap] Error in pending sequence listener:");return}}warnOnce(key,code,warning,message){if(this.state.notify.usedWarningKeys.has(key))return;this.state.notify.usedWarningKeys.add(key),this.emitWarning(code,warning,message)}flushStateChange(){if(!this.state.notify.stateChangePending||this.state.notify.stateChangeDepth>0||this.state.notify.flushingStateChange)return;this.state.notify.flushingStateChange=!0;try{let iterations=0;while(this.state.notify.stateChangePending&&this.state.notify.stateChangeDepth===0){if(iterations>=MAX_STATE_CHANGE_FLUSH_ITERATIONS){this.state.notify.stateChangePending=!1,this.emitError("state-change-feedback-loop",{iterations:MAX_STATE_CHANGE_FLUSH_ITERATIONS},`[Keymap] Possible infinite state listener feedback loop detected after ${MAX_STATE_CHANGE_FLUSH_ITERATIONS} iterations; pending state notifications were dropped`);break}iterations+=1,this.state.notify.stateChangePending=!1,this.hooks.emit("state")}}finally{this.state.notify.flushingStateChange=!1}}}class RuntimeService{state;notify;conditions;activation;constructor(state,notify,conditions,activation){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation}getData(name){return this.state.runtime.data[name]}setData(name,value){this.notify.runWithStateChangeBatch(()=>{if(value===void 0){if(!(name in this.state.runtime.data))return;delete this.state.runtime.data[name],this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange();return}if(Object.is(this.state.runtime.data[name],value))return;this.state.runtime.data[name]=value,this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange()})}getReadonlyData(){if(this.state.runtime.readonlyDataVersion===this.state.runtime.dataVersion)return this.state.runtime.readonlyData;return this.state.runtime.readonlyData=Object.freeze({...this.state.runtime.data}),this.state.runtime.readonlyDataVersion=this.state.runtime.dataVersion,this.state.runtime.readonlyData}}class CopyOnWriteRegistry{items=[];getItems(){return this.items}setItems(items){this.items=items}removeItem(value){let current=this.items;if(current.length===0)return!1;let next=current.filter((candidate)=>candidate!==value);if(next.length===current.length)return!1;return this.items=next,!0}has(){return this.items.length>0}clear(){this.items=[]}}function createKeymapState(){return{core:{order:0},environment:{tokens:new Map,layerFields:new Map,bindingExpanders:new OrderedRegistry,bindingParsers:new OrderedRegistry,bindingTransformers:new OrderedRegistry,bindingFields:new Map,commandFields:new Map},dispatch:{eventMatchResolvers:new OrderedRegistry,disambiguationResolvers:new OrderedRegistry,keyHooks:new PriorityRegistry,rawHooks:new PriorityRegistry},layers:{layers:new Set,sortedLayers:[],activeLayersVersion:0,activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],layersWithConditions:0,layersWithCommands:0,layerAnalyzers:new OrderedRegistry},commands:{commandMetadataVersion:0,registeredNames:new Map,commandResolvers:new OrderedRegistry,activeCommandViewVersion:-1,activeCommandView:void 0,registeredCommandViewVersion:-1,registeredCommandView:void 0,registeredCommandEntriesCacheVersion:-1,registeredCommandEntriesCache:[]},projection:{pendingSequence:null,pendingSequenceCacheVersion:-1,pendingSequenceCache:[],activeKeysPlainCacheVersion:-1,activeKeysPlainCache:[],activeKeysBindingsCacheVersion:-1,activeKeysBindingsCache:[],activeKeysMetadataCacheVersion:-1,activeKeysMetadataCache:[],activeKeysBindingsAndMetadataCacheVersion:-1,activeKeysBindingsAndMetadataCache:[]},conditions:{runtimeKeyDependents:new Map},runtime:{data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:EMPTY_DATA},notify:{derivedStateVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}}function getKeyMatchKey(input){return resolveKeyMatch(input)}class Keymap{host;state=createKeymapState();cleanedUp=!1;resources=new Map;cleanupListeners=[];events=new Emitter2(()=>{});hooks;notify;activation;runtime;conditions;catalog;executor;compiler;dispatch;layers;environment;keypressListener;keyreleaseListener;rawListener;focusedTargetListener;constructor(host){if(this.host=host,host.isDestroyed)throw Error("Cannot create a keymap for a destroyed host");if(this.hooks=new Emitter2((name,error2)=>{this.notify.reportListenerError(name,error2)}),this.notify=new NotificationService(this.state,this.events,this.hooks),this.conditions=new ConditionService(this.state,this.notify),this.catalog=new CommandCatalogService(this.state,this.host,this.notify,this.conditions,{onCommandResolversChanged:()=>{this.activation.ensureValidPendingSequence()}}),this.activation=new ActivationService(this.state,this.host,this.hooks,this.notify,this.conditions,this.catalog,{onPendingSequenceChanged:(previous,next)=>{this.dispatch?.handlePendingSequenceChange(previous,next)}}),this.runtime=new RuntimeService(this.state,this.notify,this.conditions,this.activation),this.executor=new CommandExecutorService(this.notify,this.runtime,this.activation,this.catalog,{keymap:this,createCommandEvent:()=>this.host.createCommandEvent()}),this.compiler=new CompilerService(this.state,this.notify,this.conditions,{warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)},warnUnknownToken:(token,sequence)=>{this.warnUnknownToken(token,sequence)}}),this.layers=new LayerService(this.state,this.notify,this.conditions,this.activation,{compiler:this.compiler,commands:this.catalog,host:this.host,warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)}}),this.environment=new EnvironmentService(this.state,this.notify,this.compiler,this.layers),this.dispatch=new DispatchService(this.state,this.notify,this.runtime,this.activation,this.conditions,this.executor,this.compiler,this.catalog,this.layers),this.keypressListener=(event)=>{this.dispatch.handleKeyEvent(event,!1)},this.keyreleaseListener=(event)=>{this.dispatch.handleKeyEvent(event,!0)},this.rawListener=(sequence)=>{return this.dispatch.handleRawSequence(sequence)},this.focusedTargetListener=(focused)=>{this.handleFocusedTargetChange(focused)},this.cleanupListeners.push(this.host.onKeyPress(this.keypressListener)),this.cleanupListeners.push(this.host.onKeyRelease(this.keyreleaseListener)),this.host.onRawInput)this.cleanupListeners.push(this.host.onRawInput(this.rawListener));if(this.cleanupListeners.push(this.host.onFocusChange(this.focusedTargetListener)),this.host.onDestroy)this.cleanupListeners.push(this.host.onDestroy(()=>{this.cleanup()}))}cleanup(){if(this.cleanedUp)return;this.cleanedUp=!0,this.activation.setPendingSequence(null);for(let resource of this.resources.values())resource.dispose();this.resources.clear(),this.layers.cleanup();for(let cleanupListener of this.cleanupListeners.splice(0))cleanupListener()}setData(name,value){this.runtime.setData(name,value)}getData(name){return this.runtime.getData(name)}hasPendingSequence(){return this.activation.ensureValidPendingSequence()!==void 0}getPendingSequence(){return this.activation.getPendingSequence()}createKeyMatcher(key){let match=this.compiler.parseTokenKey(key).match;return(input)=>{if(!input)return!1;return getKeyMatchKey(input)===match}}clearPendingSequence(){this.activation.setPendingSequence(null)}popPendingSequence(){return this.activation.popPendingSequence()}getActiveKeys(options){return this.activation.getActiveKeys(options)}getCommands(query2){return this.catalog.getCommands(query2)}getCommandEntries(query2){return this.catalog.getCommandEntries(query2)}normalizeCommandName(name){return normalizeCommandName(name)}normalizeBindings(bindings){return normalizeBindingInputs(bindings)}acquireResource(key,setup){if(this.cleanedUp||this.host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");let existing=this.resources.get(key);if(existing)return existing.count+=1,()=>{this.releaseResource(key,existing)};let resource={count:1,dispose:setup()};return this.resources.set(key,resource),()=>{this.releaseResource(key,resource)}}runCommand(cmd,options){return this.executor.runCommand(cmd,options)}dispatchCommand(cmd,options){return this.executor.dispatchCommand(cmd,options)}on(name,fn){if(name==="warning")return this.events.hook(name,fn);if(name==="error")return this.events.hook(name,fn);return this.hooks.hook(name,fn)}intercept(name,fn,options){if(name==="key")return this.dispatch.intercept(name,fn,options);return this.dispatch.intercept(name,fn,options)}registerLayer(layer){return this.layers.registerLayer(layer)}registerLayerFields(fields){return this.environment.registerLayerFields(fields)}prependBindingTransformer(transformer){return this.environment.prependBindingTransformer(transformer)}appendBindingTransformer(transformer){return this.environment.appendBindingTransformer(transformer)}clearBindingTransformers(){this.environment.clearBindingTransformers()}prependBindingParser(parser){return this.environment.prependBindingParser(parser)}appendBindingParser(parser){return this.environment.appendBindingParser(parser)}clearBindingParsers(){this.environment.clearBindingParsers()}registerToken(token){return this.environment.registerToken(token)}prependBindingExpander(expander){return this.environment.prependBindingExpander(expander)}appendBindingExpander(expander){return this.environment.appendBindingExpander(expander)}clearBindingExpanders(){this.environment.clearBindingExpanders()}registerBindingFields(fields){return this.environment.registerBindingFields(fields)}registerCommandFields(fields){return this.environment.registerCommandFields(fields)}prependCommandResolver(resolver){return this.catalog.prependCommandResolver(resolver)}appendCommandResolver(resolver){return this.catalog.appendCommandResolver(resolver)}clearCommandResolvers(){this.catalog.clearCommandResolvers()}prependLayerAnalyzer(analyzer){return this.layers.prependLayerAnalyzer(analyzer)}appendLayerAnalyzer(analyzer){return this.layers.appendLayerAnalyzer(analyzer)}clearLayerAnalyzers(){this.layers.clearLayerAnalyzers()}prependEventMatchResolver(resolver){return this.dispatch.prependEventMatchResolver(resolver)}appendEventMatchResolver(resolver){return this.dispatch.appendEventMatchResolver(resolver)}clearEventMatchResolvers(){this.dispatch.clearEventMatchResolvers()}prependDisambiguationResolver(resolver){return this.dispatch.prependDisambiguationResolver(resolver)}appendDisambiguationResolver(resolver){return this.dispatch.appendDisambiguationResolver(resolver)}clearDisambiguationResolvers(){this.dispatch.clearDisambiguationResolvers()}handleFocusedTargetChange(_focused){this.notify.runWithStateChangeBatch(()=>{this.activation.setPendingSequence(null),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(_focused),this.notify.queueStateChange()})}warnUnknownField(kind,fieldName){this.notify.warnOnce(`${kind}:${fieldName}`,`unknown-${kind}-field`,{field:fieldName,kind},`[Keymap] Unknown ${kind} field "${fieldName}" was ignored`)}warnUnknownToken(token,sequence){this.notify.warnOnce(`token:${token}`,"unknown-token",{token,sequence},`[Keymap] Unknown token "${token}" in key sequence "${sequence}" was ignored`)}releaseResource(key,resource){if(this.resources.get(key)!==resource)return;if(resource.count-=1,resource.count>0)return;resource.dispose(),this.resources.delete(key)}}function registerEscapeClearsPendingSequence(keymap,options){let shouldPreventDefault=options?.preventDefault??!0;return keymap.intercept("key",({event,consume})=>{if(event.name!=="escape")return;if(!keymap.hasPendingSequence())return;if(keymap.clearPendingSequence(),shouldPreventDefault)consume()},{priority:options?.priority??0})}function registerLeader(keymap,options){return keymap.registerToken({name:options.name??"<leader>",key:options.trigger})}var RESERVED_COMMAND_FIELDS,RESERVED_BINDING_FIELDS,RESERVED_LAYER_FIELDS,DEFAULT_COMMAND_SEARCH_FIELDS,SNAPSHOT_COMMAND_METADATA_OPTIONS,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS,EMPTY_COMMAND_FIELDS,EMPTY_COMPILE_FIELDS,EMPTY_REQUIRES,EMPTY_MATCHERS,EMPTY_CONDITION_KEYS,KEY_DISAMBIGUATION_DECISION,KEY_DEFERRED_DISAMBIGUATION_DECISION,NOOP=()=>{},NOOP2=()=>{},MAX_STATE_CHANGE_FLUSH_ITERATIONS=1000,OrderedRegistry,PriorityRegistry,EMPTY_DATA,EMPTY_FIELDS;var init_addons=__esm(()=>{RESERVED_COMMAND_FIELDS=new Set(["name","run"]),RESERVED_BINDING_FIELDS=new Set(["key","cmd","event","preventDefault","fallthrough"]),RESERVED_LAYER_FIELDS=new Set(["target","targetMode","priority","bindings","commands"]);DEFAULT_COMMAND_SEARCH_FIELDS=["name"],SNAPSHOT_COMMAND_METADATA_OPTIONS=Object.freeze({deep:!0,preserveNonPlainObjects:!0}),SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS=Object.freeze({deep:!0,freeze:!0,preserveNonPlainObjects:!0}),EMPTY_COMMAND_FIELDS=Object.freeze({});EMPTY_COMPILE_FIELDS=Object.freeze({}),EMPTY_REQUIRES=[],EMPTY_MATCHERS=[],EMPTY_CONDITION_KEYS=[];KEY_DISAMBIGUATION_DECISION=Symbol("keymap-disambiguation-decision"),KEY_DEFERRED_DISAMBIGUATION_DECISION=Symbol("keymap-deferred-disambiguation-decision");OrderedRegistry=class OrderedRegistry extends CopyOnWriteRegistry{append(value){return this.setItems([...this.getItems(),value]),()=>{this.remove(value)}}prepend(value){return this.setItems([value,...this.getItems()]),()=>{this.remove(value)}}remove(value){return this.removeItem(value)}values(){return this.getItems()}};PriorityRegistry=class PriorityRegistry extends CopyOnWriteRegistry{order=0;register(listener,options){let registered={...options,listener,order:this.order++};return this.setItems([...this.getItems(),registered].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return left.order-right.order})),()=>{this.removeItem(registered)}}entries(){return this.getItems()}};EMPTY_DATA=Object.freeze({});EMPTY_FIELDS=Object.freeze({})});function getFocusedTargetIfAvailable2(host){if(host.isDestroyed)return null;return host.getFocusedTarget()}function forEachActivationTarget2(host,focused,visit){let current=focused??host.rootTarget,isFocusedTarget=focused!==null;while(current){if(visit(current,isFocusedTarget)===!1)return;current=host.getParentTarget(current),isFocusedTarget=!1}}function getActivationPath2(host,focused){let path6=new Set;return forEachActivationTarget2(host,focused,(current)=>{path6.add(current)}),path6}function getActiveLayersForFocused2(state,host,focused){if(state.activeLayersCacheVersion===state.activeLayersVersion&&state.activeLayersCacheFocused===focused)return state.activeLayersCache;let activeLayers=[],activationPath=getActivationPath2(host,focused);for(let layer of state.sortedLayers)if(isLayerActiveForFocused2(host,layer,focused,activationPath))activeLayers.push(layer);return state.activeLayersCacheVersion=state.activeLayersVersion,state.activeLayersCacheFocused=focused,state.activeLayersCache=activeLayers,activeLayers}function invalidateCachedActiveLayers2(state){state.activeLayersCacheVersion=-1,state.activeLayersCacheFocused=void 0,state.activeLayersCache=[]}function isLayerActiveForFocused2(host,layer,focused,activationPath=getActivationPath2(host,focused)){let target=layer.target;if(!target)return!0;if(host.isTargetDestroyed(target))return!1;if(layer.targetMode==="focus")return target===focused;return activationPath.has(target)}function normalizeBindingTokenName2(token){let normalized=token.trim().toLowerCase();if(!normalized)throw Error("Invalid keymap token: token cannot be empty");return normalized}function normalizeKeyName2(name){let normalized=name.trim().toLowerCase();if(!normalized)throw Error("Invalid key name: key name cannot be empty");return normalized}function normalizeKeyStroke2(input){return{name:normalizeKeyName2(input.name),ctrl:input.ctrl??!1,shift:input.shift??!1,meta:input.meta??!1,super:input.super??!1,hyper:input.hyper||void 0}}function cloneKeyStroke2(stroke){return{name:stroke.name,ctrl:stroke.ctrl,shift:stroke.shift,meta:stroke.meta,super:stroke.super,hyper:stroke.hyper||void 0}}function createKeySequencePart2(input,options){let stroke=cloneKeyStroke2(normalizeKeyStroke2(input));return{stroke,display:options?.display??stringifyCanonicalStroke2(stroke),match:options?.match??createKeyMatch2(stroke),tokenName:options?.tokenName?normalizeBindingTokenName2(options.tokenName):void 0}}function cloneKeySequencePart2(part){return{stroke:cloneKeyStroke2(part.stroke),display:part.display,match:part.match,tokenName:part.tokenName}}function cloneKeySequence2(parts){return parts.map((part)=>cloneKeySequencePart2(part))}function resolveKeyMatch2(input){if("match"in input)return input.match;if("stroke"in input)return createKeyMatch2(input.stroke);return createKeyMatch2(input)}function createKeyMatch2(input){return`key:${buildKeyMatchId2(normalizeKeyStroke2(input))}`}function createTextKeyMatch2(id){let normalized=id.trim();if(!normalized)throw Error("Invalid keymap match id: id cannot be empty");return`text:${normalized}`}function stringifyKeyStroke2(input,options){if("stroke"in input){if(options?.preferDisplay&&input.display)return input.display;return stringifyCanonicalStroke2(input.stroke)}return stringifyCanonicalStroke2(normalizeKeyStroke2(input))}function stringifyKeySequence2(input,options){return input.map((part)=>stringifyKeyStroke2(part,options)).join("")}function stringifyCanonicalStroke2(stroke){let parts=[];if(stroke.ctrl)parts.push("ctrl");if(stroke.shift)parts.push("shift");if(stroke.meta)parts.push("meta");if(stroke.super)parts.push("super");if(stroke.hyper)parts.push("hyper");return parts.push(stroke.name==="return"?"enter":stroke.name),parts.join("+")}function buildKeyMatchId2(stroke){return`${stroke.name}:${stroke.ctrl?1:0}:${stroke.shift?1:0}:${stroke.meta?1:0}:${stroke.super?1:0}:${stroke.hyper?1:0}`}function getLiveHost2(host){if(host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");return host}function isSamePendingSequence2(current,next){if(current===next)return!0;if(!current||!next)return!1;if(current.captures.length!==next.captures.length)return!1;for(let index=0;index<current.captures.length;index+=1){let left=current.captures[index],right=next.captures[index];if(!left||!right||left.layer!==right.layer||left.node!==right.node)return!1}return!0}class ActivationService2{state;host;hooks;notify;conditions;catalog;options;constructor(state,host,hooks,notify,conditions,catalog,options={}){this.state=state,this.host=host,this.hooks=hooks,this.notify=notify,this.conditions=conditions,this.catalog=catalog,this.options=options}getFocusedTarget(){return getLiveHost2(this.host).getFocusedTarget()}getFocusedTargetIfAvailable(){return getFocusedTargetIfAvailable2(this.host)}setPendingSequence(next){let previous=this.state.projection.pendingSequence;if(isSamePendingSequence2(previous,next))return;this.state.projection.pendingSequence=next,this.options.onPendingSequenceChanged?.(previous,next),this.invalidateCaches(),this.notifyPendingSequenceChange(),this.notify.queueStateChange()}ensureValidPendingSequence(){let pending=this.state.projection.pendingSequence;if(!pending)return;let focused=this.getFocusedTarget(),captures=pending.captures.filter((capture2)=>{return this.state.layers.layers.has(capture2.layer)&&this.isLayerActiveForFocused(capture2.layer,focused)&&this.conditions.layerMatchesRuntimeState(capture2.layer)&&this.nodeHasReachableBindings(capture2.node,focused)});if(captures.length===0){this.setPendingSequence(null);return}if(captures.length!==pending.captures.length)this.setPendingSequence({captures});return this.state.projection.pendingSequence??void 0}revalidatePendingSequenceIfNeeded(){if(this.host.isDestroyed||!this.state.projection.pendingSequence)return;this.ensureValidPendingSequence()}hasPendingSequenceState(){return!this.host.isDestroyed&&this.state.projection.pendingSequence!==null}getPendingSequence(){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion;if(projections.pendingSequenceCacheVersion===derivedStateVersion)return projections.pendingSequenceCache;let pending=this.ensureValidPendingSequence(),canUseCache=!pending||pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)),sequence=pending?this.collectSequencePartsFromPending(pending):[];if(canUseCache)projections.pendingSequenceCacheVersion=derivedStateVersion,projections.pendingSequenceCache=sequence;return sequence}popPendingSequence(){let pending=this.ensureValidPendingSequence();if(!pending)return!1;let firstCapture=pending.captures[0];if(!firstCapture||firstCapture.node.depth<=1)return this.setPendingSequence(null),!0;let nextCaptures=[];for(let capture2 of pending.captures){let parent=capture2.node.parent;if(!parent||!parent.stroke)continue;nextCaptures.push({layer:capture2.layer,node:parent})}if(nextCaptures.length===0)return this.setPendingSequence(null),!0;return this.setPendingSequence({captures:nextCaptures}),!0}getActiveKeys(options){let projections=this.state.projection,derivedStateVersion=this.state.notify.derivedStateVersion,includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0;if(includeBindings){if(includeMetadata){if(projections.activeKeysBindingsAndMetadataCacheVersion===derivedStateVersion)return projections.activeKeysBindingsAndMetadataCache}else if(projections.activeKeysBindingsCacheVersion===derivedStateVersion)return projections.activeKeysBindingsCache}else if(includeMetadata){if(projections.activeKeysMetadataCacheVersion===derivedStateVersion)return projections.activeKeysMetadataCache}else if(projections.activeKeysPlainCacheVersion===derivedStateVersion)return projections.activeKeysPlainCache;let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),pending=this.ensureValidPendingSequence(),activeLayers=pending?[]:this.getActiveLayers(focused),canUseCache=pending?pending.captures.every((capture2)=>this.layerCanCacheActiveKeys(capture2.layer)):this.activeLayersCanCacheActiveKeys(activeLayers),activeKeys=pending?this.collectActiveKeysFromPending(pending.captures,includeBindings,includeMetadata,focused,activeView):this.collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView);if(!canUseCache)return activeKeys;if(includeBindings)if(includeMetadata)projections.activeKeysBindingsAndMetadataCacheVersion=derivedStateVersion,projections.activeKeysBindingsAndMetadataCache=activeKeys;else projections.activeKeysBindingsCacheVersion=derivedStateVersion,projections.activeKeysBindingsCache=activeKeys;else if(includeMetadata)projections.activeKeysMetadataCacheVersion=derivedStateVersion,projections.activeKeysMetadataCache=activeKeys;else projections.activeKeysPlainCacheVersion=derivedStateVersion,projections.activeKeysPlainCache=activeKeys;return activeKeys}getActiveKeysForCaptures(captures,options){let includeBindings=options?.includeBindings===!0,includeMetadata=options?.includeMetadata===!0,focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused);return this.collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView)}nodeHasReachableBindings(node,focused){return this.hasMatchingBindings(node.reachableBindings,focused,this.catalog.getActiveCommandView(focused))}getActiveLayers(focused){return getActiveLayersForFocused2(this.state.layers,this.host,focused)}refreshActiveLayers(focused=this.getFocusedTargetIfAvailable()){getActiveLayersForFocused2(this.state.layers,this.host,focused)}invalidateActiveLayers(){invalidateCachedActiveLayers2(this.state.layers)}isLayerActiveForFocused(layer,focused){return isLayerActiveForFocused2(this.host,layer,focused)}layerCanCacheActiveKeys(layer){return!layer.hasUnkeyedMatchers&&!layer.hasUnkeyedCommands&&!layer.hasUnkeyedBindings}activeLayersCanCacheActiveKeys(activeLayers){for(let layer of activeLayers)if(!this.layerCanCacheActiveKeys(layer))return!1;return!0}collectNodesFromNode(node){let nodes=[],current=node;while(current&¤t.stroke)nodes.push(current),current=current.parent;return nodes.reverse(),nodes}collectSequencePartsFromPending(pending){let focused=this.getFocusedTarget(),activeView=this.catalog.getActiveCommandView(focused),paths=pending.captures.map((capture2)=>this.collectNodesFromNode(capture2.node)),firstPath=paths[0];if(!firstPath||firstPath.length===0)return[];let parts=[];for(let index=0;index<firstPath.length;index+=1){let firstNode=firstPath[index];if(!firstNode?.stroke||firstNode.match===null)continue;let display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let path6 of paths){let node=path6[index];if(!node)continue;let presentation=this.getNodePresentation(node,focused,activeView);if(display===void 0){display=presentation.display,tokenName=presentation.tokenName;continue}if(!hasDisplayConflict&&display!==presentation.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==presentation.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke2(firstNode.stroke);if(hasTokenConflict)tokenName=void 0;parts.push(createKeySequencePart2(firstNode.stroke,{display,match:firstNode.match,tokenName}))}return parts}collectMatchingBindings(bindings,focused,activeView){let matches=[];for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))matches.push(binding);return matches}hasMatchingBindings(bindings,focused,activeView){for(let binding of bindings)if(this.conditions.matchesConditions(binding)&&this.catalog.isBindingVisible(binding,focused,activeView))return!0;return!1}getNodePresentation(node,focused,activeView,reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView)){if(!node.stroke)return{display:""};let partIndex=node.depth-1,display,tokenName,hasDisplayConflict=!1,hasTokenConflict=!1;for(let binding of reachableBindings){let part=binding.sequence[partIndex];if(!part)continue;if(display===void 0){display=part.display,tokenName=part.tokenName;continue}if(!hasDisplayConflict&&display!==part.display)hasDisplayConflict=!0;if(!hasTokenConflict&&tokenName!==part.tokenName)hasTokenConflict=!0}if(display===void 0||hasDisplayConflict)display=stringifyKeyStroke2(node.stroke);if(hasTokenConflict)tokenName=void 0;return{display,tokenName}}toActiveBinding(binding,focused,activeView){return{sequence:binding.sequence,command:binding.command,commandAttrs:this.catalog.getBindingCommandAttrs(binding,focused,activeView),attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough}}collectActiveBindings(bindings,focused,activeView){return bindings.map((binding)=>this.toActiveBinding(binding,focused,activeView))}collectActiveKeysAtRoot(activeLayers,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set,hasLayerConditions=this.state.layers.layersWithConditions>0;for(let layer of activeLayers){if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let[bindingKey,child]of layer.root.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}collectActiveKeysFromPending(captures,includeBindings,includeMetadata,focused,activeView){let activeKeys=new Map,stopped=new Set;for(let capture2 of captures)for(let[bindingKey,child]of capture2.node.children){if(stopped.has(bindingKey))continue;let selection=this.selectActiveKey(child,includeBindings,focused,activeView);if(!selection)continue;let existing=activeKeys.get(bindingKey);if(!existing)activeKeys.set(bindingKey,this.createActiveKeyState(child.stroke,selection,includeBindings));else this.updateActiveKeyState(existing,selection,includeBindings);if(selection.stop)stopped.add(bindingKey)}let materialized=[];for(let state of activeKeys.values()){let activeKey=this.materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView);if(activeKey)materialized.push(activeKey)}return materialized}selectActiveKey(node,includeBindings,focused,activeView){return node.children.size>0?this.selectPrefixActiveKey(node,includeBindings,focused,activeView):this.selectExactActiveKey(node,includeBindings,focused,activeView)}selectPrefixActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let reachableBindings=this.collectMatchingBindings(node.reachableBindings,focused,activeView);if(reachableBindings.length===0)return;let prefixBindings=this.selectActiveBindings(node.bindings,focused,activeView);return{...this.getNodePresentation(node,focused,activeView,reachableBindings),continues:!0,firstBinding:prefixBindings?.bindings[0],commandBinding:prefixBindings?.commandBinding,bindings:includeBindings&&prefixBindings&&prefixBindings.bindings.length>0?[...prefixBindings.bindings]:void 0,stop:!0}}selectExactActiveKey(node,includeBindings,focused,activeView){if(!node.stroke)return;let selected=this.selectActiveBindings(node.bindings,focused,activeView);if(!selected)return;let display,tokenName;if(selected.bindings.length===1){let part=selected.bindings[0]?.sequence[node.depth-1];display=part?.display??stringifyKeyStroke2(node.stroke),tokenName=part?.tokenName}else{let presentation=this.getNodePresentation(node,focused,activeView,selected.bindings);display=presentation.display,tokenName=presentation.tokenName}return{display,tokenName,continues:!1,firstBinding:selected.bindings[0],commandBinding:selected.commandBinding,bindings:includeBindings?[...selected.bindings]:void 0,stop:selected.stop}}selectActiveBindings(bindings,focused,activeView){let selected=[],commandBinding;for(let binding of bindings){if(!this.conditions.matchesConditions(binding)||!this.catalog.isBindingVisible(binding,focused,activeView))continue;if(selected.push(binding),binding.command===void 0)continue;if(commandBinding??=binding,!binding.fallthrough)return{bindings:selected,commandBinding,stop:!0}}if(selected.length===0)return;return{bindings:selected,commandBinding,stop:!1}}createActiveKeyState(stroke,selection,includeBindings){return{stroke,display:selection.display,tokenName:selection.tokenName,continues:selection.continues,firstBinding:selection.firstBinding,commandBinding:selection.commandBinding,bindings:includeBindings&&selection.bindings?[...selection.bindings]:void 0}}updateActiveKeyState(state,selection,includeBindings){if(!state.firstBinding&&selection.firstBinding)state.firstBinding=selection.firstBinding;if(!state.commandBinding&&selection.commandBinding)state.commandBinding=selection.commandBinding;if(selection.continues)state.continues=!0;if(!includeBindings||!selection.bindings||selection.bindings.length===0)return;if(!state.bindings){state.bindings=[...selection.bindings];return}state.bindings.push(...selection.bindings)}materializeActiveKey(state,includeBindings,includeMetadata,focused,activeView){if(!state.commandBinding&&!state.continues)return;let activeKey={stroke:cloneKeyStroke2(state.stroke),display:state.display,continues:state.continues};if(state.tokenName)activeKey.tokenName=state.tokenName;if(state.commandBinding)activeKey.command=state.commandBinding.command;if(includeBindings&&state.bindings&&state.bindings.length>0)activeKey.bindings=state.bindings.length===1?[this.toActiveBinding(state.bindings[0],focused,activeView)]:this.collectActiveBindings(state.bindings,focused,activeView);if(includeMetadata){if(state.firstBinding?.attrs)activeKey.bindingAttrs=state.firstBinding.attrs;let commandAttrs=state.commandBinding?this.catalog.getBindingCommandAttrs(state.commandBinding,focused,activeView):void 0;if(commandAttrs)activeKey.commandAttrs=commandAttrs}return activeKey}invalidateCaches(){this.state.projection.pendingSequenceCacheVersion=-1,this.state.projection.activeKeysPlainCacheVersion=-1,this.state.projection.activeKeysBindingsCacheVersion=-1,this.state.projection.activeKeysMetadataCacheVersion=-1,this.state.projection.activeKeysBindingsAndMetadataCacheVersion=-1}notifyPendingSequenceChange(){if(!this.hooks.has("pendingSequence"))return;this.hooks.emit("pendingSequence",this.state.projection.pendingSequence?this.collectSequencePartsFromPending(this.state.projection.pendingSequence):[])}}function mergeRequirement2(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap requirement for "${name}" from ${source}`);target[name]=value}function mergeAttribute2(target,name,value,source){if(Object.prototype.hasOwnProperty.call(target,name)&&!Object.is(target[name],value))throw Error(`Conflicting keymap attribute for "${name}" from ${source}`);target[name]=value}function isPlainObject3(value){let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function getErrorMessage2(error2,fallback){if(error2 instanceof Error&&error2.message)return error2.message;return fallback}function isPromiseLike2(value){if(!value)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return typeof value.then==="function"}function snapshotDataValue2(value,options){let deep=options?.deep===!0,freeze=options?.freeze===!0,preserveNonPlainObjects=options?.preserveNonPlainObjects===!0;if(Array.isArray(value)){let cloned=deep?value.map((entry2)=>snapshotDataValue2(entry2,options)):[...value];return freeze?Object.freeze(cloned):cloned}if(value&&typeof value==="object"){if(preserveNonPlainObjects&&!isPlainObject3(value))return value;let cloned={};for(let[key,entry2]of Object.entries(value))cloned[key]=deep?snapshotDataValue2(entry2,options):entry2;return freeze?Object.freeze(cloned):cloned}return value}function createCommandChainCacheState2(){return{resolvedWithoutRecordChains:new Map,resolvedWithRecordChains:new Map,fallbackWithoutRecord:new Map,fallbackWithRecord:new Map,fallbackWithoutRecordErrors:new Set,fallbackWithRecordErrors:new Set}}function normalizeBindingCommand2(command){if(command===void 0||typeof command==="function")return command;let trimmed=command.trim();if(!trimmed)throw Error("Invalid keymap command: command cannot be empty");return trimmed}function normalizeCommandName2(name){let trimmed=name.trim();if(!trimmed)throw Error("Invalid keymap command name: name cannot be empty");if(/\s/.test(trimmed))throw Error(`Invalid keymap command name "${name}": command names cannot contain whitespace`);return trimmed}class CommandCatalogService2{state;host;notify;conditions;options;constructor(state,host,notify,conditions,options){this.state=state,this.host=host,this.notify=notify,this.conditions=conditions,this.options=options}normalizeCommands(commands){return normalizeRegisteredCommands2({commands,commandFields:this.state.environment.commandFields,conditions:this.conditions,onError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}prependCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.prepend(resolver),resolver)}appendCommandResolver(resolver){return this.mutateCommandResolvers(()=>this.state.commands.commandResolvers.append(resolver),resolver)}clearCommandResolvers(){if(!this.state.commands.commandResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.commands.commandResolvers.clear(),this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}getCommands(query2){return this.getFilteredCommandEntries(query2).map((entry2)=>getRegisteredCommandRecord2(entry2.command))}getCommandEntries(query2){let context=this.getCommandQueryContext(query2),filteredEntries=this.getFilteredCommandEntries(query2,context);if(filteredEntries.length===0)return[];let grouped=filteredEntries.map((entry2)=>({entry:entry2,command:getRegisteredCommandRecord2(entry2.command),bindings:[]})),indexesByName=new Map;for(let[index,item]of grouped.entries()){let existing=indexesByName.get(item.command.name);if(existing)existing.push(index);else indexesByName.set(item.command.name,[index])}if(indexesByName.size>0)this.collectCommandEntryBindings(grouped,indexesByName,context);return grouped.map((item)=>({command:item.command,bindings:item.bindings}))}getResolvedCommandChain(command,focused,includeRecord){let view=this.getActiveCommandView(focused),entries=this.getResolvedCommandChainFromView(view,command,focused,includeRecord,"active",view.chainsByName.get(command)),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{entries,hadError}}getRegisteredResolvedEntries(command,includeRecord){let view=this.getRegisteredCommandView(),cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let chain=view.chainsByName.get(command);if(!chain||chain.length===0){cache.set(command,[]);return}let resolved=[];for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand2(entry2.command,{includeRecord})});return cache.set(command,resolved),resolved}getRegisteredResolverFallback(command,includeRecord){let view=this.getRegisteredCommandView(),fallback=this.getFallbackResolvedCommand(view,command,null,includeRecord,"registered"),hadError=(includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors).has(command);return{resolved:fallback?.resolved,hadError}}getCommandAttrs(command,focused){return this.getTopResolvedCommand(command,focused,!1)?.resolved.attrs}getTopCommandRecord(command,focused){return this.getTopResolvedCommand(command,focused,!0)?.resolved.record}getTopRegisteredCommandRecord(command){let top=this.getTopRegisteredCommand(command);return top?getRegisteredCommandRecord2(top.command):void 0}getDispatchUnavailableCommandState(command,focused,includeRecord){let chain=this.getRegisteredCommandView().chainsByName.get(command);if(!chain||chain.length===0)return;let inactiveEntry,disabledEntry;for(let entry2 of chain){if(!isLayerActiveForFocused2(this.host,entry2.layer,focused)){inactiveEntry??=entry2;continue}if(!this.conditions.layerMatchesRuntimeState(entry2.layer)||!this.conditions.matchesConditions(entry2.command))disabledEntry??=entry2}let unavailableEntry=disabledEntry??inactiveEntry;if(!unavailableEntry)return;return{reason:disabledEntry?"disabled":"inactive",command:includeRecord?getRegisteredCommandRecord2(unavailableEntry.command):void 0}}getActiveCommandView(focused){let currentFocused=getFocusedTargetIfAvailable2(this.host),derivedStateVersion=this.state.notify.derivedStateVersion;if(focused===currentFocused&&this.state.commands.activeCommandViewVersion===derivedStateVersion&&this.state.commands.activeCommandView?.cacheable)return this.state.commands.activeCommandView;let entries=[],reachable=[],reachableByName=new Map,chainsByName=new Map,cacheable=!0;if(this.state.layers.layersWithCommands>0)for(let layer of getActiveLayersForFocused2(this.state.layers,this.host,focused)){if(layer.commands.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;if(layer.hasUnkeyedMatchers)cacheable=!1;for(let command of layer.commands){if(command.hasUnkeyedMatchers)cacheable=!1;if(!this.conditions.matchesConditions(command))continue;let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2]);if(!reachableByName.has(command.name))reachableByName.set(command.name,entry2),reachable.push(entry2)}}let view={cacheable,entries,reachable,reachableByName,chainsByName,...createCommandChainCacheState2()};if(focused===currentFocused&&view.cacheable)this.state.commands.activeCommandViewVersion=derivedStateVersion,this.state.commands.activeCommandView=view;return view}getRegisteredCommandView(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandViewVersion===cacheVersion&&this.state.commands.registeredCommandView)return this.state.commands.registeredCommandView;let entries=[],chainsByName=new Map;for(let layer of this.state.layers.sortedLayers){if(layer.commands.length===0)continue;for(let command of layer.commands){let entry2={layer,command};entries.push(entry2);let existing=chainsByName.get(command.name);if(existing)existing.push(entry2);else chainsByName.set(command.name,[entry2])}}let view={entries,chainsByName,...createCommandChainCacheState2()};return this.state.commands.registeredCommandViewVersion=cacheVersion,this.state.commands.registeredCommandView=view,view}isBindingVisible(binding,focused,activeView){if(binding.command===void 0||binding.run)return!0;if(typeof binding.command!=="string")return!1;if(activeView.reachableByName.has(binding.command))return!0;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")!==void 0}getBindingCommandAttrs(binding,focused,activeView){if(typeof binding.command!=="string")return;let active=activeView.reachableByName.get(binding.command);if(active)return active.command.attrs;return this.getFallbackResolvedCommand(activeView,binding.command,focused,!1,"active")?.resolved.attrs}getCommandResolutionStatus(command,layerCommands){if(layerCommands?.has(command)||this.state.commands.registeredNames.has(command))return"resolved";let lookup=this.resolveCommandWithResolvers(command,getFocusedTargetIfAvailable2(this.host));if(lookup.resolved||lookup.hadError)return lookup.resolved?"resolved":"error";return"unresolved"}mutateCommandResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let off=register2();return this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange(),()=>{this.notify.runWithStateChangeBatch(()=>{if(off(),this.state.commands.commandResolvers.values().includes(resolver))return;this.state.commands.commandMetadataVersion+=1,this.options.onCommandResolversChanged(),this.notify.queueStateChange()})}})}getTopResolvedCommand(command,focused,includeRecord){let activeView=this.getActiveCommandView(focused),active=activeView.reachableByName.get(command);if(active)return{target:active.layer.target,resolved:resolveRegisteredCommand2(active.command,{includeRecord})};return this.getFallbackResolvedCommand(activeView,command,focused,includeRecord,"active")}getTopRegisteredCommand(command){return this.getRegisteredCommandView().chainsByName.get(command)?.[0]}getFallbackResolvedCommand(view,command,focused,includeRecord,mode){let cache=includeRecord?view.fallbackWithRecord:view.fallbackWithoutRecord,errorCache=includeRecord?view.fallbackWithRecordErrors:view.fallbackWithoutRecordErrors;if(cache.has(command)){let cached=cache.get(command);return cached?{resolved:cached}:void 0}let lookup=this.resolveCommandWithResolvers(command,focused,{includeRecord,mode});if(cache.set(command,lookup.resolved??null),lookup.hadError)errorCache.add(command);if(!lookup.resolved)return;return{resolved:lookup.resolved}}getResolvedCommandChainFromView(view,command,focused,includeRecord,mode,activeChain){let cache=includeRecord?view.resolvedWithRecordChains:view.resolvedWithoutRecordChains,cached=cache.get(command);if(cached)return cached.length>0?cached:void 0;let resolved=[],chain=activeChain;if(chain)for(let entry2 of chain)resolved.push({target:entry2.layer.target,resolved:resolveRegisteredCommand2(entry2.command,{includeRecord})});let fallback=this.getFallbackResolvedCommand(view,command,focused,includeRecord,mode);if(fallback)resolved.push(fallback);return cache.set(command,resolved),resolved.length>0?resolved:void 0}getRegisteredLayerCommandEntries(){let cacheVersion=this.state.commands.commandMetadataVersion;if(this.state.commands.registeredCommandEntriesCacheVersion===cacheVersion)return this.state.commands.registeredCommandEntriesCache;let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);let entries=[];for(let layer of layers)for(let command of layer.commands)entries.push({layer,command});return this.state.commands.registeredCommandEntriesCacheVersion=cacheVersion,this.state.commands.registeredCommandEntriesCache=entries,entries}getCommandQueryContext(query2){let visibility=query2?.visibility??"reachable",focused=query2&&Object.prototype.hasOwnProperty.call(query2,"focused")?query2.focused??null:getFocusedTargetIfAvailable2(this.host);if(visibility==="registered")return{visibility,focused};return{visibility,focused,activeView:this.getActiveCommandView(focused)}}getFilteredCommandEntries(query2,context=this.getCommandQueryContext(query2)){let entries;if(context.visibility==="registered")entries=this.getRegisteredLayerCommandEntries();else if(context.visibility==="active")entries=context.activeView?.entries??[];else entries=context.activeView?.reachable??[];return queryLayerCommandEntries2({entries,query:query2,getCommandRecord:(command)=>getRegisteredCommandRecord2(command),onFilterError:(error2)=>{this.notify.emitError("command-query-filter-error",error2,"[Keymap] Error in command query filter:")}})}collectCommandEntryBindings(grouped,indexesByName,context){if(context.visibility==="registered"){let layers=[...this.state.layers.layers];layers.sort((left,right)=>left.order-right.order);for(let layer of layers)for(let binding of layer.compiledBindings)this.collectBindingForCommandEntries(grouped,indexesByName,binding);return}let activeView=context.activeView;if(!activeView)return;for(let layer of getActiveLayersForFocused2(this.state.layers,this.host,context.focused)){if(layer.compiledBindings.length===0||!this.conditions.layerMatchesRuntimeState(layer))continue;for(let binding of layer.compiledBindings){if(!this.conditions.matchesConditions(binding)||!this.isBindingVisible(binding,context.focused,activeView))continue;this.collectBindingForCommandEntries(grouped,indexesByName,binding)}}}collectBindingForCommandEntries(grouped,indexesByName,binding){if(typeof binding.command!=="string")return;let indexes=indexesByName.get(binding.command);if(!indexes||indexes.length===0)return;for(let index of indexes){let item=grouped[index];if(!item)continue;item.bindings.push({sequence:binding.sequence,command:binding.command,commandAttrs:item.command.attrs,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough})}}resolveCommandWithResolvers(command,focused,options){let includeRecord=options?.includeRecord===!0,context=this.createCommandResolverContext(includeRecord,focused,options?.mode??"active");return resolveCommandWithResolvers2(command,this.state.commands.commandResolvers.values(),context,(error2)=>{this.notify.emitError("command-resolver-error",error2,`[Keymap] Error in command resolver for "${command}":`)})}createCommandResolverContext(includeRecord,focused,mode){return{getCommandAttrs:(name)=>{if(mode==="registered")return this.getTopRegisteredCommand(name)?.command.attrs;return this.getCommandAttrs(name,focused)},getCommandRecord:(name)=>{if(!includeRecord)return;if(mode==="registered")return this.getTopRegisteredCommandRecord(name);return this.getTopCommandRecord(name,focused)}}}}function getRegisteredCommandRecord2(command){if(command.record)return command.record;let fields=EMPTY_COMMAND_FIELDS2;if(command.fields!==EMPTY_COMMAND_FIELDS2&&Object.keys(command.fields).length>0)fields=snapshotDataValue2(command.fields,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2);let record=command.attrs?Object.freeze({name:command.name,fields,attrs:snapshotDataValue2(command.attrs,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2)}):Object.freeze({name:command.name,fields});return command.record=record,record}function resolveRegisteredCommand2(command,options){if(options?.includeRecord===!0){let existing2=command.resolvedWithRecord;if(existing2)return existing2;let resolved2={run:createRegisteredCommandRunner2(command)};if(command.attrs)resolved2.attrs=command.attrs;return resolved2.record=getRegisteredCommandRecord2(command),command.resolvedWithRecord=resolved2,resolved2}let existing=command.resolved;if(existing)return existing;let resolved={run:createRegisteredCommandRunner2(command)};if(command.attrs)resolved.attrs=command.attrs;return command.resolved=resolved,resolved}function normalizeRegisteredCommands2(options){let normalizedCommands=[],seen=new Set;for(let command of options.commands){let normalizedCommand;try{let mergedAttrs={},mergedFields={},mergedRequires={},matchers=[],conditionKeys=new Set,hasUnkeyedMatchers=!1,normalizedName=normalizeCommandName2(command.name);if(seen.has(normalizedName)){options.onError("duplicate-command",{command:normalizedName},`Duplicate keymap command "${normalizedName}" in the same layer`);continue}for(let[fieldName,value]of Object.entries(command)){if(RESERVED_COMMAND_FIELDS2.has(fieldName)||value===void 0)continue;mergedFields[fieldName]=snapshotDataValue2(value,SNAPSHOT_COMMAND_METADATA_OPTIONS2);let compiler=options.commandFields.get(fieldName);if(!compiler)continue;compiler(value,createCommandFieldContext2(mergedAttrs,mergedRequires,conditionKeys,matchers,options.conditions,fieldName,{onUnkeyedMatcher(){hasUnkeyedMatchers=!0}}))}let attrs=Object.keys(mergedAttrs).length===0?void 0:Object.freeze(mergedAttrs),fields=Object.keys(mergedFields).length===0?EMPTY_COMMAND_FIELDS2:Object.freeze(mergedFields);if(normalizedCommand={name:normalizedName,fields,run:command.run,requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,matchCacheDirty:!0},attrs)normalizedCommand.attrs=attrs}catch(error2){options.onError("register-command-failed",error2,getErrorMessage2(error2,`Failed to register keymap command "${String(command.name)}"`));continue}seen.add(normalizedCommand.name),normalizedCommands.push(normalizedCommand)}return normalizedCommands}function createCommandFieldContext2(mergedAttrs,mergedRequires,conditionKeys,matchers,conditions,fieldName,options){return{require(name,requiredValue){mergeRequirement2(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},attr(name,attributeValue){mergeAttribute2(mergedAttrs,name,snapshotDataValue2(attributeValue,SNAPSHOT_COMMAND_METADATA_OPTIONS2),`field ${fieldName}`)},activeWhen(matcher){let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)options.onUnkeyedMatcher();matchers.push(runtimeMatcher)}}}function createRegisteredCommandRunner2(command){if(command.runner)return command.runner;let runner=(ctx)=>{return command.run({...ctx,command:getRegisteredCommandRecord2(command)})};return command.runner=runner,runner}function resolveCommandWithResolvers2(command,resolvers,context,onResolverError){if(resolvers.length===0)return{hadError:!1};let hadError=!1;for(let resolver of resolvers){let resolved;try{resolved=resolver(command,context)}catch(error2){hadError=!0,onResolverError(error2);continue}if(resolved)return{hadError,resolved}}return{hadError}}function queryLayerCommandEntries2(options){let namespace=options.query?.namespace,normalizedSearch=options.query?.search?.trim().toLowerCase()??"",searchKeys=DEFAULT_COMMAND_SEARCH_FIELDS2;if(options.query?.searchIn&&options.query.searchIn.length>0)searchKeys=options.query.searchIn;let filter=options.query?.filter,filterEntries2,filterPredicate;if(typeof filter==="function")filterPredicate=filter;else if(filter)filterEntries2=Object.entries(filter);let results=[];for(let entry2 of options.entries){let command=entry2.command;if(!commandMatchesNamespace2(command,namespace))continue;if(!commandMatchesSearch2(command,normalizedSearch,searchKeys))continue;if(!commandMatchesFilters2(command,filterEntries2,options))continue;let record=options.getCommandRecord(command);if(filterPredicate){let matches=!1;try{matches=filterPredicate(record)}catch(error2){options.onFilterError(error2);continue}if(!matches)continue}results.push(entry2)}return results}function commandMatchesSearch2(command,search,searchKeys){if(!search)return!0;for(let key of searchKeys)if(commandKeyMatchesSearch2(command,key,search))return!0;return!1}function commandMatchesNamespace2(command,namespace){if(namespace===void 0)return!0;if(!Object.prototype.hasOwnProperty.call(command.fields,"namespace"))return!1;return commandValueMatchesFilter2(command.fields.namespace,namespace)}function commandMatchesFilters2(command,filters,options){if(!filters)return!0;for(let[key,matcher]of filters)if(!commandKeyMatchesQuery2(command,key,matcher,options))return!1;return!0}function commandKeyMatchesSearch2(command,key,search){if(key==="name"&&commandValueMatchesSearch2(command.name,search))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesSearch2(command.fields[key],search))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesSearch2(command.attrs[key],search);return!1}function commandKeyMatchesQuery2(command,key,matcher,options){if(typeof matcher==="function"){let record,getRecord=()=>{if(!record)record=options.getCommandRecord(command);return record},foundValue=!1;if(key==="name"){foundValue=!0;try{if(matcher(command.name,getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(Object.prototype.hasOwnProperty.call(command.fields,key)){foundValue=!0;try{if(matcher(command.fields[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key)){foundValue=!0;try{if(matcher(command.attrs[key],getRecord()))return!0}catch(error2){return options.onFilterError(error2),!1}}if(!foundValue)try{return matcher(void 0,getRecord())}catch(error2){return options.onFilterError(error2),!1}return!1}return commandKeyMatchesExact2(command,key,matcher)}function commandKeyMatchesExact2(command,key,matcher){if(key==="name"&&commandValueMatchesFilter2(command.name,matcher))return!0;if(Object.prototype.hasOwnProperty.call(command.fields,key)&&commandValueMatchesFilter2(command.fields[key],matcher))return!0;if(command.attrs&&Object.prototype.hasOwnProperty.call(command.attrs,key))return commandValueMatchesFilter2(command.attrs[key],matcher);return!1}function commandValueMatchesFilter2(value,matcher){if(Array.isArray(matcher)){for(let expected of matcher)if(commandValueMatchesExact2(value,expected))return!0;return!1}return commandValueMatchesExact2(value,matcher)}function commandValueMatchesExact2(value,expected){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesExact2(entry2,expected))return!0;return!1}return Object.is(value,expected)}function commandValueMatchesSearch2(value,search){if(Array.isArray(value)){for(let entry2 of value)if(commandValueMatchesSearch2(entry2,search))return!0;return!1}if(typeof value==="string")return value.toLowerCase().includes(search);if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return String(value).toLowerCase().includes(search);return!1}class CommandExecutorService2{notify;runtime;activation;catalog;options;constructor(notify,runtime,activation,catalog,options){this.notify=notify,this.runtime=runtime,this.activation=activation,this.catalog=catalog,this.options=options}runCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand2(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chain=this.catalog.getRegisteredResolvedEntries(normalized,includeRecord),rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}let fallback=this.catalog.getRegisteredResolverFallback(normalized,includeRecord);if(fallback.resolved){let execution=this.executeResolvedCommand(normalized,fallback.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(fallback.hadError)return{ok:!1,reason:"error"};return rejectedResult??{ok:!1,reason:"not-found"}}dispatchCommand(cmd,options){let normalized;try{normalized=normalizeBindingCommand2(cmd)}catch{return{ok:!1,reason:"invalid-args"}}if(typeof normalized!=="string")return{ok:!1,reason:"not-found"};let includeRecord=options?.includeCommand===!0,focused=options?.focused??this.activation.getFocusedTargetIfAvailable(),event=options?.event??this.options.createCommandEvent(),data=this.runtime.getReadonlyData(),chainLookup=this.catalog.getResolvedCommandChain(normalized,focused,includeRecord),chain=chainLookup.entries,rejectedResult;if(chain?.length===1){let[entry2]=chain;if(entry2){let execution=this.executeResolvedCommand(normalized,entry2.resolved,{keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data});if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:options?.target??entry2.target??null,data},execution=this.executeResolvedCommand(normalized,entry2.resolved,context);if(execution.status==="handled"||execution.status==="error")return execution.result;rejectedResult=execution.result}if(chainLookup.hadError)return{ok:!1,reason:"error"};let unavailable=this.catalog.getDispatchUnavailableCommandState(normalized,focused,includeRecord);if(unavailable)return unavailable.command?{ok:!1,reason:unavailable.reason,command:unavailable.command}:{ok:!1,reason:unavailable.reason};return rejectedResult??{ok:!1,reason:"not-found"}}runBinding(bindingLayer,binding,event,focused){let data=this.runtime.getReadonlyData();if(binding.run){if(this.executeResolvedCommand(typeof binding.command==="string"?binding.command:"<function>",{run:binding.run},{keymap:this.options.keymap,event,focused,target:bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects2(binding,event),!0}if(typeof binding.command!=="string")return!1;let chain=this.catalog.getResolvedCommandChain(binding.command,focused,!1).entries;if(chain?.length===1){let[entry2]=chain;if(entry2){if(this.executeResolvedCommand(binding.command,entry2.resolved,{keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data}).status==="rejected")return!1;return applyBindingEventEffects2(binding,event),!0}}else if(chain)for(let entry2 of chain){let context={keymap:this.options.keymap,event,focused,target:entry2.target??bindingLayer.target??null,data};if(this.executeResolvedCommand(binding.command,entry2.resolved,context).status==="rejected")continue;return applyBindingEventEffects2(binding,event),!0}return!1}executeResolvedCommand(commandName,resolved,context){let command=resolved.record,result2;try{result2=resolved.run(context)}catch(error2){return this.notify.emitError("command-execution-error",error2,`[Keymap] Error running command "${commandName}":`),{status:"error",result:{ok:!1,reason:"error",command}}}if(isPromiseLike2(result2))return result2.catch((error2)=>{this.notify.emitError("async-command-error",error2,`[Keymap] Async error in command "${commandName}":`)}),{status:"handled",result:{ok:!0,command}};if(result2===!1){if(resolved.rejectedResult)return{status:"rejected",result:resolved.rejectedResult};return{status:"rejected",result:{ok:!1,reason:"rejected",command}}}return{status:"handled",result:{ok:!0,command}}}}function applyBindingEventEffects2(binding,event){if(!binding.preventDefault)return;event.preventDefault(),event.stopPropagation()}function normalizeBindingInputs2(bindings){if(Array.isArray(bindings))return bindings;let normalized=[];for(let[key,cmd]of Object.entries(bindings)){if(typeof cmd!=="string"&&typeof cmd!=="function")throw Error(`Invalid keymap binding for "${key}": shorthand bindings must map to string or function commands`);normalized.push({key,cmd})}return normalized}function snapshotBindingInputs2(bindings){return normalizeBindingInputs2(bindings).map((binding)=>({...binding,key:typeof binding.key==="string"?binding.key:{...binding.key}}))}function snapshotParsedBindingInput2(binding){return{...binding,sequence:cloneKeySequence2(binding.sequence)}}function createSequenceNode2(parent,stroke,match){return{parent,depth:parent?parent.depth+1:0,stroke,match,children:new Map,bindings:[],reachableBindings:[]}}function snapshotAttributes2(attrs){if(Object.keys(attrs).length===0)return;return snapshotDataValue2(attrs,{freeze:!0})}class CompilerService2{state;notify;conditions;options;constructor(state,notify,conditions,options){this.state=state,this.notify=notify,this.conditions=conditions,this.options=options}parseTokenKey(key){return parseSingleKeyPartWithParsers2(key,this.state.environment.bindingParsers.values(),{tokens:this.state.environment.tokens,layer:EMPTY_COMPILE_FIELDS2,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})}compileBindings(bindings,tokens2,sourceTarget,sourceLayerOrder,compileFields){let root=createSequenceNode2(null,null,null),compiledBindings=[],hasTokenBindings=!1,bindingExpanders=this.state.environment.bindingExpanders.values(),bindingParsers=this.state.environment.bindingParsers.values(),bindingFieldCompilers=this.state.environment.bindingFields,allowExactPrefixAmbiguity=this.state.dispatch.disambiguationResolvers.has(),warnUnknownField=this.options.warnUnknownField,warnUnknownToken=this.options.warnUnknownToken,conditions=this.conditions;for(let[bindingIndex,binding]of bindings.entries()){let expandedBindingKeys;try{expandedBindingKeys=expandBindingInputWithExpanders2(binding.key,bindingExpanders,{layer:compileFields})}catch(error2){this.notify.emitError("binding-expand-error",error2,getErrorMessage2(error2,"Failed to expand keymap binding"));continue}for(let expandedBindingKey of expandedBindingKeys){let parsed;try{parsed=typeof expandedBindingKey==="string"?parseBindingSequenceWithParsers2(expandedBindingKey,bindingParsers,{tokens:tokens2,layer:compileFields,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)}):{parts:[this.parseObjectKeyPart(expandedBindingKey)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1}}catch(error2){this.notify.emitError("binding-parse-error",error2,getErrorMessage2(error2,"Failed to parse keymap binding"));continue}let sequence=parsed.parts;hasTokenBindings||=parsed.hasTokenBindings;for(let tokenName of parsed.unknownTokens)warnUnknownToken(tokenName,typeof expandedBindingKey==="string"?expandedBindingKey:String(expandedBindingKey.name));for(let compiledInput of this.applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields))try{let event=this.normalizeBindingEvent(compiledInput.event),compiledSequence=compiledInput.sequence,mergedRequires,mergedAttrs,matchers,conditionKeys,hasUnkeyedMatchers=!1;for(let fieldName in compiledInput){if(fieldName==="sequence")continue;if(RESERVED_BINDING_FIELDS2.has(fieldName))continue;let value=compiledInput[fieldName];if(value===void 0)continue;let compiler=bindingFieldCompilers.get(fieldName);if(!compiler){warnUnknownField("binding",fieldName);continue}compiler(value,{require(name,requiredValue){if(!mergedRequires)mergedRequires={};if(mergeRequirement2(mergedRequires,name,requiredValue,`field ${fieldName}`),!conditionKeys)conditionKeys=new Set;conditionKeys.add(name)},attr(name,attributeValue){if(!mergedAttrs)mergedAttrs={};mergeAttribute2(mergedAttrs,name,attributeValue,`field ${fieldName}`)},activeWhen:(matcher)=>{let runtimeMatcher=conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;if(!matchers)matchers=[];matchers.push(runtimeMatcher)}})}let attrs=mergedAttrs?snapshotAttributes2(mergedAttrs):void 0,command=normalizeBindingCommand2(compiledInput.cmd),compiledBinding={sequence:compiledSequence,command,event,sourceBinding:snapshotParsedBindingInput2(compiledInput),sourceTarget,sourceLayerOrder,sourceBindingIndex:bindingIndex,requires:mergedRequires?Object.entries(mergedRequires):EMPTY_REQUIRES2,matchers:matchers??EMPTY_MATCHERS2,conditionKeys:conditionKeys?[...conditionKeys]:EMPTY_CONDITION_KEYS2,hasUnkeyedMatchers,matchCacheDirty:!0,preventDefault:compiledInput.preventDefault!==!1,fallthrough:compiledInput.fallthrough??!1};if(attrs)compiledBinding.attrs=attrs;if(typeof command==="function")compiledBinding.run=command;if(compiledSequence.length===0)continue;if(event==="release"&&compiledSequence.length>1)throw Error("Keymap release bindings only support a single key stroke");if(event==="press")this.insertBinding(root,compiledBinding,allowExactPrefixAmbiguity);compiledBindings.push(compiledBinding)}catch(error2){this.notify.emitError("binding-compile-error",error2,getErrorMessage2(error2,"Failed to compile keymap binding"))}}}return{root,bindings:compiledBindings,hasTokenBindings}}parseObjectKeyPart(key,options){return createKeySequencePart2(key,options)}normalizeBindingEvent(event){if(event===void 0||event==="press")return"press";if(event==="release")return"release";throw Error(`Invalid keymap binding event "${String(event)}": expected "press" or "release"`)}applyBindingTransformers(binding,sequence,tokens2,bindingParsers,compileFields){let bindingTransformers=this.state.environment.bindingTransformers.values();if(bindingTransformers.length===0)return[{...binding,sequence:cloneKeySequence2(sequence)}];let parsedBinding={...binding,sequence:cloneKeySequence2(sequence)},extraBindings=[],keepOriginal=!0,layer=compileFields??EMPTY_COMPILE_FIELDS2;for(let transformer of bindingTransformers)try{transformer(parsedBinding,{layer,parseKey:(key)=>{return parseSingleKeyPartWithParsers2(key,bindingParsers,{tokens:tokens2,layer,parseObjectKey:(value,options)=>this.parseObjectKeyPart(value,options)})},add:(nextBinding)=>{extraBindings.push(snapshotParsedBindingInput2(nextBinding))},skipOriginal:()=>{keepOriginal=!1}})}catch(error2){this.notify.emitError("binding-transformer-error",error2,"[Keymap] Error in binding transformer:")}if(!keepOriginal)return extraBindings;if(extraBindings.length===0)return[parsedBinding];return[parsedBinding,...extraBindings]}insertBinding(root,binding,allowExactPrefixAmbiguity){let node=root,touchedNodes=[],createdNodes=[];try{for(let part of binding.sequence){if(!allowExactPrefixAmbiguity&&node.bindings.some((candidate)=>candidate.command!==void 0))throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");let bindingKey=part.match,child=node.children.get(bindingKey);if(!child)child=createSequenceNode2(node,cloneKeySequencePart2(part).stroke,part.match),node.children.set(bindingKey,child),createdNodes.push({parent:node,key:bindingKey});child.reachableBindings.push(binding),touchedNodes.push(child),node=child}if(!allowExactPrefixAmbiguity&&binding.command!==void 0&&node.children.size>0)throw Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");node.bindings=[...node.bindings,binding]}catch(error2){for(let index=touchedNodes.length-1;index>=0;index-=1){let touchedNode=touchedNodes[index];if(!touchedNode)continue;if(touchedNode.reachableBindings.at(-1)===binding){touchedNode.reachableBindings.pop();continue}touchedNode.reachableBindings=touchedNode.reachableBindings.filter((candidate)=>candidate!==binding)}for(let index=createdNodes.length-1;index>=0;index-=1){let createdNode=createdNodes[index];if(!createdNode)continue;let child=createdNode.parent.children.get(createdNode.key);if(!child)continue;if(child.children.size>0||child.reachableBindings.length>0||child.bindings.length>0)continue;createdNode.parent.children.delete(createdNode.key)}throw error2}}}function expandBindingInputWithExpanders2(key,expanders,options){if(typeof key!=="string"||expanders.length===0)return[key];let layer=options?.layer??EMPTY_COMPILE_FIELDS2,candidates=[key];for(let expander of expanders){let nextCandidates=[];for(let input of candidates){let result2=expander({input,layer});if(!result2){nextCandidates.push(input);continue}if(result2.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${input}"`);for(let expandedInput of result2){if(typeof expandedInput!=="string")throw Error(`Keymap binding expander must return string key sequences for "${input}"`);nextCandidates.push(expandedInput)}}candidates=nextCandidates}return candidates}function parseBindingSequenceWithParsers2(key,parsers2,options){if(key.length===0)throw Error("Invalid key sequence: sequence cannot be empty");if(parsers2.length===0)throw Error("No keymap binding parsers are registered");let tokens2=options.tokens??new Map,layer=options.layer??EMPTY_COMPILE_FIELDS2,parseObjectKey=options.parseObjectKey,parts=[],usedTokens=new Set,unknownTokens=new Set,index=0;while(index<key.length){let matched=!1;for(let parser of parsers2){let result2=parser({input:key,index,layer,tokens:tokens2,normalizeTokenName:normalizeBindingTokenName2,createMatch:createTextKeyMatch2,parseObjectKey});if(!result2)continue;if(result2.nextIndex<=index||result2.nextIndex>key.length)throw Error(`Keymap binding parser must advance the input for "${key}" at index ${index}`);parts.push(...result2.parts);for(let tokenName of result2.usedTokens??[])usedTokens.add(tokenName);for(let tokenName of result2.unknownTokens??[])unknownTokens.add(tokenName);index=result2.nextIndex,matched=!0;break}if(!matched)throw Error(`No keymap binding parser handled input at index ${index} in "${key}"`)}return{parts,usedTokens:[...usedTokens],unknownTokens:[...unknownTokens],hasTokenBindings:usedTokens.size>0||unknownTokens.size>0}}function parseSingleKeyPartWithParsers2(key,parsers2,options){if(typeof key!=="string")return options.parseObjectKey(key);let{parts}=parseBindingSequenceWithParsers2(key,parsers2,options),[part]=parts;if(!part||parts.length!==1)throw Error(`Invalid key "${String(key)}": expected a single key stroke`);return part}function isReactiveMatcher2(value){if(!value||typeof value!=="object")return!1;let candidate=value;return typeof candidate.get==="function"&&typeof candidate.subscribe==="function"}class ConditionService2{state;notify;constructor(state,notify){this.state=state,this.notify=notify}buildRuntimeMatcher(matcher,source){if(typeof matcher==="function")return{source,match:matcher,cacheable:!1};if(isReactiveMatcher2(matcher))return{source,match:()=>matcher.get(),cacheable:!0,subscribe:(onChange)=>matcher.subscribe(onChange)};throw Error(`Keymap ${source} expected a function or a reactive matcher`)}hasNoConditions(target){return target.requires.length===0&&target.matchers.length===0}indexRuntimeMatchable(target){if(target.conditionKeys.length>0)for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(dependents){dependents.add(target);continue}this.state.conditions.runtimeKeyDependents.set(key,new Set([target]))}if(!target.hasUnkeyedMatchers)target.matchCacheDirty=!0}unindexRuntimeMatchable(target){if(target.conditionKeys.length===0)return;for(let key of target.conditionKeys){let dependents=this.state.conditions.runtimeKeyDependents.get(key);if(!dependents)continue;if(dependents.delete(target),dependents.size===0)this.state.conditions.runtimeKeyDependents.delete(key)}}invalidateRuntimeConditionKey(name){let dependents=this.state.conditions.runtimeKeyDependents.get(name);if(!dependents)return;for(let target of dependents)target.matchCacheDirty=!0}matchesConditions(target){if(this.hasNoConditions(target))return!0;if(this.hasFreshConditionCache(target))return target.matchCache===!0;let matched=this.matchRequirements(target.requires)&&this.matchesRuntimeMatchers(target);return this.updateConditionCache(target,matched),matched}layerMatchesRuntimeState(layer){if(this.state.layers.layersWithConditions===0||this.hasNoConditions(layer))return!0;return this.matchesConditions(layer)}matchRequirements(requires){if(requires.length===0)return!0;for(let[name,value]of requires)if(!Object.is(this.state.runtime.data[name],value))return!1;return!0}hasFreshConditionCache(target){if(target.hasUnkeyedMatchers)return!1;return target.matchCacheDirty!==!0&&target.matchCache!==void 0}updateConditionCache(target,matched){if(target.hasUnkeyedMatchers)return;target.matchCacheDirty=!1,target.matchCache=matched}matchesRuntimeMatcher(matcher){try{return matcher.match()}catch(error2){return this.notify.emitError("runtime-matcher-error",error2,`[Keymap] Error evaluating runtime matcher from ${matcher.source}:`),!1}}matchesRuntimeMatchers(target){if(target.matchers.length===0)return!0;if(target.matchers.length===1){let[matcher]=target.matchers;return matcher?this.matchesRuntimeMatcher(matcher):!0}for(let matcher of target.matchers)if(!this.matchesRuntimeMatcher(matcher))return!1;return!0}}function createSyncDecision2(action,handler){return{[KEY_DISAMBIGUATION_DECISION2]:!0,action,handler}}function createDeferredDecision2(action){return{[KEY_DEFERRED_DISAMBIGUATION_DECISION2]:!0,action}}function isSyncDecision2(value){return!!value&&typeof value==="object"&&value[KEY_DISAMBIGUATION_DECISION2]===!0}function isDeferredDecision2(value){return!!value&&typeof value==="object"&&value[KEY_DEFERRED_DISAMBIGUATION_DECISION2]===!0}class DispatchService2{state;notify;runtime;activation;conditions;executor;compiler;catalog;layers;eventMatchResolverContext;pendingDisambiguation=null;nextPendingDisambiguationId=0;constructor(state,notify,runtime,activation,conditions,executor,compiler,catalog,layers){this.state=state,this.notify=notify,this.runtime=runtime,this.activation=activation,this.conditions=conditions,this.executor=executor,this.compiler=compiler,this.catalog=catalog,this.layers=layers,this.eventMatchResolverContext={resolveKey:(key)=>{return this.compiler.parseTokenKey(key).match}}}intercept(name,fn,options){if(name==="key"){let keyOptions=options;return this.state.dispatch.keyHooks.register(fn,{priority:keyOptions?.priority??0,release:keyOptions?.release??!1})}let rawOptions=options;return this.state.dispatch.rawHooks.register(fn,{priority:rawOptions?.priority??0})}prependEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.prepend(resolver)}appendEventMatchResolver(resolver){return this.state.dispatch.eventMatchResolvers.append(resolver)}clearEventMatchResolvers(){this.state.dispatch.eventMatchResolvers.clear()}prependDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.prepend(resolver),resolver)}appendDisambiguationResolver(resolver){return this.mutateDisambiguationResolvers(()=>this.state.dispatch.disambiguationResolvers.append(resolver),resolver)}clearDisambiguationResolvers(){if(!this.state.dispatch.disambiguationResolvers.has())return;this.notify.runWithStateChangeBatch(()=>{this.state.dispatch.disambiguationResolvers.clear(),this.layers.recompileBindings()})}handlePendingSequenceChange(_previous,_next){if(!this.pendingDisambiguation)return;this.cancelPendingDisambiguation()}handleRawSequence(sequence){let hooks=this.state.dispatch.rawHooks.entries();if(hooks.length===0)return!1;let stopped=!1,context={sequence,stop(){stopped=!0}};for(let hook of hooks){try{hook.listener(context)}catch(error2){this.notify.emitError("raw-intercept-error",error2,"[Keymap] Error in raw intercept listener:")}if(stopped)return!0}return!1}handleKeyEvent(event,release){if(!release)this.cancelPendingDisambiguation();let hooks=this.state.dispatch.keyHooks.entries(),context={event,setData:(name,value)=>{this.runtime.setData(name,value)},getData:(name)=>{return this.runtime.getData(name)},consume:(options)=>{let shouldPreventDefault=options?.preventDefault??!0,shouldStopPropagation=options?.stopPropagation??!0;if(shouldPreventDefault)event.preventDefault();if(shouldStopPropagation)event.stopPropagation()}};for(let hook of hooks){if(hook.release!==release)continue;try{hook.listener(context)}catch(error2){this.notify.emitError("key-intercept-error",error2,"[Keymap] Error in key intercept listener:")}if(event.propagationStopped)return}if(release){this.dispatchReleaseLayers(event);return}this.dispatchLayers(event)}mutateDisambiguationResolvers(register2,resolver){return this.notify.runWithStateChangeBatch(()=>{let hadResolvers=this.state.dispatch.disambiguationResolvers.has(),off=register2();if(!hadResolvers&&this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings();return()=>{this.notify.runWithStateChangeBatch(()=>{let hadBeforeRemoval=this.state.dispatch.disambiguationResolvers.has();if(off(),this.state.dispatch.disambiguationResolvers.values().includes(resolver))return;if(hadBeforeRemoval&&!this.state.dispatch.disambiguationResolvers.has())this.layers.recompileBindings()})}})}dispatchReleaseLayers(event){let focused=this.activation.getFocusedTarget(),activeLayers=this.activation.getActiveLayers(focused),hasLayerConditions=this.state.layers.layersWithConditions>0,matchKeys=this.resolveEventMatchKeys(event);layerLoop:for(let layer of activeLayers){if(layer.compiledBindings.length===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;for(let strokeKey of matchKeys){let result2=this.runReleaseBindings(layer,strokeKey,event,focused);if(!result2.handled)continue;if(result2.stop)return;continue layerLoop}}}dispatchLayers(event){let focused=this.activation.getFocusedTarget(),pending=this.activation.ensureValidPendingSequence(),matchKeys=this.resolveEventMatchKeys(event);if(pending){this.dispatchPendingSequence(pending,matchKeys,event,focused);return}let activeLayers=this.activation.getActiveLayers(focused);this.dispatchFromRoot(activeLayers,matchKeys,event,focused)}dispatchPendingSequence(pending,matchKeys,event,focused){let advancedCaptures=[];for(let capture2 of pending.captures){let nextNode=this.getReachableChild(capture2.node,matchKeys,focused);if(!nextNode)continue;advancedCaptures.push({layer:capture2.layer,node:nextNode})}if(advancedCaptures.length===0){this.activation.setPendingSequence(null);return}this.dispatchPendingCapturesFromIndex(advancedCaptures,0,!1,event,focused)}dispatchPendingCapturesFromIndex(advancedCaptures,startIndex,handledExact,event,focused){let hasHandledExact=handledExact;for(let index=startIndex;index<advancedCaptures.length;index+=1){let capture2=advancedCaptures[index];if(!capture2)continue;if(capture2.node.children.size>0){if(hasHandledExact)continue;let continuationCaptures=this.collectPendingCapturesFromAdvanced(advancedCaptures,index);if(this.tryResolvePendingAmbiguity(advancedCaptures,index,continuationCaptures,capture2,event,focused,hasHandledExact))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(!result2.handled)continue;if(hasHandledExact=!0,result2.stop){this.activation.setPendingSequence(null);return}}this.activation.setPendingSequence(null)}dispatchFromRoot(activeLayers,matchKeys,event,focused){this.dispatchFromRootAtIndex(activeLayers,0,matchKeys,event,focused)}dispatchFromRootAtIndex(activeLayers,startIndex,matchKeys,event,focused){let hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer)continue;if(layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode)continue;if(nextNode.children.size>0){let continuationCaptures=this.collectPendingCapturesFromRoot(activeLayers,index,matchKeys,focused);if(this.tryResolveRootAmbiguity(activeLayers,index,matchKeys,continuationCaptures,layer,nextNode,event,focused))return;this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation();return}let result2=this.runBindings(layer,nextNode.bindings,event,focused);if(!result2.handled)continue;if(result2.stop)return}}tryResolveRootAmbiguity(activeLayers,layerIndex,matchKeys,continuationCaptures,layer,node,event,focused){let applyExact=()=>{if(this.activation.setPendingSequence(null),!this.runBindings(layer,node.bindings,event,focused).stop)this.dispatchFromRootAtIndex(activeLayers,layerIndex+1,matchKeys,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:node.bindings,runExact:applyExact})}tryResolvePendingAmbiguity(advancedCaptures,captureIndex,continuationCaptures,capture2,event,focused,handledExact){let applyExact=()=>{this.activation.setPendingSequence(null);let result2=this.runBindings(capture2.layer,capture2.node.bindings,event,focused);if(result2.stop)return;this.dispatchPendingCapturesFromIndex(advancedCaptures,captureIndex+1,handledExact||result2.handled,event,focused)};return this.tryResolveAmbiguity({event,focused,continuationCaptures,exactBindingsSource:capture2.node.bindings,runExact:applyExact})}tryResolveAmbiguity(options){let{event,focused,continuationCaptures,exactBindingsSource,runExact}=options;if(!this.state.dispatch.disambiguationResolvers.has()||continuationCaptures.length===0)return!1;let activeView=this.catalog.getActiveCommandView(focused),exactBindings=this.activation.collectMatchingBindings(exactBindingsSource,focused,activeView);if(!exactBindings.some((binding)=>binding.command!==void 0))return!1;let continueSequence=()=>{this.activation.setPendingSequence({captures:continuationCaptures}),event.preventDefault(),event.stopPropagation()},clear=()=>{this.activation.setPendingSequence(null),event.preventDefault(),event.stopPropagation()},sequence,getSequence=()=>{return sequence??=this.activation.collectSequencePartsFromPending({captures:continuationCaptures}),sequence},decision=this.resolveDisambiguation({event,focused,getSequence,exactBindings,continuationCaptures,activeView});if(!decision)return this.warnUnresolvedAmbiguity(getSequence()),continueSequence(),!0;return this.applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence)}applySyncDecision(decision,continuationCaptures,runExact,continueSequence,clear,focused,getSequence){if(decision.action==="run-exact")return runExact(),!0;if(decision.action==="continue-sequence")return continueSequence(),!0;if(decision.action==="clear")return clear(),!0;return continueSequence(),this.scheduleDeferredDisambiguation(continuationCaptures,decision.handler,focused,getSequence(),(nextDecision)=>{if(!nextDecision)return;if(nextDecision.action==="run-exact"){runExact();return}if(nextDecision.action==="continue-sequence"){continueSequence();return}clear()}),!0}resolveDisambiguation(options){let activation=this.activation,runtime=this.runtime,sequence,exact,continuations,strokePart,ctx={event:options.event,focused:options.focused,get sequence(){return sequence??=cloneKeySequence2(options.getSequence()),sequence},get stroke(){let stroke=options.getSequence().at(-1);if(!stroke)throw Error("Disambiguation context expected a non-empty sequence");return strokePart??={...stroke,stroke:cloneKeyStroke2(stroke.stroke)},strokePart},get exact(){return exact??=activation.collectActiveBindings(options.exactBindings,options.focused,options.activeView).map((binding)=>({...binding,sequence:cloneKeySequence2(binding.sequence)})),exact},get continuations(){return continuations??=activation.getActiveKeysForCaptures(options.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),continuations},getData:(name)=>{return runtime.getData(name)},setData:(name,value)=>{runtime.setData(name,value)},runExact:()=>createSyncDecision2("run-exact"),continueSequence:()=>createSyncDecision2("continue-sequence"),clear:()=>createSyncDecision2("clear"),defer:(run)=>createSyncDecision2("defer",run)};for(let resolver of this.state.dispatch.disambiguationResolvers.values()){let result2;try{result2=resolver(ctx)}catch(error2){this.notify.emitError("disambiguation-resolver-error",error2,"[Keymap] Error in disambiguation resolver:");continue}if(result2===void 0)continue;if(isPromiseLike2(result2)){this.notify.emitError("invalid-disambiguation-resolver-return",result2,"[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling");continue}if(!isSyncDecision2(result2)){this.notify.emitError("invalid-disambiguation-decision",result2,"[Keymap] Invalid disambiguation decision returned by resolver:");continue}return result2}return}scheduleDeferredDisambiguation(captures,handler,focused,sequence,apply){this.cancelPendingDisambiguation();let controller=new AbortController,pending={id:this.nextPendingDisambiguationId++,controller,captures,apply};this.pendingDisambiguation=pending,queueMicrotask(()=>{this.executeDeferredDisambiguation(pending,handler,focused,sequence)})}executeDeferredDisambiguation(pending,handler,focused,sequence){if(!this.isPendingDisambiguationCurrent(pending))return;let ctx={signal:pending.controller.signal,sequence:cloneKeySequence2(sequence),focused,sleep:(ms)=>{return this.sleepWithSignal(ms,pending.controller.signal)},runExact:()=>createDeferredDecision2("run-exact"),continueSequence:()=>createDeferredDecision2("continue-sequence"),clear:()=>createDeferredDecision2("clear")},result2;try{result2=handler(ctx)}catch(error2){if(this.isPendingDisambiguationCurrent(pending))this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending);return}if(isPromiseLike2(result2)){result2.then((resolved)=>{this.applyDeferredDisambiguationResult(pending,resolved)}).catch((error2)=>{if(!this.isPendingDisambiguationCurrent(pending))return;this.notify.emitError("deferred-disambiguation-error",error2,"[Keymap] Error in deferred disambiguation handler:"),this.finishPendingDisambiguation(pending)});return}this.applyDeferredDisambiguationResult(pending,result2)}applyDeferredDisambiguationResult(pending,result2){if(!this.isPendingDisambiguationCurrent(pending))return;if(result2!==void 0&&!isDeferredDecision2(result2)){this.notify.emitError("invalid-deferred-disambiguation-decision",result2,"[Keymap] Invalid deferred disambiguation decision returned by handler:"),this.finishPendingDisambiguation(pending);return}this.finishPendingDisambiguation(pending),pending.apply(result2)}finishPendingDisambiguation(pending){if(!this.isPendingDisambiguationCurrent(pending))return;this.pendingDisambiguation=null}cancelPendingDisambiguation(){let pending=this.pendingDisambiguation;if(!pending)return;this.pendingDisambiguation=null,pending.controller.abort()}isPendingDisambiguationCurrent(pending){return this.pendingDisambiguation===pending}sleepWithSignal(ms,signal){if(signal.aborted)return Promise.resolve(!1);return new Promise((resolve21)=>{let timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve21(!0)},Math.max(0,ms)),onAbort=()=>{clearTimeout(timeout),signal.removeEventListener("abort",onAbort),resolve21(!1)};signal.addEventListener("abort",onAbort,{once:!0})})}warnUnresolvedAmbiguity(sequence){let display=stringifyKeySequence2(sequence,{preferDisplay:!0});this.notify.warnOnce(`unresolved-disambiguation:${display}`,"unresolved-disambiguation",{sequence:display},`[Keymap] Ambiguous exact/prefix sequence "${display}" fell back to prefix handling because no disambiguation resolver resolved it`)}collectPendingCapturesFromRoot(activeLayers,startIndex,matchKeys,focused){let captures=[],hasLayerConditions=this.state.layers.layersWithConditions>0;for(let index=startIndex;index<activeLayers.length;index+=1){let layer=activeLayers[index];if(!layer||layer.root.children.size===0)continue;if(hasLayerConditions&&!this.conditions.hasNoConditions(layer)&&!this.conditions.matchesConditions(layer))continue;let nextNode=this.getReachableChild(layer.root,matchKeys,focused);if(!nextNode||nextNode.children.size===0)continue;captures.push({layer,node:nextNode})}return captures}collectPendingCapturesFromAdvanced(advancedCaptures,startIndex){return advancedCaptures.filter((candidate,candidateIndex)=>{return candidateIndex>=startIndex&&candidate.node.children.size>0})}resolveEventMatchKeys(event){let resolvers=this.state.dispatch.eventMatchResolvers.values();if(resolvers.length===0)return[];if(resolvers.length===1)return resolveSingleEventMatchKeys2(resolvers[0],event,this.eventMatchResolverContext,this.notify);let keys=[],seen=new Set;for(let resolver of resolvers){let resolved;try{resolved=resolver(event,this.eventMatchResolverContext)}catch(error2){this.notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:");continue}if(!resolved||resolved.length===0)continue;for(let candidate of resolved){if(typeof candidate!=="string"){this.notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}}return keys}runReleaseBindings(layer,strokeKey,event,focused){let handled=!1;for(let binding of layer.compiledBindings){if(binding.event!=="release")continue;let firstPart=binding.sequence[0];if(!firstPart||firstPart.match!==strokeKey)continue;if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}getReachableChild(node,matchKeys,focused){for(let strokeKey of matchKeys){let child=node.children.get(strokeKey);if(!child||!this.activation.nodeHasReachableBindings(child,focused))continue;return child}return}runBindings(layer,bindings,event,focused){let handled=!1;for(let binding of bindings){if(!this.conditions.matchesConditions(binding))continue;if(!this.executor.runBinding(layer,binding,event,focused))continue;if(handled=!0,!binding.fallthrough)return{handled:!0,stop:!0}}return{handled,stop:!1}}}function resolveSingleEventMatchKeys2(resolver,event,ctx,notify){let resolved;try{resolved=resolver(event,ctx)}catch(error2){return notify.emitError("event-match-resolver-error",error2,"[Keymap] Error in event match resolver:"),[]}if(!resolved||resolved.length===0)return[];if(resolved.length===1){let[candidate]=resolved;if(typeof candidate!=="string")return notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:"),[];return[candidate]}let keys=[],seen=new Set;for(let candidate of resolved){if(typeof candidate!=="string"){notify.emitError("invalid-event-match-resolver-candidate",candidate,"[Keymap] Invalid event match resolver candidate:");continue}if(seen.has(candidate))continue;seen.add(candidate),keys.push(candidate)}return keys}function registerFieldCompilers2(fields,options){let{kind,reservedFields,registeredFields,emitError}=options,entries=Object.entries(fields),registered=[];for(let[name]of entries){if(reservedFields.has(name)){emitError(`reserved-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is reserved`);continue}if(registeredFields.has(name))emitError(`duplicate-${kind}-field`,{field:name,kind},`Keymap ${kind} field "${name}" is already registered`)}for(let[name,compiler]of entries){if(reservedFields.has(name)||registeredFields.has(name))continue;registeredFields.set(name,compiler),registered.push([name,compiler])}return()=>{for(let[name,compiler]of registered)if(registeredFields.get(name)===compiler)registeredFields.delete(name)}}class EnvironmentService2{state;notify;compiler;layers;constructor(state,notify,compiler,layers){this.state=state,this.notify=notify,this.compiler=compiler,this.layers=layers}prependBindingTransformer(transformer){return this.state.environment.bindingTransformers.prepend(transformer)}appendBindingTransformer(transformer){return this.state.environment.bindingTransformers.append(transformer)}clearBindingTransformers(){this.state.environment.bindingTransformers.clear()}prependBindingParser(parser){return this.state.environment.bindingParsers.prepend(parser)}appendBindingParser(parser){return this.state.environment.bindingParsers.append(parser)}clearBindingParsers(){this.state.environment.bindingParsers.clear()}registerToken(token){let normalizedToken;try{normalizedToken=normalizeBindingTokenName2(token.name)}catch(error2){return this.notify.emitError("token-name-normalize-error",error2,getErrorMessage2(error2,"Failed to register keymap token")),NOOP3}if(this.state.environment.tokens.has(normalizedToken))return this.notify.emitError("duplicate-token",{token:normalizedToken},`Keymap token "${normalizedToken}" is already registered`),NOOP3;let parsedToken;try{parsedToken=this.compiler.parseTokenKey(token.key)}catch(error2){return this.notify.emitError("token-parse-error",error2,getErrorMessage2(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP3}let registeredToken={stroke:parsedToken.stroke,match:parsedToken.match},nextTokens=new Map(this.state.environment.tokens);nextTokens.set(normalizedToken,registeredToken);try{this.layers.applyTokenState(nextTokens)}catch(error2){return this.notify.emitError("token-register-error",error2,getErrorMessage2(error2,`Failed to register keymap token "${normalizedToken}"`)),NOOP3}return()=>{if(this.state.environment.tokens.get(normalizedToken)!==registeredToken)return;let nextTokens2=new Map(this.state.environment.tokens);nextTokens2.delete(normalizedToken);try{this.layers.applyTokenState(nextTokens2)}catch(error2){this.notify.emitError("token-unregister-error",error2,getErrorMessage2(error2,`Failed to unregister keymap token "${normalizedToken}"`))}}}prependBindingExpander(expander){return this.state.environment.bindingExpanders.prepend(expander)}appendBindingExpander(expander){return this.state.environment.bindingExpanders.append(expander)}clearBindingExpanders(){this.state.environment.bindingExpanders.clear()}registerLayerFields(fields){return registerFieldCompilers2(fields,{kind:"layer",reservedFields:RESERVED_LAYER_FIELDS2,registeredFields:this.state.environment.layerFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerBindingFields(fields){return registerFieldCompilers2(fields,{kind:"binding",reservedFields:RESERVED_BINDING_FIELDS2,registeredFields:this.state.environment.bindingFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}registerCommandFields(fields){return registerFieldCompilers2(fields,{kind:"command",reservedFields:RESERVED_COMMAND_FIELDS2,registeredFields:this.state.environment.commandFields,emitError:(code,error2,message)=>{this.notify.emitError(code,error2,message)}})}}function sortLayers2(layers){return[...layers].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return right.order-left.order})}function createCommandLookup2(commands){if(commands.length===0)return;let lookup=new Map;for(let command of commands)lookup.set(command.name,command);return lookup}function addRegisteredCommandNames2(target,commands){for(let command of commands)target.set(command.name,(target.get(command.name)??0)+1)}function removeRegisteredCommandNames2(target,commands){for(let command of commands){let count=target.get(command.name);if(!count||count<=1){target.delete(command.name);continue}target.set(command.name,count-1)}}function getSequenceNode2(root,sequence){let node=root;for(let part of sequence)if(node=node.children.get(part.match),!node)return;return node}function buildLayerBindingAnalyses2(root,compiledBindings){return compiledBindings.map((binding)=>{let node=binding.event==="press"?getSequenceNode2(root,binding.sequence):void 0;return{sequence:cloneKeySequence2(binding.sequence),command:binding.command,attrs:binding.attrs,event:binding.event,preventDefault:binding.preventDefault,fallthrough:binding.fallthrough,sourceBinding:snapshotParsedBindingInput2(binding.sourceBinding),sourceTarget:binding.sourceTarget,sourceLayerOrder:binding.sourceLayerOrder,sourceBindingIndex:binding.sourceBindingIndex,hasCommandAtSequence:node?node.bindings.some((candidate)=>candidate.command!==void 0):!1,hasContinuations:node?node.children.size>0:!1}})}class LayerService2{state;notify;conditions;activation;options;constructor(state,notify,conditions,activation,options){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation,this.options=options}registerLayer(layer){return this.notify.runWithStateChangeBatch(()=>{let target=layer.target;if(target&&this.options.host.isTargetDestroyed(target))return this.notify.emitError("destroyed-layer-target",{target},"Cannot register a keymap layer for a destroyed keymap target"),NOOP22;let bindingInputs,requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields,commands,commandLookup,targetMode;try{targetMode=this.normalizeTargetMode(layer),bindingInputs=snapshotBindingInputs2(layer.bindings??[]),commands=!layer.commands||layer.commands.length===0?[]:this.options.commands.normalizeCommands(layer.commands),commandLookup=createCommandLookup2(commands),{requires,matchers,conditionKeys,hasUnkeyedMatchers,compileFields}=this.compileLayerRuntimeState(layer)}catch(error2){return this.notify.emitError("register-layer-failed",error2,getErrorMessage2(error2,"Failed to register keymap layer")),NOOP22}let order=this.state.core.order++,compiledBindings=this.options.compiler.compileBindings(bindingInputs,this.state.environment.tokens,target,order,compileFields);if(compiledBindings.bindings.length===0&&!compiledBindings.hasTokenBindings&&commands.length===0)return NOOP22;this.runLayerAnalyzers({target,order,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,root:compiledBindings.root,hasTokenBindings:compiledBindings.hasTokenBindings});let registeredLayer={order,target,targetMode,priority:layer.priority??0,requires,matchers,conditionKeys,hasUnkeyedMatchers,matchCacheDirty:!0,compileFields,commands,commandLookup,bindingInputs,compiledBindings:compiledBindings.bindings,hasUnkeyedCommands:commands.some((command)=>command.hasUnkeyedMatchers),hasUnkeyedBindings:compiledBindings.bindings.some((binding)=>binding.hasUnkeyedMatchers),hasTokenBindings:compiledBindings.hasTokenBindings,root:compiledBindings.root};if(this.state.layers.layers.add(registeredLayer),registeredLayer.commands.length>0)this.state.layers.layersWithCommands+=1,this.state.commands.commandMetadataVersion+=1,addRegisteredCommandNames2(this.state.commands.registeredNames,registeredLayer.commands);if(registeredLayer.requires.length>0||registeredLayer.matchers.length>0)this.state.layers.layersWithConditions+=1;this.connectRuntimeMatchable(registeredLayer);for(let command of registeredLayer.commands)this.connectRuntimeMatchable(command);for(let binding of registeredLayer.compiledBindings)this.connectRuntimeMatchable(binding);if(this.indexLayer(registeredLayer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),target){let onTargetDestroy=()=>{this.unregisterLayer(registeredLayer)};registeredLayer.offTargetDestroy=this.options.host.onTargetDestroy(target,onTargetDestroy)}if(registeredLayer.commands.length>0)this.activation.ensureValidPendingSequence();return this.notify.queueStateChange(),()=>{this.unregisterLayer(registeredLayer)}})}applyTokenState(nextTokens){this.notify.runWithStateChangeBatch(()=>{let nextCompilations=new Map;for(let layer of this.state.layers.layers){if(!layer.hasTokenBindings)continue;nextCompilations.set(layer,this.compileLayerBindings(layer,nextTokens))}this.state.environment.tokens=nextTokens;let shouldClearPending=!1;for(let[layer,compilation]of nextCompilations)if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;if(shouldClearPending)this.activation.setPendingSequence(null);if(nextCompilations.size>0)this.notify.queueStateChange()})}recompileBindings(){this.notify.runWithStateChangeBatch(()=>{let recompiledLayers=0,shouldClearPending=!1;for(let layer of this.state.layers.layers){if(layer.bindingInputs.length===0)continue;let compilation=this.compileLayerBindings(layer,this.state.environment.tokens);if(this.applyCompiledBindings(layer,compilation))shouldClearPending=!0;recompiledLayers+=1}if(shouldClearPending)this.activation.setPendingSequence(null);if(recompiledLayers>0)this.notify.queueStateChange()})}prependLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.prepend(analyzer)}appendLayerAnalyzer(analyzer){return this.state.layers.layerAnalyzers.append(analyzer)}clearLayerAnalyzers(){this.state.layers.layerAnalyzers.clear()}cleanup(){for(let layer of this.state.layers.layers){this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0}}normalizeTargetMode(layer){if(layer.targetMode){if(!layer.target)throw Error(`Keymap targetMode "${layer.targetMode}" requires a target`);return layer.targetMode}return layer.target?"focus-within":void 0}runLayerAnalyzers(options){let analyzers=this.state.layers.layerAnalyzers.values();if(analyzers.length===0)return;let bindings=buildLayerBindingAnalyses2(options.root,options.compiledBindings),ctx={target:options.target,order:options.order,bindingInputs:options.bindingInputs,bindings,hasTokenBindings:options.hasTokenBindings,checkCommandResolution:(command)=>{return this.options.commands.getCommandResolutionStatus(command,options.commandLookup)},warn:(code,warning,message)=>{this.notify.emitWarning(code,warning,message)},warnOnce:(key,code,warning,message)=>{this.notify.warnOnce(key,code,warning,message)},error:(code,error2,message)=>{this.notify.emitError(code,error2,message)}};for(let analyzer of analyzers)try{analyzer(ctx)}catch(error2){this.notify.emitError("layer-analyzer-error",error2,"[Keymap] Error in layer analyzer:")}}compileLayerRuntimeState(layer){let mergedRequires={},matchers=[],compileFields=Object.create(null),conditionKeys=new Set,hasUnkeyedMatchers=!1;for(let[fieldName,value]of Object.entries(layer)){if(RESERVED_LAYER_FIELDS2.has(fieldName))continue;if(value===void 0)continue;compileFields[fieldName]=snapshotDataValue2(value);let compiler=this.state.environment.layerFields.get(fieldName);if(!compiler){this.options.warnUnknownField("layer",fieldName);continue}compiler(value,{require:(name,requiredValue)=>{mergeRequirement2(mergedRequires,name,requiredValue,`field ${fieldName}`),conditionKeys.add(name)},activeWhen:(matcher)=>{let runtimeMatcher=this.conditions.buildRuntimeMatcher(matcher,`field ${fieldName}`);if(!runtimeMatcher.cacheable)hasUnkeyedMatchers=!0;matchers.push(runtimeMatcher)}})}return{requires:Object.entries(mergedRequires),matchers,conditionKeys:[...conditionKeys],hasUnkeyedMatchers,compileFields:Object.keys(compileFields).length>0?Object.freeze(compileFields):void 0}}compileLayerBindings(layer,tokens2){return this.options.compiler.compileBindings(layer.bindingInputs,tokens2,layer.target,layer.order,layer.compileFields)}applyCompiledBindings(layer,compilation){this.runLayerAnalyzers({target:layer.target,order:layer.order,commandLookup:layer.commandLookup,bindingInputs:layer.bindingInputs,compiledBindings:compilation.bindings,root:compilation.root,hasTokenBindings:compilation.hasTokenBindings});for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);layer.root=compilation.root,layer.compiledBindings=compilation.bindings,layer.hasUnkeyedBindings=compilation.bindings.some((binding)=>binding.hasUnkeyedMatchers),layer.hasTokenBindings=compilation.hasTokenBindings;for(let binding of layer.compiledBindings)this.connectRuntimeMatchable(binding);return this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer)??!1}indexLayer(layer){this.state.layers.sortedLayers=sortLayers2([...this.state.layers.sortedLayers,layer]),this.state.layers.activeLayersVersion+=1}removeLayerFromIndex(layer){this.state.layers.sortedLayers=this.state.layers.sortedLayers.filter((candidate)=>candidate!==layer),this.state.layers.activeLayersVersion+=1}unregisterLayer(layer){this.notify.runWithStateChangeBatch(()=>{if(!this.state.layers.layers.delete(layer))return;if(layer.requires.length>0||layer.matchers.length>0)this.state.layers.layersWithConditions-=1;if(layer.commands.length>0)this.state.layers.layersWithCommands-=1,this.state.commands.commandMetadataVersion+=1,removeRegisteredCommandNames2(this.state.commands.registeredNames,layer.commands);this.disconnectRuntimeMatchable(layer);for(let command of layer.commands)this.disconnectRuntimeMatchable(command);for(let binding of layer.compiledBindings)this.disconnectRuntimeMatchable(binding);if(this.removeLayerFromIndex(layer),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(),layer.offTargetDestroy?.(),layer.offTargetDestroy=void 0,this.state.projection.pendingSequence?.captures.some((capture2)=>capture2.layer===layer))this.activation.setPendingSequence(null);else if(layer.commands.length>0&&!this.options.host.isDestroyed)this.activation.ensureValidPendingSequence();this.notify.queueStateChange()})}connectRuntimeMatchable(target){this.attachReactiveMatchers(target),this.conditions.indexRuntimeMatchable(target)}disconnectRuntimeMatchable(target){this.detachReactiveMatchers(target),this.conditions.unindexRuntimeMatchable(target)}attachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.subscribe)continue;try{matcher.dispose=matcher.subscribe(()=>{if(target.matchCacheDirty=!0,!this.activation.hasPendingSequenceState()){this.notify.queueStateChange();return}this.notify.runWithStateChangeBatch(()=>{this.activation.revalidatePendingSequenceIfNeeded(),this.notify.queueStateChange()})})}catch(error2){this.notify.emitError("reactive-matcher-subscribe-error",error2,getErrorMessage2(error2,`Failed to subscribe to reactive matcher from ${matcher.source}`))}}}detachReactiveMatchers(target){for(let matcher of target.matchers){if(!matcher.dispose)continue;try{matcher.dispose()}catch(error2){this.notify.emitError("reactive-matcher-dispose-error",error2,getErrorMessage2(error2,`Failed to dispose reactive matcher from ${matcher.source}`))}matcher.dispose=void 0}}}class Emitter3{onError;listeners=Object.create(null);constructor(onError){this.onError=onError}hook(name,listener){let current=this.listeners[name]??[];return this.listeners[name]=[...current,listener],()=>{let current2=this.listeners[name];if(!current2||current2.length===0)return;let next=current2.filter((candidate)=>candidate!==listener);if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}}has(name){return(this.listeners[name]?.length??0)>0}off(name,listener){let current=this.listeners[name];if(!current||current.length===0)return;let next=current.filter((candidate)=>candidate!==listener);if(next.length===current.length)return;if(next.length===0){delete this.listeners[name];return}this.listeners[name]=next}clear(){this.listeners=Object.create(null)}emit(name,...args){let listeners2=this.listeners[name];if(!listeners2||listeners2.length===0)return;for(let listener of listeners2)try{if(args.length===0)listener();else listener(args[0])}catch(error2){this.onError(name,error2)}}}class NotificationService2{state;events;hooks;constructor(state,events,hooks){this.state=state,this.events=events,this.hooks=hooks}runWithStateChangeBatch(fn){this.state.notify.stateChangeDepth+=1;try{return fn()}finally{if(this.state.notify.stateChangeDepth-=1,this.state.notify.stateChangeDepth===0)this.flushStateChange()}}queueStateChange(){if(this.state.notify.derivedStateVersion+=1,!this.hooks.has("state"))return;if(this.state.notify.stateChangePending=!0,this.state.notify.stateChangeDepth===0&&!this.state.notify.flushingStateChange)this.flushStateChange()}emitWarning(code,warning,message){if(!this.events.has("warning")){let consoleMessage=`[${code}] ${message}`;if(warning instanceof Error)console.warn(consoleMessage,warning);else console.warn(consoleMessage);return}this.events.emit("warning",{code,message,warning})}emitError(code,error2,message){if(!this.events.has("error")){let consoleMessage=`[${code}] ${message}`;if(error2 instanceof Error)console.error(consoleMessage,error2);else console.error(consoleMessage);return}this.events.emit("error",{code,message,error:error2})}reportListenerError(name,error2){if(name==="state"){this.emitError("state-listener-error",error2,"[Keymap] Error in state listener:");return}if(name==="pendingSequence"){this.emitError("pending-sequence-listener-error",error2,"[Keymap] Error in pending sequence listener:");return}}warnOnce(key,code,warning,message){if(this.state.notify.usedWarningKeys.has(key))return;this.state.notify.usedWarningKeys.add(key),this.emitWarning(code,warning,message)}flushStateChange(){if(!this.state.notify.stateChangePending||this.state.notify.stateChangeDepth>0||this.state.notify.flushingStateChange)return;this.state.notify.flushingStateChange=!0;try{let iterations=0;while(this.state.notify.stateChangePending&&this.state.notify.stateChangeDepth===0){if(iterations>=MAX_STATE_CHANGE_FLUSH_ITERATIONS2){this.state.notify.stateChangePending=!1,this.emitError("state-change-feedback-loop",{iterations:MAX_STATE_CHANGE_FLUSH_ITERATIONS2},`[Keymap] Possible infinite state listener feedback loop detected after ${MAX_STATE_CHANGE_FLUSH_ITERATIONS2} iterations; pending state notifications were dropped`);break}iterations+=1,this.state.notify.stateChangePending=!1,this.hooks.emit("state")}}finally{this.state.notify.flushingStateChange=!1}}}class RuntimeService2{state;notify;conditions;activation;constructor(state,notify,conditions,activation){this.state=state,this.notify=notify,this.conditions=conditions,this.activation=activation}getData(name){return this.state.runtime.data[name]}setData(name,value){this.notify.runWithStateChangeBatch(()=>{if(value===void 0){if(!(name in this.state.runtime.data))return;delete this.state.runtime.data[name],this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange();return}if(Object.is(this.state.runtime.data[name],value))return;this.state.runtime.data[name]=value,this.state.runtime.dataVersion+=1,this.conditions.invalidateRuntimeConditionKey(name),this.activation.ensureValidPendingSequence(),this.notify.queueStateChange()})}getReadonlyData(){if(this.state.runtime.readonlyDataVersion===this.state.runtime.dataVersion)return this.state.runtime.readonlyData;return this.state.runtime.readonlyData=Object.freeze({...this.state.runtime.data}),this.state.runtime.readonlyDataVersion=this.state.runtime.dataVersion,this.state.runtime.readonlyData}}class CopyOnWriteRegistry2{items=[];getItems(){return this.items}setItems(items){this.items=items}removeItem(value){let current=this.items;if(current.length===0)return!1;let next=current.filter((candidate)=>candidate!==value);if(next.length===current.length)return!1;return this.items=next,!0}has(){return this.items.length>0}clear(){this.items=[]}}function createKeymapState2(){return{core:{order:0},environment:{tokens:new Map,layerFields:new Map,bindingExpanders:new OrderedRegistry2,bindingParsers:new OrderedRegistry2,bindingTransformers:new OrderedRegistry2,bindingFields:new Map,commandFields:new Map},dispatch:{eventMatchResolvers:new OrderedRegistry2,disambiguationResolvers:new OrderedRegistry2,keyHooks:new PriorityRegistry2,rawHooks:new PriorityRegistry2},layers:{layers:new Set,sortedLayers:[],activeLayersVersion:0,activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],layersWithConditions:0,layersWithCommands:0,layerAnalyzers:new OrderedRegistry2},commands:{commandMetadataVersion:0,registeredNames:new Map,commandResolvers:new OrderedRegistry2,activeCommandViewVersion:-1,activeCommandView:void 0,registeredCommandViewVersion:-1,registeredCommandView:void 0,registeredCommandEntriesCacheVersion:-1,registeredCommandEntriesCache:[]},projection:{pendingSequence:null,pendingSequenceCacheVersion:-1,pendingSequenceCache:[],activeKeysPlainCacheVersion:-1,activeKeysPlainCache:[],activeKeysBindingsCacheVersion:-1,activeKeysBindingsCache:[],activeKeysMetadataCacheVersion:-1,activeKeysMetadataCache:[],activeKeysBindingsAndMetadataCacheVersion:-1,activeKeysBindingsAndMetadataCache:[]},conditions:{runtimeKeyDependents:new Map},runtime:{data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:EMPTY_DATA2},notify:{derivedStateVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}}function getKeyMatchKey2(input){return resolveKeyMatch2(input)}class Keymap2{host;state=createKeymapState2();cleanedUp=!1;resources=new Map;cleanupListeners=[];events=new Emitter3(()=>{});hooks;notify;activation;runtime;conditions;catalog;executor;compiler;dispatch;layers;environment;keypressListener;keyreleaseListener;rawListener;focusedTargetListener;constructor(host){if(this.host=host,host.isDestroyed)throw Error("Cannot create a keymap for a destroyed host");if(this.hooks=new Emitter3((name,error2)=>{this.notify.reportListenerError(name,error2)}),this.notify=new NotificationService2(this.state,this.events,this.hooks),this.conditions=new ConditionService2(this.state,this.notify),this.catalog=new CommandCatalogService2(this.state,this.host,this.notify,this.conditions,{onCommandResolversChanged:()=>{this.activation.ensureValidPendingSequence()}}),this.activation=new ActivationService2(this.state,this.host,this.hooks,this.notify,this.conditions,this.catalog,{onPendingSequenceChanged:(previous,next)=>{this.dispatch?.handlePendingSequenceChange(previous,next)}}),this.runtime=new RuntimeService2(this.state,this.notify,this.conditions,this.activation),this.executor=new CommandExecutorService2(this.notify,this.runtime,this.activation,this.catalog,{keymap:this,createCommandEvent:()=>this.host.createCommandEvent()}),this.compiler=new CompilerService2(this.state,this.notify,this.conditions,{warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)},warnUnknownToken:(token,sequence)=>{this.warnUnknownToken(token,sequence)}}),this.layers=new LayerService2(this.state,this.notify,this.conditions,this.activation,{compiler:this.compiler,commands:this.catalog,host:this.host,warnUnknownField:(kind,fieldName)=>{this.warnUnknownField(kind,fieldName)}}),this.environment=new EnvironmentService2(this.state,this.notify,this.compiler,this.layers),this.dispatch=new DispatchService2(this.state,this.notify,this.runtime,this.activation,this.conditions,this.executor,this.compiler,this.catalog,this.layers),this.keypressListener=(event)=>{this.dispatch.handleKeyEvent(event,!1)},this.keyreleaseListener=(event)=>{this.dispatch.handleKeyEvent(event,!0)},this.rawListener=(sequence)=>{return this.dispatch.handleRawSequence(sequence)},this.focusedTargetListener=(focused)=>{this.handleFocusedTargetChange(focused)},this.cleanupListeners.push(this.host.onKeyPress(this.keypressListener)),this.cleanupListeners.push(this.host.onKeyRelease(this.keyreleaseListener)),this.host.onRawInput)this.cleanupListeners.push(this.host.onRawInput(this.rawListener));if(this.cleanupListeners.push(this.host.onFocusChange(this.focusedTargetListener)),this.host.onDestroy)this.cleanupListeners.push(this.host.onDestroy(()=>{this.cleanup()}))}cleanup(){if(this.cleanedUp)return;this.cleanedUp=!0,this.activation.setPendingSequence(null);for(let resource of this.resources.values())resource.dispose();this.resources.clear(),this.layers.cleanup();for(let cleanupListener of this.cleanupListeners.splice(0))cleanupListener()}setData(name,value){this.runtime.setData(name,value)}getData(name){return this.runtime.getData(name)}hasPendingSequence(){return this.activation.ensureValidPendingSequence()!==void 0}getPendingSequence(){return this.activation.getPendingSequence()}createKeyMatcher(key){let match=this.compiler.parseTokenKey(key).match;return(input)=>{if(!input)return!1;return getKeyMatchKey2(input)===match}}clearPendingSequence(){this.activation.setPendingSequence(null)}popPendingSequence(){return this.activation.popPendingSequence()}getActiveKeys(options){return this.activation.getActiveKeys(options)}getCommands(query2){return this.catalog.getCommands(query2)}getCommandEntries(query2){return this.catalog.getCommandEntries(query2)}normalizeCommandName(name){return normalizeCommandName2(name)}normalizeBindings(bindings){return normalizeBindingInputs2(bindings)}acquireResource(key,setup){if(this.cleanedUp||this.host.isDestroyed)throw Error("Cannot use a keymap after its host was destroyed");let existing=this.resources.get(key);if(existing)return existing.count+=1,()=>{this.releaseResource(key,existing)};let resource={count:1,dispose:setup()};return this.resources.set(key,resource),()=>{this.releaseResource(key,resource)}}runCommand(cmd,options){return this.executor.runCommand(cmd,options)}dispatchCommand(cmd,options){return this.executor.dispatchCommand(cmd,options)}on(name,fn){if(name==="warning")return this.events.hook(name,fn);if(name==="error")return this.events.hook(name,fn);return this.hooks.hook(name,fn)}intercept(name,fn,options){if(name==="key")return this.dispatch.intercept(name,fn,options);return this.dispatch.intercept(name,fn,options)}registerLayer(layer){return this.layers.registerLayer(layer)}registerLayerFields(fields){return this.environment.registerLayerFields(fields)}prependBindingTransformer(transformer){return this.environment.prependBindingTransformer(transformer)}appendBindingTransformer(transformer){return this.environment.appendBindingTransformer(transformer)}clearBindingTransformers(){this.environment.clearBindingTransformers()}prependBindingParser(parser){return this.environment.prependBindingParser(parser)}appendBindingParser(parser){return this.environment.appendBindingParser(parser)}clearBindingParsers(){this.environment.clearBindingParsers()}registerToken(token){return this.environment.registerToken(token)}prependBindingExpander(expander){return this.environment.prependBindingExpander(expander)}appendBindingExpander(expander){return this.environment.appendBindingExpander(expander)}clearBindingExpanders(){this.environment.clearBindingExpanders()}registerBindingFields(fields){return this.environment.registerBindingFields(fields)}registerCommandFields(fields){return this.environment.registerCommandFields(fields)}prependCommandResolver(resolver){return this.catalog.prependCommandResolver(resolver)}appendCommandResolver(resolver){return this.catalog.appendCommandResolver(resolver)}clearCommandResolvers(){this.catalog.clearCommandResolvers()}prependLayerAnalyzer(analyzer){return this.layers.prependLayerAnalyzer(analyzer)}appendLayerAnalyzer(analyzer){return this.layers.appendLayerAnalyzer(analyzer)}clearLayerAnalyzers(){this.layers.clearLayerAnalyzers()}prependEventMatchResolver(resolver){return this.dispatch.prependEventMatchResolver(resolver)}appendEventMatchResolver(resolver){return this.dispatch.appendEventMatchResolver(resolver)}clearEventMatchResolvers(){this.dispatch.clearEventMatchResolvers()}prependDisambiguationResolver(resolver){return this.dispatch.prependDisambiguationResolver(resolver)}appendDisambiguationResolver(resolver){return this.dispatch.appendDisambiguationResolver(resolver)}clearDisambiguationResolvers(){this.dispatch.clearDisambiguationResolvers()}handleFocusedTargetChange(_focused){this.notify.runWithStateChangeBatch(()=>{this.activation.setPendingSequence(null),this.activation.invalidateActiveLayers(),this.activation.refreshActiveLayers(_focused),this.notify.queueStateChange()})}warnUnknownField(kind,fieldName){this.notify.warnOnce(`${kind}:${fieldName}`,`unknown-${kind}-field`,{field:fieldName,kind},`[Keymap] Unknown ${kind} field "${fieldName}" was ignored`)}warnUnknownToken(token,sequence){this.notify.warnOnce(`token:${token}`,"unknown-token",{token,sequence},`[Keymap] Unknown token "${token}" in key sequence "${sequence}" was ignored`)}releaseResource(key,resource){if(this.resources.get(key)!==resource)return;if(resource.count-=1,resource.count>0)return;resource.dispose(),this.resources.delete(key)}}function parseObjectKeyInput(ctx,key,display,match,tokenName){return ctx.parseObjectKey(key,{display,match,tokenName})}function isNamedSingleStrokeKey(input,extraNames){let normalized=input.trim().toLowerCase();if(!normalized)return!1;if(namedSingleStrokeKeys.has(normalized))return!0;if(extraNames?.has(normalized))return!0;return/^f\d{1,2}$/i.test(normalized)}function isSingleStrokeString(input,tokens2,normalizeTokenName,extraNames){if(input===" "||input==="+")return!0;if(input.length===1)return!0;if(tokens2.has(normalizeTokenName(input)))return!0;if(input.includes("+"))return!0;return isNamedSingleStrokeKey(input,extraNames)}function parseStringKeyPart(input,ctx){if(input===" ")return ctx.parseObjectKey({name:"space"},{display:"space"});if(input==="+")return ctx.parseObjectKey({name:"+"},{display:"+"});let parts=input.split("+"),name="",displayName="",ctrl=!1,shift=!1,meta=!1,superKey=!1,hyper=!1;for(let rawPart of parts){let part=rawPart.trim();if(!part)continue;let lowered=part.toLowerCase();if(lowered==="ctrl"||lowered==="control"){ctrl=!0;continue}if(lowered==="shift"){shift=!0;continue}if(lowered==="meta"||lowered==="alt"||lowered==="option"){meta=!0;continue}if(lowered==="super"){superKey=!0;continue}if(lowered==="hyper"){hyper=!0;continue}if(name)throw Error(`Invalid key "${input}": multiple key names are not supported`);name=part,displayName=lowered}if(!name)throw Error(`Invalid key "${input}": missing key name`);let displayParts=[];if(ctrl)displayParts.push("ctrl");if(shift)displayParts.push("shift");if(meta)displayParts.push("meta");if(superKey)displayParts.push("super");if(hyper)displayParts.push("hyper");return displayParts.push(displayName),ctx.parseObjectKey({name,ctrl,shift,meta,super:superKey,hyper:hyper||void 0},{display:displayParts.join("+")})}function registerDefaultBindingParser(keymap){return keymap.appendBindingParser(defaultBindingParser)}function registerDefaultEventMatchResolver(keymap){return keymap.appendEventMatchResolver(defaultEventMatchResolver)}function registerDefaultKeys(keymap){let offParser=registerDefaultBindingParser(keymap),offResolver=registerDefaultEventMatchResolver(keymap);return()=>{offResolver(),offParser()}}function isReactiveMatcher22(value){if(!value||typeof value!=="object")return!1;let candidate=value;return typeof candidate.get==="function"&&typeof candidate.subscribe==="function"}function normalizeEnabledValue(fieldName,value){if(typeof value==="boolean")return value;if(typeof value==="function")return value;if(isReactiveMatcher22(value))return value;throw Error(`Keymap enabled field "${fieldName}" must be a boolean, a function, or a reactive matcher`)}function registerEnabledFields(keymap){let offLayerFields=keymap.registerLayerFields({enabled(value,ctx){let normalized=normalizeEnabledValue("enabled",value);if(normalized===!0)return;if(normalized===!1){ctx.activeWhen(()=>!1);return}ctx.activeWhen(normalized)}}),offCommandFields=keymap.registerCommandFields({enabled(value,ctx){let normalized=normalizeEnabledValue("enabled",value);if(normalized===!0)return;if(normalized===!1){ctx.activeWhen(()=>!1);return}ctx.activeWhen(normalized)}});return()=>{offCommandFields(),offLayerFields()}}function normalizeMetadataText(fieldName,value){if(typeof value!=="string")throw Error(`Keymap metadata field "${fieldName}" must be a string`);let trimmed=value.trim();if(!trimmed)throw Error(`Keymap metadata field "${fieldName}" cannot be empty`);return trimmed}function registerMetadataFields(keymap){let offBindingFields=keymap.registerBindingFields({desc(value,ctx){ctx.attr("desc",normalizeMetadataText("desc",value))},group(value,ctx){ctx.attr("group",normalizeMetadataText("group",value))}}),offCommandFields=keymap.registerCommandFields({desc(value,ctx){ctx.attr("desc",normalizeMetadataText("desc",value))},title(value,ctx){ctx.attr("title",normalizeMetadataText("title",value))},category(value,ctx){ctx.attr("category",normalizeMetadataText("category",value))}});return()=>{offCommandFields(),offBindingFields()}}function createSyntheticCommandEvent(){return new KeyEvent({name:"command",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:"",number:!1,raw:"",eventType:"press",source:"raw"})}function createOpenTuiKeymapHost(renderer){return{rootTarget:renderer.root,get isDestroyed(){return renderer.isDestroyed},getFocusedTarget(){let focused=renderer.currentFocusedRenderable;if(!focused||focused.isDestroyed||!focused.focused)return null;return focused},getParentTarget(target){return target.parent},isTargetDestroyed(target){return target.isDestroyed},onKeyPress(listener){return renderer.keyInput.prependListener("keypress",listener),()=>{renderer.keyInput.off("keypress",listener)}},onKeyRelease(listener){return renderer.keyInput.prependListener("keyrelease",listener),()=>{renderer.keyInput.off("keyrelease",listener)}},onFocusChange(listener){return renderer.on(CliRenderEvents.FOCUSED_RENDERABLE,listener),()=>{renderer.off(CliRenderEvents.FOCUSED_RENDERABLE,listener)}},onDestroy(listener){return renderer.once(CliRenderEvents.DESTROY,listener),()=>{renderer.off(CliRenderEvents.DESTROY,listener)}},onTargetDestroy(target,listener){return target.once(RenderableEvents.DESTROYED,listener),()=>{target.off(RenderableEvents.DESTROYED,listener)}},onRawInput(listener){return renderer.prependInputHandler(listener),()=>{renderer.removeInputHandler(listener)}},createCommandEvent(){return createSyntheticCommandEvent()}}}function createOpenTuiKeymap(renderer){if(renderer.isDestroyed)throw Error("Cannot create a keymap for a destroyed renderer");return new Keymap2(createOpenTuiKeymapHost(renderer))}function createDefaultOpenTuiKeymap(renderer){let keymap=createOpenTuiKeymap(renderer);return registerDefaultKeys(keymap),registerEnabledFields(keymap),registerMetadataFields(keymap),keymap}var RESERVED_COMMAND_FIELDS2,RESERVED_BINDING_FIELDS2,RESERVED_LAYER_FIELDS2,DEFAULT_COMMAND_SEARCH_FIELDS2,SNAPSHOT_COMMAND_METADATA_OPTIONS2,SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2,EMPTY_COMMAND_FIELDS2,EMPTY_COMPILE_FIELDS2,EMPTY_REQUIRES2,EMPTY_MATCHERS2,EMPTY_CONDITION_KEYS2,KEY_DISAMBIGUATION_DECISION2,KEY_DEFERRED_DISAMBIGUATION_DECISION2,NOOP3=()=>{},NOOP22=()=>{},MAX_STATE_CHANGE_FLUSH_ITERATIONS2=1000,OrderedRegistry2,PriorityRegistry2,EMPTY_DATA2,namedSingleStrokeKeys,defaultBindingParser=(ctx)=>{let{input,index,tokens:tokens2,normalizeTokenName}=ctx;if(index===0&&isSingleStrokeString(input,tokens2,normalizeTokenName)){if(input===" "||input==="+")return{parts:[parseStringKeyPart(input,ctx)],nextIndex:input.length};let normalizedToken=normalizeTokenName(input),token=tokens2.get(normalizedToken);if(token)return{parts:[parseObjectKeyInput(ctx,token.stroke,normalizedToken,token.match,normalizedToken)],nextIndex:input.length,usedTokens:[normalizedToken]};return{parts:[parseStringKeyPart(input,ctx)],nextIndex:input.length}}let char=input[index];if(char===void 0)return;if(char==="<"){let end=input.indexOf(">",index);if(end===-1)throw Error(`Invalid key sequence "${input}": unterminated token`);let tokenName=normalizeTokenName(input.slice(index,end+1)),token=tokens2.get(tokenName);if(!token)return{parts:[],nextIndex:end+1,unknownTokens:[tokenName]};return{parts:[parseObjectKeyInput(ctx,token.stroke,tokenName,token.match,tokenName)],nextIndex:end+1,usedTokens:[tokenName]}}return{parts:[parseStringKeyPart(char,ctx)],nextIndex:index+1}},defaultEventMatchResolver=(event,ctx)=>{return[ctx.resolveKey({name:event.name,ctrl:event.ctrl,shift:event.shift,meta:event.meta,super:event.super??!1,hyper:event.hyper||void 0})]};var init_opentui=__esm(async()=>{await init_core();RESERVED_COMMAND_FIELDS2=new Set(["name","run"]),RESERVED_BINDING_FIELDS2=new Set(["key","cmd","event","preventDefault","fallthrough"]),RESERVED_LAYER_FIELDS2=new Set(["target","targetMode","priority","bindings","commands"]);DEFAULT_COMMAND_SEARCH_FIELDS2=["name"],SNAPSHOT_COMMAND_METADATA_OPTIONS2=Object.freeze({deep:!0,preserveNonPlainObjects:!0}),SNAPSHOT_FROZEN_COMMAND_METADATA_OPTIONS2=Object.freeze({deep:!0,freeze:!0,preserveNonPlainObjects:!0}),EMPTY_COMMAND_FIELDS2=Object.freeze({});EMPTY_COMPILE_FIELDS2=Object.freeze({}),EMPTY_REQUIRES2=[],EMPTY_MATCHERS2=[],EMPTY_CONDITION_KEYS2=[];KEY_DISAMBIGUATION_DECISION2=Symbol("keymap-disambiguation-decision"),KEY_DEFERRED_DISAMBIGUATION_DECISION2=Symbol("keymap-deferred-disambiguation-decision");OrderedRegistry2=class OrderedRegistry2 extends CopyOnWriteRegistry2{append(value){return this.setItems([...this.getItems(),value]),()=>{this.remove(value)}}prepend(value){return this.setItems([value,...this.getItems()]),()=>{this.remove(value)}}remove(value){return this.removeItem(value)}values(){return this.getItems()}};PriorityRegistry2=class PriorityRegistry2 extends CopyOnWriteRegistry2{order=0;register(listener,options){let registered={...options,listener,order:this.order++};return this.setItems([...this.getItems(),registered].sort((left,right)=>{let priorityDiff=right.priority-left.priority;if(priorityDiff!==0)return priorityDiff;return left.order-right.order})),()=>{this.removeItem(registered)}}entries(){return this.getItems()}};EMPTY_DATA2=Object.freeze({});namedSingleStrokeKeys=new Set(["up","down","left","right","clear","escape","return","linefeed","enter","tab","backspace","delete","insert","home","end","pageup","pagedown","space","lt","gt","plus","minus","equal","comma","period","slash","backslash","semicolon","quote","backquote","leftbracket","rightbracket","capslock","numlock","scrolllock","printscreen","pause","menu","apps","kp0","kp1","kp2","kp3","kp4","kp5","kp6","kp7","kp8","kp9","kpdecimal","kpdivide","kpmultiply","kpminus","kpplus","kpenter","kpequal","kpseparator","kpleft","kpright","kpup","kpdown","kppageup","kppagedown","kphome","kpend","kpinsert","kpdelete","mediaplay","mediapause","mediaplaypause","mediareverse","mediastop","mediafastforward","mediarewind","medianext","mediaprev","mediarecord","volumedown","volumeup","mute","leftshift","leftctrl","leftalt","leftsuper","lefthyper","leftmeta","rightshift","rightctrl","rightalt","rightsuper","righthyper","rightmeta","iso_level3_shift","iso_level5_shift","option","alt","meta","super","hyper","control","ctrl","shift"])});function createTuiKeymap(renderer){let keymap=createDefaultOpenTuiKeymap(renderer);return registerLeader(keymap,{trigger:{name:"space"}}),registerEscapeClearsPendingSequence(keymap),keymap}var init_keymap=__esm(async()=>{init_addons();await init_opentui()});import{spawnSync as spawnSync10}from"child_process";import{existsSync as existsSync76}from"fs";function resolveTuiTmuxConf(){let tuiConf=`${process.env.GENIE_HOME??`${process.env.HOME}/.genie`}/tui-tmux.conf`;return existsSync76(tuiConf)?tuiConf:"/dev/null"}function safeHex(value,fallback){if(!value)return fallback;let trimmed=value.trim();return HEX_COLOR_RE.test(trimmed)?trimmed:fallback}function resolveThemePalette(snapshot){if(snapshot.mode==="dark")return{bg:palette.bg,bgRaised:palette.bgRaised,text:palette.text,textDim:palette.textDim,textMuted:palette.textMuted,border:palette.border,accent:palette.accent,accentDim:palette.accentDim,accentBright:palette.accentBright,warning:palette.warning,info:palette.info};return{...lightPalette,bg:safeHex(snapshot.terminalBackground,lightPalette.bg),text:safeHex(snapshot.terminalForeground,lightPalette.text)}}function flattenTmuxCommands(commands){let args=[];return commands.forEach((command,index)=>{if(index>0)args.push(";");args.push(...command)}),args}function buildTuiTmuxThemeCommands(snapshot){let theme=resolveThemePalette(snapshot),terminalForeground=safeHex(snapshot.terminalForeground,theme.text),terminalBackground=safeHex(snapshot.terminalBackground,theme.bg);return flattenTmuxCommands([["set-environment","-g","GENIE_TUI_THEME_MODE",snapshot.mode],["set-environment","-g","GENIE_TUI_TERMINAL_FG",terminalForeground],["set-environment","-g","GENIE_TUI_TERMINAL_BG",terminalBackground],["set-environment","-g","GENIE_TUI_TMUX_BG",theme.bg],["set-environment","-g","GENIE_TUI_TMUX_TEXT",theme.text],["set-environment","-g","GENIE_TUI_TMUX_ACCENT",theme.accent],["set-option","-g","pane-border-style",`fg=${theme.border}`],["set-option","-g","pane-active-border-style",`fg=${theme.accent}`],["set-option","-g","message-style",`bg=${theme.bgRaised},fg=${theme.info}`],["set-option","-g","message-command-style",`bg=${theme.bgRaised},fg=${theme.warning}`],["set-option","-g","status-style",`bg=${theme.bg},fg=${theme.text}`],["set-window-option","-g","mode-style",`bg=${theme.accent},fg=${theme.bg}`],["set-window-option","-g","clock-mode-colour",theme.accent]])}function syncTuiTmuxTheme(snapshot,deps={}){let run=deps.spawnSync??spawnSync10,tmux=deps.tmuxBin??tmuxBin(),socketName=deps.socketName??TUI_TMUX_SOCKET,configPath2=deps.configPath??resolveTuiTmuxConf(),timeoutMs=deps.timeoutMs??DEFAULT_TMUX_SYNC_TIMEOUT_MS;return run(tmux,["-L",socketName,"-f",configPath2,...buildTuiTmuxThemeCommands(snapshot)],{stdio:"ignore",timeout:timeoutMs}).status===0}var TUI_TMUX_SOCKET="genie-tui",DEFAULT_TMUX_SYNC_TIMEOUT_MS=300,HEX_COLOR_RE,lightPalette;var init_tmux_theme_sync=__esm(()=>{init_ensure_tmux();init_theme2();HEX_COLOR_RE=/^#[0-9a-f]{6}$/i,lightPalette={bg:"#f5efe4",bgRaised:"#ebe3d7",text:"#24323a",textDim:"#56656d",textMuted:"#718087",border:"#c8bdae",accent:"#2f7a62",accentDim:"#3e9277",accentBright:"#17694f",warning:"#9a651e",info:"#406f8b"}});function readBool(env2,name,fallback){let raw=env2[name];if(!raw)return fallback;let normalized=raw.trim().toLowerCase();if(TRUTHY3.has(normalized))return!0;if(FALSY.has(normalized))return!1;return fallback}function readPositiveInt(env2,name,fallback){let raw=env2[name];if(!raw)return fallback;let parsed=Number.parseInt(raw,10);return Number.isFinite(parsed)&&parsed>0?parsed:fallback}function inferThemeMode(background){if(!background||!/^#[0-9a-f]{6}$/i.test(background))return null;let r=Number.parseInt(background.slice(1,3),16),g2=Number.parseInt(background.slice(3,5),16),b3=Number.parseInt(background.slice(5,7),16);return(0.2126*r+0.7152*g2+0.0722*b3)/255>=0.5?"light":"dark"}function snapshotKey(snapshot){return[snapshot.mode,snapshot.terminalForeground??"",snapshot.terminalBackground??""].join("|")}function buildSnapshot(mode,colors8){let resolvedMode=mode??inferThemeMode(colors8?.defaultBackground);if(!resolvedMode)return null;return{mode:resolvedMode,terminalForeground:colors8?.defaultForeground,terminalBackground:colors8?.defaultBackground}}function installOpenTui20Bridge(renderer,options={}){let env2=options.env??process.env;if(!readBool(env2,"GENIE_TUI_TMUX_THEME_SYNC",!0))return()=>{};let syncTheme=options.syncTheme??syncTuiTmuxTheme,themeQueryTimeoutMs=readPositiveInt(env2,"GENIE_TUI_THEME_QUERY_TIMEOUT_MS",DEFAULT_THEME_QUERY_TIMEOUT_MS),tmuxApplyTimeoutMs=readPositiveInt(env2,"GENIE_TUI_TMUX_THEME_SYNC_TIMEOUT_MS",DEFAULT_TMUX_APPLY_TIMEOUT_MS),disposed=!1,lastSnapshot="",syncSnapshot=(snapshot)=>{if(disposed||!snapshot)return;let key=snapshotKey(snapshot);if(key===lastSnapshot)return;lastSnapshot=key;try{syncTheme(snapshot,{timeoutMs:tmuxApplyTimeoutMs})}catch{}},syncFromMode=(mode,colors8)=>{syncSnapshot(buildSnapshot(mode,colors8))},onThemeMode=(mode)=>syncFromMode(mode);renderer.on("theme_mode",onThemeMode),syncFromMode(renderer.themeMode),renderer.waitForThemeMode(themeQueryTimeoutMs).then((mode)=>syncFromMode(mode)).catch(()=>{});let paletteOptions={size:OPEN_TUI_02_PALETTE_SIZE,timeout:themeQueryTimeoutMs};return renderer.getPalette(paletteOptions).then((colors8)=>syncFromMode(renderer.themeMode,colors8)).catch(()=>{}),()=>{disposed=!0,renderer.off("theme_mode",onThemeMode)}}var TRUTHY3,FALSY,DEFAULT_THEME_QUERY_TIMEOUT_MS=700,DEFAULT_TMUX_APPLY_TIMEOUT_MS=300,OPEN_TUI_02_PALETTE_SIZE=16;var init_opentui_bridge=__esm(()=>{init_tmux_theme_sync();TRUTHY3=new Set(["1","true","yes","on"]),FALSY=new Set(["0","false","no","off"])});var exports_render={};__export(exports_render,{resolveTuiRendererConfig:()=>resolveTuiRendererConfig,renderNav:()=>renderNav});function readBool2(env2,name,fallback){let raw=env2[name];if(!raw)return fallback;let normalized=raw.trim().toLowerCase();if(TRUTHY4.has(normalized))return!0;if(FALSY2.has(normalized))return!1;return fallback}function readPositiveInt2(env2,name){let raw=env2[name];if(!raw)return;let parsed=Number.parseInt(raw,10);return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveTuiRendererConfig(env2=process.env,platform2=process.platform){let isDarwin=platform2==="darwin",targetFps=readPositiveInt2(env2,"GENIE_TUI_TARGET_FPS")??(isDarwin?8:30),configuredMaxFps=readPositiveInt2(env2,"GENIE_TUI_MAX_FPS")??(isDarwin?12:60),maxFps=Math.max(configuredMaxFps,targetFps),useMouse=readBool2(env2,"GENIE_TUI_MOUSE",!0),enableMouseMovement=useMouse&&readBool2(env2,"GENIE_TUI_MOUSE_MOVEMENT",!isDarwin),consoleEnabled=readBool2(env2,"GENIE_TUI_CONSOLE",!0),kittyKeyboardOptIn=readBool2(env2,"GENIE_TUI_KITTY_KEYBOARD",!isDarwin);return{exitOnCtrlC:!1,useThread:!isDarwin,targetFps,maxFps,useMouse,enableMouseMovement,useKittyKeyboard:kittyKeyboardOptIn?void 0:null,consoleMode:consoleEnabled?void 0:"disabled",openConsoleOnError:consoleEnabled&&!isDarwin}}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(resolveTuiRendererConfig()),disposeOpenTui20Bridge=installOpenTui20Bridge(renderer),keymap=createTuiKeymap(renderer);createRoot(renderer).render(import_jsx_dev_runtime2.jsxDEV(KeymapProvider,{keymap,children:import_jsx_dev_runtime2.jsxDEV(App,{rightPane,workspaceRoot,initialAgent},void 0,!1,void 0,this)},void 0,!1,void 0,this)),await new Promise((resolve21)=>{renderer.once("destroy",()=>{disposeOpenTui20Bridge(),resolve21()})})}var TRUTHY4,FALSY2;var init_render=__esm(async()=>{init_react();init_opentui_bridge();init_jsx_dev_runtime();await __promiseAll([init_core(),init_react2(),init_app(),init_keymap()]);TRUTHY4=new Set(["1","true","yes","on"]),FALSY2=new Set(["0","false","no","off"])});var exports_tui={};__export(exports_tui,{launchTui:()=>launchTui});import{appendFileSync as appendFileSync5,closeSync as closeSync6,mkdirSync as mkdirSync35,openSync as openSync6,readSync as readSync3,statSync as statSync16}from"fs";import{homedir as homedir51}from"os";import{join as join93}from"path";function genieHome6(){return process.env.GENIE_HOME??join93(homedir51(),".genie")}function extractPreviousRunCrashOutput(logPath){let fd=null;try{let size=statSync16(logPath).size;if(size===0)return"";let readSize=Math.min(size,TUI_CRASH_LOG_RECOVERY_MAX_BYTES);fd=openSync6(logPath,"r");let buffer2=Buffer.alloc(readSize);readSync3(fd,buffer2,0,readSize,size-readSize);let text=buffer2.toString("utf-8"),lastBannerIndex=text.lastIndexOf(TUI_CRASH_LOG_BANNER_PREFIX);if(lastBannerIndex<0)return"";let afterBannerNewline=text.indexOf(`
|
|
3962
3965
|
`,lastBannerIndex);if(afterBannerNewline<0)return"";return text.slice(afterBannerNewline+1).trim()}catch{return""}finally{if(fd!==null)try{closeSync6(fd)}catch{}}}async function ingestPreviousRunCrash(logPath){let body=extractPreviousRunCrashOutput(logPath);if(!body)return;let truncated=body.length>TUI_CRASH_LOG_RECOVERY_MAX_MSG_CHARS?`${body.slice(0,TUI_CRASH_LOG_RECOVERY_MAX_MSG_CHARS)}
|
|
3963
|
-
\u2026[truncated]`:body;try{let{emitEvent:emitEvent2}=await Promise.resolve().then(() => (init_emit(),exports_emit));emitEvent2("error.raised",{error_class:"TuiCrash",message:truncated,subsystem:"tui",severity:"error",retryable:!0})}catch{}}async function recordTuiLaunchBreadcrumb(){try{let logsDir=join93(genieHome6(),"logs");
|
|
3966
|
+
\u2026[truncated]`:body;try{let{emitEvent:emitEvent2}=await Promise.resolve().then(() => (init_emit(),exports_emit));emitEvent2("error.raised",{error_class:"TuiCrash",message:truncated,subsystem:"tui",severity:"error",retryable:!0})}catch{}}async function recordTuiLaunchBreadcrumb(){try{let logsDir=join93(genieHome6(),"logs");mkdirSync35(logsDir,{recursive:!0});let logPath=join93(logsDir,"tui-crash.log");await ingestPreviousRunCrash(logPath);let ts3=new Date().toISOString(),line=`${TUI_CRASH_LOG_BANNER_PREFIX}${ts3} pid=${process.pid} platform=${process.platform} arch=${process.arch} ---
|
|
3964
3967
|
`;appendFileSync5(logPath,line,{mode:420})}catch{}}function installTuiExitSignals(){let exitOnSignal=(signal)=>{process.exit(signal==="SIGHUP"?0:128+(signal==="SIGINT"?2:15))};process.on("SIGHUP",exitOnSignal),process.on("SIGINT",exitOnSignal),process.on("SIGTERM",exitOnSignal)}async function launchTui(){installTuiExitSignals(),await recordTuiLaunchBreadcrumb();let{renderNav:renderNav2}=await init_render().then(() => exports_render);await renderNav2()}var TUI_CRASH_LOG_BANNER_PREFIX="--- tui-launch ",TUI_CRASH_LOG_RECOVERY_MAX_BYTES=65536,TUI_CRASH_LOG_RECOVERY_MAX_MSG_CHARS=3000;var init_tui=()=>{};var exports_resolve_agent_cwd={};__export(exports_resolve_agent_cwd,{resolveAgentFromCwd:()=>resolveAgentFromCwd});import{existsSync as existsSync77}from"fs";import{basename as basename16,dirname as dirname34,join as join94,relative as relative10,sep as sep3}from"path";function isRelativeWithin(rel,original){return!rel.startsWith("..")&&rel!==original}function resolveFromCanonicalDir(cwd,agentsDir){let relToAgents=relative10(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(!existsSync77(join94(agentsDir,agentName,"AGENTS.md")))return null;let source=segments.length===1?"exact":"parent";return{agent:agentName,source}}function resolveFromWalkUp(cwd,workspaceRoot){let wsRel=relative10(workspaceRoot,cwd);if(!isRelativeWithin(wsRel,cwd))return null;let current=cwd;while(current!==workspaceRoot&¤t!==dirname34(current)){if(existsSync77(join94(current,"AGENTS.md")))return{agent:basename16(current),source:"parent"};current=dirname34(current)}return null}function resolveAgentFromCwd(cwd,workspaceRoot){return resolveFromCanonicalDir(cwd,join94(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_doctor();import{execFileSync as execFileSync2,spawnSync as spawnSync2}from"child_process";import{existsSync as existsSync21,mkdirSync as mkdirSync11,writeFileSync as writeFileSync8}from"fs";import{homedir as homedir21}from"os";import{join as join26}from"path";var PM2_PROCESS_NAME="genie-serve",HARDENED_DEFAULTS={maxRestarts:50,minUptimeMs:1e4,restartDelayMs:4000,expBackoffRestartDelayMs:100,maxMemory:process.env.GENIE_SERVE_MAX_MEMORY||"4G",killTimeoutMs:60000,logDateFormat:"YYYY-MM-DD HH:mm:ss.SSS"};function getLogsDir(){return join26(homedir21(),".genie","logs")}function ok(msg){process.stdout.write(`genie install: ${msg}
|
|
3965
3968
|
`)}function fail(msg){process.stderr.write(`genie install: ${msg}
|
|
3966
3969
|
`),process.exit(1)}function which(cmd){try{return execFileSync2("which",[cmd],{encoding:"utf8",timeout:3000,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function pm2GetProcess(name){try{let out=execFileSync2("pm2",["jlist"],{encoding:"utf8",timeout:5000,stdio:["ignore","pipe","ignore"]});return JSON.parse(out).find((p)=>p.name===name)??null}catch{return null}}function pm2IsAvailable(){try{return execFileSync2("pm2",["--version"],{encoding:"utf8",timeout:3000,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}}function pgserveIsAvailable(){return which("pgserve")!==null}function buildCanonicalPgserveHint(reason){return[`Error: canonical pgserve registration failed (${reason}).`,"Genie depends on pm2-supervised pgserve. To proceed:"," bun add -g pgserve@^2"," pgserve install"," genie install","See https://github.com/automagik-dev/genie/blob/main/docs/install.md for details.",""].join(`
|
|
@@ -4319,8 +4322,8 @@ Done. ${results.length} migration${results.length===1?"":"s"} applied.`),await s
|
|
|
4319
4322
|
`,count=Number(rows[0].cnt);console.log(`Would delete ${count} event${count===1?"":"s"} older than ${options.olderThan}.`)}else{let result2=await sql`
|
|
4320
4323
|
DELETE FROM genie_runtime_events
|
|
4321
4324
|
WHERE created_at < now() - make_interval(secs => ${intervalSec})
|
|
4322
|
-
`,count=Number(result2.count);console.log(`Deleted ${count} event${count===1?"":"s"} older than ${options.olderThan}.`)}await shutdown()}catch(err){let message=err instanceof Error?err.message:String(err);console.error(`Prune failed: ${message}`),process.exit(1)}}function registerDbCommands(program2){let db=program2.command("db").description("Database management (pgserve)");db.command("status").description("Show pgserve health, port, data dir, and table counts").action(dbStatusCommand),db.command("migrate").description("Run pending database migrations").action(dbMigrateCommand),db.command("query <sql>").description("Execute arbitrary SQL and print results").action(dbQueryCommand),db.command("url").description("Print postgres connection URL for direct access").option("--quiet","Print URL only, no trailing newline (for scripts)").action(async(options)=>{await isAvailable();let url;if(isSocketMode())url=`postgresql:///postgres?host=${resolvePgserveSocketDir()}`;else url=`postgres://postgres:postgres@127.0.0.1:${getActivePort()}/genie`;if(options.quiet)process.stdout.write(url);else console.log(url);await shutdown()}),db.command("prune-events").description("Prune old runtime events beyond retention period").option("--older-than <duration>","Delete events older than (e.g., 30d, 7d)","14d").option("--dry-run","Show count without deleting").action(dbPruneEventsCommand),db.command("backup").description("Dump database to .genie/snapshot.sql.gz").action(dbBackupCommand),db.command("restore [file]").description("Restore database from snapshot (default: .genie/snapshot.sql.gz)").option("-y, --yes","Skip confirmation prompt").action(dbRestoreCommand),registerDbMigrateV1Command(db),registerDbLsCommand(db)}init_dispatch();function registerDispatchGroupCommands(program2){let dispatch3=program2.command("dispatch").description("Framework skill dispatch primitives (brainstorm/wish/review)");dispatch3.command("brainstorm <agent> <slug>").description("Spawn agent with brainstorm DRAFT.md context").action(async(agent,slug)=>{await brainstormCommand(agent,slug)}),dispatch3.command("wish <agent> <slug>").description("Spawn agent with wish DESIGN.md context").action(async(agent,slug)=>{await wishCommand(agent,slug)}),dispatch3.command("review <agent> <ref>").description("Spawn agent with review scope for a wish group (format: <slug>#<group>)").action(async(agent,ref)=>{await reviewCommand(agent,ref)})}init_dispatch();init_export_format();import{existsSync as existsSync65,mkdirSync as
|
|
4323
|
-
`);let tables=Object.keys(doc.data),rows=Object.values(doc.data).reduce((sum,arr)=>sum+arr.length,0);if(console.log(`Exported ${tables.length} tables (${rows} rows) to ${options.output}`),doc.skippedTables.length>0)console.log(`Skipped tables (not found): ${doc.skippedTables.join(", ")}`)}else console.log(json2)}function autoOutputName(){let d=new Date;return`genie-backup-${`${d.getFullYear()}${String(d.getMonth()+1).padStart(2,"0")}${String(d.getDate()).padStart(2,"0")}`}.json`}async function exportGroup(sql,group,filter){let tables=GROUP_TABLES[group],{available,skipped}=await detectTables(sql,tables),data={};for(let table of available)if(filter)data[table]=[...await sql.unsafe(`SELECT * FROM ${table} WHERE ${filter.column} = $1`,[filter.value])];else data[table]=[...await sql.unsafe(`SELECT * FROM ${table}`)];return{data,skipped}}async function exportBoards(sql,name){let tables=GROUP_TABLES.boards,{available,skipped}=await detectTables(sql,tables),data={};for(let table of available)if(name&&table==="boards")data[table]=[...await sql`SELECT * FROM boards WHERE name = ${name}`];else if(table==="task_types")data[table]=[...await sql`SELECT * FROM task_types WHERE is_builtin = false`];else data[table]=[...await sql.unsafe(`SELECT * FROM ${table}`)];return{data,skipped}}var TASK_JOIN_ALIASES={task_tags:"tt",task_actors:"ta",task_dependencies:"td",task_stage_log:"tsl"};async function resolveProjectId2(sql,projectName){let projects=await sql`SELECT id FROM projects WHERE name = ${projectName}`;if(projects.length===0)throw Error(`Project not found: ${projectName}`);return projects[0].id}function stripEphemeralFields(rows){return rows.map((r)=>{let{checkout_run_id,execution_locked_at,session_id,pane_id,...rest}=r;return rest})}async function exportTaskTable(sql,table,projectId){let alias=TASK_JOIN_ALIASES[table];if(table==="tasks"){let rows=projectId?[...await sql.unsafe("SELECT * FROM tasks WHERE project_id = $1",[projectId])]:[...await sql`SELECT * FROM tasks`];return stripEphemeralFields(rows)}if(alias&&projectId)return[...await sql.unsafe(`SELECT ${alias}.* FROM ${table} ${alias} JOIN tasks t ON ${alias}.task_id = t.id WHERE t.project_id = $1`,[projectId])];return[...await sql.unsafe(`SELECT * FROM ${table}`)]}async function exportTasks(sql,projectName){let tables=GROUP_TABLES.tasks,{available,skipped}=await detectTables(sql,tables),data={},projectId=projectName?await resolveProjectId2(sql,projectName):null;for(let table of available)data[table]=await exportTaskTable(sql,table,projectId);return{data,skipped}}async function exportSchedules(sql,name){let{available,skipped}=await detectTables(sql,["schedules"]),data={};if(available.includes("schedules"))if(name)data.schedules=[...await sql`SELECT * FROM schedules WHERE name = ${name}`];else data.schedules=[...await sql`SELECT * FROM schedules`];return{data,skipped}}async function exportTags(sql){let{available,skipped}=await detectTables(sql,["tags"]),data={};if(available.includes("tags"))data.tags=[...await sql`SELECT * FROM tags WHERE name NOT LIKE 'test-%'`];return{data,skipped}}async function exportAll(sql){let allSkipped=[],allData={};for(let group of ALL_GROUPS){let result2;switch(group){case"boards":result2=await exportBoards(sql);break;case"tasks":result2=await exportTasks(sql);break;case"tags":result2=await exportTags(sql);break;case"schedules":result2=await exportSchedules(sql);break;default:result2=await exportGroup(sql,group);break}Object.assign(allData,result2.data),allSkipped.push(...result2.skipped)}return{data:allData,skipped:allSkipped}}async function runExport(groups,type2,exportFn,options){let sql=await getSql(),[version,actor]=await Promise.all([getVersion(),getActorName()]),doc=createExportDocument(type2,groups,version,actor),{data,skipped}=await exportFn(sql);doc.data=data,doc.skippedTables=skipped,outputDocument(doc,options)}function registerExportCommands(program2){let exp=program2.command("export").description("Export genie data as JSON").option("--output <file>","Write to file instead of stdout").option("-o <file>","Alias for --output").option("--pretty","Pretty-print JSON").action(async(options)=>{try{if(!options.output)options.output=autoOutputName();await runExport([...ALL_GROUPS],"full",(sql)=>exportAll(sql),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts=(cmd)=>cmd.option("--output <file>","Write to file instead of stdout").option("--pretty","Pretty-print JSON");sharedOpts(exp.command("all").description("Full backup (all present tables)")).action(async(options)=>{try{if(!options.output)options.output=autoOutputName();await runExport([...ALL_GROUPS],"full",(sql)=>exportAll(sql),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("boards [name]").description("Export boards, templates, and task types")).action(async(name,options)=>{try{await runExport(["boards"],"partial",(sql)=>exportBoards(sql,name),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("tasks").description("Export tasks with deps, actors, and stage log").option("--project <name>","Filter by project name")).action(async(options)=>{try{await runExport(["tasks"],"partial",(sql)=>exportTasks(sql,options.project),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("tags").description("Export tags")).action(async(options)=>{try{await runExport(["tags"],"partial",(sql)=>exportTags(sql),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("projects").description("Export projects")).action(async(options)=>{try{await runExport(["projects"],"partial",(sql)=>exportGroup(sql,"projects"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("schedules [name]").description("Export schedules with run_spec")).action(async(name,options)=>{try{await runExport(["schedules"],"partial",(sql)=>exportSchedules(sql,name),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("agents").description("Export agents, templates, and checkpoints")).action(async(options)=>{try{await runExport(["agents"],"partial",(sql)=>exportGroup(sql,"agents"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("comms").description("Export conversations, messages, mailbox")).action(async(options)=>{try{await runExport(["comms"],"partial",(sql)=>exportGroup(sql,"comms"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("config").description("Export OS config (graceful skip if missing)")).action(async(options)=>{try{await runExport(["config"],"partial",(sql)=>exportGroup(sql,"config"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_history();init_export_format();import{readFileSync as readFileSync41}from"fs";var IMPORT_LEVELS=[["schedules","sessions","projects","agent_templates","agent_checkpoints","tags","task_types","notification_preferences","os_config","golden_images","warm_pool","instances"],["triggers","boards","board_templates","agents","conversations"],["tasks","runs","messages","conversation_members","mailbox","team_chat"],["task_tags","task_actors","task_dependencies","task_stage_log","heartbeats","machine_snapshots"]],SELF_REFERENTIAL_COLUMNS={tasks:"parent_id",messages:"reply_to_id",conversations:"parent_message_id"};function getTableLevel(table){for(let i2=0;i2<IMPORT_LEVELS.length;i2++)if(IMPORT_LEVELS[i2].includes(table))return i2;return-1}function sortByImportOrder(tables){return[...tables].sort((a,b2)=>{let la=getTableLevel(a),lb=getTableLevel(b2);return(la===-1?999:la)-(lb===-1?999:lb)})}function getPrimaryKey(table){return{task_tags:["task_id","tag_id"],task_actors:["task_id","actor_type","actor_id","role"],task_dependencies:["task_id","depends_on_id"],conversation_members:["conversation_id","actor_type","actor_id"],notification_preferences:["actor_type","actor_id","channel"]}[table]??["id"]}var VALID_TABLES=new Set(Object.values(GROUP_TABLES).flat());function assertValidTable(name){if(!VALID_TABLES.has(name))throw Error(`Invalid table name: "${name}" is not in the schema whitelist`)}var VALID_COLUMN_RE=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function assertValidColumnName(name){if(!VALID_COLUMN_RE.test(name))throw Error(`Invalid column name: "${name.slice(0,60)}" contains disallowed characters. Column names must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`)}async function getSql2(){let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return getConnection2()}async function getActorName2(){let{getActor:getActor2}=await Promise.resolve().then(() => (init_audit(),exports_audit));return getActor2()}async function detectTables2(sql,tables){let{filterAvailableTables:filterAvailableTables2}=await Promise.resolve().then(() => exports_table_detect);return filterAvailableTables2(sql,tables)}async function detectConflicts(sql,table,rows){if(rows.length===0)return[];assertValidTable(table);let pk=getPrimaryKey(table);if(pk.length===1){let key=pk[0],ids=rows.map((r)=>r[key]),existing=await sql.unsafe(`SELECT ${key} FROM ${table} WHERE ${key} = ANY($1)`,[ids]),existingSet=new Set(existing.map((r)=>String(r[key])));return rows.filter((r)=>existingSet.has(String(r[key])))}let conflicts=[];for(let row2 of rows){let conditions=pk.map((col,i2)=>`${col} = $${i2+1}`).join(" AND "),values2=pk.map((col)=>row2[col]);if((await sql.unsafe(`SELECT 1 FROM ${table} WHERE ${conditions} LIMIT 1`,values2)).length>0)conflicts.push(row2)}return conflicts}function prepareRow(row2,table,selfRefUpdates){let selfRefCol=SELF_REFERENTIAL_COLUMNS[table],entries=Object.entries(row2),columns=entries.map(([k])=>k),values2=entries.map(([,v])=>v);for(let col of columns)assertValidColumnName(col);if(selfRefCol&&row2[selfRefCol]!=null){let idx=columns.indexOf(selfRefCol);if(idx!==-1){let originalSelfRef=values2[idx];values2[idx]=null;let pk=getPrimaryKey(table);selfRefUpdates.push({pk:pk.length===1?row2[pk[0]]:pk.map((k)=>row2[k]),value:originalSelfRef})}}return{columns,values:values2,quotedCols:columns.map((c)=>`"${c}"`).join(", "),placeholders:values2.map((_,i2)=>`$${i2+1}`).join(", ")}}async function insertOneRow(tx,table,row2,prepared,mode){assertValidTable(table);let{quotedCols,placeholders,values:values2}=prepared,pk=getPrimaryKey(table);if(mode==="overwrite"){let pkCondition=pk.map((col,i2)=>`"${col}" = $${values2.length+i2+1}`).join(" AND "),pkValues=pk.map((col)=>row2[col]);await tx.unsafe(`DELETE FROM ${table} WHERE ${pkCondition}`,pkValues),await tx.unsafe(`INSERT INTO ${table} (${quotedCols}) VALUES (${placeholders})`,values2)}else if(mode==="merge"){let onConflict=pk.map((c)=>`"${c}"`).join(", ");await tx.unsafe(`INSERT INTO ${table} (${quotedCols}) VALUES (${placeholders}) ON CONFLICT (${onConflict}) DO NOTHING`,values2)}else await tx.unsafe(`INSERT INTO ${table} (${quotedCols}) VALUES (${placeholders})`,values2)}async function updateSelfRefs(tx,table,updates){assertValidTable(table);let selfRefCol=SELF_REFERENTIAL_COLUMNS[table],pk=getPrimaryKey(table);if(pk.length!==1)return;for(let{pk:pkVal,value}of updates)await tx.unsafe(`UPDATE ${table} SET "${selfRefCol}" = $1 WHERE "${pk[0]}" = $2`,[value,pkVal])}async function insertRows(tx,table,rows,mode){if(rows.length===0)return 0;let selfRefUpdates=[];for(let row2 of rows){let prepared=prepareRow(row2,table,selfRefUpdates);await insertOneRow(tx,table,row2,prepared,mode)}if(selfRefUpdates.length>0)await updateSelfRefs(tx,table,selfRefUpdates);return rows.length}function parseExportFile(filePath){let raw=readFileSync41(filePath,"utf-8"),parsed;try{parsed=JSON.parse(raw)}catch{throw Error(`Invalid JSON in ${filePath}`)}let validation=validateExportDocument(parsed);if(!validation.valid)throw Error(`Invalid export document: ${validation.error}`);return validation.doc}async function filterTablesByGroup(allTables,groupFilter){if(!groupFilter||groupFilter.length===0)return allTables;let{GROUP_TABLES:GROUP_TABLES2}=await Promise.resolve().then(() => (init_export_format(),exports_export_format)),allowedTables=new Set;for(let group of groupFilter){let tables=GROUP_TABLES2[group];if(tables)for(let t of tables)allowedTables.add(t);else console.warn(`Warning: Unknown group "${group}", skipping`)}return allTables.filter((t)=>allowedTables.has(t))}async function checkConflicts(sql,tables,data){for(let table of tables){let rows=data[table];if(!rows||rows.length===0)continue;let conflicts=await detectConflicts(sql,table,rows);if(conflicts.length>0){let pk=getPrimaryKey(table),ids=conflicts.slice(0,5).map((r)=>pk.map((k)=>r[k]).join(",")).join("; ");throw Error(`Conflict in table "${table}": ${conflicts.length} existing row(s) (e.g., ${ids}). Use --merge or --overwrite to resolve.`)}}}async function runImport(filePath,mode,groupFilter){let doc=parseExportFile(filePath),tablesToImport=await filterTablesByGroup(Object.keys(doc.data),groupFilter);if(tablesToImport.length===0){console.log("No tables to import.");return}tablesToImport=sortByImportOrder(tablesToImport);let sql=await getSql2(),{available}=await detectTables2(sql,tablesToImport),skippedTables=tablesToImport.filter((t)=>!available.includes(t));if(tablesToImport=available,skippedTables.length>0)console.log(`Skipping tables not in database: ${skippedTables.join(", ")}`);if(mode==="fail")await checkConflicts(sql,tablesToImport,doc.data);let totalInserted=0,tableStats={};await sql.begin(async(tx)=>{for(let table of tablesToImport){let rows=doc.data[table];if(!rows||rows.length===0)continue;let count=await insertRows(tx,table,rows,mode);tableStats[table]=count,totalInserted+=count}});let actor=await getActorName2(),{recordAuditEvent:recordAuditEvent3}=await Promise.resolve().then(() => (init_audit(),exports_audit));await recordAuditEvent3("import",filePath,"import_complete",actor,{mode,tables:tableStats,totalRows:totalInserted,skippedTables,sourceVersion:doc.version,sourceDate:doc.exportedAt}),console.log(`Import complete: ${totalInserted} rows across ${Object.keys(tableStats).length} tables`);for(let[table,count]of Object.entries(tableStats))if(count>0)console.log(` ${table}: ${count} rows`);if(skippedTables.length>0)console.log(`Skipped (not in DB): ${skippedTables.join(", ")}`)}function registerImportCommands(program2){program2.command("import <file>").description("Import genie data from JSON export").option("--fail","Abort on any conflict (default)").option("--merge","Skip existing rows, import new ones").option("--overwrite","Replace existing rows with imported data").option("--groups <list>","Comma-separated groups to import (e.g., boards,tags)").action(async(file,options)=>{try{let mode="fail";if(options.overwrite)mode="overwrite";else if(options.merge)mode="merge";let groupFilter=options.groups?.split(",").map((g)=>g.trim());await runImport(file,mode,groupFilter)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_esm14();import{existsSync as existsSync69,mkdirSync as mkdirSync32,symlinkSync,writeFileSync as writeFileSync31}from"fs";import{basename as basename12,join as join81,relative as relative7,resolve as resolve15,sep as sep2}from"path";import{cpSync,existsSync as existsSync67,mkdirSync as mkdirSync30,renameSync as renameSync11,rmSync as rmSync4}from"fs";import{join as join78,relative as relative6}from"path";var import_ignore=__toESM(require_ignore(),1);import{existsSync as existsSync66,readFileSync as readFileSync42,readdirSync as readdirSync14,statSync as statSync14}from"fs";import{join as join77,relative as relative5}from"path";var GENIEIGNORE_DEFAULTS=`node_modules
|
|
4325
|
+
`,count=Number(result2.count);console.log(`Deleted ${count} event${count===1?"":"s"} older than ${options.olderThan}.`)}await shutdown()}catch(err){let message=err instanceof Error?err.message:String(err);console.error(`Prune failed: ${message}`),process.exit(1)}}function registerDbCommands(program2){let db=program2.command("db").description("Database management (pgserve)");db.command("status").description("Show pgserve health, port, data dir, and table counts").action(dbStatusCommand),db.command("migrate").description("Run pending database migrations").action(dbMigrateCommand),db.command("query <sql>").description("Execute arbitrary SQL and print results").action(dbQueryCommand),db.command("url").description("Print postgres connection URL for direct access").option("--quiet","Print URL only, no trailing newline (for scripts)").action(async(options)=>{await isAvailable();let url;if(isSocketMode())url=`postgresql:///postgres?host=${resolvePgserveSocketDir()}`;else url=`postgres://postgres:postgres@127.0.0.1:${getActivePort()}/genie`;if(options.quiet)process.stdout.write(url);else console.log(url);await shutdown()}),db.command("prune-events").description("Prune old runtime events beyond retention period").option("--older-than <duration>","Delete events older than (e.g., 30d, 7d)","14d").option("--dry-run","Show count without deleting").action(dbPruneEventsCommand),db.command("backup").description("Dump database to .genie/snapshot.sql.gz").action(dbBackupCommand),db.command("restore [file]").description("Restore database from snapshot (default: .genie/snapshot.sql.gz)").option("-y, --yes","Skip confirmation prompt").action(dbRestoreCommand),registerDbMigrateV1Command(db),registerDbLsCommand(db)}init_dispatch();function registerDispatchGroupCommands(program2){let dispatch3=program2.command("dispatch").description("Framework skill dispatch primitives (brainstorm/wish/review)");dispatch3.command("brainstorm <agent> <slug>").description("Spawn agent with brainstorm DRAFT.md context").action(async(agent,slug)=>{await brainstormCommand(agent,slug)}),dispatch3.command("wish <agent> <slug>").description("Spawn agent with wish DESIGN.md context").action(async(agent,slug)=>{await wishCommand(agent,slug)}),dispatch3.command("review <agent> <ref>").description("Spawn agent with review scope for a wish group (format: <slug>#<group>)").action(async(agent,ref)=>{await reviewCommand(agent,ref)})}init_dispatch();init_export_format();import{existsSync as existsSync65,mkdirSync as mkdirSync30,writeFileSync as writeFileSync28}from"fs";import{dirname as dirname26}from"path";async function getSql(){let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return getConnection2()}async function getVersion(){let{VERSION:VERSION2}=await Promise.resolve().then(() => (init_version(),exports_version));return VERSION2}async function getActorName(){let{getActor:getActor2}=await Promise.resolve().then(() => (init_audit(),exports_audit));return getActor2()}async function detectTables(sql,tables){let{filterAvailableTables:filterAvailableTables2}=await Promise.resolve().then(() => exports_table_detect);return filterAvailableTables2(sql,tables)}function outputDocument(doc,options){let json2=options.pretty?JSON.stringify(doc,null,2):JSON.stringify(doc);if(options.output){let dir=dirname26(options.output);if(!existsSync65(dir))mkdirSync30(dir,{recursive:!0});writeFileSync28(options.output,`${json2}
|
|
4326
|
+
`);let tables=Object.keys(doc.data),rows=Object.values(doc.data).reduce((sum,arr)=>sum+arr.length,0);if(console.log(`Exported ${tables.length} tables (${rows} rows) to ${options.output}`),doc.skippedTables.length>0)console.log(`Skipped tables (not found): ${doc.skippedTables.join(", ")}`)}else console.log(json2)}function autoOutputName(){let d=new Date;return`genie-backup-${`${d.getFullYear()}${String(d.getMonth()+1).padStart(2,"0")}${String(d.getDate()).padStart(2,"0")}`}.json`}async function exportGroup(sql,group,filter){let tables=GROUP_TABLES[group],{available,skipped}=await detectTables(sql,tables),data={};for(let table of available)if(filter)data[table]=[...await sql.unsafe(`SELECT * FROM ${table} WHERE ${filter.column} = $1`,[filter.value])];else data[table]=[...await sql.unsafe(`SELECT * FROM ${table}`)];return{data,skipped}}async function exportBoards(sql,name){let tables=GROUP_TABLES.boards,{available,skipped}=await detectTables(sql,tables),data={};for(let table of available)if(name&&table==="boards")data[table]=[...await sql`SELECT * FROM boards WHERE name = ${name}`];else if(table==="task_types")data[table]=[...await sql`SELECT * FROM task_types WHERE is_builtin = false`];else data[table]=[...await sql.unsafe(`SELECT * FROM ${table}`)];return{data,skipped}}var TASK_JOIN_ALIASES={task_tags:"tt",task_actors:"ta",task_dependencies:"td",task_stage_log:"tsl"};async function resolveProjectId2(sql,projectName){let projects=await sql`SELECT id FROM projects WHERE name = ${projectName}`;if(projects.length===0)throw Error(`Project not found: ${projectName}`);return projects[0].id}function stripEphemeralFields(rows){return rows.map((r)=>{let{checkout_run_id,execution_locked_at,session_id,pane_id,...rest}=r;return rest})}async function exportTaskTable(sql,table,projectId){let alias=TASK_JOIN_ALIASES[table];if(table==="tasks"){let rows=projectId?[...await sql.unsafe("SELECT * FROM tasks WHERE project_id = $1",[projectId])]:[...await sql`SELECT * FROM tasks`];return stripEphemeralFields(rows)}if(alias&&projectId)return[...await sql.unsafe(`SELECT ${alias}.* FROM ${table} ${alias} JOIN tasks t ON ${alias}.task_id = t.id WHERE t.project_id = $1`,[projectId])];return[...await sql.unsafe(`SELECT * FROM ${table}`)]}async function exportTasks(sql,projectName){let tables=GROUP_TABLES.tasks,{available,skipped}=await detectTables(sql,tables),data={},projectId=projectName?await resolveProjectId2(sql,projectName):null;for(let table of available)data[table]=await exportTaskTable(sql,table,projectId);return{data,skipped}}async function exportSchedules(sql,name){let{available,skipped}=await detectTables(sql,["schedules"]),data={};if(available.includes("schedules"))if(name)data.schedules=[...await sql`SELECT * FROM schedules WHERE name = ${name}`];else data.schedules=[...await sql`SELECT * FROM schedules`];return{data,skipped}}async function exportTags(sql){let{available,skipped}=await detectTables(sql,["tags"]),data={};if(available.includes("tags"))data.tags=[...await sql`SELECT * FROM tags WHERE name NOT LIKE 'test-%'`];return{data,skipped}}async function exportAll(sql){let allSkipped=[],allData={};for(let group of ALL_GROUPS){let result2;switch(group){case"boards":result2=await exportBoards(sql);break;case"tasks":result2=await exportTasks(sql);break;case"tags":result2=await exportTags(sql);break;case"schedules":result2=await exportSchedules(sql);break;default:result2=await exportGroup(sql,group);break}Object.assign(allData,result2.data),allSkipped.push(...result2.skipped)}return{data:allData,skipped:allSkipped}}async function runExport(groups,type2,exportFn,options){let sql=await getSql(),[version,actor]=await Promise.all([getVersion(),getActorName()]),doc=createExportDocument(type2,groups,version,actor),{data,skipped}=await exportFn(sql);doc.data=data,doc.skippedTables=skipped,outputDocument(doc,options)}function registerExportCommands(program2){let exp=program2.command("export").description("Export genie data as JSON").option("--output <file>","Write to file instead of stdout").option("-o <file>","Alias for --output").option("--pretty","Pretty-print JSON").action(async(options)=>{try{if(!options.output)options.output=autoOutputName();await runExport([...ALL_GROUPS],"full",(sql)=>exportAll(sql),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts=(cmd)=>cmd.option("--output <file>","Write to file instead of stdout").option("--pretty","Pretty-print JSON");sharedOpts(exp.command("all").description("Full backup (all present tables)")).action(async(options)=>{try{if(!options.output)options.output=autoOutputName();await runExport([...ALL_GROUPS],"full",(sql)=>exportAll(sql),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("boards [name]").description("Export boards, templates, and task types")).action(async(name,options)=>{try{await runExport(["boards"],"partial",(sql)=>exportBoards(sql,name),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("tasks").description("Export tasks with deps, actors, and stage log").option("--project <name>","Filter by project name")).action(async(options)=>{try{await runExport(["tasks"],"partial",(sql)=>exportTasks(sql,options.project),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("tags").description("Export tags")).action(async(options)=>{try{await runExport(["tags"],"partial",(sql)=>exportTags(sql),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("projects").description("Export projects")).action(async(options)=>{try{await runExport(["projects"],"partial",(sql)=>exportGroup(sql,"projects"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("schedules [name]").description("Export schedules with run_spec")).action(async(name,options)=>{try{await runExport(["schedules"],"partial",(sql)=>exportSchedules(sql,name),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("agents").description("Export agents, templates, and checkpoints")).action(async(options)=>{try{await runExport(["agents"],"partial",(sql)=>exportGroup(sql,"agents"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("comms").description("Export conversations, messages, mailbox")).action(async(options)=>{try{await runExport(["comms"],"partial",(sql)=>exportGroup(sql,"comms"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),sharedOpts(exp.command("config").description("Export OS config (graceful skip if missing)")).action(async(options)=>{try{await runExport(["config"],"partial",(sql)=>exportGroup(sql,"config"),options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_history();init_export_format();import{readFileSync as readFileSync41}from"fs";var IMPORT_LEVELS=[["schedules","sessions","projects","agent_templates","agent_checkpoints","tags","task_types","notification_preferences","os_config","golden_images","warm_pool","instances"],["triggers","boards","board_templates","agents","conversations"],["tasks","runs","messages","conversation_members","mailbox","team_chat"],["task_tags","task_actors","task_dependencies","task_stage_log","heartbeats","machine_snapshots"]],SELF_REFERENTIAL_COLUMNS={tasks:"parent_id",messages:"reply_to_id",conversations:"parent_message_id"};function getTableLevel(table){for(let i2=0;i2<IMPORT_LEVELS.length;i2++)if(IMPORT_LEVELS[i2].includes(table))return i2;return-1}function sortByImportOrder(tables){return[...tables].sort((a,b2)=>{let la=getTableLevel(a),lb=getTableLevel(b2);return(la===-1?999:la)-(lb===-1?999:lb)})}function getPrimaryKey(table){return{task_tags:["task_id","tag_id"],task_actors:["task_id","actor_type","actor_id","role"],task_dependencies:["task_id","depends_on_id"],conversation_members:["conversation_id","actor_type","actor_id"],notification_preferences:["actor_type","actor_id","channel"]}[table]??["id"]}var VALID_TABLES=new Set(Object.values(GROUP_TABLES).flat());function assertValidTable(name){if(!VALID_TABLES.has(name))throw Error(`Invalid table name: "${name}" is not in the schema whitelist`)}var VALID_COLUMN_RE=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function assertValidColumnName(name){if(!VALID_COLUMN_RE.test(name))throw Error(`Invalid column name: "${name.slice(0,60)}" contains disallowed characters. Column names must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`)}async function getSql2(){let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return getConnection2()}async function getActorName2(){let{getActor:getActor2}=await Promise.resolve().then(() => (init_audit(),exports_audit));return getActor2()}async function detectTables2(sql,tables){let{filterAvailableTables:filterAvailableTables2}=await Promise.resolve().then(() => exports_table_detect);return filterAvailableTables2(sql,tables)}async function detectConflicts(sql,table,rows){if(rows.length===0)return[];assertValidTable(table);let pk=getPrimaryKey(table);if(pk.length===1){let key=pk[0],ids=rows.map((r)=>r[key]),existing=await sql.unsafe(`SELECT ${key} FROM ${table} WHERE ${key} = ANY($1)`,[ids]),existingSet=new Set(existing.map((r)=>String(r[key])));return rows.filter((r)=>existingSet.has(String(r[key])))}let conflicts=[];for(let row2 of rows){let conditions=pk.map((col,i2)=>`${col} = $${i2+1}`).join(" AND "),values2=pk.map((col)=>row2[col]);if((await sql.unsafe(`SELECT 1 FROM ${table} WHERE ${conditions} LIMIT 1`,values2)).length>0)conflicts.push(row2)}return conflicts}function prepareRow(row2,table,selfRefUpdates){let selfRefCol=SELF_REFERENTIAL_COLUMNS[table],entries=Object.entries(row2),columns=entries.map(([k])=>k),values2=entries.map(([,v])=>v);for(let col of columns)assertValidColumnName(col);if(selfRefCol&&row2[selfRefCol]!=null){let idx=columns.indexOf(selfRefCol);if(idx!==-1){let originalSelfRef=values2[idx];values2[idx]=null;let pk=getPrimaryKey(table);selfRefUpdates.push({pk:pk.length===1?row2[pk[0]]:pk.map((k)=>row2[k]),value:originalSelfRef})}}return{columns,values:values2,quotedCols:columns.map((c)=>`"${c}"`).join(", "),placeholders:values2.map((_,i2)=>`$${i2+1}`).join(", ")}}async function insertOneRow(tx,table,row2,prepared,mode){assertValidTable(table);let{quotedCols,placeholders,values:values2}=prepared,pk=getPrimaryKey(table);if(mode==="overwrite"){let pkCondition=pk.map((col,i2)=>`"${col}" = $${values2.length+i2+1}`).join(" AND "),pkValues=pk.map((col)=>row2[col]);await tx.unsafe(`DELETE FROM ${table} WHERE ${pkCondition}`,pkValues),await tx.unsafe(`INSERT INTO ${table} (${quotedCols}) VALUES (${placeholders})`,values2)}else if(mode==="merge"){let onConflict=pk.map((c)=>`"${c}"`).join(", ");await tx.unsafe(`INSERT INTO ${table} (${quotedCols}) VALUES (${placeholders}) ON CONFLICT (${onConflict}) DO NOTHING`,values2)}else await tx.unsafe(`INSERT INTO ${table} (${quotedCols}) VALUES (${placeholders})`,values2)}async function updateSelfRefs(tx,table,updates){assertValidTable(table);let selfRefCol=SELF_REFERENTIAL_COLUMNS[table],pk=getPrimaryKey(table);if(pk.length!==1)return;for(let{pk:pkVal,value}of updates)await tx.unsafe(`UPDATE ${table} SET "${selfRefCol}" = $1 WHERE "${pk[0]}" = $2`,[value,pkVal])}async function insertRows(tx,table,rows,mode){if(rows.length===0)return 0;let selfRefUpdates=[];for(let row2 of rows){let prepared=prepareRow(row2,table,selfRefUpdates);await insertOneRow(tx,table,row2,prepared,mode)}if(selfRefUpdates.length>0)await updateSelfRefs(tx,table,selfRefUpdates);return rows.length}function parseExportFile(filePath){let raw=readFileSync41(filePath,"utf-8"),parsed;try{parsed=JSON.parse(raw)}catch{throw Error(`Invalid JSON in ${filePath}`)}let validation=validateExportDocument(parsed);if(!validation.valid)throw Error(`Invalid export document: ${validation.error}`);return validation.doc}async function filterTablesByGroup(allTables,groupFilter){if(!groupFilter||groupFilter.length===0)return allTables;let{GROUP_TABLES:GROUP_TABLES2}=await Promise.resolve().then(() => (init_export_format(),exports_export_format)),allowedTables=new Set;for(let group of groupFilter){let tables=GROUP_TABLES2[group];if(tables)for(let t of tables)allowedTables.add(t);else console.warn(`Warning: Unknown group "${group}", skipping`)}return allTables.filter((t)=>allowedTables.has(t))}async function checkConflicts(sql,tables,data){for(let table of tables){let rows=data[table];if(!rows||rows.length===0)continue;let conflicts=await detectConflicts(sql,table,rows);if(conflicts.length>0){let pk=getPrimaryKey(table),ids=conflicts.slice(0,5).map((r)=>pk.map((k)=>r[k]).join(",")).join("; ");throw Error(`Conflict in table "${table}": ${conflicts.length} existing row(s) (e.g., ${ids}). Use --merge or --overwrite to resolve.`)}}}async function runImport(filePath,mode,groupFilter){let doc=parseExportFile(filePath),tablesToImport=await filterTablesByGroup(Object.keys(doc.data),groupFilter);if(tablesToImport.length===0){console.log("No tables to import.");return}tablesToImport=sortByImportOrder(tablesToImport);let sql=await getSql2(),{available}=await detectTables2(sql,tablesToImport),skippedTables=tablesToImport.filter((t)=>!available.includes(t));if(tablesToImport=available,skippedTables.length>0)console.log(`Skipping tables not in database: ${skippedTables.join(", ")}`);if(mode==="fail")await checkConflicts(sql,tablesToImport,doc.data);let totalInserted=0,tableStats={};await sql.begin(async(tx)=>{for(let table of tablesToImport){let rows=doc.data[table];if(!rows||rows.length===0)continue;let count=await insertRows(tx,table,rows,mode);tableStats[table]=count,totalInserted+=count}});let actor=await getActorName2(),{recordAuditEvent:recordAuditEvent3}=await Promise.resolve().then(() => (init_audit(),exports_audit));await recordAuditEvent3("import",filePath,"import_complete",actor,{mode,tables:tableStats,totalRows:totalInserted,skippedTables,sourceVersion:doc.version,sourceDate:doc.exportedAt}),console.log(`Import complete: ${totalInserted} rows across ${Object.keys(tableStats).length} tables`);for(let[table,count]of Object.entries(tableStats))if(count>0)console.log(` ${table}: ${count} rows`);if(skippedTables.length>0)console.log(`Skipped (not in DB): ${skippedTables.join(", ")}`)}function registerImportCommands(program2){program2.command("import <file>").description("Import genie data from JSON export").option("--fail","Abort on any conflict (default)").option("--merge","Skip existing rows, import new ones").option("--overwrite","Replace existing rows with imported data").option("--groups <list>","Comma-separated groups to import (e.g., boards,tags)").action(async(file,options)=>{try{let mode="fail";if(options.overwrite)mode="overwrite";else if(options.merge)mode="merge";let groupFilter=options.groups?.split(",").map((g)=>g.trim());await runImport(file,mode,groupFilter)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_esm14();import{existsSync as existsSync69,mkdirSync as mkdirSync33,symlinkSync,writeFileSync as writeFileSync31}from"fs";import{basename as basename12,join as join81,relative as relative7,resolve as resolve15,sep as sep2}from"path";import{cpSync,existsSync as existsSync67,mkdirSync as mkdirSync31,renameSync as renameSync12,rmSync as rmSync4}from"fs";import{join as join78,relative as relative6}from"path";var import_ignore=__toESM(require_ignore(),1);import{existsSync as existsSync66,readFileSync as readFileSync42,readdirSync as readdirSync14,statSync as statSync15}from"fs";import{join as join77,relative as relative5}from"path";var GENIEIGNORE_DEFAULTS=`node_modules
|
|
4324
4327
|
.git
|
|
4325
4328
|
.genie/worktrees
|
|
4326
4329
|
dist
|
|
@@ -4333,17 +4336,17 @@ __pycache__
|
|
|
4333
4336
|
target
|
|
4334
4337
|
coverage
|
|
4335
4338
|
.cache
|
|
4336
|
-
`;function loadIgnoreRules(ignoreFilePath){let ig=import_ignore.default();if(existsSync66(ignoreFilePath)){let content=readFileSync42(ignoreFilePath,"utf-8");ig.add(content)}return ig}async function*scanForAgents(root,ignoreFilePath){let ig=loadIgnoreRules(ignoreFilePath??join77(root,".genieignore"));ig.add("agents"),yield*walkDir(root,root,ig)}function*walkDir(dir,root,ig){let names;try{names=readdirSync14(dir)}catch{return}for(let name of names){let fullPath=join77(dir,name);try{if(!
|
|
4339
|
+
`;function loadIgnoreRules(ignoreFilePath){let ig=import_ignore.default();if(existsSync66(ignoreFilePath)){let content=readFileSync42(ignoreFilePath,"utf-8");ig.add(content)}return ig}async function*scanForAgents(root,ignoreFilePath){let ig=loadIgnoreRules(ignoreFilePath??join77(root,".genieignore"));ig.add("agents"),yield*walkDir(root,root,ig)}function*walkDir(dir,root,ig){let names;try{names=readdirSync14(dir)}catch{return}for(let name of names){let fullPath=join77(dir,name);try{if(!statSync15(fullPath).isDirectory())continue}catch{continue}let relPath=`${relative5(root,fullPath)}/`;if(ig.ignores(relPath))continue;let agentsMdPath=join77(fullPath,"AGENTS.md");if(existsSync66(agentsMdPath)){let hasSubAgents=hasSubAgentDirs(fullPath);if(yield{path:fullPath,dirName:name,hasSubAgents,isSubAgent:!1},hasSubAgents)yield*scanSubAgents2(fullPath,name)}yield*walkDir(fullPath,root,ig)}}function hasSubAgentDirs(agentDir){let subAgentsDir=join77(agentDir,".genie","agents");if(!existsSync66(subAgentsDir))return!1;try{return readdirSync14(subAgentsDir).some((name)=>{let subPath=join77(subAgentsDir,name);try{return statSync15(subPath).isDirectory()&&existsSync66(join77(subPath,"AGENTS.md"))}catch{return!1}})}catch{return!1}}function*scanSubAgents2(parentDir,parentName){let subAgentsDir=join77(parentDir,".genie","agents");if(!existsSync66(subAgentsDir))return;let names;try{names=readdirSync14(subAgentsDir)}catch{return}for(let name of names){let subDir=join77(subAgentsDir,name);try{if(!statSync15(subDir).isDirectory())continue}catch{continue}if(!existsSync66(join77(subDir,"AGENTS.md")))continue;yield{path:subDir,dirName:name,hasSubAgents:!1,isSubAgent:!0,parentName}}}async function scanForAgentsAll(root,ignoreFilePath){let results=[];for await(let agent of scanForAgents(root,ignoreFilePath))results.push(agent);return results}init_workspace();async function discoverExternalAgents(workspaceRoot){let allScanned=await scanForAgentsAll(workspaceRoot),canonicalNames=new Set(scanAgents(workspaceRoot)),agentsDir=join78(workspaceRoot,"agents"),external2=[];for(let scanned of allScanned){if(scanned.path.startsWith(agentsDir))continue;if(canonicalNames.has(scanned.dirName))continue;external2.push({name:scanned.dirName,path:scanned.path,relativePath:relative6(workspaceRoot,scanned.path),isSubAgent:scanned.isSubAgent,parentName:scanned.parentName})}return external2}function importAgents(workspaceRoot,agents){let agentsDir=join78(workspaceRoot,"agents");mkdirSync31(agentsDir,{recursive:!0});let result2={imported:[],skipped:[],errors:[]};for(let agent of agents){let destName=resolveUniqueName(agentsDir,agent.name),destPath=join78(agentsDir,destName);if(existsSync67(destPath)){result2.skipped.push(agent.name);continue}try{moveDirectory(agent.path,destPath),result2.imported.push(destName)}catch(err){result2.errors.push({name:agent.name,error:err instanceof Error?err.message:String(err)})}}return result2}function moveDirectory(src,dest){try{renameSync12(src,dest)}catch{cpSync(src,dest,{recursive:!0}),rmSync4(src,{recursive:!0,force:!0})}}function resolveUniqueName(agentsDir,name){if(!existsSync67(join78(agentsDir,name)))return name;let suffix=2;while(existsSync67(join78(agentsDir,`${name}-${suffix}`)))suffix++;return`${name}-${suffix}`}init_interactivity();init_defaults();import{readFileSync as readFileSync43,writeFileSync as writeFileSync29}from"fs";import{join as join79}from"path";function formatDefaults(workspaceDefaults){let effective=computeEffectiveDefaults(workspaceDefaults),lines=[];for(let key of Object.keys(BUILTIN_DEFAULTS)){let value=effective[key],source=workspaceDefaults?.[key]!==void 0?"workspace":"built-in";lines.push(` ${key}: ${value} (${source})`)}return lines.join(`
|
|
4337
4340
|
`)}function formatWelcome(ctx){let lines=["",` Workspace: ${ctx.workspaceName}`,` Agents: ${ctx.canonicalAgentCount} registered`];if(ctx.discovered.length>0)lines.push(` Discovered: ${ctx.discovered.length} external agent(s) found`);return lines.push(""),lines.push(" Effective defaults:"),lines.push(formatDefaults(ctx.config.agents?.defaults)),lines.push(""),lines.join(`
|
|
4338
4341
|
`)}function formatNextSteps(ctx){let lines=[""," Next steps:"];if(ctx.canonicalAgentCount===0)lines.push(" genie init agent <name> Scaffold your first agent");return lines.push(" genie spawn <agent> Launch an agent"),lines.push(" genie team create <name> Create a multi-agent team"),lines.push(" /wizard Full guided onboarding"),lines.push(""),lines.join(`
|
|
4339
4342
|
`)}var MODEL_CHOICES=[{name:"opus (most capable)",value:"opus"},{name:"sonnet (balanced)",value:"sonnet"},{name:"haiku (fastest)",value:"haiku"}];async function runMiniWizard(ctx){let{confirm:confirm3}=await Promise.resolve().then(() => (init_esm14(),exports_esm));console.log(formatWelcome(ctx));let wantCustomize=await confirm3({message:"Customize workspace defaults?",default:!1}),result2={customized:!1,importedAgents:[],completed:!0};if(wantCustomize){let newDefaults=await customizeDefaults(ctx.config.agents?.defaults);if(newDefaults)result2.customized=!0,result2.defaults=newDefaults,persistDefaults(ctx.workspaceRoot,newDefaults)}if(ctx.pending.length>0){console.log(`
|
|
4340
4343
|
Found ${ctx.pending.length} agent(s) in your project tree:`);for(let agent of ctx.pending)console.log(` ${agent.name} (${agent.relativePath})`);if(await confirm3({message:"Import discovered agents into workspace?",default:!0}))result2.importedAgents=ctx.pending.map((a)=>a.name)}return console.log(formatNextSteps(ctx)),result2}async function customizeDefaults(currentDefaults){let{select:select2}=await Promise.resolve().then(() => (init_esm14(),exports_esm)),effective=computeEffectiveDefaults(currentDefaults),updates={},changed=!1,model=await select2({message:"Default model:",choices:MODEL_CHOICES,default:effective.model});if(model!==BUILTIN_DEFAULTS.model)updates.model=model,changed=!0;let permissionMode=await select2({message:"Default permission mode:",choices:[{name:"auto (tool-by-tool judgment \u2014 default)",value:"auto"},{name:"default (ask for risky tools)",value:"default"},{name:"plan (require plan approval)",value:"plan"},{name:"bypassPermissions (auto-approve all)",value:"bypassPermissions"}],default:effective.permissionMode});if(permissionMode!==BUILTIN_DEFAULTS.permissionMode)updates.permissionMode=permissionMode,changed=!0;return changed?updates:null}function persistDefaults(workspaceRoot,newDefaults){let configPath2=join79(workspaceRoot,".genie","workspace.json");try{let raw=readFileSync43(configPath2,"utf-8"),config=JSON.parse(raw);if(!config.agents)config.agents={};if(!config.agents.defaults)config.agents.defaults={};Object.assign(config.agents.defaults,newDefaults),writeFileSync29(configPath2,`${JSON.stringify(config,null,2)}
|
|
4341
|
-
`,"utf-8"),console.log(" Workspace defaults updated.")}catch(err){console.error(` Failed to update workspace.json: ${err instanceof Error?err.message:String(err)}`)}}import{existsSync as existsSync68,mkdirSync as
|
|
4342
|
-
`,"utf-8")}function refreshPending(workspaceRoot,discovered){let existing=loadPending(workspaceRoot),dismissedSet=new Set(existing.agents.filter((a)=>a.dismissed).map((a)=>a.path)),now=new Date().toISOString(),store={agents:discovered.map((d)=>({name:d.name,path:d.path,relativePath:d.relativePath,isSubAgent:d.isSubAgent,parentName:d.parentName,discoveredAt:existing.agents.find((a)=>a.path===d.path)?.discoveredAt??now,dismissed:dismissedSet.has(d.path)}))};return savePending(workspaceRoot,store),store}function listPending(workspaceRoot){return loadPending(workspaceRoot).agents.filter((a)=>!a.dismissed)}function removePending(workspaceRoot,agentPath){let store=loadPending(workspaceRoot),idx=store.agents.findIndex((a)=>a.path===agentPath);if(idx===-1)return!1;return store.agents.splice(idx,1),savePending(workspaceRoot,store),!0}init_workspace();init_templates();function detectPgUrl(){if(process.env.DATABASE_URL)return process.env.DATABASE_URL;if(process.env.PG_URL)return process.env.PG_URL;try{let{execSync:execSync16}=__require("child_process"),match=execSync16("pgrep -af pgserve 2>/dev/null",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).match(/postgres(?:ql)?:\/\/[^\s]+/);if(match)return match[0]}catch{}return}async function ensureSetupCompleteForInit(){let{isSetupComplete:isSetupComplete2}=await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config));if(isSetupComplete2())return;console.log("Genie setup not complete. Running `genie setup` before continuing...");let{setupCommand:setupCommand2}=await Promise.resolve().then(() => (init_setup(),exports_setup));await setupCommand2()}function scaffoldAgentInWorkspace(workspaceRoot,name,agentsDir){let baseDir=agentsDir??join81(workspaceRoot,"agents"),agentDir=join81(baseDir,name);if(existsSync69(agentDir))throw Error(`Agent directory already exists: ${agentDir}`);
|
|
4344
|
+
`,"utf-8"),console.log(" Workspace defaults updated.")}catch(err){console.error(` Failed to update workspace.json: ${err instanceof Error?err.message:String(err)}`)}}import{existsSync as existsSync68,mkdirSync as mkdirSync32,readFileSync as readFileSync44,writeFileSync as writeFileSync30}from"fs";import{join as join80}from"path";function pendingPath(workspaceRoot){return join80(workspaceRoot,".genie","pending-agents.json")}function loadPending(workspaceRoot){let filePath=pendingPath(workspaceRoot);if(!existsSync68(filePath))return{agents:[]};try{let raw=readFileSync44(filePath,"utf-8"),parsed=JSON.parse(raw);return{agents:Array.isArray(parsed.agents)?parsed.agents:[]}}catch{return{agents:[]}}}function savePending(workspaceRoot,store){let filePath=pendingPath(workspaceRoot);mkdirSync32(join80(workspaceRoot,".genie"),{recursive:!0}),writeFileSync30(filePath,`${JSON.stringify(store,null,2)}
|
|
4345
|
+
`,"utf-8")}function refreshPending(workspaceRoot,discovered){let existing=loadPending(workspaceRoot),dismissedSet=new Set(existing.agents.filter((a)=>a.dismissed).map((a)=>a.path)),now=new Date().toISOString(),store={agents:discovered.map((d)=>({name:d.name,path:d.path,relativePath:d.relativePath,isSubAgent:d.isSubAgent,parentName:d.parentName,discoveredAt:existing.agents.find((a)=>a.path===d.path)?.discoveredAt??now,dismissed:dismissedSet.has(d.path)}))};return savePending(workspaceRoot,store),store}function listPending(workspaceRoot){return loadPending(workspaceRoot).agents.filter((a)=>!a.dismissed)}function removePending(workspaceRoot,agentPath){let store=loadPending(workspaceRoot),idx=store.agents.findIndex((a)=>a.path===agentPath);if(idx===-1)return!1;return store.agents.splice(idx,1),savePending(workspaceRoot,store),!0}init_workspace();init_templates();function detectPgUrl(){if(process.env.DATABASE_URL)return process.env.DATABASE_URL;if(process.env.PG_URL)return process.env.PG_URL;try{let{execSync:execSync16}=__require("child_process"),match=execSync16("pgrep -af pgserve 2>/dev/null",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).match(/postgres(?:ql)?:\/\/[^\s]+/);if(match)return match[0]}catch{}return}async function ensureSetupCompleteForInit(){let{isSetupComplete:isSetupComplete2}=await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config));if(isSetupComplete2())return;console.log("Genie setup not complete. Running `genie setup` before continuing...");let{setupCommand:setupCommand2}=await Promise.resolve().then(() => (init_setup(),exports_setup));await setupCommand2()}function scaffoldAgentInWorkspace(workspaceRoot,name,agentsDir){let baseDir=agentsDir??join81(workspaceRoot,"agents"),agentDir=join81(baseDir,name);if(existsSync69(agentDir))throw Error(`Agent directory already exists: ${agentDir}`);mkdirSync33(agentDir,{recursive:!0}),mkdirSync33(join81(agentDir,"brain","memory"),{recursive:!0}),mkdirSync33(join81(agentDir,".claude"),{recursive:!0});let workspaceDefaults;try{workspaceDefaults=getWorkspaceConfig(workspaceRoot).agents?.defaults}catch{}scaffoldAgentFiles(agentDir,name,workspaceDefaults);let settings={agentName:name,autoMemoryEnabled:!0,autoMemoryDirectory:"./brain/memory"};writeFileSync31(join81(agentDir,".claude","settings.local.json"),`${JSON.stringify(settings,null,2)}
|
|
4343
4346
|
`),writeFileSync31(join81(agentDir,"brain","memory","MEMORY.md"),`# Memory Index
|
|
4344
4347
|
|
|
4345
4348
|
_This file is maintained by the auto-memory system. New memories are added automatically._
|
|
4346
|
-
`);let reposTarget=join81(workspaceRoot,"repos");if(existsSync69(reposTarget))try{symlinkSync(reposTarget,join81(agentDir,"repos"))}catch{}if(console.log(`Agent scaffolded: agents/${name}/`),console.log(" AGENTS.md, SOUL.md, HEARTBEAT.md"),console.log(" brain/memory/MEMORY.md (seeded)"),console.log(" .claude/settings.local.json (auto-memory enabled)"),existsSync69(join81(agentDir,"repos")))console.log(" repos -> ../repos (symlink)")}async function maybeBootstrapDefaultAgent(workspaceRoot){if(scanAgents(workspaceRoot).length>0)return!1;if(!await esm_default4({message:"No agent found in this workspace. Scaffold the default `genie` agent now?",default:!0}))return console.log(" Skipped default agent bootstrap. Run `genie init agent genie` later."),!1;return scaffoldAgentInWorkspace(workspaceRoot,"genie"),!0}async function syncWorkspaceAgents(workspaceRoot){let agents=scanAgents(workspaceRoot);if(agents.length===0)return;console.log(` Found ${agents.length} agent(s): ${agents.join(", ")}`);try{let{syncAgentDirectory:syncAgentDirectory2}=await Promise.resolve().then(() => (init_agent_sync(),exports_agent_sync)),result2=await syncAgentDirectory2(workspaceRoot);if(result2.registered.length>0)console.log(` Registered: ${result2.registered.join(", ")}`);if(result2.updated.length>0)console.log(` Updated: ${result2.updated.join(", ")}`)}catch{}}async function initWorkspace(){let cwd=process.cwd(),existing=findWorkspace(cwd);if(existing){if(console.log(`Already inside workspace: ${existing.root}`),await maybeBootstrapDefaultAgent(existing.root))await syncWorkspaceAgents(existing.root);return}let genieDir=join81(cwd,".genie");
|
|
4349
|
+
`);let reposTarget=join81(workspaceRoot,"repos");if(existsSync69(reposTarget))try{symlinkSync(reposTarget,join81(agentDir,"repos"))}catch{}if(console.log(`Agent scaffolded: agents/${name}/`),console.log(" AGENTS.md, SOUL.md, HEARTBEAT.md"),console.log(" brain/memory/MEMORY.md (seeded)"),console.log(" .claude/settings.local.json (auto-memory enabled)"),existsSync69(join81(agentDir,"repos")))console.log(" repos -> ../repos (symlink)")}async function maybeBootstrapDefaultAgent(workspaceRoot){if(scanAgents(workspaceRoot).length>0)return!1;if(!await esm_default4({message:"No agent found in this workspace. Scaffold the default `genie` agent now?",default:!0}))return console.log(" Skipped default agent bootstrap. Run `genie init agent genie` later."),!1;return scaffoldAgentInWorkspace(workspaceRoot,"genie"),!0}async function syncWorkspaceAgents(workspaceRoot){let agents=scanAgents(workspaceRoot);if(agents.length===0)return;console.log(` Found ${agents.length} agent(s): ${agents.join(", ")}`);try{let{syncAgentDirectory:syncAgentDirectory2}=await Promise.resolve().then(() => (init_agent_sync(),exports_agent_sync)),result2=await syncAgentDirectory2(workspaceRoot);if(result2.registered.length>0)console.log(` Registered: ${result2.registered.join(", ")}`);if(result2.updated.length>0)console.log(` Updated: ${result2.updated.join(", ")}`)}catch{}}async function initWorkspace(){let cwd=process.cwd(),existing=findWorkspace(cwd);if(existing){if(console.log(`Already inside workspace: ${existing.root}`),await maybeBootstrapDefaultAgent(existing.root))await syncWorkspaceAgents(existing.root);return}let genieDir=join81(cwd,".genie");mkdirSync33(genieDir,{recursive:!0});let pgUrl=detectPgUrl(),config={name:basename12(cwd),pgUrl,agents:{defaults:{}},tmux:{socket:"genie"},sdk:{}};writeFileSync31(join81(genieDir,"workspace.json"),`${JSON.stringify(config,null,2)}
|
|
4347
4350
|
`);let genieignorePath=join81(cwd,".genieignore");if(!existsSync69(genieignorePath))writeFileSync31(genieignorePath,GENIEIGNORE_DEFAULTS,"utf-8"),console.log(" Created .genieignore");if(console.log(`Workspace created: ${cwd}`),pgUrl)console.log(` pgUrl: ${pgUrl}`);await maybeBootstrapDefaultAgent(cwd),await syncWorkspaceAgents(cwd),await runPostInitFlow(cwd,config)}async function runPostInitFlow(workspaceRoot,config){if(!isInteractive())return;let discovered=await discoverExternalAgents(workspaceRoot);refreshPending(workspaceRoot,discovered);let pending=listPending(workspaceRoot),ctx={workspaceRoot,workspaceName:basename12(workspaceRoot),config,discovered,pending,canonicalAgentCount:scanAgents(workspaceRoot).length},result2=await runMiniWizard(ctx);if(result2.importedAgents.length>0){let toImport=pending.filter((p)=>result2.importedAgents.includes(p.name)),discoveredToImport=toImport.map((p)=>({name:p.name,path:p.path,relativePath:p.relativePath,isSubAgent:p.isSubAgent,parentName:p.parentName})),importResult=importAgents(workspaceRoot,discoveredToImport);for(let name of importResult.imported){let agent=toImport.find((a)=>a.name===name);if(agent)removePending(workspaceRoot,agent.path);console.log(` Imported: ${name}`)}for(let err of importResult.errors)console.error(` Import failed (${err.name}): ${err.error}`);await syncWorkspaceAgents(workspaceRoot)}}function resolveAgentsDir(wsRoot,dirOption){if(dirOption)return resolve15(dirOption);let cwd=process.cwd(),rel=relative7(wsRoot,cwd);if(rel.startsWith(".."))return join81(wsRoot,"agents");let segments=rel===""?[]:rel.split(sep2),idx=segments.indexOf("agents");if(idx===-1)return join81(wsRoot,"agents");return join81(wsRoot,...segments.slice(0,idx+1))}async function initAgent(name,options){if(!name||/[\/\\]/.test(name)||name==="."||name===".."||name.includes(".."))console.error("Error: Agent name must not contain path separators or traversal sequences."),process.exit(1);let cwd=process.cwd(),ws=findWorkspace(cwd);if(!ws)console.error("Error: Not in a genie workspace. Run `genie init` first."),process.exit(1);let agentsDir=resolveAgentsDir(ws.root,options.dir);try{scaffoldAgentInWorkspace(ws.root,name,agentsDir)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}function registerInitCommands(program2){program2.command("init").description("Initialize a genie workspace").action(async()=>{await ensureSetupCompleteForInit(),await initWorkspace()}).command("agent <name>").description("Scaffold a new agent in the workspace").option("--dir <path>","Target directory for agent (default: CWD if inside agents/, else workspace agents/)").action(async(name,options)=>{await ensureSetupCompleteForInit(),await initAgent(name,options)})}init_db();init_runtime_events();init_term_format();function parseSince4(since){let match=since.match(/^(\d+)([smhd])$/);if(!match)return since;let amount=Number.parseInt(match[1],10),unit=match[2],ms={s:1000,m:60000,h:3600000,d:86400000}[unit]??3600000;return new Date(Date.now()-amount*ms).toISOString()}async function metricsNowCommand(options){if(!await isAvailable())console.error("Database not available."),process.exit(1);let sql=await getConnection(),snapshots=await sql`SELECT * FROM machine_snapshots ORDER BY created_at DESC LIMIT 1`,agentCount=await sql`SELECT count(DISTINCT agent_id)::int as cnt FROM executors WHERE state NOT IN ('done', 'error', 'terminated')`,teamCount=await sql`SELECT count(*)::int as cnt FROM teams WHERE status = 'in_progress'`,snapshot=snapshots[0]??{},throughput=await queryRuntimeEventThroughput(60),data={active_workers:snapshot.active_workers??agentCount[0]?.cnt??0,active_teams:snapshot.active_teams??teamCount[0]?.cnt??0,tmux_sessions:snapshot.tmux_sessions??0,cpu_percent:snapshot.cpu_percent??null,memory_mb:snapshot.memory_mb??null,snapshot_at:snapshot.created_at?new Date(snapshot.created_at).toISOString():null,events_emitted_last_60s:throughput.emitted};if(options.json){console.log(JSON.stringify(data,null,2));return}if(console.log("Machine State:"),console.log(` Workers: ${data.active_workers}`),console.log(` Teams: ${data.active_teams}`),console.log(` Tmux: ${data.tmux_sessions} sessions`),data.cpu_percent!==null)console.log(` CPU: ${data.cpu_percent}%`);if(data.memory_mb!==null)console.log(` Memory: ${data.memory_mb} MB`);if(data.snapshot_at)console.log(` As of: ${formatRelativeTimestamp(data.snapshot_at)}`);console.log(`
|
|
4348
4351
|
Event Throughput (last 60s):`),console.log(` Emitted: ${data.events_emitted_last_60s}`)}async function metricsHistoryCommand(options){if(!await isAvailable())console.error("Database not available."),process.exit(1);let sql=await getConnection(),sinceTs=parseSince4(options.since??"1h"),rows=await sql`
|
|
4349
4352
|
SELECT active_workers, active_teams, tmux_sessions, cpu_percent, memory_mb, created_at
|
|
@@ -4352,7 +4355,7 @@ Event Throughput (last 60s):`),console.log(` Emitted: ${data.events_emitted_la
|
|
|
4352
4355
|
ORDER BY created_at ASC
|
|
4353
4356
|
`;if(options.json){console.log(JSON.stringify(rows,null,2));return}if(rows.length===0){console.log("No snapshots in the given time range.");return}let headers=["Time","Workers","Teams","Tmux","CPU%","Mem MB"],data=rows.map((r)=>[formatRelativeTimestamp(r.created_at),String(r.active_workers??0),String(r.active_teams??0),String(r.tmux_sessions??0),r.cpu_percent!==null?String(r.cpu_percent):"-",r.memory_mb!==null?String(r.memory_mb):"-"]),widths=headers.map((h,i2)=>{let colVals=data.map((row2)=>row2[i2]);return Math.max(h.length,...colVals.map((v)=>v.length))});console.log(headers.map((h,i2)=>padRight(h,widths[i2])).join(" | ")),console.log(widths.map((w)=>"-".repeat(w)).join("-+-"));for(let row2 of data)console.log(row2.map((v,i2)=>padRight(v,widths[i2])).join(" | "));console.log(`
|
|
4354
4357
|
(${rows.length} snapshot${rows.length===1?"":"s"})`)}async function metricsAgentsCommand(options){if(options.json){console.log(JSON.stringify({deprecated:!0,replacement:"genie status",message:"Use `genie status` for live agent state."}));return}console.error("\u26A0\uFE0F `genie metrics agents` is deprecated and will be removed in a future release."),console.error(" Use `genie status` for live agent state.")}function registerMetricsCommands(program2){let metrics=program2.command("metrics").description("Machine metrics \u2014 snapshots, heartbeats, agents");metrics.command("now",{isDefault:!0}).description("Current machine state").option("--json","Output as JSON").action(async(options)=>{await metricsNowCommand(options)}),metrics.command("history").description("Machine snapshot history").option("--since <duration>","Time window (e.g., 1h, 6h, 1d)","1h").option("--json","Output as JSON").action(async(options)=>{await metricsHistoryCommand(options)}),metrics.command("agents").description("[DEPRECATED] Use `genie status` for live agent state").option("--json","Output as JSON").action(async(options)=>{await metricsAgentsCommand(options)})}init_msg();init_term_format();var _taskService4;async function getTaskService4(){if(!_taskService4)_taskService4=await Promise.resolve().then(() => (init_task_service(),exports_task_service));return _taskService4}function currentActor2(){return{actorType:"local",actorId:process.env.GENIE_AGENT_NAME??"cli"}}async function handleNotifySet(options){let ts3=await getTaskService4(),actor=currentActor2(),pref=await ts3.setPreference(actor,options.channel,{priorityThreshold:options.priority,isDefault:options.default}),defaultLabel=pref.isDefault?", default":"";console.log(`Notification preference set: ${pref.channel} (threshold: ${pref.priorityThreshold}${defaultLabel}).`)}function printPrefsTable(prefs){console.log(` ${padRight("CHANNEL",15)} ${padRight("THRESHOLD",12)} ${padRight("DEFAULT",10)} ENABLED`),console.log(` ${"\u2500".repeat(45)}`);for(let p of prefs){let dflt=p.isDefault?"yes":"no",enabled=p.enabled?"yes":"no";console.log(` ${padRight(p.channel,15)} ${padRight(p.priorityThreshold,12)} ${padRight(dflt,10)} ${enabled}`)}console.log(`
|
|
4355
|
-
${prefs.length} preference${prefs.length===1?"":"s"}`)}async function handleNotifyList(options){let ts3=await getTaskService4(),actor=currentActor2(),prefs=await ts3.getPreferences(actor);if(options.json){console.log(JSON.stringify(prefs,null,2));return}if(prefs.length===0){console.log("No notification preferences configured.");return}printPrefsTable(prefs)}async function handleNotifyRemove(options){let ts3=await getTaskService4(),actor=currentActor2();if(await ts3.deletePreference(actor,options.channel))console.log(`Removed notification preference for channel: ${options.channel}`);else console.log(`No preference found for channel: ${options.channel}`)}function registerNotifyCommands(program2){let notify=program2.command("notify").description("Notification preference management");notify.command("set").description("Set notification preference for a channel").requiredOption("--channel <channel>","Channel: whatsapp, telegram, email, slack, discord, tmux").option("--priority <priority>","Minimum priority threshold","normal").option("--default","Set as default channel").action(async(options)=>{try{await handleNotifySet(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),notify.command("list").description("List notification preferences").option("--json","Output as JSON").action(async(options)=>{try{await handleNotifyList(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),notify.command("remove").description("Remove a notification preference").requiredOption("--channel <channel>","Channel to remove").action(async(options)=>{try{await handleNotifyRemove(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_agent_observability();init_term_format();var FLAG_LABELS2={stale_executor:"STALE",missing_session:"NO-SESSION",missing_attribution:"UNATTRIBUTED",high_hook_latency:"SLOW-HOOK",recent_failure:"TOOL-ERR",cost_spike:"COST"};function summarize(snap){let name=snap.customName??snap.role??snap.agentId,namePart=padRight(truncate2(name,28),28),exec3=snap.executorState??"-",execPart=padRight(truncate2(exec3,12),12),tools=`${snap.recentToolCount} tools / ${snap.recentErrorCount} err`,cost=snap.recentCostUsd>0?`$${snap.recentCostUsd.toFixed(2)}`:"$0",last=snap.recentLastToolAt?formatRelativeTimestamp(snap.recentLastToolAt):"-",health=snap.health.flags.length===0?color("green","OK"):color("yellow",snap.health.flags.map((f)=>FLAG_LABELS2[f]).join(","));return` ${namePart} ${execPart} ${padRight(tools,18)} ${padRight(cost,8)} last:${padRight(last,9)} ${health}`}function renderHumanFleet(snaps,includeHarness){if(console.log(""),console.log(color("bold",includeHarness?"AGENTS + HARNESS":"AGENTS")),console.log("-".repeat(72)),snaps.length===0){console.log(color("dim"," (none)")),console.log("");return}for(let snap of snaps)console.log(summarize(snap));let degraded=snaps.filter((s2)=>s2.health.degraded).length;console.log(""),console.log(color("dim",` ${snaps.length} rows, ${degraded} degraded \u2014 schema v${AGENT_OBSERVABILITY_SCHEMA_VERSION}`)),console.log("")}async function observeAgentsCommand(opts={}){let limit=opts.limit?Number.parseInt(opts.limit,10):void 0,snaps=await listAgentObservability({includeHarness:opts.includeHarness===!0,limit:Number.isFinite(limit)?limit:void 0});if(opts.json)console.log(JSON.stringify({_source:{schemaVersion:AGENT_OBSERVABILITY_SCHEMA_VERSION,view:"v_agent_observability"},agents:snaps},null,2));else renderHumanFleet(snaps,opts.includeHarness===!0);if(opts.strict&&snaps.some((s2)=>s2.health.degraded))process.exit(1)}function registerObserveCommands(program2){let observe=program2.command("observe").description("Canonical observability snapshots");observe.command("agents").description("Fleet-level agent observability snapshot").option("--json","Emit machine-readable JSON").option("--include-harness","Include rows whose classification is `harness`").option("--strict","Exit with code 1 when any row is degraded").option("--limit <n>","Maximum rows to return").action(async(options)=>{try{await observeAgentsCommand(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`observe: ${message}`),process.exit(2)}}),observe.on("command:*",(operands)=>{let cmd=operands[0],available=observe.commands.map((c)=>c.name()).join(", ");observe.error(`Unknown observe command '${cmd}'. Available: ${available}`)})}init_genie_config2();import{generateKeyPairSync}from"crypto";import{chmodSync as chmodSync3,existsSync as existsSync70,mkdirSync as
|
|
4358
|
+
${prefs.length} preference${prefs.length===1?"":"s"}`)}async function handleNotifyList(options){let ts3=await getTaskService4(),actor=currentActor2(),prefs=await ts3.getPreferences(actor);if(options.json){console.log(JSON.stringify(prefs,null,2));return}if(prefs.length===0){console.log("No notification preferences configured.");return}printPrefsTable(prefs)}async function handleNotifyRemove(options){let ts3=await getTaskService4(),actor=currentActor2();if(await ts3.deletePreference(actor,options.channel))console.log(`Removed notification preference for channel: ${options.channel}`);else console.log(`No preference found for channel: ${options.channel}`)}function registerNotifyCommands(program2){let notify=program2.command("notify").description("Notification preference management");notify.command("set").description("Set notification preference for a channel").requiredOption("--channel <channel>","Channel: whatsapp, telegram, email, slack, discord, tmux").option("--priority <priority>","Minimum priority threshold","normal").option("--default","Set as default channel").action(async(options)=>{try{await handleNotifySet(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),notify.command("list").description("List notification preferences").option("--json","Output as JSON").action(async(options)=>{try{await handleNotifyList(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}}),notify.command("remove").description("Remove a notification preference").requiredOption("--channel <channel>","Channel to remove").action(async(options)=>{try{await handleNotifyRemove(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_agent_observability();init_term_format();var FLAG_LABELS2={stale_executor:"STALE",missing_session:"NO-SESSION",missing_attribution:"UNATTRIBUTED",high_hook_latency:"SLOW-HOOK",recent_failure:"TOOL-ERR",cost_spike:"COST"};function summarize(snap){let name=snap.customName??snap.role??snap.agentId,namePart=padRight(truncate2(name,28),28),exec3=snap.executorState??"-",execPart=padRight(truncate2(exec3,12),12),tools=`${snap.recentToolCount} tools / ${snap.recentErrorCount} err`,cost=snap.recentCostUsd>0?`$${snap.recentCostUsd.toFixed(2)}`:"$0",last=snap.recentLastToolAt?formatRelativeTimestamp(snap.recentLastToolAt):"-",health=snap.health.flags.length===0?color("green","OK"):color("yellow",snap.health.flags.map((f)=>FLAG_LABELS2[f]).join(","));return` ${namePart} ${execPart} ${padRight(tools,18)} ${padRight(cost,8)} last:${padRight(last,9)} ${health}`}function renderHumanFleet(snaps,includeHarness){if(console.log(""),console.log(color("bold",includeHarness?"AGENTS + HARNESS":"AGENTS")),console.log("-".repeat(72)),snaps.length===0){console.log(color("dim"," (none)")),console.log("");return}for(let snap of snaps)console.log(summarize(snap));let degraded=snaps.filter((s2)=>s2.health.degraded).length;console.log(""),console.log(color("dim",` ${snaps.length} rows, ${degraded} degraded \u2014 schema v${AGENT_OBSERVABILITY_SCHEMA_VERSION}`)),console.log("")}async function observeAgentsCommand(opts={}){let limit=opts.limit?Number.parseInt(opts.limit,10):void 0,snaps=await listAgentObservability({includeHarness:opts.includeHarness===!0,limit:Number.isFinite(limit)?limit:void 0});if(opts.json)console.log(JSON.stringify({_source:{schemaVersion:AGENT_OBSERVABILITY_SCHEMA_VERSION,view:"v_agent_observability"},agents:snaps},null,2));else renderHumanFleet(snaps,opts.includeHarness===!0);if(opts.strict&&snaps.some((s2)=>s2.health.degraded))process.exit(1)}function registerObserveCommands(program2){let observe=program2.command("observe").description("Canonical observability snapshots");observe.command("agents").description("Fleet-level agent observability snapshot").option("--json","Emit machine-readable JSON").option("--include-harness","Include rows whose classification is `harness`").option("--strict","Exit with code 1 when any row is degraded").option("--limit <n>","Maximum rows to return").action(async(options)=>{try{await observeAgentsCommand(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`observe: ${message}`),process.exit(2)}}),observe.on("command:*",(operands)=>{let cmd=operands[0],available=observe.commands.map((c)=>c.name()).join(", ");observe.error(`Unknown observe command '${cmd}'. Available: ${available}`)})}init_genie_config2();import{generateKeyPairSync}from"crypto";import{chmodSync as chmodSync3,existsSync as existsSync70,mkdirSync as mkdirSync34,readFileSync as readFileSync45,writeFileSync as writeFileSync32}from"fs";import{hostname as osHostname}from"os";import{dirname as dirname27,join as join82,resolve as resolvePath5}from"path";function keyPaths2(){let home=process.env.GENIE_HOME??join82(process.env.HOME??"/root",".genie"),dir=join82(home,"keys");return{dir,privateKey:join82(dir,"genie-host.ed25519"),publicKey:join82(dir,"genie-host.ed25519.pub"),hostJson:join82(dir,"host.json")}}function assertNotInsideGitRepo(dir){let probe=resolvePath5(dir);for(let depth=0;depth<16;depth++){if(existsSync70(join82(probe,".git")))throw Error(`Refusing to write keys to ${dir} \u2014 it lives inside a git working tree (${join82(probe,".git")}). Set $GENIE_HOME to a path outside any git repo and re-run.`);let parent=dirname27(probe);if(parent===probe)return;probe=parent}}function generateAndPersistKeypair(paths){if(!existsSync70(paths.dir))mkdirSync34(paths.dir,{recursive:!0,mode:448});let{publicKey,privateKey}=generateKeyPairSync("ed25519"),rawPub=publicKey.export({format:"der",type:"spki"}),pubkeyB64Url=rawPub.subarray(rawPub.length-32).toString("base64url");return writeFileSync32(paths.privateKey,privateKey.export({format:"pem",type:"pkcs8"}),{mode:384}),writeFileSync32(paths.publicKey,pubkeyB64Url,{mode:420}),chmodSync3(paths.privateKey,384),{pubkeyB64Url}}function loadExistingPubkey(paths){if(!existsSync70(paths.publicKey))return null;return readFileSync45(paths.publicKey,"utf-8").trim()}function loadHostJson(paths){if(!existsSync70(paths.hostJson))return null;try{return JSON.parse(readFileSync45(paths.hostJson,"utf-8"))}catch{return null}}function writeHostJson(paths,record){writeFileSync32(paths.hostJson,`${JSON.stringify(record,null,2)}
|
|
4356
4359
|
`,{mode:420})}async function resolveOmniApiKey2(){let envKey=process.env.OMNI_API_KEY;if(envKey)return envKey;return(await loadGenieConfig()).omni?.apiKey}async function callTrustEndpoint(apiUrl,apiKey,method,path3,body){let headers={"Content-Type":"application/json"};if(apiKey)headers.Authorization=`Bearer ${apiKey}`;let res=await fetch(`${apiUrl.replace(/\/+$/,"")}/api/v2/trust${path3}`,{method,headers,body:body===void 0?void 0:JSON.stringify(body)});if(!res.ok){let text=await res.text().catch(()=>"");throw Error(`omni trust ${method} ${path3}: HTTP ${res.status}${text?` \u2014 ${text}`:""}`)}return await res.json()}async function handleHandshake(options){let apiUrl=await resolveOmniApiUrl();if(!apiUrl)throw Error("Omni is not configured. Set OMNI_API_URL or `omni.apiUrl` in your genie config first.\nExample: omni install");let apiKey=await resolveOmniApiKey2();if(!apiKey)throw Error("Omni API key not configured. Set OMNI_API_KEY or `omni.apiKey` in your genie config.");let paths=keyPaths2();assertNotInsideGitRepo(paths.dir);let previousRecord=loadHostJson(paths),pubkey=loadExistingPubkey(paths);if(options.rotate){if(!previousRecord)throw Error("Cannot --rotate: no existing host record at ~/.genie/keys/host.json. Run a plain handshake first.");pubkey=generateAndPersistKeypair(paths).pubkeyB64Url}else if(!pubkey)pubkey=generateAndPersistKeypair(paths).pubkeyB64Url;let hostname2=options.hostname??previousRecord?.hostname??osHostname()??"unknown-host",capabilities={genieVersion:process.env.GENIE_VERSION??"unknown",platform:process.platform,nodeVersion:process.version},{data:host}=await callTrustEndpoint(apiUrl,apiKey,"POST","/handshake",{pubkey,hostname:hostname2,capabilities}),newRecord={hostId:host.id,pubkey:host.pubkey,hostname:host.hostname,registeredAt:new Date().toISOString(),...options.rotate&&previousRecord?{rotatedFrom:previousRecord.hostId}:{}};if(writeHostJson(paths,newRecord),options.rotate&&previousRecord&&previousRecord.hostId!==host.id)try{await callTrustEndpoint(apiUrl,apiKey,"DELETE",`/hosts/${previousRecord.hostId}`)}catch(err){let message=err instanceof Error?err.message:String(err);console.warn(`
|
|
4357
4360
|
\u26A0 Rotated key registered as ${host.id}, but revoking the old host (${previousRecord.hostId}) failed:
|
|
4358
4361
|
${message}
|
|
@@ -4362,7 +4365,7 @@ Event Throughput (last 60s):`),console.log(` Emitted: ${data.events_emitted_la
|
|
|
4362
4365
|
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(`
|
|
4363
4366
|
By status:`);for(let[status2,count]of Object.entries(byStatus).sort())console.log(` ${padRight(status2,15)} ${count}`);console.log(`
|
|
4364
4367
|
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();init_db();var DEFAULT_TTL_HOURS={zombies:24,errored:1},TARGET_LABEL={zombies:"zombie agent",errored:"errored agent"};function parsePositiveInt(value,name){let parsed=Number.parseInt(value,10);if(!Number.isFinite(parsed)||parsed<=0)throw Error(`Invalid ${name}: ${value} (expected a positive integer)`);return parsed}async function listTargets(mode,ttlHours){return mode==="zombies"?listExhaustedZombies(ttlHours):listAllExhaustedErrored(ttlHours)}async function archiveTargets(mode,ttlHours){return mode==="zombies"?archiveExhaustedZombies(ttlHours):archiveAllExhaustedErrored(ttlHours)}async function runDryRun(mode,ttlHours){let rows=await listTargets(mode,ttlHours);if(rows.length===0){console.log(`No exhausted ${TARGET_LABEL[mode]}s older than ${ttlHours}h.`);return}let plural=rows.length===1?"":"s";console.log(`Would archive ${rows.length} ${TARGET_LABEL[mode]}${plural} older than ${ttlHours}h:`);for(let r of rows)console.log(` ${r.id} (last state change: ${r.lastStateChange})`)}async function runArchive(mode,ttlHours){let ids=await archiveTargets(mode,ttlHours);if(ids.length===0){console.log(`No exhausted ${TARGET_LABEL[mode]}s older than ${ttlHours}h. Nothing to archive.`);return}let plural=ids.length===1?"":"s";console.log(`Archived ${ids.length} ${TARGET_LABEL[mode]}${plural} older than ${ttlHours}h:`);for(let id of ids)console.log(` ${id}`)}function resolveMode(options){if(options.zombies&&options.errored)console.error("Error: --zombies and --errored are mutually exclusive."),process.exit(2);if(options.zombies)return"zombies";if(options.errored)return"errored";console.error("Error: no prune target specified. Use `--zombies` or `--errored`."),console.error("See `genie prune --help` for available targets."),process.exit(2)}async function pruneCommand(options){let mode=resolveMode(options),ttlHours=options.ttlHours??DEFAULT_TTL_HOURS[mode];if(!await isAvailable())console.error("Database is not running. Start it with: genie db status"),process.exit(1);try{await(options.dryRun?runDryRun(mode,ttlHours):runArchive(mode,ttlHours))}catch(err){let message=err instanceof Error?err.message:String(err);console.error(`Prune failed: ${message}`),process.exit(1)}finally{await shutdown().catch(()=>{})}}function registerPruneCommands(program2){program2.command("prune").description("Bulk cleanup of stale or exhausted registry entries").option("--zombies","Archive reconciler-tagged dead-pane zombies (24h default TTL)").option("--errored","Archive any exhausted error-state agent regardless of reason (1h default TTL; set auto_resume=true to keep a row visible)").option("--dry-run","List targets that would be affected without mutating").option("--ttl-hours <hours>","Override the mode default TTL in hours (24 for --zombies, 1 for --errored)",(v)=>parsePositiveInt(v,"--ttl-hours")).action(pruneCommand)}init_agent_registry();import{readFile as readFile16,stat as stat10}from"fs/promises";import{join as join85}from"path";import{readFile as readFile14}from"fs/promises";async function parseQaSpec(filePath){let content=await readFile14(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(`
|
|
4365
|
-
`),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 mkdir11,rm as rm4,writeFile as writeFile10}from"fs/promises";import{tmpdir as tmpdir4}from"os";import{dirname as dirname28,join as join84,resolve as resolve17}from"path";var{$:$4}=globalThis.Bun;import{createHash as createHash9}from"crypto";import{mkdir as mkdir10,readFile as readFile15,readdir as readdir10,stat as stat9,writeFile as writeFile9}from"fs/promises";import{homedir as
|
|
4368
|
+
`),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 mkdir11,rm as rm4,writeFile as writeFile10}from"fs/promises";import{tmpdir as tmpdir4}from"os";import{dirname as dirname28,join as join84,resolve as resolve17}from"path";var{$:$4}=globalThis.Bun;import{createHash as createHash9}from"crypto";import{mkdir as mkdir10,readFile as readFile15,readdir as readdir10,stat as stat9,writeFile as writeFile9}from"fs/promises";import{homedir as homedir49}from"os";import{join as join83,relative as relative8,resolve as resolve16}from"path";function repoHash(repoPath){return createHash9("sha256").update(resolve16(repoPath)).digest("hex").slice(0,12)}function resultsDir(repoPath){let base=process.env.GENIE_HOME??join83(homedir49(),".genie");return join83(base,"qa",repoHash(repoPath))}function resultsPath(repoPath){return join83(resultsDir(repoPath),"results.json")}async function loadResults(repoPath){try{let raw=await readFile15(resultsPath(repoPath),"utf-8");return JSON.parse(raw)}catch{return{}}}async function saveResult(repoPath,specKey,report2){let dir=resultsDir(repoPath);await mkdir10(dir,{recursive:!0});let results=await loadResults(repoPath),specHash=await hashSpecFile(report2.file);results[specKey]={lastRun:new Date().toISOString(),result:report2.result,durationMs:report2.durationMs,specHash,expectations:report2.expectations,error:report2.error},await writeFile9(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 readFile15(filePath,"utf-8");return createHash9("sha256").update(content).digest("hex").slice(0,12)}catch{return"unknown"}}async function walkSpecs(baseDir,dir,entries){let items=await readdir10(dir);for(let item of items){let fullPath=join83(dir,item);if((await stat9(fullPath)).isDirectory())await walkSpecs(baseDir,fullPath,entries);else if(item.endsWith(".md")){let rel=relative8(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 relative8(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)}
|
|
4366
4369
|
`)}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(status2,parts,index){if(status2.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:status2.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 status2=parts[i2++]??"";if(!status2)break;let{op,nextIndex}=parseStatusEntry(status2,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(join84(worktreePath,op.path),{recursive:!0,force:!0});continue}if(op.kind==="rename"){await rm4(join84(worktreePath,op.from),{recursive:!0,force:!0});let src2=join84(repoPath,op.to),dest2=join84(worktreePath,op.to);await mkdir11(dirname28(dest2),{recursive:!0}),await cp2(src2,dest2,{recursive:!0,force:!0});continue}let src=join84(repoPath,op.path),dest=join84(worktreePath,op.path);await mkdir11(dirname28(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(`
|
|
4367
4370
|
[qa] Creating ${entries.length} teams...`);for(let entry2 of entries){let teamName=`qa-${Date.now().toString(36)}-${entry2.name.slice(0,8)}`;try{let spec=await parseQaSpec(entry2.filePath),config=await createTeam(teamName,repoPath);await overlayDirtyWorkingTree(repoPath,config.worktreePath),await hireAgent(teamName,"qa");let prompt2=buildTeamLeadPrompt(spec,teamName,repoPath),promptFile=join84(tmpdir4(),`genie-qa-${teamName}.md`);await writeFile10(promptFile,prompt2),prepared.push({entry:entry2,spec,teamName,worktreePath:config.worktreePath,promptFile}),console.error(` \u2713 ${entry2.name}`),await emitQaEvent(repoPath,"team-created",{type:"qa:team-created",specKey:entry2.key,domain:entry2.domain,team:teamName},ndjson)}catch(err){console.error(` \u2717 ${entry2.name}: ${err instanceof Error?err.message:err}`)}await new Promise((r)=>setTimeout(r,200))}return prepared}async function emitSpecDone(repoPath,specKey,domain,team,report2,ndjson){await emitQaEvent(repoPath,"spec-done",{type:"qa:spec-done",specKey,domain,team,result:report2.result,durationMs:report2.durationMs,expectations:report2.expectations,error:report2.error},ndjson)}async function runSpecEntries(entries,specDir,options){let repoPath=resolve17(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(`
|
|
4368
4371
|
[qa] Running ${prepared.length} specs (max ${maxConcurrency} parallel)
|
|
@@ -4877,5 +4880,5 @@ Examples:
|
|
|
4877
4880
|
genie spawn engineer # Spawn built-in engineer role
|
|
4878
4881
|
genie spawn researcher --model sonnet # Spawn with model override
|
|
4879
4882
|
genie spawn my-agent --team my-feature # Spawn into a specific team
|
|
4880
|
-
genie spawn council--questioner --provider codex # Use Codex provider`).action(async(name,options)=>{if(options.autoSync===!1)options.noAutoSync=!0;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("status").description("Aggregated observability \u2014 agents to resume, active alerts, optional health checklist").option("--health","Add the four-item health checklist (partition, watchdog, spill, watcher metrics)").option("--all","Include archived / done agents").option("--debug","Add structural-inference audit (former `doctor --state`)").option("--json","Emit JSON instead of human output").action(async(options)=>{try{await statusCommand2(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});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)").option("--all","Include archived agents (hidden by default)").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){let{isTuiDisabled:isTuiDisabled2,noticeTuiSkipped:noticeTuiSkipped2}=await Promise.resolve().then(() => (init_tui_disable(),exports_tui_disable));if(isTuiDisabled2())noticeTuiSkipped2("renderer"),await new Promise(()=>{}),process.exit(0);if(tuiRightPane)process.env.GENIE_TUI_RIGHT=tuiRightPane;let{launchTui:launchTui2}=await Promise.resolve().then(() => (init_tui(),exports_tui));await launchTui2(),process.exit(0)}if(args.length===0){{let{isTuiDisabled:isTuiDisabled2,noticeTuiSkipped:noticeTuiSkipped2}=await Promise.resolve().then(() => (init_tui_disable(),exports_tui_disable));if(isTuiDisabled2())noticeTuiSkipped2("attach"),console.error(" Use `genie ls`, `genie spawn <agent>`, `genie log`, etc. directly."),console.error(" Unset GENIE_TUI_DISABLE (or omit --no-tui) to re-enable the TUI."),process.exit(0)}if(process.env.TMUX?.includes("genie-tui")){let{findWorkspace:findWorkspace3}=await Promise.resolve().then(() => (init_workspace(),exports_workspace)),ws2=findWorkspace3();if(ws2){let{resolveAgentFromCwd:resolveAgentFromCwd3}=await Promise.resolve().then(() => (init_resolve_agent_cwd(),exports_resolve_agent_cwd)),resolved2=resolveAgentFromCwd3(process.cwd(),ws2.root);if(resolved2.source!=="default"){let{writeFileSync:writeFileSync34}=await import("fs"),{join:join95}=await import("path"),home=process.env.GENIE_HOME??join95((await import("os")).homedir(),".genie");try{writeFileSync34(join95(home,"tui-initial-agent"),resolved2.agent,"utf-8")}catch{}console.log(`Navigating to ${resolved2.agent}...`)}else console.log("Already inside the genie TUI. Use Ctrl-b d to detach, or run genie commands directly.")}else 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:confirm3}=await Promise.resolve().then(() => (init_esm14(),exports_esm));if(!await confirm3({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:
|
|
4883
|
+
genie spawn council--questioner --provider codex # Use Codex provider`).action(async(name,options)=>{if(options.autoSync===!1)options.noAutoSync=!0;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("status").description("Aggregated observability \u2014 agents to resume, active alerts, optional health checklist").option("--health","Add the four-item health checklist (partition, watchdog, spill, watcher metrics)").option("--all","Include archived / done agents").option("--debug","Add structural-inference audit (former `doctor --state`)").option("--json","Emit JSON instead of human output").action(async(options)=>{try{await statusCommand2(options)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}});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)").option("--all","Include archived agents (hidden by default)").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){let{isTuiDisabled:isTuiDisabled2,noticeTuiSkipped:noticeTuiSkipped2}=await Promise.resolve().then(() => (init_tui_disable(),exports_tui_disable));if(isTuiDisabled2())noticeTuiSkipped2("renderer"),await new Promise(()=>{}),process.exit(0);if(tuiRightPane)process.env.GENIE_TUI_RIGHT=tuiRightPane;let{launchTui:launchTui2}=await Promise.resolve().then(() => (init_tui(),exports_tui));await launchTui2(),process.exit(0)}if(args.length===0){{let{isTuiDisabled:isTuiDisabled2,noticeTuiSkipped:noticeTuiSkipped2}=await Promise.resolve().then(() => (init_tui_disable(),exports_tui_disable));if(isTuiDisabled2())noticeTuiSkipped2("attach"),console.error(" Use `genie ls`, `genie spawn <agent>`, `genie log`, etc. directly."),console.error(" Unset GENIE_TUI_DISABLE (or omit --no-tui) to re-enable the TUI."),process.exit(0)}if(process.env.TMUX?.includes("genie-tui")){let{findWorkspace:findWorkspace3}=await Promise.resolve().then(() => (init_workspace(),exports_workspace)),ws2=findWorkspace3();if(ws2){let{resolveAgentFromCwd:resolveAgentFromCwd3}=await Promise.resolve().then(() => (init_resolve_agent_cwd(),exports_resolve_agent_cwd)),resolved2=resolveAgentFromCwd3(process.cwd(),ws2.root);if(resolved2.source!=="default"){let{writeFileSync:writeFileSync34}=await import("fs"),{join:join95}=await import("path"),home=process.env.GENIE_HOME??join95((await import("os")).homedir(),".genie");try{writeFileSync34(join95(home,"tui-initial-agent"),resolved2.agent,"utf-8")}catch{}console.log(`Navigating to ${resolved2.agent}...`)}else console.log("Already inside the genie TUI. Use Ctrl-b d to detach, or run genie commands directly.")}else 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:confirm3}=await Promise.resolve().then(() => (init_esm14(),exports_esm));if(!await confirm3({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:mkdirSync36,writeFileSync:writeFileSync34}=await import("fs"),{basename:basename17,join:join95}=await import("path"),cwd=process.cwd(),genieDir=join95(cwd,".genie");mkdirSync36(genieDir,{recursive:!0});let config={name:basename17(cwd),agents:{defaults:{}},tmux:{socket:"genie"},sdk:{}};if(writeFileSync34(join95(genieDir,"workspace.json"),`${JSON.stringify(config,null,2)}
|
|
4881
4884
|
`),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:execSync19}=await import("child_process");try{execSync19(`tmux has-session -t =${initialAgent} 2>/dev/null`,{stdio:"pipe"})}catch{console.log(`Spawning ${initialAgent}...`);try{execSync19(`genie spawn ${initialAgent}`,{stdio:"inherit",timeout:15000})}catch{}}}if(initialAgent){let{writeFileSync:writeFileSync34}=await import("fs"),{join:join95}=await import("path"),home=process.env.GENIE_HOME??join95((await import("os")).homedir(),".genie");try{writeFileSync34(join95(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{await stopOtelReceiver().catch(()=>{}),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(await stopOtelReceiver().catch(()=>{}),await shutdown().catch(()=>{}),process.env.GENIE_PROFILE_DB)console.error(`[profile] shutdown=${Date.now()-_shutStart}ms`)}
|