@automagik/genie 4.260506.2 → 4.260506.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/genie.js
CHANGED
|
@@ -2611,10 +2611,11 @@ ${queryContent}`;let{messages:queryMessages}=state.provider.runQuery({agentId:se
|
|
|
2611
2611
|
`}}class TurnTracker{turns=new Map;open(sessionKey2,turnId,messageId){this.turns.set(sessionKey2,{turnId,sessionKey:sessionKey2,messageId,startedAt:Date.now(),closed:!1})}close(sessionKey2,action){let turn=this.turns.get(sessionKey2);if(turn&&!turn.closed)turn.closed=!0,turn.closedAction=action}isOpen(sessionKey2){let turn=this.turns.get(sessionKey2);return turn!==void 0&&!turn.closed}getTurnId(sessionKey2){return this.turns.get(sessionKey2)?.turnId}getByTurnId(turnId){for(let turn of this.turns.values())if(turn.turnId===turnId)return turn;return}delete(sessionKey2){this.turns.delete(sessionKey2)}}var exports_omni_bridge={};__export(exports_omni_bridge,{OmniBridge:()=>OmniBridge});import{closeSync as closeSync4,existsSync as existsSync48,mkdirSync as mkdirSync21,openSync as openSync4,readFileSync as readFileSync30,unlinkSync as unlinkSync9,writeSync}from"fs";import{dirname as dirname18}from"path";function withTimeout2(p,ms,label){return new Promise((resolve11,reject)=>{let timer2=setTimeout(()=>reject(Error(`${label} timed out after ${ms}ms`)),ms);timer2.unref?.(),p.then((v)=>{clearTimeout(timer2),resolve11(v)},(err)=>{clearTimeout(timer2),reject(err)})})}function isPgConnectionError(err){if(!err||typeof err!=="object")return!1;let e=err,code=e.code??"";if(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EPIPE","EHOSTUNREACH"].includes(code))return!0;let msg=e.message??String(err);return/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EPIPE|connection terminated|connection closed|server closed the connection|the database system is shutting down/i.test(msg)}class OmniBridge{nc=null;sub=null;executor;turnTracker=new TurnTracker;heartbeatPublisher=null;sessions=new Map;messageQueue=[];recentMessageIds=new Map;idleCheckTimer=null;sc=import_nats4.StringCodec();sql=null;pgAvailable=!1;pgProvider;natsConnectFn;queueConfig;queue=null;sessionStore=null;natsUrl;idleTimeoutMs;maxConcurrent;executorType;pidfilePath=null;startedAtMs=0;pingSub=null;signalCleanup=null;constructor(config={}){if(this.natsUrl=config.natsUrl??process.env.GENIE_NATS_URL??DEFAULT_NATS_URL2,this.idleTimeoutMs=config.idleTimeoutMs??(process.env.GENIE_IDLE_TIMEOUT_MS?Number(process.env.GENIE_IDLE_TIMEOUT_MS):DEFAULT_IDLE_TIMEOUT_MS2),this.maxConcurrent=config.maxConcurrent??(process.env.GENIE_MAX_CONCURRENT?Number(process.env.GENIE_MAX_CONCURRENT):DEFAULT_MAX_CONCURRENT),this.pgProvider=config.pgProvider??(async()=>{let{getConnection:getConnection2}=await Promise.resolve().then(() => (init_db(),exports_db));return await getConnection2()}),this.natsConnectFn=config.natsConnectFn??import_nats4.connect,this.queueConfig=config.queue??{},this.executorType=resolveExecutorType(config.executorType),this.executorType==="sdk")this.executor=new ClaudeSdkOmniExecutor;else this.executor=new ClaudeCodeOmniExecutor}async start(){if(this.nc){console.log("[omni-bridge] Already running");return}console.log(`[omni-bridge] Connecting to NATS at ${this.natsUrl}...`),this.nc=await this.natsConnectFn({servers:this.natsUrl,name:"genie-omni-bridge",reconnect:!0,maxReconnectAttempts:-1,reconnectTimeWait:2000}),console.log("[omni-bridge] Connected to NATS"),await this.setupPg(),this.wireExecutorHooks(),this.subscribeOmniChannels(),this.startedAtMs=Date.now(),this.subscribePingChannel(),await this.claimPidfile(),this.armSignalCleanup(),this.idleCheckTimer=setInterval(()=>this.checkIdleSessions(),IDLE_CHECK_INTERVAL_MS),console.log(`[omni-bridge] Listening on omni.message.> (max_concurrent=${this.maxConcurrent}, idle_timeout=${this.idleTimeoutMs}ms)`)}async setupPg(){if(await this.probePg(),this.pgAvailable&&this.sql)this.sessionStore=new BridgeSessionStore(this.sql),await this.recoverSessions();if(this.executorType==="sdk"&&this.pgAvailable&&this.sql)this.queue=new OmniQueue(this.sql,(_req,msg)=>this.routeMessage(msg),this.queueConfig),await this.queue.recoverStale(),this.queue.start()}wireExecutorHooks(){this.executor.setSafePgCall(this.safePgCall.bind(this));let sc=this.sc,nc=this.nc;if(!nc)return;let publish=(topic,payload)=>{nc.publish(topic,sc.encode(payload))};this.executor.setNatsPublish(publish),this.heartbeatPublisher=new HeartbeatPublisher({publish})}subscribeOmniChannels(){if(!this.nc)return;this.sub=this.nc.subscribe("omni.message.>",{queue:"genie-bridge"}),this.processSubscription();let turnSubs=["omni.turn.open.>","omni.turn.done.>","omni.turn.nudge.>","omni.turn.timeout.>"];for(let topic of turnSubs){let sub=this.nc.subscribe(topic,{queue:"genie-bridge"});this.processTurnEvents(sub)}let sessionResetSub=this.nc.subscribe("omni.session.reset.>",{queue:"genie-bridge"});this.processSessionResetEvents(sessionResetSub)}subscribePingChannel(){if(!this.nc)return;this.pingSub=this.nc.subscribe(BRIDGE_PING_SUBJECT);let pingSub=this.pingSub,pingSc=this.sc,pingStart=this.startedAtMs;(async()=>{for await(let m of pingSub){let pong={ok:!0,pid:process.pid,uptimeMs:Date.now()-pingStart,subjects:["omni.message.>","omni.turn.open.>","omni.session.reset.>",BRIDGE_PING_SUBJECT]};try{m.respond(pingSc.encode(JSON.stringify(pong)))}catch{}}})().catch(()=>{})}async claimPidfile(){this.pidfilePath=getBridgePidfilePath();try{mkdirSync21(dirname18(this.pidfilePath),{recursive:!0}),this.evictStalePidfile(this.pidfilePath);let fd=openSync4(this.pidfilePath,"wx"),payload=JSON.stringify({pid:process.pid,startedAt:this.startedAtMs,subjects:["omni.message.>","omni.turn.open.>","omni.session.reset.>",BRIDGE_PING_SUBJECT],natsUrl:this.natsUrl});writeSync(fd,payload),closeSync4(fd)}catch(err){await this.rollbackStartOnPidfileError(err)}}evictStalePidfile(path3){if(!existsSync48(path3))return;let stalePid=null;try{let raw=readFileSync30(path3,"utf8"),parsed=JSON.parse(raw);if(typeof parsed.pid==="number"&&Number.isFinite(parsed.pid))stalePid=parsed.pid}catch{}if(stalePid!==null&&this.isPidAlive(stalePid))throw Error(`pidfile locked by PID ${stalePid}`);try{unlinkSync9(path3)}catch{}}isPidAlive(pid){try{return process.kill(pid,0),!0}catch(probeErr){return probeErr.code!=="ESRCH"}}async rollbackStartOnPidfileError(err){this.pidfilePath=null;let detail=err instanceof Error?err.message:String(err);try{if(this.pingSub)this.pingSub.unsubscribe()}catch{}this.pingSub=null;try{await this.nc?.drain()}catch{}throw this.nc=null,Error(`[omni-bridge] pidfile locked at ${getBridgePidfilePath()}: ${detail}`)}armSignalCleanup(){let onSignal=()=>{if(this.pidfilePath){try{unlinkSync9(this.pidfilePath)}catch{}this.pidfilePath=null}};process.once("SIGTERM",onSignal),process.once("SIGINT",onSignal),this.signalCleanup=()=>{process.removeListener("SIGTERM",onSignal),process.removeListener("SIGINT",onSignal)}}async stop(){if(!this.nc){console.log("[omni-bridge] Not running");return}if(console.log("[omni-bridge] Shutting down..."),this.queue)this.queue.stop(),this.queue=null;if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null;if(this.heartbeatPublisher?.stopAll(),this.heartbeatPublisher=null,await this.shutdownActiveSessions(),this.unsubscribeChannels(),this.clearPidfileOnStop(),this.signalCleanup)this.signalCleanup(),this.signalCleanup=null;try{await this.nc.drain()}catch{}this.nc=null,this.sql=null,this.pgAvailable=!1,this.sessionStore=null,console.log("[omni-bridge] Stopped")}async shutdownActiveSessions(){for(let[key,entry2]of this.sessions){if(entry2.idleTimer)clearTimeout(entry2.idleTimer);if(entry2.spawning||!entry2.session)continue;if(entry2.session.executorType==="tmux"){console.log(`[omni-bridge] Detaching from tmux session ${key} (pane stays alive)`);continue}try{await this.executor.shutdown(entry2.session)}catch(err){console.warn(`[omni-bridge] Error shutting down session ${key}:`,err)}let closeId=entry2.pgBridgeSessionId;if(closeId&&this.sessionStore)await this.safePgCall("session_close_sdk",(sql)=>new BridgeSessionStore(sql).close(closeId),void 0)}this.sessions.clear()}unsubscribeChannels(){if(this.sub)this.sub.unsubscribe(),this.sub=null;if(this.pingSub){try{this.pingSub.unsubscribe()}catch{}this.pingSub=null}}clearPidfileOnStop(){if(!this.pidfilePath)return;try{unlinkSync9(this.pidfilePath)}catch{}this.pidfilePath=null}async status(){let now=Date.now(),activeFromPg=null,executorIds=[];if(this.pgAvailable&&this.sql){let rows=await this.safePgCall("status_active_count",async(sql)=>sql`
|
|
2612
2612
|
SELECT id FROM executors
|
|
2613
2613
|
WHERE ended_at IS NULL AND metadata->>'source' = 'omni'
|
|
2614
|
-
`,null);if(rows)activeFromPg=rows.length,executorIds=rows.map((r)=>r.id)}let pgQueue=null;if(this.queue)pgQueue=await this.safePgCall("status_queue_stats",(_sql)=>this.queue?.stats()??Promise.resolve(null),null);return{connected:this.nc!==null,natsUrl:this.natsUrl,pgAvailable:this.pgAvailable,activeSessions:activeFromPg??this.sessions.size,maxConcurrent:this.maxConcurrent,idleTimeoutMs:this.idleTimeoutMs,queueDepth:pgQueue?pgQueue.pending+pgQueue.processing:this.messageQueue.length,executorType:this.executorType,executorIds,pgQueue,sessions:Array.from(this.sessions.entries()).map(([key,entry2])=>({id:key,agentName:entry2.session.agentName,chatId:entry2.session.chatId,instanceId:entry2.instanceId,executorType:entry2.session.executorType,spawning:entry2.spawning,idleMs:now-entry2.session.lastActivityAt,bufferSize:entry2.buffer.length}))}}async probePg(){try{let sql=await withTimeout2(this.pgProvider(),PG_STARTUP_PROBE_TIMEOUT_MS,"PG provider startup");await withTimeout2(Promise.resolve(sql`SELECT 1`),PG_STARTUP_PROBE_TIMEOUT_MS,"PG SELECT 1 probe"),this.sql=sql,this.pgAvailable=!0,console.log("[omni-bridge] PG reachable \u2014 session recovery enabled")}catch(err){this.sql=null,this.pgAvailable=!1;let msg=err instanceof Error?err.message:String(err);if(isPgConnectionError(err)){console.warn(`[omni-bridge] PG unavailable \u2014 session recovery disabled (${msg})`);return}throw Error(`[omni-bridge] PG schema mismatch or setup error: ${msg}. ${"Run `bun run migrate` (or the equivalent migration command) and retry."}`)}}async recoverSessions(){if(!this.sessionStore)return;let orphanedCount=await this.safePgCall("recover_orphan_all",(sql)=>new BridgeSessionStore(sql).markAllOrphaned(),0);if(orphanedCount>0)console.log(`[omni-bridge] Startup cleanup: orphaned ${orphanedCount} stale session(s) from previous run`)}async safePgCall(op,fn,fallback,ctx){if(!this.pgAvailable||!this.sql)return fallback;let sql=this.sql;try{return await withTimeout2(fn(sql),PG_RUNTIME_QUERY_TIMEOUT_MS,`safePgCall(${op})`)}catch(err){let msg=err instanceof Error?err.message:String(err),execPart=ctx?.executorId?` executor_id=${ctx.executorId}`:"",chatPart=ctx?.chatId?` chat_id=${ctx.chatId}`:"";if(console.warn(`[omni-bridge] safePgCall(${op}) failed${execPart}${chatPart}: ${msg}`),isPgConnectionError(err))this.pgAvailable=!1,this.sql=null,console.warn("[omni-bridge] PG connection lost \u2014 switching to degraded mode");return fallback}}fillSubjectMetadata(parsed,subject){let parts=subject.split(".");if(parts.length<4)return;parsed.instanceId=parsed.instanceId||parts[2],parsed.chatId=parsed.chatId||parts[3]}isDuplicateMessage(messageId){if(!messageId)return!1;if(this.recentMessageIds.has(messageId))return!0;if(this.recentMessageIds.set(messageId,Date.now()),this.recentMessageIds.size>1000){let cutoff=Date.now()-60000;for(let[id,ts3]of this.recentMessageIds)if(ts3<cutoff)this.recentMessageIds.delete(id)}return!1}async dispatchMessage(parsed){if(this.queue){let env=parsed.env??{};await this.queue.enqueue(parsed,env);return}let key=`${parsed.agent}:${parsed.chatId}`,hasSession=this.sessions.has(key);console.log(`[omni-bridge] Routing message for ${key} (hasSession=${hasSession}, queue=${!!this.queue})`),await this.routeMessage(parsed),console.log(`[omni-bridge] routeMessage done for ${key}`)}async processSubscription(){if(!this.sub)return;for await(let msg of this.sub)try{let data=this.sc.decode(msg.data),parsed=JSON.parse(data);this.fillSubjectMetadata(parsed,msg.subject),console.log(`[omni-bridge] NATS message received: ${msg.subject} agent=${parsed.agent} chat=${parsed.chatId}`);let messageId=parsed.messageId;if(this.isDuplicateMessage(messageId)){console.log(`[omni-bridge] Dedup: skipping duplicate messageId=${messageId}`);continue}if(!parsed.chatId||!parsed.agent){console.warn("[omni-bridge] Dropping message: missing chatId or agent",msg.subject);continue}await this.dispatchMessage(parsed)}catch(err){console.error("[omni-bridge] Error processing message:",err)}}async processTurnEvents(sub){for await(let msg of sub)try{let payload=JSON.parse(this.sc.decode(msg.data)),parts=msg.subject.split("."),eventType=parts[2],instanceId=parts[3],chatId=parts.slice(4).join(".");console.log(`[omni-bridge] Turn event: ${eventType} instance=${instanceId} chat=${chatId}`);let sessionKey2=this.findSessionKey(instanceId,chatId);if(!sessionKey2&&payload.turnId){if(sessionKey2=this.findSessionKeyByTurnId(payload.turnId),sessionKey2)console.log(`[omni-bridge] Matched session via turnId fallback: ${sessionKey2}`)}if(sessionKey2)await this.routeTurnEvent(eventType,sessionKey2,payload);else console.log(`[omni-bridge] No session found for turn.${eventType} (instance=${instanceId}, chat=${chatId})`)}catch(err){console.warn("[omni-bridge] Error processing turn event:",err)}}async routeTurnEvent(eventType,sessionKey2,payload){switch(eventType){case"open":this.turnTracker.open(sessionKey2,payload.turnId,payload.messageId),this.startHeartbeat(sessionKey2,payload);break;case"done":this.turnTracker.close(sessionKey2,payload.action),this.heartbeatPublisher?.stop(sessionKey2),await this.handleTurnDone(sessionKey2);break;case"nudge":await this.handleTurnNudge(sessionKey2,payload.message);break;case"timeout":this.heartbeatPublisher?.stop(sessionKey2),await this.handleTurnTimeout(sessionKey2);break}}startHeartbeat(sessionKey2,payload){let publisher=this.heartbeatPublisher;if(!publisher)return;let entry2=this.sessions.get(sessionKey2);if(!entry2)return;let turnId=payload.turnId;if(!turnId)return;publisher.start(sessionKey2,{instanceId:entry2.instanceId,chatId:entry2.session?.chatId??"",turnId,isBusy:async()=>{let live=this.sessions.get(sessionKey2);if(!live?.session)return!1;try{return await this.executor.isBusy(live.session)}catch{return!1}}})}findSessionKeyByTurnId(turnId){for(let[key]of this.sessions)if(this.turnTracker.getTurnId(key)===turnId)return key;return}chatIdMap=new Map;findSessionKey(instanceId,chatId){let resolvedChatId=this.chatIdMap.get(chatId);for(let[key,entry2]of this.sessions){if(entry2.instanceId!==instanceId)continue;if(entry2.session?.chatId===chatId)return key;if(resolvedChatId&&entry2.session?.chatId===resolvedChatId)return key;if(entry2.spawning&&key.endsWith(`:${chatId}`))return key;if(resolvedChatId&&entry2.spawning&&key.endsWith(`:${resolvedChatId}`))return key}return}async handleTurnNudge(sessionKey2,nudgeText){let entry2=this.sessions.get(sessionKey2);if(!entry2?.session)return;try{await this.executor.injectNudge(entry2.session,nudgeText)}catch(err){console.warn(`[omni-bridge] Failed to inject nudge for ${sessionKey2}:`,err)}}async processSessionResetEvents(sub){for await(let msg of sub)try{let parts=msg.subject.split(".");if(parts.length<5){console.warn(`[omni-bridge] Malformed session-reset subject: ${msg.subject}`);continue}let instanceId=parts[3],chatId=parts.slice(4).join("."),action;try{action=JSON.parse(this.sc.decode(msg.data)).action}catch{}await this.handleSessionReset(instanceId,chatId,action)}catch(err){console.warn("[omni-bridge] Error processing session reset event:",err)}}async handleSessionReset(instanceId,chatId,action){let sessionKey2=this.findSessionKey(instanceId,chatId);if(!sessionKey2){console.log(`[omni-bridge] Session reset for cold chat ${instanceId}/${chatId} \u2014 no-op`);return}let entry2=this.sessions.get(sessionKey2);if(!entry2)return;let actionTag=action?` (action=${action})`:"";if(entry2.spawning){console.log(`[omni-bridge] Session reset for spawning ${sessionKey2}${actionTag}, marking cancelled`),entry2.cancelled=!0,entry2.buffer=[],this.turnTracker.close(sessionKey2,"reset"),this.heartbeatPublisher?.stop(sessionKey2),await this.removeSession(sessionKey2),await this.drainQueue();return}if(!entry2.session)return;console.log(`[omni-bridge] Session reset for ${sessionKey2}${actionTag}, evicting`),this.turnTracker.close(sessionKey2,"reset"),this.heartbeatPublisher?.stop(sessionKey2);try{await this.executor.shutdown(entry2.session)}catch(err){console.warn(`[omni-bridge] Error shutting down reset session ${sessionKey2}:`,err)}await this.removeSession(sessionKey2),await this.drainQueue()}async handleTurnDone(sessionKey2){if(!this.sessions.get(sessionKey2)?.session)return;console.log(`[omni-bridge] Turn done for ${sessionKey2}, session stays alive for next message`),this.resetIdleTimer(sessionKey2)}async handleTurnTimeout(sessionKey2){let entry2=this.sessions.get(sessionKey2);if(!entry2?.session)return;console.warn(`[omni-bridge] Turn timed out for ${sessionKey2}, evicting session`),this.turnTracker.close(sessionKey2,"timeout"),this.heartbeatPublisher?.stop(sessionKey2);try{await this.executor.shutdown(entry2.session)}catch(err){console.warn(`[omni-bridge] Error shutting down timed-out session ${sessionKey2}:`,err)}this.sessions.delete(sessionKey2)}async routeMessage(message){let key=`${message.agent}:${message.chatId}`,entry2=this.sessions.get(key);if(entry2){if(entry2.spawning){if(entry2.buffer.length<MAX_BUFFER_PER_CHAT)entry2.buffer.push(message);else console.warn(`[omni-bridge] Buffer full (${MAX_BUFFER_PER_CHAT}) for ${key}, dropping message from ${message.sender}`),await this.publishBufferFullReply(message);return}if(await this.executor.isAlive(entry2.session)){await this.executor.deliver(entry2.session,message),this.resetIdleTimer(key);let bsId=entry2.pgBridgeSessionId;if(bsId&&this.sessionStore)this.safePgCall("session_activity",(sql)=>new BridgeSessionStore(sql).recordActivity(bsId),void 0,{chatId:message.chatId});return}await this.removeSession(key)}await this.spawnSession(message)}async spawnSession(message){let key=`${message.agent}:${message.chatId}`,existing=this.sessions.get(key);if(existing){if(existing.buffer.length<MAX_BUFFER_PER_CHAT)existing.buffer.push(message),console.log(`[omni-bridge] Buffered message for existing session ${key} (buffer=${existing.buffer.length})`);return}if(this.sessions.size>=this.maxConcurrent){this.messageQueue.push(message),await this.publishAutoReply(message),console.log(`[omni-bridge] Max concurrent (${this.maxConcurrent}) reached, queued message for ${key}`);return}let placeholder={session:null,instanceId:message.instanceId,spawning:!0,buffer:[message],idleTimer:null};this.sessions.set(key,placeholder);try{let raw=message,payloadEnv=raw.env,spawnEnv={OMNI_API_KEY:payloadEnv?.OMNI_API_KEY??process.env.OMNI_API_KEY??"",OMNI_INSTANCE:payloadEnv?.OMNI_INSTANCE??message.instanceId,OMNI_CHAT:payloadEnv?.OMNI_CHAT??message.chatId,OMNI_MESSAGE:payloadEnv?.OMNI_MESSAGE??raw.messageId??"",OMNI_TURN_ID:payloadEnv?.OMNI_TURN_ID||"",OMNI_SENDER_NAME:payloadEnv?.OMNI_SENDER_NAME??message.sender??""};console.log(`[omni-bridge] Spawning session for ${key}...`);let session=await this.executor.spawn(message.agent,message.chatId,spawnEnv,message.content);if(placeholder.cancelled){console.log(`[omni-bridge] Spawn for ${key} completed but was cancelled by reset, shutting down`);try{await this.executor.shutdown(session)}catch(err){console.warn(`[omni-bridge] Error shutting down cancelled spawn for ${key}:`,err)}return}if(placeholder.session=session,placeholder.spawning=!1,this.sessionStore){let claudeSessionId=session.sdk?.claudeSessionId??session.tmux?.claudeSessionId,pgId=await this.safePgCall("session_create",(sql)=>new BridgeSessionStore(sql).create({instanceId:message.instanceId,chatId:message.chatId,agentName:message.agent,executorId:session.sdk?.executorId,tmuxPaneId:session.tmux?.paneId,claudeSessionId}),void 0,{chatId:message.chatId});if(pgId)placeholder.pgBridgeSessionId=pgId}for(let buffered of placeholder.buffer)await this.executor.deliver(session,buffered);placeholder.buffer=[],this.resetIdleTimer(key);let sessionTag=session.executorType==="tmux"?`(tmux pane=${session.tmux?.paneId})`:"(executor=sdk)";console.log(`[omni-bridge] Session active: ${key} ${sessionTag}`)}catch(err){console.error(`[omni-bridge] Failed to spawn session for ${key}:`,err);let lostMessages=placeholder.buffer;if(lostMessages.length>0)console.warn(`[omni-bridge] Re-queuing ${lostMessages.length} buffered message(s) from failed spawn for ${key}`),this.messageQueue.push(...lostMessages);this.sessions.delete(key)}}resetIdleTimer(key){let entry2=this.sessions.get(key);if(!entry2)return;if(entry2.idleTimer)clearTimeout(entry2.idleTimer);entry2.idleTimer=setTimeout(async()=>{console.log(`[omni-bridge] Idle timeout for ${key}, shutting down...`);try{await this.executor.shutdown(entry2.session)}catch{}await this.removeSession(key),await this.drainQueue()},this.idleTimeoutMs)}async checkIdleSessions(){let now=Date.now();for(let[key,entry2]of this.sessions){if(entry2.spawning)continue;if(!await this.executor.isAlive(entry2.session)){console.log(`[omni-bridge] Dead session detected: ${key}`),await this.removeSession(key);continue}let idleMs=now-entry2.session.lastActivityAt;if(idleMs>this.idleTimeoutMs){console.log(`[omni-bridge] Forcing idle shutdown: ${key} (idle ${Math.round(idleMs/1000)}s)`);try{await this.executor.shutdown(entry2.session)}catch{}await this.removeSession(key)}}}async removeSession(key){let entry2=this.sessions.get(key);if(entry2?.idleTimer)clearTimeout(entry2.idleTimer);this.heartbeatPublisher?.stop(key);let closeId=entry2?.pgBridgeSessionId;if(closeId&&this.sessionStore)await this.safePgCall("session_close",(sql)=>new BridgeSessionStore(sql).close(closeId),void 0);this.sessions.delete(key)}async drainQueue(){while(this.messageQueue.length>0){if(this.sessions.size>=this.maxConcurrent)break;let message=this.messageQueue.shift();if(message)await this.spawnSession(message)}}async publishBufferFullReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Fila de mensagens cheia, por favor aguarde e tente novamente.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}async publishAutoReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Aguarde um momento, estou atendendo outros clientes.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}}var import_nats4,DEFAULT_NATS_URL2="localhost:4222",DEFAULT_IDLE_TIMEOUT_MS2=900000,DEFAULT_MAX_CONCURRENT=20,MAX_BUFFER_PER_CHAT=50,IDLE_CHECK_INTERVAL_MS=30000,PG_STARTUP_PROBE_TIMEOUT_MS=5000,PG_RUNTIME_QUERY_TIMEOUT_MS=2000;var init_omni_bridge=__esm(()=>{init_bridge_status();init_executor_config();init_agent_heartbeat();init_claude_code2();init_claude_sdk2();import_nats4=__toESM(require_mod4(),1)});import{existsSync as existsSync49,mkdirSync as mkdirSync22,readFileSync as readFileSync31,readdirSync as readdirSync11,renameSync as renameSync8,statSync as statSync12,writeFileSync as writeFileSync19}from"fs";import{homedir as homedir39}from"os";import{dirname as dirname19,join as join61,resolve as resolvePath4}from"path";import{pathToFileURL}from"url";function scanDir(dirAbs){if(!existsSync49(dirAbs))return[];return readdirSync11(dirAbs).filter((name)=>name.endsWith(".ts")&&!name.startsWith("_")&&!name.endsWith(".test.ts")).map((name)=>join61(dirAbs,name)).filter((p)=>{try{return statSync12(p).isFile()}catch{return!1}})}function discoverHooks(opts){let home=homedir39(),discovered=[],teamsRoot=join61(home,".claude","teams");if(existsSync49(teamsRoot))for(let teamName of readdirSync11(teamsRoot)){if(teamName.startsWith("_"))continue;let teamHooksDir=join61(teamsRoot,teamName,"hooks");for(let path3 of scanDir(teamHooksDir))discovered.push({path:path3,scope:"team",teamName})}if(opts.repoRoot){let repoHooksDir=join61(opts.repoRoot,".genie","hooks"),repoRemoteUrl=opts.resolveRepoRemoteUrl?.(opts.repoRoot)??void 0;for(let path3 of scanDir(repoHooksDir))discovered.push({path:path3,scope:"repo",repoRemoteUrl})}let globalHooksDir=join61(home,".genie","hooks");for(let path3 of scanDir(globalHooksDir))discovered.push({path:path3,scope:"global"});return discovered}function quarantine(filePath,errorMessage){let dir=dirname19(filePath),quarantineDir=join61(dir,"_quarantine");if(!existsSync49(quarantineDir))mkdirSync22(quarantineDir,{recursive:!0});let basename10=filePath.split("/").pop()??"unknown.ts",target=join61(quarantineDir,basename10);try{renameSync8(filePath,target)}catch{}try{writeFileSync19(`${target}.error`,errorMessage,"utf-8")}catch{}return target}function validateHandler(imported){if(typeof imported!=="object"||imported===null)return"expected default export to be an object";let handler=imported;if(handler.version!=="1")return`unknown handler version: ${String(handler.version)} (expected '1')`;if(typeof handler.name!=="string"||handler.name.length===0)return"handler.name must be a non-empty string";if(typeof handler.event!=="string")return"handler.event must be a HookEventName string";if(typeof handler.priority!=="number"||Number.isNaN(handler.priority))return"handler.priority must be a finite number";if(typeof handler.fn!=="function")return"handler.fn must be a function";return null}async function loadExternalHooks(opts={}){let trustPath=opts.trustPath??defaultTrustPath(),trustFile;try{trustFile=readTrustFile(trustPath)}catch(err){let msg=err instanceof Error?err.message:String(err);return console.warn(`[hook-loader] trust file unreadable at ${trustPath}: ${msg} \u2014 refusing to load any external hooks`),[]}let importer=opts.importer??((url)=>import(url.href)),discovered=discoverHooks(opts),loaded=[],seenNames=new Map,outcomes=[];for(let source of discovered){let verify=verifyTrust(source.path,trustFile,{currentRepoRemoteUrl:source.repoRemoteUrl});if(!verify.trusted){outcomes.push({kind:"untrusted",reason:verify.reason,source});continue}let imported;try{imported=await importer(pathToFileURL(resolvePath4(source.path)))}catch(err){let msg=err instanceof Error?`${err.name}: ${err.message}`:String(err),quarantined=quarantine(source.path,msg);outcomes.push({kind:"broken",error:msg,source,quarantined});continue}let handlerCandidate=imported.default,validationError=validateHandler(handlerCandidate);if(validationError!==null){let quarantined=quarantine(source.path,validationError);outcomes.push({kind:"broken",error:validationError,source,quarantined});continue}let stamped={...handlerCandidate,source:source.scope,manifest_path:source.path},existing=seenNames.get(stamped.name);if(existing){if(console.warn(`[hook-loader] handler name collision: "${stamped.name}" registered from ${existing.path} (${existing.scope}) shadows ${source.path} (${source.scope})`),opts.strict)throw Error(`--strict-hooks: handler name collision on "${stamped.name}" between ${existing.path} and ${source.path}`);outcomes.push({kind:"shadowed",handler:stamped,source,shadowedBy:existing});continue}parseCapabilities(readFileSync31(source.path,"utf-8")),seenNames.set(stamped.name,source),loaded.push(stamped),outcomes.push({kind:"loaded",handler:stamped,source})}let builtins=getRegistry().filter((h)=>h.source==="builtin");return setRegistry([...builtins,...loaded]),outcomes}var init_loader=__esm(()=>{init_hooks();init_trust()});var exports_hook_socket={};__export(exports_hook_socket,{startHookSocket:()=>startHookSocket,defaultHookSocketPath:()=>defaultHookSocketPath});import{existsSync as existsSync50,unlinkSync as unlinkSync10}from"fs";import{mkdir as mkdir7}from"fs/promises";import{createServer,connect as netConnect}from"net";import{homedir as homedir40}from"os";import{dirname as dirname20,join as join62}from"path";function defaultHookSocketPath(){if(process.env.GENIE_HOOK_SOCK)return process.env.GENIE_HOOK_SOCK;let home=process.env.GENIE_HOME??join62(homedir40(),".genie");return join62(home,"hook.sock")}async function detectStaleAndCleanup(socketPath){if(!existsSync50(socketPath))return"clean";if(await new Promise((resolve11)=>{let probe=netConnect(socketPath),finish=(alive)=>{try{probe.destroy()}catch{}resolve11(alive)};probe.once("connect",()=>finish(!0)),probe.once("error",()=>finish(!1)),setTimeout(()=>finish(!1),200).unref()}))return"live";try{return unlinkSync10(socketPath),"stale-removed"}catch(err){throw Error(`Failed to remove stale hook socket at ${socketPath}: ${err.message}`)}}function parseFrame(acc,length){if(length===-1){if(acc.length<4)return{kind:"incomplete",length:-1};let declared=acc.readUInt32BE(0);if(declared>MAX_FRAME_BYTES2)return{kind:"error",reason:`frame length ${declared} exceeds MAX_FRAME_BYTES`};if(declared===0)return{kind:"done",body:Buffer.alloc(0)};if(acc.length>=4+declared)return{kind:"done",body:acc.subarray(4,4+declared)};return{kind:"incomplete",length:declared}}if(acc.length>=4+length)return{kind:"done",body:acc.subarray(4,4+length)};return{kind:"incomplete",length}}function readOneFrame(socket){return new Promise((resolve11,reject)=>{let acc=Buffer.alloc(0),length=-1,cleanup=()=>{socket.off("data",onData),socket.off("end",onEnd),socket.off("error",onError)},onData=(chunk)=>{acc=acc.length===0?Buffer.from(chunk):Buffer.concat([acc,Buffer.from(chunk)],acc.length+chunk.length);let result2=parseFrame(acc,length);if(result2.kind==="incomplete"){length=result2.length;return}if(cleanup(),result2.kind==="done")resolve11(result2.body);else reject(Error(result2.reason))},onEnd=()=>{cleanup(),reject(Error(`socket closed after ${acc.length} bytes (expected ${length===-1?"4+":4+length})`))},onError=(err)=>{cleanup(),reject(err)};socket.on("data",onData),socket.on("end",onEnd),socket.on("error",onError)})}function writeFrame(socket,payload){let body=Buffer.from(payload,"utf-8");if(body.length>MAX_FRAME_BYTES2){let empty=Buffer.alloc(4);socket.end(empty);return}let header=Buffer.alloc(4);header.writeUInt32BE(body.length,0),socket.end(Buffer.concat([header,body]))}async function handleConnection(socket){socket.setNoDelay(!0);try{let body=await readOneFrame(socket),stdin=body.length===0?"":body.toString("utf-8"),reply=await dispatch(stdin);writeFrame(socket,reply??"")}catch(err){try{writeFrame(socket,"")}catch{}if(process.env.GENIE_HOOK_SOCK_DEBUG==="1")console.warn(`[hook-socket] connection error: ${err.message}`)}}async function startHookSocket(options={}){if(process.env.GENIE_WIDE_EMIT===void 0)process.env.GENIE_WIDE_EMIT="1";let loaderOutcomes=[];if(options.loadExternal!==!1)loaderOutcomes=await loadExternalHooks({repoRoot:options.repoRoot,strict:options.strict}),summarizeLoaderOutcomes(loaderOutcomes);let socketPath=defaultHookSocketPath();await mkdir7(dirname20(socketPath),{recursive:!0});let state=await detectStaleAndCleanup(socketPath);if(state==="live")throw Error(`hook socket at ${socketPath} is already live \u2014 another genie serve daemon is running. Refusing to start.`);if(state==="stale-removed")console.log(`hook-socket: removed stale socket at ${socketPath}`);let liveSockets=new Set,server3=createServer((socket)=>{liveSockets.add(socket),socket.once("close",()=>liveSockets.delete(socket)),handleConnection(socket)});await new Promise((resolve11,reject)=>{let onError=(err)=>{server3.off("listening",onListening),reject(err)},onListening=()=>{server3.off("error",onError),resolve11()};server3.once("error",onError),server3.once("listening",onListening),server3.listen(socketPath)}),console.log(`hook-socket: listening at ${socketPath}`);let stopped=!1;return{path:socketPath,stop:async()=>{if(stopped)return;stopped=!0;for(let sock of liveSockets)try{sock.destroy()}catch{}if(liveSockets.clear(),await new Promise((resolve11)=>{server3.close(()=>resolve11())}),existsSync50(socketPath))try{unlinkSync10(socketPath)}catch{}},loaderOutcomes}}function summarizeLoaderOutcomes(outcomes){if(outcomes.length===0)return;let loaded=0,untrusted=0,broken=0,shadowed=0;for(let outcome of outcomes)if(outcome.kind==="loaded")loaded+=1;else if(outcome.kind==="untrusted")untrusted+=1;else if(outcome.kind==="broken")broken+=1;else shadowed+=1;let parts=[`hook-loader: ${loaded} loaded`];if(untrusted>0)parts.push(`${untrusted} untrusted`);if(broken>0)parts.push(`${broken} broken (quarantined)`);if(shadowed>0)parts.push(`${shadowed} shadowed`);console.log(parts.join(", "))}var MAX_FRAME_BYTES2=1048576;var init_hook_socket=__esm(()=>{init_hooks();init_loader()});var exports_serve={};__export(exports_serve,{writeStoppingLockSync:()=>writeStoppingLockSync,startBrainServerIfEnabled:()=>startBrainServerIfEnabled,registerServeCommands:()=>registerServeCommands,isTuiSessionReady:()=>isTuiSessionReady,isStoppingLockActive:()=>isStoppingLockActive,isServeRunning:()=>isServeRunning,getTuiQuitBindingArgs:()=>getTuiQuitBindingArgs,getTuiKeybindings:()=>getTuiKeybindings,ensureTuiSession:()=>ensureTuiSession,clearStoppingLock:()=>clearStoppingLock,autoStartServe:()=>autoStartServe});import{execSync as execSync10,spawn as spawn4,spawnSync as spawnSync6}from"child_process";import{closeSync as closeSync5,existsSync as existsSync51,mkdirSync as mkdirSync23,openSync as openSync5,readFileSync as readFileSync32,unlinkSync as unlinkSync11,writeFileSync as writeFileSync20,writeSync as writeSync2}from"fs";import{homedir as homedir41}from"os";import{dirname as dirname21,join as join63}from"path";function genieHome3(){return process.env.GENIE_HOME??join63(homedir41(),".genie")}function servePidPath(){return join63(genieHome3(),"serve.pid")}function serveStartupStatusPath(){return join63(genieHome3(),"state",`serve-startup-${process.pid}-${Date.now()}.json`)}function readServePid(){let path3=servePidPath();if(!existsSync51(path3))return null;let raw=readFileSync32(path3,"utf-8").trim();if(raw==="")return null;let sepIdx=raw.indexOf(":");if(sepIdx<0){let pid2=Number.parseInt(raw,10);if(Number.isNaN(pid2)||pid2<=0)return null;return{pid:pid2,startTime:null}}let pidPart=raw.slice(0,sepIdx),startTimePart=raw.slice(sepIdx+1).trim(),pid=Number.parseInt(pidPart,10);if(Number.isNaN(pid)||pid<=0)return null;return{pid,startTime:startTimePart===""||startTimePart==="unknown"?null:startTimePart}}function removeServePid(){let path3=servePidPath();if(!existsSync51(path3))return;try{let current=readServePid();if(current&¤t.pid!==process.pid)return;unlinkSync11(path3)}catch{}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}function stoppingLockPath(){return join63(genieHome3(),"serve.stopping.lock")}function writeStoppingLockSync(ttlMs=STOPPING_LOCK_TTL_MS){mkdirSync23(genieHome3(),{recursive:!0}),writeFileSync20(stoppingLockPath(),String(Date.now()+ttlMs),"utf-8")}function clearStoppingLock(){try{unlinkSync11(stoppingLockPath())}catch{}}function isStoppingLockActive(){let path3=stoppingLockPath();if(!existsSync51(path3))return!1;let raw;try{raw=readFileSync32(path3,"utf-8").trim()}catch{return!1}let expiresAt=Number.parseInt(raw,10);if(raw===""||Number.isNaN(expiresAt)||expiresAt<=Date.now())return clearStoppingLock(),!1;return!0}function tuiTmuxConf(){return[join63(genieHome3(),"tui-tmux.conf")].find((p)=>existsSync51(p))??"/dev/null"}function tuiTmux(subcmd){return`${tmuxBin()} -L genie-tui -f ${tuiTmuxConf()} ${subcmd}`}function isGenieTmuxRunning(){try{return execSync10(genieTmuxCmd("list-sessions"),{stdio:"ignore"}),!0}catch{return!1}}function getTuiKeybindings(sessionName=TUI_SESSION){return[`bind-key -T root Tab if-shell "[ '#{pane_index}' = '0' ]" "select-pane -t ${sessionName}:0.1" "select-pane -t ${sessionName}:0.0"`,`bind-key -T root C-1 select-pane -t ${sessionName}:0.0`,`bind-key -T root C-2 select-pane -t ${sessionName}:0.1`,`bind-key -T root C-b if-shell "[ $(tmux display-message -p '#\\{pane_width\\}' -t ${sessionName}:0.0) -gt 5 ]" "resize-pane -t ${sessionName}:0.0 -x 0" "resize-pane -t ${sessionName}:0.0 -x ${NAV_WIDTH}"`,`bind-key -T root C-t select-pane -t ${sessionName}:0.0 \\; send-keys -t ${sessionName}:0.0 C-t`,"bind-key -T root C-d detach-client",`bind-key -T root C-q select-pane -t ${sessionName}:0.0 \\; send-keys -t ${sessionName}:0.0 C-q`]}function getTuiQuitBindingArgs(sessionName=TUI_SESSION){return["bind-key","-T","root","C-q","select-pane","-t",`${sessionName}:0.0`,"\\;","send-keys","-t",`${sessionName}:0.0`,"C-q"]}function applyTuiStyle(){let cmds=[`set-option -t ${TUI_SESSION} pane-border-style 'fg=${TUI_STYLE.inactiveBorder}'`,`set-option -t ${TUI_SESSION} pane-active-border-style 'fg=${TUI_STYLE.activeBorder}'`,...process.env.GENIE_TMUX_MOUSE!=="off"?[`set-option -t ${TUI_SESSION} mouse on`]:[],`set-option -t ${TUI_SESSION} status off`,`set-option -t ${TUI_SESSION} pane-border-status off`];for(let cmd of cmds)try{execSync10(tuiTmux(cmd),{stdio:"ignore"})}catch{}}function setupTuiKeybindings(){for(let cmd of getTuiKeybindings())try{if(cmd.startsWith("bind-key -T root C-q "))spawnSync6(tmuxBin(),["-L","genie-tui","-f",tuiTmuxConf(),...getTuiQuitBindingArgs()],{stdio:"ignore"});else execSync10(tuiTmux(cmd),{stdio:"ignore"})}catch{}}function startTuiTmuxServer(){try{execSync10(tuiTmux(`has-session -t ${TUI_SESSION}`),{stdio:"ignore"});let panes2=execSync10(tuiTmux(`list-panes -t ${TUI_SESSION}:0 -F '#{pane_id}'`),{encoding:"utf-8"}).trim().split(`
|
|
2615
|
-
|
|
2616
|
-
`);applyTuiStyle(),setupTuiKeybindings();try{execSync10(tuiTmux(`select-pane -t ${
|
|
2617
|
-
`)
|
|
2614
|
+
`,null);if(rows)activeFromPg=rows.length,executorIds=rows.map((r)=>r.id)}let pgQueue=null;if(this.queue)pgQueue=await this.safePgCall("status_queue_stats",(_sql)=>this.queue?.stats()??Promise.resolve(null),null);return{connected:this.nc!==null,natsUrl:this.natsUrl,pgAvailable:this.pgAvailable,activeSessions:activeFromPg??this.sessions.size,maxConcurrent:this.maxConcurrent,idleTimeoutMs:this.idleTimeoutMs,queueDepth:pgQueue?pgQueue.pending+pgQueue.processing:this.messageQueue.length,executorType:this.executorType,executorIds,pgQueue,sessions:Array.from(this.sessions.entries()).map(([key,entry2])=>({id:key,agentName:entry2.session.agentName,chatId:entry2.session.chatId,instanceId:entry2.instanceId,executorType:entry2.session.executorType,spawning:entry2.spawning,idleMs:now-entry2.session.lastActivityAt,bufferSize:entry2.buffer.length}))}}async probePg(){try{let sql=await withTimeout2(this.pgProvider(),PG_STARTUP_PROBE_TIMEOUT_MS,"PG provider startup");await withTimeout2(Promise.resolve(sql`SELECT 1`),PG_STARTUP_PROBE_TIMEOUT_MS,"PG SELECT 1 probe"),this.sql=sql,this.pgAvailable=!0,console.log("[omni-bridge] PG reachable \u2014 session recovery enabled")}catch(err){this.sql=null,this.pgAvailable=!1;let msg=err instanceof Error?err.message:String(err);if(isPgConnectionError(err)){console.warn(`[omni-bridge] PG unavailable \u2014 session recovery disabled (${msg})`);return}throw Error(`[omni-bridge] PG schema mismatch or setup error: ${msg}. ${"Run `bun run migrate` (or the equivalent migration command) and retry."}`)}}async recoverSessions(){if(!this.sessionStore)return;let orphanedCount=await this.safePgCall("recover_orphan_all",(sql)=>new BridgeSessionStore(sql).markAllOrphaned(),0);if(orphanedCount>0)console.log(`[omni-bridge] Startup cleanup: orphaned ${orphanedCount} stale session(s) from previous run`)}async safePgCall(op,fn,fallback,ctx){if(!this.pgAvailable||!this.sql)return fallback;let sql=this.sql;try{return await withTimeout2(fn(sql),PG_RUNTIME_QUERY_TIMEOUT_MS,`safePgCall(${op})`)}catch(err){let msg=err instanceof Error?err.message:String(err),execPart=ctx?.executorId?` executor_id=${ctx.executorId}`:"",chatPart=ctx?.chatId?` chat_id=${ctx.chatId}`:"";if(console.warn(`[omni-bridge] safePgCall(${op}) failed${execPart}${chatPart}: ${msg}`),isPgConnectionError(err))this.pgAvailable=!1,this.sql=null,console.warn("[omni-bridge] PG connection lost \u2014 switching to degraded mode");return fallback}}fillSubjectMetadata(parsed,subject){let parts=subject.split(".");if(parts.length<4)return;parsed.instanceId=parsed.instanceId||parts[2],parsed.chatId=parsed.chatId||parts[3]}isDuplicateMessage(messageId){if(!messageId)return!1;if(this.recentMessageIds.has(messageId))return!0;if(this.recentMessageIds.set(messageId,Date.now()),this.recentMessageIds.size>1000){let cutoff=Date.now()-60000;for(let[id,ts3]of this.recentMessageIds)if(ts3<cutoff)this.recentMessageIds.delete(id)}return!1}async dispatchMessage(parsed){if(this.queue){let env=parsed.env??{};await this.queue.enqueue(parsed,env);return}let key=`${parsed.agent}:${parsed.chatId}`,hasSession=this.sessions.has(key);console.log(`[omni-bridge] Routing message for ${key} (hasSession=${hasSession}, queue=${!!this.queue})`),await this.routeMessage(parsed),console.log(`[omni-bridge] routeMessage done for ${key}`)}async processSubscription(){if(!this.sub)return;for await(let msg of this.sub)try{let data=this.sc.decode(msg.data),parsed=JSON.parse(data);this.fillSubjectMetadata(parsed,msg.subject),console.log(`[omni-bridge] NATS message received: ${msg.subject} agent=${parsed.agent} chat=${parsed.chatId}`);let messageId=parsed.messageId;if(this.isDuplicateMessage(messageId)){console.log(`[omni-bridge] Dedup: skipping duplicate messageId=${messageId}`);continue}if(!parsed.chatId||!parsed.agent){console.warn("[omni-bridge] Dropping message: missing chatId or agent",msg.subject);continue}await this.dispatchMessage(parsed)}catch(err){console.error("[omni-bridge] Error processing message:",err)}}async processTurnEvents(sub){for await(let msg of sub)try{let payload=JSON.parse(this.sc.decode(msg.data)),parts=msg.subject.split("."),eventType=parts[2],instanceId=parts[3],chatId=parts.slice(4).join(".");console.log(`[omni-bridge] Turn event: ${eventType} instance=${instanceId} chat=${chatId}`);let sessionKey2=this.findSessionKey(instanceId,chatId);if(!sessionKey2&&payload.turnId){if(sessionKey2=this.findSessionKeyByTurnId(payload.turnId),sessionKey2)console.log(`[omni-bridge] Matched session via turnId fallback: ${sessionKey2}`)}if(sessionKey2)await this.routeTurnEvent(eventType,sessionKey2,payload);else console.log(`[omni-bridge] No session found for turn.${eventType} (instance=${instanceId}, chat=${chatId})`)}catch(err){console.warn("[omni-bridge] Error processing turn event:",err)}}async routeTurnEvent(eventType,sessionKey2,payload){switch(eventType){case"open":this.turnTracker.open(sessionKey2,payload.turnId,payload.messageId),this.startHeartbeat(sessionKey2,payload);break;case"done":this.turnTracker.close(sessionKey2,payload.action),this.heartbeatPublisher?.stop(sessionKey2),await this.handleTurnDone(sessionKey2);break;case"nudge":await this.handleTurnNudge(sessionKey2,payload.message);break;case"timeout":this.heartbeatPublisher?.stop(sessionKey2),await this.handleTurnTimeout(sessionKey2);break}}startHeartbeat(sessionKey2,payload){let publisher=this.heartbeatPublisher;if(!publisher)return;let entry2=this.sessions.get(sessionKey2);if(!entry2)return;let turnId=payload.turnId;if(!turnId)return;publisher.start(sessionKey2,{instanceId:entry2.instanceId,chatId:entry2.session?.chatId??"",turnId,isBusy:async()=>{let live=this.sessions.get(sessionKey2);if(!live?.session)return!1;try{return await this.executor.isBusy(live.session)}catch{return!1}}})}findSessionKeyByTurnId(turnId){for(let[key]of this.sessions)if(this.turnTracker.getTurnId(key)===turnId)return key;return}chatIdMap=new Map;findSessionKey(instanceId,chatId){let resolvedChatId=this.chatIdMap.get(chatId);for(let[key,entry2]of this.sessions){if(entry2.instanceId!==instanceId)continue;if(entry2.session?.chatId===chatId)return key;if(resolvedChatId&&entry2.session?.chatId===resolvedChatId)return key;if(entry2.spawning&&key.endsWith(`:${chatId}`))return key;if(resolvedChatId&&entry2.spawning&&key.endsWith(`:${resolvedChatId}`))return key}return}async handleTurnNudge(sessionKey2,nudgeText){let entry2=this.sessions.get(sessionKey2);if(!entry2?.session)return;try{await this.executor.injectNudge(entry2.session,nudgeText)}catch(err){console.warn(`[omni-bridge] Failed to inject nudge for ${sessionKey2}:`,err)}}async processSessionResetEvents(sub){for await(let msg of sub)try{let parts=msg.subject.split(".");if(parts.length<5){console.warn(`[omni-bridge] Malformed session-reset subject: ${msg.subject}`);continue}let instanceId=parts[3],chatId=parts.slice(4).join("."),action;try{action=JSON.parse(this.sc.decode(msg.data)).action}catch{}await this.handleSessionReset(instanceId,chatId,action)}catch(err){console.warn("[omni-bridge] Error processing session reset event:",err)}}async handleSessionReset(instanceId,chatId,action){let sessionKey2=this.findSessionKey(instanceId,chatId);if(!sessionKey2){console.log(`[omni-bridge] Session reset for cold chat ${instanceId}/${chatId} \u2014 no-op`);return}let entry2=this.sessions.get(sessionKey2);if(!entry2)return;let actionTag=action?` (action=${action})`:"";if(entry2.spawning){console.log(`[omni-bridge] Session reset for spawning ${sessionKey2}${actionTag}, marking cancelled`),entry2.cancelled=!0,entry2.buffer=[],this.turnTracker.close(sessionKey2,"reset"),this.heartbeatPublisher?.stop(sessionKey2),await this.removeSession(sessionKey2),await this.drainQueue();return}if(!entry2.session)return;console.log(`[omni-bridge] Session reset for ${sessionKey2}${actionTag}, evicting`),this.turnTracker.close(sessionKey2,"reset"),this.heartbeatPublisher?.stop(sessionKey2);try{await this.executor.shutdown(entry2.session)}catch(err){console.warn(`[omni-bridge] Error shutting down reset session ${sessionKey2}:`,err)}await this.removeSession(sessionKey2),await this.drainQueue()}async handleTurnDone(sessionKey2){if(!this.sessions.get(sessionKey2)?.session)return;console.log(`[omni-bridge] Turn done for ${sessionKey2}, session stays alive for next message`),this.resetIdleTimer(sessionKey2)}async handleTurnTimeout(sessionKey2){let entry2=this.sessions.get(sessionKey2);if(!entry2?.session)return;console.warn(`[omni-bridge] Turn timed out for ${sessionKey2}, evicting session`),this.turnTracker.close(sessionKey2,"timeout"),this.heartbeatPublisher?.stop(sessionKey2);try{await this.executor.shutdown(entry2.session)}catch(err){console.warn(`[omni-bridge] Error shutting down timed-out session ${sessionKey2}:`,err)}this.sessions.delete(sessionKey2)}async routeMessage(message){let key=`${message.agent}:${message.chatId}`,entry2=this.sessions.get(key);if(entry2){if(entry2.spawning){if(entry2.buffer.length<MAX_BUFFER_PER_CHAT)entry2.buffer.push(message);else console.warn(`[omni-bridge] Buffer full (${MAX_BUFFER_PER_CHAT}) for ${key}, dropping message from ${message.sender}`),await this.publishBufferFullReply(message);return}if(await this.executor.isAlive(entry2.session)){await this.executor.deliver(entry2.session,message),this.resetIdleTimer(key);let bsId=entry2.pgBridgeSessionId;if(bsId&&this.sessionStore)this.safePgCall("session_activity",(sql)=>new BridgeSessionStore(sql).recordActivity(bsId),void 0,{chatId:message.chatId});return}await this.removeSession(key)}await this.spawnSession(message)}async spawnSession(message){let key=`${message.agent}:${message.chatId}`,existing=this.sessions.get(key);if(existing){if(existing.buffer.length<MAX_BUFFER_PER_CHAT)existing.buffer.push(message),console.log(`[omni-bridge] Buffered message for existing session ${key} (buffer=${existing.buffer.length})`);return}if(this.sessions.size>=this.maxConcurrent){this.messageQueue.push(message),await this.publishAutoReply(message),console.log(`[omni-bridge] Max concurrent (${this.maxConcurrent}) reached, queued message for ${key}`);return}let placeholder={session:null,instanceId:message.instanceId,spawning:!0,buffer:[message],idleTimer:null};this.sessions.set(key,placeholder);try{let raw=message,payloadEnv=raw.env,spawnEnv={OMNI_API_KEY:payloadEnv?.OMNI_API_KEY??process.env.OMNI_API_KEY??"",OMNI_INSTANCE:payloadEnv?.OMNI_INSTANCE??message.instanceId,OMNI_CHAT:payloadEnv?.OMNI_CHAT??message.chatId,OMNI_MESSAGE:payloadEnv?.OMNI_MESSAGE??raw.messageId??"",OMNI_TURN_ID:payloadEnv?.OMNI_TURN_ID||"",OMNI_SENDER_NAME:payloadEnv?.OMNI_SENDER_NAME??message.sender??""};console.log(`[omni-bridge] Spawning session for ${key}...`);let session=await this.executor.spawn(message.agent,message.chatId,spawnEnv,message.content);if(placeholder.cancelled){console.log(`[omni-bridge] Spawn for ${key} completed but was cancelled by reset, shutting down`);try{await this.executor.shutdown(session)}catch(err){console.warn(`[omni-bridge] Error shutting down cancelled spawn for ${key}:`,err)}return}if(placeholder.session=session,placeholder.spawning=!1,this.sessionStore){let claudeSessionId=session.sdk?.claudeSessionId??session.tmux?.claudeSessionId,pgId=await this.safePgCall("session_create",(sql)=>new BridgeSessionStore(sql).create({instanceId:message.instanceId,chatId:message.chatId,agentName:message.agent,executorId:session.sdk?.executorId,tmuxPaneId:session.tmux?.paneId,claudeSessionId}),void 0,{chatId:message.chatId});if(pgId)placeholder.pgBridgeSessionId=pgId}for(let buffered of placeholder.buffer)await this.executor.deliver(session,buffered);placeholder.buffer=[],this.resetIdleTimer(key);let sessionTag=session.executorType==="tmux"?`(tmux pane=${session.tmux?.paneId})`:"(executor=sdk)";console.log(`[omni-bridge] Session active: ${key} ${sessionTag}`)}catch(err){console.error(`[omni-bridge] Failed to spawn session for ${key}:`,err);let lostMessages=placeholder.buffer;if(lostMessages.length>0)console.warn(`[omni-bridge] Re-queuing ${lostMessages.length} buffered message(s) from failed spawn for ${key}`),this.messageQueue.push(...lostMessages);this.sessions.delete(key)}}resetIdleTimer(key){let entry2=this.sessions.get(key);if(!entry2)return;if(entry2.idleTimer)clearTimeout(entry2.idleTimer);entry2.idleTimer=setTimeout(async()=>{console.log(`[omni-bridge] Idle timeout for ${key}, shutting down...`);try{await this.executor.shutdown(entry2.session)}catch{}await this.removeSession(key),await this.drainQueue()},this.idleTimeoutMs)}async checkIdleSessions(){let now=Date.now();for(let[key,entry2]of this.sessions){if(entry2.spawning)continue;if(!await this.executor.isAlive(entry2.session)){console.log(`[omni-bridge] Dead session detected: ${key}`),await this.removeSession(key);continue}let idleMs=now-entry2.session.lastActivityAt;if(idleMs>this.idleTimeoutMs){console.log(`[omni-bridge] Forcing idle shutdown: ${key} (idle ${Math.round(idleMs/1000)}s)`);try{await this.executor.shutdown(entry2.session)}catch{}await this.removeSession(key)}}}async removeSession(key){let entry2=this.sessions.get(key);if(entry2?.idleTimer)clearTimeout(entry2.idleTimer);this.heartbeatPublisher?.stop(key);let closeId=entry2?.pgBridgeSessionId;if(closeId&&this.sessionStore)await this.safePgCall("session_close",(sql)=>new BridgeSessionStore(sql).close(closeId),void 0);this.sessions.delete(key)}async drainQueue(){while(this.messageQueue.length>0){if(this.sessions.size>=this.maxConcurrent)break;let message=this.messageQueue.shift();if(message)await this.spawnSession(message)}}async publishBufferFullReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Fila de mensagens cheia, por favor aguarde e tente novamente.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}async publishAutoReply(message){if(!this.nc)return;let topic=`omni.reply.${message.instanceId}.${message.chatId}`,reply={content:"Aguarde um momento, estou atendendo outros clientes.",agent:message.agent,chat_id:message.chatId,instance_id:message.instanceId,timestamp:new Date().toISOString(),auto_reply:!0};this.nc.publish(topic,this.sc.encode(JSON.stringify(reply)))}}var import_nats4,DEFAULT_NATS_URL2="localhost:4222",DEFAULT_IDLE_TIMEOUT_MS2=900000,DEFAULT_MAX_CONCURRENT=20,MAX_BUFFER_PER_CHAT=50,IDLE_CHECK_INTERVAL_MS=30000,PG_STARTUP_PROBE_TIMEOUT_MS=5000,PG_RUNTIME_QUERY_TIMEOUT_MS=2000;var init_omni_bridge=__esm(()=>{init_bridge_status();init_executor_config();init_agent_heartbeat();init_claude_code2();init_claude_sdk2();import_nats4=__toESM(require_mod4(),1)});import{existsSync as existsSync49,mkdirSync as mkdirSync22,readFileSync as readFileSync31,readdirSync as readdirSync11,renameSync as renameSync8,statSync as statSync12,writeFileSync as writeFileSync19}from"fs";import{homedir as homedir39}from"os";import{dirname as dirname19,join as join61,resolve as resolvePath4}from"path";import{pathToFileURL}from"url";function scanDir(dirAbs){if(!existsSync49(dirAbs))return[];return readdirSync11(dirAbs).filter((name)=>name.endsWith(".ts")&&!name.startsWith("_")&&!name.endsWith(".test.ts")).map((name)=>join61(dirAbs,name)).filter((p)=>{try{return statSync12(p).isFile()}catch{return!1}})}function discoverHooks(opts){let home=homedir39(),discovered=[],teamsRoot=join61(home,".claude","teams");if(existsSync49(teamsRoot))for(let teamName of readdirSync11(teamsRoot)){if(teamName.startsWith("_"))continue;let teamHooksDir=join61(teamsRoot,teamName,"hooks");for(let path3 of scanDir(teamHooksDir))discovered.push({path:path3,scope:"team",teamName})}if(opts.repoRoot){let repoHooksDir=join61(opts.repoRoot,".genie","hooks"),repoRemoteUrl=opts.resolveRepoRemoteUrl?.(opts.repoRoot)??void 0;for(let path3 of scanDir(repoHooksDir))discovered.push({path:path3,scope:"repo",repoRemoteUrl})}let globalHooksDir=join61(home,".genie","hooks");for(let path3 of scanDir(globalHooksDir))discovered.push({path:path3,scope:"global"});return discovered}function quarantine(filePath,errorMessage){let dir=dirname19(filePath),quarantineDir=join61(dir,"_quarantine");if(!existsSync49(quarantineDir))mkdirSync22(quarantineDir,{recursive:!0});let basename10=filePath.split("/").pop()??"unknown.ts",target=join61(quarantineDir,basename10);try{renameSync8(filePath,target)}catch{}try{writeFileSync19(`${target}.error`,errorMessage,"utf-8")}catch{}return target}function validateHandler(imported){if(typeof imported!=="object"||imported===null)return"expected default export to be an object";let handler=imported;if(handler.version!=="1")return`unknown handler version: ${String(handler.version)} (expected '1')`;if(typeof handler.name!=="string"||handler.name.length===0)return"handler.name must be a non-empty string";if(typeof handler.event!=="string")return"handler.event must be a HookEventName string";if(typeof handler.priority!=="number"||Number.isNaN(handler.priority))return"handler.priority must be a finite number";if(typeof handler.fn!=="function")return"handler.fn must be a function";return null}async function loadExternalHooks(opts={}){let trustPath=opts.trustPath??defaultTrustPath(),trustFile;try{trustFile=readTrustFile(trustPath)}catch(err){let msg=err instanceof Error?err.message:String(err);return console.warn(`[hook-loader] trust file unreadable at ${trustPath}: ${msg} \u2014 refusing to load any external hooks`),[]}let importer=opts.importer??((url)=>import(url.href)),discovered=discoverHooks(opts),loaded=[],seenNames=new Map,outcomes=[];for(let source of discovered){let verify=verifyTrust(source.path,trustFile,{currentRepoRemoteUrl:source.repoRemoteUrl});if(!verify.trusted){outcomes.push({kind:"untrusted",reason:verify.reason,source});continue}let imported;try{imported=await importer(pathToFileURL(resolvePath4(source.path)))}catch(err){let msg=err instanceof Error?`${err.name}: ${err.message}`:String(err),quarantined=quarantine(source.path,msg);outcomes.push({kind:"broken",error:msg,source,quarantined});continue}let handlerCandidate=imported.default,validationError=validateHandler(handlerCandidate);if(validationError!==null){let quarantined=quarantine(source.path,validationError);outcomes.push({kind:"broken",error:validationError,source,quarantined});continue}let stamped={...handlerCandidate,source:source.scope,manifest_path:source.path},existing=seenNames.get(stamped.name);if(existing){if(console.warn(`[hook-loader] handler name collision: "${stamped.name}" registered from ${existing.path} (${existing.scope}) shadows ${source.path} (${source.scope})`),opts.strict)throw Error(`--strict-hooks: handler name collision on "${stamped.name}" between ${existing.path} and ${source.path}`);outcomes.push({kind:"shadowed",handler:stamped,source,shadowedBy:existing});continue}parseCapabilities(readFileSync31(source.path,"utf-8")),seenNames.set(stamped.name,source),loaded.push(stamped),outcomes.push({kind:"loaded",handler:stamped,source})}let builtins=getRegistry().filter((h)=>h.source==="builtin");return setRegistry([...builtins,...loaded]),outcomes}var init_loader=__esm(()=>{init_hooks();init_trust()});var exports_hook_socket={};__export(exports_hook_socket,{startHookSocket:()=>startHookSocket,defaultHookSocketPath:()=>defaultHookSocketPath});import{existsSync as existsSync50,unlinkSync as unlinkSync10}from"fs";import{mkdir as mkdir7}from"fs/promises";import{createServer,connect as netConnect}from"net";import{homedir as homedir40}from"os";import{dirname as dirname20,join as join62}from"path";function defaultHookSocketPath(){if(process.env.GENIE_HOOK_SOCK)return process.env.GENIE_HOOK_SOCK;let home=process.env.GENIE_HOME??join62(homedir40(),".genie");return join62(home,"hook.sock")}async function detectStaleAndCleanup(socketPath){if(!existsSync50(socketPath))return"clean";if(await new Promise((resolve11)=>{let probe=netConnect(socketPath),finish=(alive)=>{try{probe.destroy()}catch{}resolve11(alive)};probe.once("connect",()=>finish(!0)),probe.once("error",()=>finish(!1)),setTimeout(()=>finish(!1),200).unref()}))return"live";try{return unlinkSync10(socketPath),"stale-removed"}catch(err){throw Error(`Failed to remove stale hook socket at ${socketPath}: ${err.message}`)}}function parseFrame(acc,length){if(length===-1){if(acc.length<4)return{kind:"incomplete",length:-1};let declared=acc.readUInt32BE(0);if(declared>MAX_FRAME_BYTES2)return{kind:"error",reason:`frame length ${declared} exceeds MAX_FRAME_BYTES`};if(declared===0)return{kind:"done",body:Buffer.alloc(0)};if(acc.length>=4+declared)return{kind:"done",body:acc.subarray(4,4+declared)};return{kind:"incomplete",length:declared}}if(acc.length>=4+length)return{kind:"done",body:acc.subarray(4,4+length)};return{kind:"incomplete",length}}function readOneFrame(socket){return new Promise((resolve11,reject)=>{let acc=Buffer.alloc(0),length=-1,cleanup=()=>{socket.off("data",onData),socket.off("end",onEnd),socket.off("error",onError)},onData=(chunk)=>{acc=acc.length===0?Buffer.from(chunk):Buffer.concat([acc,Buffer.from(chunk)],acc.length+chunk.length);let result2=parseFrame(acc,length);if(result2.kind==="incomplete"){length=result2.length;return}if(cleanup(),result2.kind==="done")resolve11(result2.body);else reject(Error(result2.reason))},onEnd=()=>{cleanup(),reject(Error(`socket closed after ${acc.length} bytes (expected ${length===-1?"4+":4+length})`))},onError=(err)=>{cleanup(),reject(err)};socket.on("data",onData),socket.on("end",onEnd),socket.on("error",onError)})}function writeFrame(socket,payload){let body=Buffer.from(payload,"utf-8");if(body.length>MAX_FRAME_BYTES2){let empty=Buffer.alloc(4);socket.end(empty);return}let header=Buffer.alloc(4);header.writeUInt32BE(body.length,0),socket.end(Buffer.concat([header,body]))}async function handleConnection(socket){socket.setNoDelay(!0);try{let body=await readOneFrame(socket),stdin=body.length===0?"":body.toString("utf-8"),reply=await dispatch(stdin);writeFrame(socket,reply??"")}catch(err){try{writeFrame(socket,"")}catch{}if(process.env.GENIE_HOOK_SOCK_DEBUG==="1")console.warn(`[hook-socket] connection error: ${err.message}`)}}async function startHookSocket(options={}){if(process.env.GENIE_WIDE_EMIT===void 0)process.env.GENIE_WIDE_EMIT="1";let loaderOutcomes=[];if(options.loadExternal!==!1)loaderOutcomes=await loadExternalHooks({repoRoot:options.repoRoot,strict:options.strict}),summarizeLoaderOutcomes(loaderOutcomes);let socketPath=defaultHookSocketPath();await mkdir7(dirname20(socketPath),{recursive:!0});let state=await detectStaleAndCleanup(socketPath);if(state==="live")throw Error(`hook socket at ${socketPath} is already live \u2014 another genie serve daemon is running. Refusing to start.`);if(state==="stale-removed")console.log(`hook-socket: removed stale socket at ${socketPath}`);let liveSockets=new Set,server3=createServer((socket)=>{liveSockets.add(socket),socket.once("close",()=>liveSockets.delete(socket)),handleConnection(socket)});await new Promise((resolve11,reject)=>{let onError=(err)=>{server3.off("listening",onListening),reject(err)},onListening=()=>{server3.off("error",onError),resolve11()};server3.once("error",onError),server3.once("listening",onListening),server3.listen(socketPath)}),console.log(`hook-socket: listening at ${socketPath}`);let stopped=!1;return{path:socketPath,stop:async()=>{if(stopped)return;stopped=!0;for(let sock of liveSockets)try{sock.destroy()}catch{}if(liveSockets.clear(),await new Promise((resolve11)=>{server3.close(()=>resolve11())}),existsSync50(socketPath))try{unlinkSync10(socketPath)}catch{}},loaderOutcomes}}function summarizeLoaderOutcomes(outcomes){if(outcomes.length===0)return;let loaded=0,untrusted=0,broken=0,shadowed=0;for(let outcome of outcomes)if(outcome.kind==="loaded")loaded+=1;else if(outcome.kind==="untrusted")untrusted+=1;else if(outcome.kind==="broken")broken+=1;else shadowed+=1;let parts=[`hook-loader: ${loaded} loaded`];if(untrusted>0)parts.push(`${untrusted} untrusted`);if(broken>0)parts.push(`${broken} broken (quarantined)`);if(shadowed>0)parts.push(`${shadowed} shadowed`);console.log(parts.join(", "))}var MAX_FRAME_BYTES2=1048576;var init_hook_socket=__esm(()=>{init_hooks();init_loader()});var exports_serve={};__export(exports_serve,{writeStoppingLockSync:()=>writeStoppingLockSync,startTuiTmuxServer:()=>startTuiTmuxServer,startBrainServerIfEnabled:()=>startBrainServerIfEnabled,registerServeCommands:()=>registerServeCommands,isTuiSessionReady:()=>isTuiSessionReady,isStoppingLockActive:()=>isStoppingLockActive,isServeRunning:()=>isServeRunning,getTuiQuitBindingArgs:()=>getTuiQuitBindingArgs,getTuiKeybindings:()=>getTuiKeybindings,ensureTuiSession:()=>ensureTuiSession,clearStoppingLock:()=>clearStoppingLock,autoStartServe:()=>autoStartServe});import{execSync as execSync10,spawn as spawn4,spawnSync as spawnSync6}from"child_process";import{appendFileSync as appendFileSync5,closeSync as closeSync5,existsSync as existsSync51,mkdirSync as mkdirSync23,openSync as openSync5,readFileSync as readFileSync32,unlinkSync as unlinkSync11,writeFileSync as writeFileSync20,writeSync as writeSync2}from"fs";import{homedir as homedir41}from"os";import{dirname as dirname21,join as join63}from"path";function genieHome3(){return process.env.GENIE_HOME??join63(homedir41(),".genie")}function servePidPath(){return join63(genieHome3(),"serve.pid")}function serveStartupStatusPath(){return join63(genieHome3(),"state",`serve-startup-${process.pid}-${Date.now()}.json`)}function readServePid(){let path3=servePidPath();if(!existsSync51(path3))return null;let raw=readFileSync32(path3,"utf-8").trim();if(raw==="")return null;let sepIdx=raw.indexOf(":");if(sepIdx<0){let pid2=Number.parseInt(raw,10);if(Number.isNaN(pid2)||pid2<=0)return null;return{pid:pid2,startTime:null}}let pidPart=raw.slice(0,sepIdx),startTimePart=raw.slice(sepIdx+1).trim(),pid=Number.parseInt(pidPart,10);if(Number.isNaN(pid)||pid<=0)return null;return{pid,startTime:startTimePart===""||startTimePart==="unknown"?null:startTimePart}}function removeServePid(){let path3=servePidPath();if(!existsSync51(path3))return;try{let current=readServePid();if(current&¤t.pid!==process.pid)return;unlinkSync11(path3)}catch{}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}function stoppingLockPath(){return join63(genieHome3(),"serve.stopping.lock")}function writeStoppingLockSync(ttlMs=STOPPING_LOCK_TTL_MS){mkdirSync23(genieHome3(),{recursive:!0}),writeFileSync20(stoppingLockPath(),String(Date.now()+ttlMs),"utf-8")}function clearStoppingLock(){try{unlinkSync11(stoppingLockPath())}catch{}}function isStoppingLockActive(){let path3=stoppingLockPath();if(!existsSync51(path3))return!1;let raw;try{raw=readFileSync32(path3,"utf-8").trim()}catch{return!1}let expiresAt=Number.parseInt(raw,10);if(raw===""||Number.isNaN(expiresAt)||expiresAt<=Date.now())return clearStoppingLock(),!1;return!0}function tuiTmuxConf(){return[join63(genieHome3(),"tui-tmux.conf")].find((p)=>existsSync51(p))??"/dev/null"}function tuiTmux(subcmd){return`${tmuxBin()} -L genie-tui -f ${tuiTmuxConf()} ${subcmd}`}function isGenieTmuxRunning(){try{return execSync10(genieTmuxCmd("list-sessions"),{stdio:"ignore"}),!0}catch{return!1}}function getTuiKeybindings(sessionName=TUI_SESSION){return[`bind-key -T root Tab if-shell "[ '#{pane_index}' = '0' ]" "select-pane -t ${sessionName}:0.1" "select-pane -t ${sessionName}:0.0"`,`bind-key -T root C-1 select-pane -t ${sessionName}:0.0`,`bind-key -T root C-2 select-pane -t ${sessionName}:0.1`,`bind-key -T root C-b if-shell "[ $(tmux display-message -p '#\\{pane_width\\}' -t ${sessionName}:0.0) -gt 5 ]" "resize-pane -t ${sessionName}:0.0 -x 0" "resize-pane -t ${sessionName}:0.0 -x ${NAV_WIDTH}"`,`bind-key -T root C-t select-pane -t ${sessionName}:0.0 \\; send-keys -t ${sessionName}:0.0 C-t`,"bind-key -T root C-d detach-client",`bind-key -T root C-q select-pane -t ${sessionName}:0.0 \\; send-keys -t ${sessionName}:0.0 C-q`]}function getTuiQuitBindingArgs(sessionName=TUI_SESSION){return["bind-key","-T","root","C-q","select-pane","-t",`${sessionName}:0.0`,"\\;","send-keys","-t",`${sessionName}:0.0`,"C-q"]}function applyTuiStyle(){let cmds=[`set-option -t ${TUI_SESSION} pane-border-style 'fg=${TUI_STYLE.inactiveBorder}'`,`set-option -t ${TUI_SESSION} pane-active-border-style 'fg=${TUI_STYLE.activeBorder}'`,...process.env.GENIE_TMUX_MOUSE!=="off"?[`set-option -t ${TUI_SESSION} mouse on`]:[],`set-option -t ${TUI_SESSION} status off`,`set-option -t ${TUI_SESSION} pane-border-status off`];for(let cmd of cmds)try{execSync10(tuiTmux(cmd),{stdio:"ignore"})}catch{}}function setupTuiKeybindings(){for(let cmd of getTuiKeybindings())try{if(cmd.startsWith("bind-key -T root C-q "))spawnSync6(tmuxBin(),["-L","genie-tui","-f",tuiTmuxConf(),...getTuiQuitBindingArgs()],{stdio:"ignore"});else execSync10(tuiTmux(cmd),{stdio:"ignore"})}catch{}}function runTuiTmuxCapturing(cmd){try{return execSync10(tuiTmux(cmd),{encoding:"utf-8",stdio:["ignore","pipe","pipe"]})}catch(err){let e=err,stderr=typeof e.stderr==="string"?e.stderr:e.stderr?.toString("utf-8"),stdout=typeof e.stdout==="string"?e.stdout:e.stdout?.toString("utf-8"),detail=(stderr??stdout??e.message??"unknown tmux error").trim();throw Error(`tmux ${cmd}: ${detail}`)}}function logTuiStartupFailure(message){try{let home=genieHome3(),logsDir=join63(home,"logs");mkdirSync23(logsDir,{recursive:!0});let crashLog=join63(logsDir,"tui-crash.log"),line=`[startTuiTmuxServer] ${new Date().toISOString()} ${message.replace(/\s+/g," ").trim()}
|
|
2615
|
+
`;appendFileSync5(crashLog,line)}catch{}}function freshCreateTuiSession(){runTuiTmuxCapturing(`new-session -d -s ${TUI_SESSION} -x 120 -y 40`),runTuiTmuxCapturing(`split-window -h -t ${TUI_SESSION}:0 -l ${120-NAV_WIDTH-1}`);let panes=execSync10(tuiTmux(`list-panes -t ${TUI_SESSION}:0 -F '#{pane_id}'`),{encoding:"utf-8"}).trim().split(`
|
|
2616
|
+
`);applyTuiStyle(),setupTuiKeybindings();try{execSync10(tuiTmux(`select-pane -t ${panes[0]}`),{stdio:"ignore"})}catch{}return{leftPane:panes[0],rightPane:panes[1]||panes[0]}}function startTuiTmuxServer(){try{execSync10(tuiTmux(`has-session -t ${TUI_SESSION}`),{stdio:"ignore"})}catch{return freshCreateTuiSession()}try{let panes=execSync10(tuiTmux(`list-panes -t ${TUI_SESSION}:0 -F '#{pane_id}'`),{encoding:"utf-8"}).trim().split(`
|
|
2617
|
+
`).filter((id)=>id.length>0);if(panes.length>=2){try{execSync10(tuiTmux(`respawn-pane -k -t ${panes[1]} 'cat'`),{stdio:"ignore"})}catch{}return{leftPane:panes[0],rightPane:panes[1]}}let cols=Number.parseInt(execSync10(tuiTmux(`display-message -t ${TUI_SESSION}:0 -p '#{window_width}'`),{encoding:"utf-8"}).trim(),10)||120;runTuiTmuxCapturing(`split-window -h -t ${TUI_SESSION}:0 -l ${cols-NAV_WIDTH-1}`);let refreshed=execSync10(tuiTmux(`list-panes -t ${TUI_SESSION}:0 -F '#{pane_id}'`),{encoding:"utf-8"}).trim().split(`
|
|
2618
|
+
`);applyTuiStyle(),setupTuiKeybindings();try{execSync10(tuiTmux(`select-pane -t ${refreshed[0]}`),{stdio:"ignore"})}catch{}return{leftPane:refreshed[0],rightPane:refreshed[1]||refreshed[0]}}catch(err){let message=err instanceof Error?err.message:String(err);logTuiStartupFailure(message);try{execSync10(tuiTmux(`kill-session -t ${TUI_SESSION}`),{stdio:"ignore"})}catch{}return freshCreateTuiSession()}}function sendTuiLaunchScript(leftPane,rightPane,workspaceRoot){let home=genieHome3(),bunPath=process.execPath||"bun",genieBin=process.argv[1]||"genie",scriptPath=join63(home,"tui-launch.sh"),logsDir=join63(home,"logs"),crashLog=join63(logsDir,"tui-crash.log"),envVars=["GENIE_TUI_PANE=left",`GENIE_TUI_RIGHT=${rightPane}`];if(workspaceRoot)envVars.push(`GENIE_TUI_WORKSPACE=${workspaceRoot}`);let content=["#!/bin/sh",`mkdir -p '${logsDir}'`,`exec 2>> '${crashLog}'`,`printf -- '--- tui-launch %s pid=%s ---\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" >&2`,`export ${envVars.join(`
|
|
2618
2619
|
export `)}`,`exec ${bunPath} ${genieBin}`,""].join(`
|
|
2619
2620
|
`);writeFileSync20(scriptPath,content,{mode:493});try{execSync10(tuiTmux(`send-keys -t '${leftPane}' '${scriptPath}' Enter`),{stdio:"ignore"})}catch{}}function killTuiSession(){try{execSync10(tuiTmux("kill-server"),{stdio:"ignore"})}catch{}}function listAgentSessions(){try{return execSync10(genieTmuxCmd("list-sessions -F '#{session_name}'"),{encoding:"utf-8"}).trim().split(`
|
|
2620
2621
|
`).filter(Boolean)}catch{return[]}}function isServeRunning(){let entry2=readServePid();return entry2!==null&&isProcessAlive(entry2.pid)}async function autoStartServe(){if(isStoppingLockActive()){console.log("genie serve is shutting down \u2014 skipping auto-start.");return}if(isServeRunning())return;let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie",{spawn:spawnChild}=await import("child_process");spawnChild(bunPath,[genieBin,"serve","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref();let deadline=Date.now()+15000;while(Date.now()<deadline)if(await new Promise((resolve11)=>setTimeout(resolve11,500)),isServeRunning()&&isTuiSessionReady())return;if(!isServeRunning())throw Error("genie serve failed to start within 15s. Run `genie serve` manually.")}function isTuiSessionReady(){try{return execSync10(tuiTmux(`has-session -t ${TUI_SESSION}`),{stdio:"ignore"}),!0}catch{return!1}}function ensureTuiSession(workspaceRoot){if(isTuiDisabled()){noticeTuiSkipped("session ensure");return}if(isTuiSessionReady())return;let{leftPane,rightPane}=startTuiTmuxServer();sendTuiLaunchScript(leftPane,rightPane,workspaceRoot)}async function startAgentSync(){try{let{findWorkspace:findWorkspace2,genieHome:genieHome4}=(init_workspace(),__toCommonJS(exports_workspace)),ws=findWorkspace2();if(!ws){let{join:join64}=__require("path"),configPath2=join64(genieHome4(),"config.json");return console.warn(` Agent sync: DISABLED \u2014 no workspace found from cwd or ${configPath2}`),console.warn(" Fix: `cd <workspace> && genie serve restart`, or run `genie init` to bootstrap one"),null}let{syncAgentDirectory:syncAgentDirectory2,watchAgentDirectory:watchAgentDirectory2}=await Promise.resolve().then(() => (init_agent_sync(),exports_agent_sync)),syncResult=await syncAgentDirectory2(ws.root);if(syncResult.registered.length+syncResult.updated.length>0)console.log(` Agent sync: ${syncResult.registered.length} registered, ${syncResult.updated.length} updated (workspace: ${ws.root})`);else console.log(` Agent sync: up to date (workspace: ${ws.root})`);if(syncResult.errors.length>0){console.warn(` Agent sync: ${syncResult.errors.length} error(s) \u2014 these agents were NOT registered:`);for(let e of syncResult.errors)console.warn(` ${e.name}: ${e.error}`)}let watcher2=watchAgentDirectory2(ws.root,{onSync:(name,action)=>{console.log(` [agent-watcher] ${name}: ${action}`)}});if(watcher2)console.log(" Agent watcher started (watching agents/ directory)");else console.warn(" Agent watcher: FAILED to start \u2014 new agents will not be auto-registered");return watcher2}catch(err){let msg=err instanceof Error?err.message:String(err);return console.error(` Agent sync failed: ${msg}`),null}}async function requirePgserveReady(){console.log(" Probing pgserve transport...");try{let{resolvePgserveTransport:resolvePgserveTransport2}=await Promise.resolve().then(() => (init_db(),exports_db)),transport=await resolvePgserveTransport2();if(transport.kind==="unix")console.log(` pgserve ready: unix socket ${transport.socketDir}/.s.PGSQL.${transport.port}`);else console.log(` pgserve ready: tcp ${transport.host}:${transport.port}`);try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("pgserve-owner",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` pgserve unreachable: ${msg}`),process.env.GENIE_PG_NO_AUTOSTART="1",process.env.GENIE_PG_DISABLE_AUTOSTART="1"}}async function startScheduler(){console.log(" Starting scheduler daemon...");try{let{startDaemon:startDaemon2}=await Promise.resolve().then(() => (init_scheduler_daemon(),exports_scheduler_daemon));handles.schedulerHandle=startDaemon2(),console.log(" Scheduler started (includes event-router + inbox-watcher)");try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("scheduler",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Scheduler failed: ${msg}`)}try{let{startDerivedSignalsEngine:startDerivedSignalsEngine2}=await Promise.resolve().then(() => (init_derived_signals(),exports_derived_signals));handles.derivedSignals=await startDerivedSignalsEngine2(),console.log(" Derived-signal rule engine subscribed")}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Derived-signal engine failed: ${msg}`)}}function claimServePidOrExit(){let path3=servePidPath();mkdirSync23(genieHome3(),{recursive:!0});let startTime=getProcessStartTime(process.pid)??"unknown",payload=`${process.pid}:${startTime}`;for(let attempt=0;attempt<2;attempt++)try{let fd=openSync5(path3,"wx",420);try{writeSync2(fd,payload)}finally{closeSync5(fd)}return}catch(err){if(err.code!=="EEXIST")throw err;let existing=readServePid();if(existing&&existing.startTime!==null&&isProcessAlive(existing.pid))console.log(`genie serve already running (PID ${existing.pid})`),warnIfHookSocketMissing(),process.exit(0);forceRemoveServePid()}console.error("Could not claim serve.pid after 2 attempts \u2014 another genie serve is racing this one. "+"Wait a moment and retry, or run `genie serve status`."),process.exit(1)}function resolveServeMode(headless){let tuiDisabled=isTuiDisabled();if(tuiDisabled&&!headless)noticeTuiSkipped("serve");return{skipTui:Boolean(headless)||tuiDisabled,mode:headless?"headless":tuiDisabled?"no-tui":"full"}}async function loadBrainStartupConfig(deps){return deps.loadConfig?.()??(await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config))).loadGenieConfigSync()}async function importBrainForStartup(deps){if(deps.importBrain)return deps.importBrain();return import("@khal-os/brain")}async function getBrainStartupPgPort(deps){return deps.getActivePort?.()??(await Promise.resolve().then(() => (init_db(),exports_db))).getActivePort()}function assignBrainHandles(deps,brainHandles){if(deps.setBrainHandles){deps.setBrainHandles(brainHandles);return}handles.brainHandles=brainHandles}function isMissingBrainModule(message){return message.includes("Cannot find")||message.includes("not found")||message.includes("MODULE_NOT_FOUND")}async function startBrainServer(deps,config,log2,warn){let brain=await importBrainForStartup(deps);if(!brain.startEmbeddedBrainServer)return[];let pgPort=await getBrainStartupPgPort(deps);if(!pgPort)return log2(" Brain server: pgserve not available (skipped)"),[];let resolveVaults=deps.resolveVaults??resolveBrainVaults,startVaults=deps.startVaults??startResolvedBrainVaults,resolution=await resolveVaults({brain,config,warn});if(resolution.paths.length===0)return log2(` Brain server: no ${resolution.source} brain vaults found (skipped)`),[];log2(` Starting brain server (${resolution.paths.length} ${resolution.source} vault(s))...`);let brainHandles=await startVaults(resolution,brain,pgPort,{warn,log:log2});if(assignBrainHandles(deps,brainHandles),brainHandles.length===0)log2(" Brain server: no vaults started");return brainHandles}async function startBrainServerIfEnabled(deps={}){let config=await loadBrainStartupConfig(deps),brainEmbedded=config.brain?.embedded!==!1,log2=deps.log??console.log,warn=deps.warn??console.warn;if(!brainEmbedded)return log2(" Brain server: skipped (brain.embedded=false \u2014 managed externally)"),[];try{return await startBrainServer(deps,config,log2,warn)}catch(err){let msg=err instanceof Error?err.message:String(err);if(isMissingBrainModule(msg))return[];return warn(` Brain server: failed: ${msg}`),[]}}function logAgentSessionInfo(){let sessions=listAgentSessions();if(sessions.length>0)console.log(` Agent server (-L genie): ${sessions.length} sessions`);else console.log(" Agent server (-L genie): no sessions yet (created on first spawn)")}function startTuiSessionIfEnabled(skipTui){if(skipTui)return;console.log(" Setting up TUI session...");let{leftPane,rightPane}=startTuiTmuxServer(),ws=(()=>{try{let{findWorkspace:findWorkspace2}=(init_workspace(),__toCommonJS(exports_workspace));return findWorkspace2()}catch{return null}})();sendTuiLaunchScript(leftPane,rightPane,ws?.root),console.log(" TUI server ready (session: genie-tui)")}async function startDetectorSchedulerSafely(){try{await Promise.resolve().then(() => (init_built_in(),exports_built_in));let{start:startDetectorScheduler}=await Promise.resolve().then(() => (init_detector_scheduler(),exports_detector_scheduler)),{listDetectors:listDetectors2}=await Promise.resolve().then(() => (init_detectors(),exports_detectors));handles.detectorScheduler=startDetectorScheduler();let registered=listDetectors2().map((d)=>d.id);console.log(` Detector scheduler started (measurement only, 60s \xB1 5s cadence) \u2014 registered: [${registered.join(", ")}]`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Detector scheduler: failed \u2014 ${msg}`)}}async function startExecutorReadEndpointSafely(){try{let{startExecutorReadEndpoint:startExecutorReadEndpoint2,getExecutorReadPort:getExecutorReadPort2}=await Promise.resolve().then(() => (init_executor_read(),exports_executor_read));if(await startExecutorReadEndpoint2())console.log(` Executor read endpoint ready on port ${getExecutorReadPort2()}`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Executor read endpoint: failed \u2014 ${msg}`)}}async function startOmniApprovalHandlerSafely(){try{let{startOmniApprovalHandler:startOmniApprovalHandler2}=await Promise.resolve().then(() => (init_omni_approval_handler(),exports_omni_approval_handler)),handler=await startOmniApprovalHandler2();if(handler)handles.omniApprovalHandler=handler,console.log(" Omni approval handler started")}catch{}}async function startOmniBridgeSafely(){let{OmniBridge:OmniBridge2}=await Promise.resolve().then(() => (init_omni_bridge(),exports_omni_bridge)),bridge=new OmniBridge2({natsUrl:process.env.GENIE_NATS_URL??"localhost:4222",maxConcurrent:Number(process.env.GENIE_MAX_CONCURRENT??"20"),idleTimeoutMs:Number(process.env.GENIE_IDLE_TIMEOUT_MS??"900000")});try{await bridge.start(),handles.omniBridge=bridge,console.log(" Omni bridge started")}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.GENIE_OMNI_REQUIRED==="1")console.error(` Omni bridge: FAILED \u2014 ${msg}`),process.exit(1);console.warn(` Omni bridge: degraded \u2014 ${msg}; set GENIE_OMNI_REQUIRED=1 to make this fatal`)}}async function stopSchedulerHandles(){handles.agentWatcher?.close();let schedulerHandle=handles.schedulerHandle;if(schedulerHandle){schedulerHandle.stop();try{await schedulerHandle.done}catch{}handles.schedulerHandle=null}if(handles.detectorScheduler)handles.detectorScheduler.stop(),handles.detectorScheduler=null;if(handles.derivedSignals)await handles.derivedSignals.stop().catch(()=>{}),handles.derivedSignals=null}async function stopOmniAndBrainServices(){if(handles.omniApprovalHandler)await handles.omniApprovalHandler.stop().catch(()=>{}),handles.omniApprovalHandler=null;if(handles.omniBridge)await handles.omniBridge.stop().catch(()=>{}),handles.omniBridge=null;if(Promise.resolve().then(() => (init_executor_read(),exports_executor_read)).then((m)=>m.stopExecutorReadEndpoint().catch(()=>{})),handles.brainHandles.length>0){for(let handle of handles.brainHandles)await handle.stop().catch(()=>{});handles.brainHandles=[]}}function killRegisteredServices(){try{let{killAllServices:killAllServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));killAllServices2()}catch{}}function removeLegacyPgservePortLockfileIfForcedTcp(){if(process.env.GENIE_PG_FORCE_TCP!=="1")return;try{let lockfilePath=join63(genieHome3(),"pgserve.port");if(existsSync51(lockfilePath))unlinkSync11(lockfilePath)}catch{}}function sigKillRegisteredServices(){try{let{getRegisteredServices:getRegisteredServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));for(let svc of getRegisteredServices2())try{process.kill(svc.pid,"SIGKILL")}catch{}}catch{}}async function startHookSocketSafely(){try{let{startHookSocket:startHookSocket2}=await Promise.resolve().then(() => (init_hook_socket(),exports_hook_socket));handles.hookSocket=await startHookSocket2({strict:process.env.GENIE_STRICT_HOOKS==="1",repoRoot:operatorCwd})}catch(err){if(process.env.GENIE_STRICT_HOOKS==="1"&&err.message.includes("--strict-hooks"))throw err;console.warn(` Hook socket: DISABLED \u2014 ${err.message}`),handles.hookSocket=null}}async function stopHookSocketSafely(){if(!handles.hookSocket)return;try{await handles.hookSocket.stop()}catch{}handles.hookSocket=null}function buildShutdownFn(headless){let shutdownStarted=!1;return{shutdown:async()=>{if(shutdownStarted)return;if(shutdownStarted=!0,console.log(`
|
|
@@ -3966,10 +3967,10 @@ Bus `);for(let i2=1;i2<parts.length;i2++){let usb2=parseLinuxUsb(parts[i2]);resu
|
|
|
3966
3967
|
`);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(`
|
|
3967
3968
|
`);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(`
|
|
3968
3969
|
`);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(`
|
|
3969
|
-
`),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=scanAgents2(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?scanAgents2(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:"Close TUI?"},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 close "},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:"Daemon keeps running. `genie serve stop` to shut down."},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";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{execSync18("tmux -L genie-tui kill-server",{stdio:"ignore"})}catch{}},[]);useBindings(()=>({commands:[{name:"app.quit",title:"Close TUI",desc:"Close TUI window (daemon keeps running \u2014 use `genie serve stop` to shut down)",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(`
|
|
3970
|
+
`),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=scanAgents2(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?scanAgents2(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:"Close TUI?"},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 close "},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:"Daemon keeps running. `genie serve stop` to shut down."},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";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{execSync18("tmux -L genie-tui kill-server",{stdio:"ignore"})}catch{}},[]);useBindings(()=>({commands:[{name:"app.quit",title:"Close TUI",desc:"Close TUI window (daemon keeps running \u2014 use `genie serve stop` to shut down)",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 appendFileSync6,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(`
|
|
3970
3971
|
`,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)}
|
|
3971
3972
|
\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} ---
|
|
3972
|
-
`;
|
|
3973
|
+
`;appendFileSync6(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}
|
|
3973
3974
|
`)}function fail(msg){process.stderr.write(`genie install: ${msg}
|
|
3974
3975
|
`),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(`
|
|
3975
3976
|
`)}function failCanonicalPgserve(reason){process.stderr.write(buildCanonicalPgserveHint(reason)),process.exit(1)}function requirePgserveInstall(){if(!pgserveIsAvailable())failCanonicalPgserve("pgserve binary not found in PATH");let result2=spawnSync2("pgserve",["install"],{stdio:"inherit"});if(result2.status!==0)failCanonicalPgserve(`exit code ${result2.status}`)}function tryPgservePort(){if(!pgserveIsAvailable())return null;let result2=spawnSync2("pgserve",["port"],{encoding:"utf8",timeout:5000});if(result2.status!==0)return null;let port=Number.parseInt((result2.stdout??"").trim(),10);if(!Number.isFinite(port)||port<=0||port>65535)return null;return port}function buildGenieDatabaseUrl(port){return`postgresql://postgres:postgres@localhost:${port}/genie`}function resolveGenieBinary(){let wired=which("genie");if(wired)return wired;return process.argv[1]??"genie"}function getEcosystemConfigPath(){return join26(homedir21(),".genie",`${PM2_PROCESS_NAME}.config.cjs`)}function buildEcosystemConfigSource(geniePath,databaseUrl){let logs={out:join26(getLogsDir(),`${PM2_PROCESS_NAME}-out.log`),error:join26(getLogsDir(),`${PM2_PROCESS_NAME}-error.log`)},cfg={name:PM2_PROCESS_NAME,script:geniePath,args:"serve start --headless --no-tui --no-interactive",interpreter:"none",autorestart:!0,max_restarts:HARDENED_DEFAULTS.maxRestarts,min_uptime:HARDENED_DEFAULTS.minUptimeMs,restart_delay:HARDENED_DEFAULTS.restartDelayMs,exp_backoff_restart_delay:HARDENED_DEFAULTS.expBackoffRestartDelayMs,max_memory_restart:HARDENED_DEFAULTS.maxMemory,kill_timeout:HARDENED_DEFAULTS.killTimeoutMs,log_date_format:HARDENED_DEFAULTS.logDateFormat,error_file:logs.error,out_file:logs.out,merge_logs:!0,time:!0};if(databaseUrl)cfg.env={DATABASE_URL:databaseUrl};return`// Generated by \`genie install\` \u2014 do not edit by hand.
|
|
@@ -3984,8 +3985,8 @@ module.exports = {
|
|
|
3984
3985
|
`);return}process.stdout.write(`id status appliedAt from
|
|
3985
3986
|
`),process.stdout.write(`------------------------------- ---------- ------------------------ ------------
|
|
3986
3987
|
`);for(let r of rows){let id=r.id.padEnd(31),st=r.status.padEnd(10),at=(r.appliedAt||"-").padEnd(24),from=r.appliedFrom||"-";process.stdout.write(`${id} ${st} ${at} ${from}
|
|
3987
|
-
`)}return}let result2=await migrate({quiet:options.quiet,dryRun:options.dryRun});process.exit(result2.ok?0:1)}init_setup();init_shortcuts();import{existsSync as existsSync26}from"fs";import{homedir as homedir26}from"os";import{join as join32}from"path";async function shortcutsShowCommand(){displayShortcuts();let home=homedir26(),tmuxConf=join32(home,".tmux.conf"),zshrc=join32(home,".zshrc"),bashrc=join32(home,".bashrc");if(console.log("Installation status:"),isShortcutsInstalled(tmuxConf))console.log(" \x1B[32m\u2713\x1B[0m tmux.conf");else console.log(" \x1B[33m-\x1B[0m tmux.conf");let shellRc=existsSync26(zshrc)?zshrc:bashrc;if(isShortcutsInstalled(shellRc))console.log(` \x1B[32m\u2713\x1B[0m ${shellRc.replace(home,"~")}`);else console.log(` \x1B[33m-\x1B[0m ${shellRc.replace(home,"~")}`);console.log(),console.log("Run \x1B[36mgenie shortcuts install\x1B[0m to install shortcuts."),console.log("Run \x1B[36mgenie shortcuts uninstall\x1B[0m to remove shortcuts."),console.log()}async function shortcutsInstallCommand(){await installShortcuts()}async function shortcutsUninstallCommand(){await uninstallShortcuts()}init_esm14();init_claude_settings();init_genie_config2();import{existsSync as existsSync27,lstatSync,rmSync as rmSync2,unlinkSync as unlinkSync8}from"fs";import{homedir as homedir27}from"os";import{join as join33}from"path";var ORCHESTRATION_RULES_PATH=join33(homedir27(),".claude","rules","genie-orchestration.md"),LOCAL_BIN=join33(homedir27(),".local","bin"),SYMLINKS=["genie","term"];function isGenieSymlink(path3){try{if(!existsSync27(path3))return!1;if(!lstatSync(path3).isSymbolicLink())return!1;return!0}catch{return!1}}function removeSymlinks(){let removed=[];for(let name of SYMLINKS){let symlinkPath=join33(LOCAL_BIN,name);if(isGenieSymlink(symlinkPath))try{unlinkSync8(symlinkPath),removed.push(name)}catch{}}return removed}function tryRemoveStep(label,successMsg,fn){console.log(`\x1B[2m${label}\x1B[0m`);try{fn(),console.log(` \x1B[32m+\x1B[0m ${successMsg}`)}catch(error){let message=error instanceof Error?error.message:String(error);console.log(` \x1B[33m!\x1B[0m ${label.replace("...","")} failed: ${message}`)}}function performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir){if(hasHookScript)tryRemoveStep("Removing hook script...","Hook script removed",()=>removeHookScript());if(existingSymlinks.length>0){console.log("\x1B[2mRemoving symlinks...\x1B[0m");let removed=removeSymlinks();if(removed.length>0)console.log(` \x1B[32m+\x1B[0m Removed: ${removed.join(", ")}`)}if(existsSync27(ORCHESTRATION_RULES_PATH))tryRemoveStep("Removing orchestration rules...","Orchestration rules removed (~/.claude/rules/genie-orchestration.md)",()=>unlinkSync8(ORCHESTRATION_RULES_PATH));if(hasGenieDir)tryRemoveStep("Removing genie directory...","Directory removed",()=>rmSync2(genieDir,{recursive:!0,force:!0}))}async function uninstallCommand(){console.log(),console.log("\x1B[1m\x1B[33m Uninstall Genie CLI\x1B[0m"),console.log();let genieDir=getGenieDir(),hasGenieDir=existsSync27(genieDir),hasHookScript=hookScriptExists(),hasOrchestrationRules=existsSync27(ORCHESTRATION_RULES_PATH),existingSymlinks=SYMLINKS.filter((name)=>isGenieSymlink(join33(LOCAL_BIN,name)));if(console.log("\x1B[2mThis will remove:\x1B[0m"),hasHookScript)console.log(" \x1B[31m-\x1B[0m Hook script (~/.claude/hooks/genie-bash-hook.sh)");if(hasOrchestrationRules)console.log(" \x1B[31m-\x1B[0m Orchestration rules (~/.claude/rules/genie-orchestration.md)");if(hasGenieDir)console.log(` \x1B[31m-\x1B[0m Genie directory (${contractPath(genieDir)})`);if(existingSymlinks.length>0)console.log(` \x1B[31m-\x1B[0m Symlinks from ~/.local/bin: ${existingSymlinks.join(", ")}`);if(console.log(),!hasGenieDir&&!hasHookScript&&!hasOrchestrationRules&&existingSymlinks.length===0){console.log("\x1B[33mNothing to uninstall.\x1B[0m"),console.log();return}if(!await esm_default4({message:"Are you sure you want to uninstall Genie CLI?",default:!1})){console.log(),console.log("\x1B[2mUninstall cancelled.\x1B[0m"),console.log();return}console.log(),performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir),console.log(),console.log("\x1B[32m+\x1B[0m Genie CLI uninstalled."),console.log(),console.log("\x1B[2mNote: If you installed via npm/bun, also run:\x1B[0m"),console.log(" \x1B[36mbun remove -g @automagik/genie\x1B[0m"),console.log(" \x1B[2mor\x1B[0m"),console.log(" \x1B[36mnpm uninstall -g @automagik/genie\x1B[0m"),console.log()}init_genie_config2();init_version();import{execSync as execSync3,spawn as spawn3}from"child_process";import{chmodSync as chmodSync2,closeSync as closeSync3,copyFileSync as copyFileSync3,existsSync as existsSync29,mkdirSync as mkdirSync15,openSync as openSync3,readFileSync as readFileSync20,readSync as readSync2,readdirSync as readdirSync9,rmSync as rmSync3,statSync as statSync7,writeFileSync as writeFileSync13}from"fs";import{chmod,copyFile,mkdir as mkdir5,unlink as unlink2}from"fs/promises";import{homedir as homedir28}from"os";import{join as join34}from"path";var REGISTRY=[];async function cleanupLegacyArtifacts(skipList,registry=REGISTRY){let entries=[];for(let artifact of registry){if(skipList.has(artifact.name)){entries.push({name:artifact.name,outcome:"skipped",removed:[],warnings:[]});continue}if(!await artifact.detect()){entries.push({name:artifact.name,outcome:"absent",removed:[],warnings:[]});continue}let result2=await artifact.cleanup();entries.push({name:artifact.name,outcome:"cleaned",removed:result2.removed,warnings:result2.warnings})}return{entries}}function parseSkipCleanupFlag(value){let skip=new Set;if(!value)return skip;for(let part of value.split(",")){let name=part.trim();if(name)skip.add(name)}return skip}var GENIE_HOME2=process.env.GENIE_HOME||join34(homedir28(),".genie"),GENIE_SRC=join34(GENIE_HOME2,"src"),GENIE_BIN=join34(GENIE_HOME2,"bin"),LOCAL_BIN2=join34(homedir28(),".local","bin"),TRUTHY=new Set(["1","true","yes","on"]),UPDATE_DIAGNOSTIC_SCHEMA_VERSION=2,VERIFY_PROBE_DEADLINE_MS=15000,VERIFY_PROBE_POLL_INTERVAL_MS=500,FETCH_LATEST_TIMEOUT_MS=5000;function normalizeVersion(value){let trimmed=value.trim(),plusIdx=trimmed.indexOf("+");return plusIdx===-1?trimmed:trimmed.slice(0,plusIdx)}function decideVerify(args){if(args.skipReason)return{kind:"skipped",reason:args.skipReason};if(args.serverHealthBody===null)return{kind:"health-unreachable",endpoint:args.endpoint};let cliVersion=normalizeVersion(args.cliVersion),rawServerVersion=args.serverHealthBody.version??null,serverVersion=rawServerVersion===null?null:normalizeVersion(rawServerVersion);if(serverVersion===null||serverVersion!==cliVersion)return{kind:"version-mismatch",cliVersion,serverVersion};return{kind:"ok",cliVersion,serverVersion}}function shortCircuitIfCurrent(currentVersion,latestVersion){if(!latestVersion)return!1;return normalizeVersion(currentVersion)===normalizeVersion(latestVersion)}async function fetchLatestVersion(channel){let candidates=[{cmd:"npm",args:["view",`@automagik/genie@${channel}`,"version"]},{cmd:"bunx",args:["npm","view",`@automagik/genie@${channel}`,"version"]}];for(let{cmd,args}of candidates){let result2=await runCommandSilent(cmd,args,void 0,FETCH_LATEST_TIMEOUT_MS);if(!result2.success)continue;let trimmed=result2.output.trim();if(!trimmed)continue;let lines=trimmed.split(/\r?\n/).filter(Boolean),tokens2=lines[lines.length-1].split(/\s+/),candidate=tokens2[tokens2.length-1].replace(/^['"]|['"]$/g,"");if(/^\d+\.\d+/.test(candidate))return candidate}return null}async function promptConfirm(question){if(!process.stdin.isTTY||!process.stdout.isTTY)return!0;return process.stdout.write(`${question} [Y/n] `),new Promise((resolve5)=>{let onData=(chunk)=>{process.stdin.removeListener("data",onData),process.stdin.pause();let answer=chunk.toString("utf-8").trim().toLowerCase();if(answer===""||answer==="y"||answer==="yes")resolve5(!0);else resolve5(!1)};process.stdin.resume(),process.stdin.once("data",onData)})}function shouldAutoConfirm(opts){if(opts.yes)return!0;return isTruthyEnv(process.env.GENIE_UPDATE_YES)}var VERIFY_PROBE_ENDPOINT="pgserve status --json + ~/.genie/serve.pid";async function readServerHealth(){if(!(await runCommandSilent("pgserve",["status","--json"],void 0,3000)).success)return null;let pidPath=join34(GENIE_HOME2,"serve.pid"),rawPid=safeRead(pidPath,32);if(!rawPid)return null;let pid=Number.parseInt(rawPid.trim(),10);if(!Number.isFinite(pid)||pid<=0)return null;try{process.kill(pid,0)}catch{return null}return{version:VERSION}}async function pollHealth(readHealth,deadlineMs,intervalMs){let startedAt=Date.now();while(Date.now()-startedAt<deadlineMs){let body=null;try{body=await readHealth()}catch{}if(body!==null)return body;await new Promise((r)=>setTimeout(r,intervalMs))}return null}async function runVerifyProbe(opts){if(opts.skipReason)return decideVerify({cliVersion:opts.cliVersion,serverHealthBody:null,endpoint:VERIFY_PROBE_ENDPOINT,skipReason:opts.skipReason});let reader=opts.readHealth??readServerHealth,deadline=opts.deadlineMs??VERIFY_PROBE_DEADLINE_MS,interval=opts.intervalMs??VERIFY_PROBE_POLL_INTERVAL_MS,body=await pollHealth(reader,deadline,interval);return decideVerify({cliVersion:opts.cliVersion,serverHealthBody:body,endpoint:VERIFY_PROBE_ENDPOINT})}function formatVerifyBanner(result2){let lines=[];switch(result2.kind){case"ok":lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} CLI: v${result2.cliVersion}`),lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} Server: v${result2.serverVersion} (healthy)`);break;case"health-unreachable":lines.push(`${colorize("\x1B[33m","\x1B[0m","!")} CLI: v${VERSION}`),lines.push(`${colorize("\x1B[31m","\x1B[0m","\u2716")} Server: unreachable (probe: ${result2.endpoint})`);break;case"version-mismatch":lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} CLI: v${result2.cliVersion}`),lines.push(`${colorize("\x1B[31m","\x1B[0m","\u2716")} Server: v${result2.serverVersion??"unknown"} (mismatch)`);break;case"auth-invalid":lines.push(`${colorize("\x1B[31m","\x1B[0m","\u2716")} Auth: invalid`);break;case"skipped":lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} CLI: v${VERSION}`),lines.push(`${colorize("\x1B[2m","\x1B[0m",`\xB7 Server: v\u2026 (skipped: ${result2.reason})`)}`);break}return lines}function colorEnabled(){if(process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0")return!0;return Boolean(process.stdout.isTTY)}function colorize(open4,close,text){return colorEnabled()?`${open4}${text}${close}`:text}function log(message){console.log(`${colorize("\x1B[32m","\x1B[0m","\u25B8")} ${message}`)}function success(message){console.log(`${colorize("\x1B[32m","\x1B[0m","\u2714")} ${message}`)}function error(message){console.log(`${colorize("\x1B[31m","\x1B[0m","\u2716")} ${message}`)}function formatDuration2(ms){if(ms<1000)return`${ms}ms`;return`${(ms/1000).toFixed(1)}s`}function isTruthyEnv(value){return value!==void 0&&TRUTHY.has(value.trim().toLowerCase())}async function withTemporaryEnv(key,value,fn){let previous=process.env[key];process.env[key]=value;try{return await fn()}finally{if(previous===void 0)delete process.env[key];else process.env[key]=previous}}function safeExec(command,timeoutMs=1500){try{return execSync3(command,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:timeoutMs}).trim()}catch(err){let stdout=err.stdout;if(typeof stdout==="string"&&stdout.trim())return stdout.trim();return""}}function safeRead(path3,maxChars=4000){try{let value=readFileSync20(path3,"utf-8");if(value.length<=maxChars)return value;return value.slice(value.length-maxChars)}catch{return null}}function tailLines(path3,maxBytes=64000,maxLines=200){let fd=null;try{let stat4=statSync7(path3),bytesToRead=Math.min(stat4.size,maxBytes),buffer2=Buffer.alloc(bytesToRead);return fd=openSync3(path3,"r"),readSync2(fd,buffer2,0,bytesToRead,Math.max(0,stat4.size-bytesToRead)),buffer2.toString("utf-8").split(/\r?\n/).map((line)=>line.trim()).filter(Boolean).slice(-maxLines)}catch{return[]}finally{if(fd!==null)try{closeSync3(fd)}catch{}}}function summarizeJsonlSignals(path3){let signals2=new Map;for(let line of tailLines(path3))try{let event=JSON.parse(line),level=typeof event.level==="string"?event.level:"unknown";if(level!=="error"&&level!=="warn")continue;let name=typeof event.event==="string"?event.event:"unknown",key=`${level}:${name}`,existing=signals2.get(key)??{level,event:name,count:0};if(existing.count++,typeof event.timestamp==="string")existing.lastTimestamp=event.timestamp;if(typeof event.error==="string")existing.lastError=event.error;signals2.set(key,existing)}catch{}return[...signals2.values()].sort((a,b2)=>b2.count-a.count).slice(0,10)}async function collectUpdateDiagnostics(ctx,maintenance,extras){let logsDir=join34(GENIE_HOME2,"logs");mkdirSync15(logsDir,{recursive:!0});let generatedAt=new Date().toISOString(),safeStamp=generatedAt.replace(/[:.]/g,"-"),path3=join34(logsDir,`update-diagnostics-${safeStamp}.json`),schedulerLog=join34(logsDir,"scheduler.log"),tuiCrashLog=join34(logsDir,"tui-crash.log"),signals2=summarizeJsonlSignals(schedulerLog),diagnostics={schemaVersion:UPDATE_DIAGNOSTIC_SCHEMA_VERSION,cli:"genie",generatedAt,verify:extras.verify,cleanups:extras.cleanups,update:ctx,runtime:{platform:process.platform,arch:process.arch,cwd:process.cwd(),node:process.version,bun:(await runCommandSilent("bun",["--version"])).output.trim()||null,npm:(await runCommandSilent("npm",["--version"])).output.trim()||null,genie:{which:(await runCommandSilent("which",["genie"])).output.trim()||null,tuiDisabled:isTruthyEnv(process.env.GENIE_TUI_DISABLE),updateSkipMaintenance:isTruthyEnv(process.env.GENIE_UPDATE_SKIP_MAINTENANCE)}},paths:{genieHome:GENIE_HOME2,logsDir,servePid:safeRead(join34(GENIE_HOME2,"serve.pid"),200),pgservePort:safeRead(join34(GENIE_HOME2,"pgserve.port"),200),schedulerLog,tuiCrashLog},processSnapshot:{genie:safeExec("ps -axo pid,ppid,pgid,stat,pcpu,pmem,etime,command -r | rg -i 'dist/genie.js|/src/genie.ts|pgserve|postgres -D .*\\.genie/data/pgserve|tmux -L genie-tui|bun' || true",2000)||null,tuiTmux:safeExec("tmux -L genie-tui ls 2>/dev/null || true",1000)||null},maintenance:{...maintenance,pgAutostartDisabled:!0,legend:{"[ok]":"healthy","[fix]":"fixed during maintenance","[--]":"skipped/non-blocking","[!!]":"operator action needed; update still completed"}},recentLogSignals:{scheduler:signals2,schedulerTail:tailLines(schedulerLog,32000,80),tuiCrashTail:tailLines(tuiCrashLog,32000,80)}};return writeFileSync13(path3,`${JSON.stringify(diagnostics,null,2)}
|
|
3988
|
-
`),{path:path3,signals:signals2}}async function runCommand(command,args,cwd){return new Promise((resolve5)=>{let output=[],child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}});child.stdout?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stdout.write(str2)}),child.stderr?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stderr.write(str2)}),child.on("close",(code)=>{resolve5({success:code===0,output:output.join("")})}),child.on("error",(err)=>{error(err.message),resolve5({success:!1,output:err.message})})})}async function getGitInfo(cwd){try{let branchResult=await runCommandSilent("git",["rev-parse","--abbrev-ref","HEAD"],cwd),commitResult=await runCommandSilent("git",["rev-parse","--short","HEAD"],cwd),dateResult=await runCommandSilent("git",["log","-1","--format=%ci"],cwd);if(branchResult.success&&commitResult.success&&dateResult.success)return{branch:branchResult.output.trim(),commit:commitResult.output.trim(),commitDate:dateResult.output.trim().split(" ")[0]}}catch{}return null}async function runCommandSilent(command,args,cwd,timeoutMs=4000){return new Promise((resolve5)=>{let output=[],settled=!1,child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"]}),timer2=setTimeout(()=>{if(settled)return;settled=!0,child.kill("SIGTERM"),resolve5({success:!1,output:`Timed out after ${timeoutMs}ms`})},timeoutMs);child.stdout?.on("data",(data)=>{output.push(data.toString())}),child.stderr?.on("data",(data)=>{output.push(data.toString())}),child.on("close",(code)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve5({success:code===0,output:output.join("")})}),child.on("error",(err)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve5({success:!1,output:err.message})})})}function detectFromBinaryPath(path3){let resolved=path3;try{resolved=__require("fs").realpathSync(path3)}catch{}if(resolved.includes(".bun"))return"bun";if(resolved.includes("node_modules"))return"npm";if(path3===join34(LOCAL_BIN2,"genie")||resolved.startsWith(GENIE_BIN))return"source";return null}async function detectInstallationType(){let whichResult=await runCommandSilent("which",["genie"]);if(whichResult.success){let detected=detectFromBinaryPath(whichResult.output.trim());if(detected)return detected}if(genieConfigExists())try{let config=await loadGenieConfig();if(config.installMethod)return config.installMethod}catch{}if(existsSync29(join34(GENIE_SRC,".git")))return"source";return(await runCommandSilent("which",["bun"])).success?"bun":"npm"}async function updateViaBun(channel){try{__require("fs").unlinkSync(join34(homedir28(),".bun","install","global","bun.lock"))}catch{}if(log(`Updating via bun (channel: ${channel})...`),!(await runCommand("bun",["add","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via bun"),!1;return console.log(),success(`Genie CLI updated via bun (${channel})!`),!0}async function updateViaNpm(channel){if(log(`Updating via npm (channel: ${channel})...`),!(await runCommand("npm",["install","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via npm"),!1;return console.log(),success(`Genie CLI updated via npm (${channel})!`),!0}async function detectGlobalInstalls(){let found=new Set,[npmResult,bunResult]=await Promise.all([runCommandSilent("npm",["list","-g","@automagik/genie"]),runCommandSilent("bun",["pm","ls","-g"])]);if(npmResult.success&&!npmResult.output.includes("(empty)"))found.add("npm");if(bunResult.success&&bunResult.output.includes("@automagik/genie"))found.add("bun");return found}async function updateSource(){if(!existsSync29(GENIE_SRC))error(`Source install path not found: ${GENIE_SRC}`),console.error(" Detection picked the source-install path, but the directory does not exist."),console.error(" This usually means a stale install hint (config or ~/.genie/src/.git) is"),console.error(" pointing somewhere genuine. Either:"),console.error(` 1. Re-clone the source: git clone https://github.com/automagik-dev/genie ${GENIE_SRC}`),console.error(" 2. Update via package manager instead: genie update --next --via bun"),console.error(" 3. Inspect detection: genie doctor --update-detection"),process.exit(1);if(!existsSync29(join34(GENIE_SRC,".git")))error(`Source install path is not a git checkout: ${GENIE_SRC}`),console.error(` ${GENIE_SRC} exists but has no .git/. Cannot run \`git fetch\` from it.`),console.error(` Either delete ${GENIE_SRC} and re-clone, or update via package manager:`),console.error(" genie update --next --via bun"),process.exit(1);let beforeInfo=await getGitInfo(GENIE_SRC);if(beforeInfo)console.log(`Current: \x1B[2m${beforeInfo.branch}@${beforeInfo.commit} (${beforeInfo.commitDate})\x1B[0m`),console.log();if(log("Fetching latest changes..."),!(await runCommand("git",["fetch","origin"],GENIE_SRC)).success)error("Failed to fetch from origin"),process.exit(1);if(log("Resetting to origin/main..."),!(await runCommand("git",["reset","--hard","origin/main"],GENIE_SRC)).success)error("Failed to reset to origin/main"),process.exit(1);console.log();let afterInfo=await getGitInfo(GENIE_SRC);if(beforeInfo&&afterInfo&&beforeInfo.commit===afterInfo.commit){success("Already up to date!"),console.log();return}if(log("Installing dependencies..."),!(await runCommand("bun",["install"],GENIE_SRC)).success)error("Failed to install dependencies"),process.exit(1);if(console.log(),log("Building..."),!(await runCommand("bun",["run","build"],GENIE_SRC)).success)error("Failed to build"),process.exit(1);console.log(),log("Installing binaries...");try{await mkdir5(GENIE_BIN,{recursive:!0}),await mkdir5(LOCAL_BIN2,{recursive:!0});let binaries=["genie.js","term.js"],names=["genie","term"];for(let i2=0;i2<binaries.length;i2++){let src=join34(GENIE_SRC,"dist",binaries[i2]),binDest=join34(GENIE_BIN,binaries[i2]),linkDest=join34(LOCAL_BIN2,names[i2]);await copyFile(src,binDest),await chmod(binDest,493),await symlinkOrCopy(binDest,linkDest)}for(let legacy of["claudio.js","claudio"]){let legacyBin=join34(GENIE_BIN,legacy),legacyLink=join34(LOCAL_BIN2,legacy);try{await unlink2(legacyBin)}catch{}try{await unlink2(legacyLink)}catch{}}success("Binaries installed")}catch(err){error(`Failed to install binaries: ${err}`),process.exit(1)}if(console.log(),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),success("Genie CLI updated successfully!"),console.log(),afterInfo)console.log(`Version: \x1B[36m${afterInfo.branch}@${afterInfo.commit}\x1B[0m (${afterInfo.commitDate})`),console.log()}async function symlinkOrCopy(src,dest){let{symlink:symlink2,unlink:unlink3}=await import("fs/promises");try{if(existsSync29(dest))await unlink3(dest);await symlink2(src,dest)}catch{await copyFile(src,dest)}}var FRAMEWORK_MARKER_FILES=new Set([".orphaned_at"]);function copyDirSync(src,dest){mkdirSync15(dest,{recursive:!0});for(let entry2 of readdirSync9(src,{withFileTypes:!0})){if(FRAMEWORK_MARKER_FILES.has(entry2.name))continue;let srcPath=join34(src,entry2.name),destPath=join34(dest,entry2.name);if(entry2.isDirectory())copyDirSync(srcPath,destPath);else copyFileSync3(srcPath,destPath)}}async function resolveGlobalPkgDir(installType){if(installType==="bun"){let bunPath=join34(homedir28(),".bun","install","global","node_modules","@automagik","genie");if(existsSync29(bunPath))return bunPath}if(installType==="npm"){let npmRootResult=await runCommandSilent("npm",["root","-g"]);if(npmRootResult.success){let npmPath=join34(npmRootResult.output.trim(),"@automagik","genie");if(existsSync29(npmPath))return npmPath}}let bunFallback=join34(homedir28(),".bun","install","global","node_modules","@automagik","genie");if(existsSync29(bunFallback))return bunFallback;let npmRootFallback=await runCommandSilent("npm",["root","-g"]);if(npmRootFallback.success){let npmPath=join34(npmRootFallback.output.trim(),"@automagik","genie");if(existsSync29(npmPath))return npmPath}return null}function updatePluginRegistry(claudePlugins,cacheDir,version){let registryPath=join34(claudePlugins,"installed_plugins.json");try{if(!existsSync29(registryPath))return;let registry=JSON.parse(readFileSync20(registryPath,"utf-8")),entries=registry.plugins?.["genie@automagik"];if(!Array.isArray(entries))return;for(let entry2 of entries)if(entry2.scope==="user")entry2.installPath=cacheDir,entry2.version=version,entry2.lastUpdated=new Date().toISOString();writeFileSync13(registryPath,JSON.stringify(registry,null,2))}catch(err){log(`Registry update failed (non-fatal): ${err}`)}}function syncTmuxConf(tmuxScriptsSrc){mkdirSync15(GENIE_HOME2,{recursive:!0});let tmuxConfSrc=join34(tmuxScriptsSrc,"genie.tmux.conf"),tmuxConfDest=join34(GENIE_HOME2,"tmux.conf");if(existsSync29(tmuxConfSrc))try{copyFileSync3(tmuxConfSrc,tmuxConfDest),success(`Installed tmux config to ${tmuxConfDest}`);try{let{tmuxBin:tmuxBin2}=(init_ensure_tmux(),__toCommonJS(exports_ensure_tmux));execSync3(`${tmuxBin2()} -L genie source-file '${tmuxConfDest}'`,{stdio:"ignore"}),success("Reloaded genie tmux server configuration")}catch{}}catch{}let tuiConfSrc=join34(tmuxScriptsSrc,"tui-tmux.conf"),tuiConfDest=join34(GENIE_HOME2,"tui-tmux.conf");if(existsSync29(tuiConfSrc))try{copyFileSync3(tuiConfSrc,tuiConfDest),success(`Installed TUI tmux config to ${tuiConfDest}`)}catch{}let themeSrc=join34(tmuxScriptsSrc,".generated.theme.conf"),themeDest=join34(GENIE_HOME2,".generated.theme.conf");if(existsSync29(themeSrc))try{copyFileSync3(themeSrc,themeDest),success(`Installed tmux theme to ${themeDest}`)}catch{}let osc52Src=join34(tmuxScriptsSrc,"osc52-copy.sh"),osc52Dest=join34(GENIE_HOME2,"scripts","osc52-copy.sh");if(existsSync29(osc52Src))try{copyFileSync3(osc52Src,osc52Dest),chmodSync2(osc52Dest,493),success(`Installed OSC 52 clipboard helper to ${osc52Dest}`)}catch{}}function syncTmuxScripts(globalPkgDir){let tmuxScriptsSrc=join34(globalPkgDir,"scripts","tmux");if(!existsSync29(tmuxScriptsSrc))return;let scriptsDir=join34(GENIE_HOME2,"scripts");mkdirSync15(scriptsDir,{recursive:!0});let scriptCount=0;for(let entry2 of readdirSync9(tmuxScriptsSrc))if(entry2.endsWith(".sh")||entry2==="genie.tmux.conf"||entry2==="tui-tmux.conf"||entry2===".generated.theme.conf"){let src=join34(tmuxScriptsSrc,entry2),dest=join34(scriptsDir,entry2);copyFileSync3(src,dest);try{chmodSync2(dest,entry2.endsWith(".sh")?493:420)}catch{}scriptCount++}if(scriptCount>0)success(`Refreshed ${scriptCount} tmux scripts at ${scriptsDir}`);syncTmuxConf(tmuxScriptsSrc)}function syncMarketplaceVersion(claudePlugins,version){let marketplacePath=join34(claudePlugins,"marketplaces","automagik",".claude-plugin","marketplace.json");try{if(!existsSync29(marketplacePath))return;let data=JSON.parse(readFileSync20(marketplacePath,"utf-8"));if(Array.isArray(data.plugins)){for(let plugin of data.plugins)if(plugin.name==="genie")plugin.version=version}writeFileSync13(marketplacePath,JSON.stringify(data,null,2)),success(`Updated marketplace.json to v${version}`)}catch(err){log(`Marketplace version update failed (non-fatal): ${err}`)}}function syncPluginPackageVersion(claudePlugins,version){let pkgPath=join34(claudePlugins,"marketplaces","automagik","plugins","genie","package.json");try{if(!existsSync29(pkgPath))return;let data=JSON.parse(readFileSync20(pkgPath,"utf-8"));data.version=version,writeFileSync13(pkgPath,JSON.stringify(data,null,2)),success(`Updated plugin package.json to v${version}`)}catch(err){log(`Plugin package.json update failed (non-fatal): ${err}`)}}function syncSkillsSymlink(claudePlugins,version){let skillsLink=join34(claudePlugins,"marketplaces","automagik","plugins","genie","skills"),cacheSkills=join34("..","..","..","..","cache","automagik","genie",version,"skills");try{let{symlinkSync,unlinkSync:unlinkSync9,lstatSync:lstatSync2}=__require("fs");try{lstatSync2(skillsLink),unlinkSync9(skillsLink)}catch{}symlinkSync(cacheSkills,skillsLink),success(`Skills symlink \u2192 cache/${version}/skills`)}catch(err){log(`Skills symlink update failed (non-fatal): ${err}`)}}async function syncPlugin(installType){log("Syncing Claude Code plugin...");let globalPkgDir=await resolveGlobalPkgDir(installType);if(!globalPkgDir)return log("Could not find installed package \u2014 skipping plugin sync"),{skippedReason:"installed package not found"};let pluginSrc=join34(globalPkgDir,"plugins","genie");if(!existsSync29(pluginSrc))return log("Plugin source not found in package \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"plugin source not found in package"};let version;try{version=JSON.parse(readFileSync20(join34(globalPkgDir,"package.json"),"utf-8")).version}catch{return log("Could not read package version \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"could not read package version"}}let claudePlugins=join34(homedir28(),".claude","plugins"),cacheDir=join34(claudePlugins,"cache","automagik","genie",version);try{if(existsSync29(cacheDir))rmSync3(cacheDir,{recursive:!0,force:!0});copyDirSync(pluginSrc,cacheDir);let skillsSrc=join34(globalPkgDir,"skills");if(existsSync29(skillsSrc)&&!existsSync29(join34(cacheDir,"skills")))copyDirSync(skillsSrc,join34(cacheDir,"skills"))}catch(err){return error(`Failed to copy plugin: ${err}`),{version,globalPkgDir,cacheDir,skippedReason:`failed to copy plugin: ${err}`}}return updatePluginRegistry(claudePlugins,cacheDir,version),syncMarketplaceVersion(claudePlugins,version),syncPluginPackageVersion(claudePlugins,version),syncSkillsSymlink(claudePlugins,version),syncTmuxScripts(globalPkgDir),success(`Plugin synced to v${version}`),{version,globalPkgDir,cacheDir}}async function resolveChannel(options){if(options.next)return"next";if(options.stable)return"latest";if(genieConfigExists())try{let config=await loadGenieConfig();if(config.updateChannel)return config.updateChannel}catch{}return"latest"}async function persistChannel(channel){try{let config=await loadGenieConfig();config.updateChannel=channel,await saveGenieConfig(config)}catch{}}async function updateCommand(options={}){console.log(),console.log(`${colorize("\x1B[1m","\x1B[0m","\uD83E\uDDDE Genie CLI Update")}`),console.log(`${colorize("\x1B[2m","\x1B[0m","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`),console.log();let cleanupSkipList=buildCleanupSkipList(options),noRestart=options.restart===!1||isTruthyEnv(process.env.GENIE_UPDATE_NO_RESTART),noVerify=options.verify===!1||isTruthyEnv(process.env.GENIE_UPDATE_NO_VERIFY),channel=await resolveChannel(options);if(options.next||options.stable)await persistChannel(channel);let latestVersion=await fetchLatestVersion(channel);if(shortCircuitIfCurrent(VERSION,latestVersion)){success(`Already up to date (v${normalizeVersion(VERSION)}, channel ${channel})`),console.log();return}let installType=await detectInstallationType();if(log(`Detected installation: ${installType}`),log(`Channel: ${channel}${channel==="next"?" (dev builds)":" (stable)"}`),latestVersion)log(`Update available: ${normalizeVersion(VERSION)} \u2192 ${normalizeVersion(latestVersion)}`);else log(`Registry version unavailable (proceeding with reinstall of channel ${channel})`);if(console.log(),installType==="unknown")error("No Genie CLI installation found"),console.log(),console.log("Install method not configured. Please reinstall genie:"),console.log(`${colorize("\x1B[36m","\x1B[0m"," curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash")}`),console.log(),process.exit(1);if(!shouldAutoConfirm(options)){let proceedQuestion=latestVersion?`Update v${normalizeVersion(VERSION)} \u2192 v${normalizeVersion(latestVersion)}?`:`Reinstall channel "${channel}"?`;if(!await promptConfirm(proceedQuestion)){console.log(),log("Update declined."),console.log();return}}if(installType==="source"){await updateSource();return}let globalInstalls=await detectGlobalInstalls(),primaryMethod=installType;if(!(primaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))process.exit(1);let secondaryMethod=primaryMethod==="bun"?"npm":"bun";if(globalInstalls.has(secondaryMethod)){if(console.log(),log(`Also updating ${secondaryMethod}-global install...`),!(secondaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))error(`Secondary update via ${secondaryMethod} failed (non-blocking)`)}let plugin=await syncPlugin(installType),cleanupReport=await runLegacyCleanupSafe(cleanupSkipList);await runPostUpdateMaintenanceSafe({...options,noRestart,noVerify},{channel,installType,primaryMethod,globalInstalls:[...globalInstalls].sort(),plugin,latestVersion,cliVersion:VERSION},cleanupReport)}function buildCleanupSkipList(options){let skipList=parseSkipCleanupFlag(options.skipCleanup);if(options.sidecarCleanup===!1)skipList.add("nats-reply-sidecar"),log("--no-sidecar-cleanup (no-op for genie, retained for cross-CLI portability)");return skipList}async function runLegacyCleanupSafe(skipList){try{return await cleanupLegacyArtifacts(skipList)}catch(err){let msg=err instanceof Error?err.message:String(err);return log(`Legacy artifact cleanup failed (non-fatal): ${msg}`),{entries:[]}}}function printPostUpdateMaintenanceIntro(){console.log(),log("Running post-update maintenance..."),console.log(" Purpose: make first launch after update fast and collect upgrade health signals."),console.log(" Checks: runtime partitions, watchdog status, session backfill drift, zombie rows, team config orphans."),console.log(" PG policy: read-only; uses an already-running pgserve when available and will not auto-start it."),console.log(" Legend: [ok]=healthy, [fix]=fixed, [--]=skipped/non-blocking, [!!]=operator action needed.")}async function runMaintenanceWithCapturedLines(maintenanceLines){let{runPostUpdateMaintenance:runPostUpdateMaintenance2}=await Promise.resolve().then(() => (init_doctor(),exports_doctor));await withTemporaryEnv("GENIE_PG_NO_AUTOSTART","1",()=>runPostUpdateMaintenance2({log:(line)=>{maintenanceLines.push(line),console.log(line)}}))}function printDiagnosticsSummary(diagnostics){if(log("Post-update diagnostics captured."),console.log(` Report: ${diagnostics.path}`),console.log(" Include this file when opening a GitHub issue; it contains install metadata, step output,"),console.log(" local process state, and recent scheduler/TUI log signals."),diagnostics.signals.length===0)return;console.log(" Recent scheduler signals:");for(let signal of diagnostics.signals.slice(0,3)){let errorDetail=signal.lastError?` \u2014 ${signal.lastError}`:"";console.log(` ${signal.level}:${signal.event} \xD7${signal.count}${errorDetail}`)}}async function capturePostUpdateDiagnostics(diagnosticsCtx,maintenance,extras){if(!diagnosticsCtx)return;try{let diagnostics=await collectUpdateDiagnostics(diagnosticsCtx,maintenance,extras);printDiagnosticsSummary(diagnostics)}catch(err){let msg=err instanceof Error?err.message:String(err);log(`Post-update diagnostics capture failed (non-fatal): ${msg}`)}}function printVerifyBanner(result2){console.log();for(let line of formatVerifyBanner(result2))console.log(` ${line}`);console.log()}async function runPostUpdateMaintenanceSafe(options,diagnosticsCtx,cleanupReport){if(options.noRestart){log("--no-restart: skipping maintenance and verify probe.");let verify2=await runVerifyProbe({cliVersion:VERSION,skipReason:"no-restart"});printVerifyBanner(verify2),await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome:"completed",durationMs:0,lines:[]},{verify:verify2,cleanups:cleanupReport});return}if(options.skipMaintenance||isTruthyEnv(process.env.GENIE_UPDATE_SKIP_MAINTENANCE)){log("Skipping post-update maintenance (requested).");let verify2=await runVerifyProbe({cliVersion:VERSION,skipReason:"no-restart"});printVerifyBanner(verify2),await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome:"completed",durationMs:0,lines:[]},{verify:verify2,cleanups:cleanupReport});return}let startedAt=Date.now(),maintenanceLines=[],outcome="completed",maintenanceError;try{printPostUpdateMaintenanceIntro(),await runMaintenanceWithCapturedLines(maintenanceLines),success(`Post-update maintenance complete (${formatDuration2(Date.now()-startedAt)}).`)}catch(err){outcome="failed",maintenanceError=err instanceof Error?err.message:String(err),error(`Post-update maintenance skipped: ${maintenanceError}`)}let verify=options.noVerify?await runVerifyProbe({cliVersion:VERSION,skipReason:"no-verify-flag"}):await runVerifyProbe({cliVersion:VERSION});if(printVerifyBanner(verify),await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome,durationMs:Date.now()-startedAt,lines:maintenanceLines,error:maintenanceError},{verify,cleanups:cleanupReport}),verify.kind==="health-unreachable"&&!options.noVerify)process.exitCode=1}init_version();init_trust();init_trust();init_trust();import{execSync as execSync4}from"child_process";import{existsSync as existsSync31,mkdirSync as mkdirSync16,readFileSync as readFileSync22,renameSync as renameSync6,writeFileSync as writeFileSync14}from"fs";import{dirname as dirname13,isAbsolute,join as join36,resolve as resolve5}from"path";function resolveOriginUrl(repoRoot){try{return execSync4("git config --get remote.origin.url",{cwd:repoRoot,encoding:"utf-8"}).trim()||null}catch{return null}}function findRepoRoot(start){let current=start;while(current!=="/"){if(existsSync31(join36(current,".git")))return current;current=dirname13(current)}return null}function writeTrustFile(path3,file){let dir=dirname13(path3);if(!existsSync31(dir))mkdirSync16(dir,{recursive:!0});let sorted={version:1,entries:[...file.entries].sort((a,b2)=>a.path.localeCompare(b2.path))},serialized=`${JSON.stringify(sorted,null,2)}
|
|
3988
|
+
`)}return}let result2=await migrate({quiet:options.quiet,dryRun:options.dryRun});process.exit(result2.ok?0:1)}init_setup();init_shortcuts();import{existsSync as existsSync26}from"fs";import{homedir as homedir26}from"os";import{join as join32}from"path";async function shortcutsShowCommand(){displayShortcuts();let home=homedir26(),tmuxConf=join32(home,".tmux.conf"),zshrc=join32(home,".zshrc"),bashrc=join32(home,".bashrc");if(console.log("Installation status:"),isShortcutsInstalled(tmuxConf))console.log(" \x1B[32m\u2713\x1B[0m tmux.conf");else console.log(" \x1B[33m-\x1B[0m tmux.conf");let shellRc=existsSync26(zshrc)?zshrc:bashrc;if(isShortcutsInstalled(shellRc))console.log(` \x1B[32m\u2713\x1B[0m ${shellRc.replace(home,"~")}`);else console.log(` \x1B[33m-\x1B[0m ${shellRc.replace(home,"~")}`);console.log(),console.log("Run \x1B[36mgenie shortcuts install\x1B[0m to install shortcuts."),console.log("Run \x1B[36mgenie shortcuts uninstall\x1B[0m to remove shortcuts."),console.log()}async function shortcutsInstallCommand(){await installShortcuts()}async function shortcutsUninstallCommand(){await uninstallShortcuts()}init_esm14();init_claude_settings();init_genie_config2();import{existsSync as existsSync27,lstatSync,rmSync as rmSync2,unlinkSync as unlinkSync8}from"fs";import{homedir as homedir27}from"os";import{join as join33}from"path";var ORCHESTRATION_RULES_PATH=join33(homedir27(),".claude","rules","genie-orchestration.md"),LOCAL_BIN=join33(homedir27(),".local","bin"),SYMLINKS=["genie","term"];function isGenieSymlink(path3){try{if(!existsSync27(path3))return!1;if(!lstatSync(path3).isSymbolicLink())return!1;return!0}catch{return!1}}function removeSymlinks(){let removed=[];for(let name of SYMLINKS){let symlinkPath=join33(LOCAL_BIN,name);if(isGenieSymlink(symlinkPath))try{unlinkSync8(symlinkPath),removed.push(name)}catch{}}return removed}function tryRemoveStep(label,successMsg,fn){console.log(`\x1B[2m${label}\x1B[0m`);try{fn(),console.log(` \x1B[32m+\x1B[0m ${successMsg}`)}catch(error){let message=error instanceof Error?error.message:String(error);console.log(` \x1B[33m!\x1B[0m ${label.replace("...","")} failed: ${message}`)}}function performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir){if(hasHookScript)tryRemoveStep("Removing hook script...","Hook script removed",()=>removeHookScript());if(existingSymlinks.length>0){console.log("\x1B[2mRemoving symlinks...\x1B[0m");let removed=removeSymlinks();if(removed.length>0)console.log(` \x1B[32m+\x1B[0m Removed: ${removed.join(", ")}`)}if(existsSync27(ORCHESTRATION_RULES_PATH))tryRemoveStep("Removing orchestration rules...","Orchestration rules removed (~/.claude/rules/genie-orchestration.md)",()=>unlinkSync8(ORCHESTRATION_RULES_PATH));if(hasGenieDir)tryRemoveStep("Removing genie directory...","Directory removed",()=>rmSync2(genieDir,{recursive:!0,force:!0}))}async function uninstallCommand(){console.log(),console.log("\x1B[1m\x1B[33m Uninstall Genie CLI\x1B[0m"),console.log();let genieDir=getGenieDir(),hasGenieDir=existsSync27(genieDir),hasHookScript=hookScriptExists(),hasOrchestrationRules=existsSync27(ORCHESTRATION_RULES_PATH),existingSymlinks=SYMLINKS.filter((name)=>isGenieSymlink(join33(LOCAL_BIN,name)));if(console.log("\x1B[2mThis will remove:\x1B[0m"),hasHookScript)console.log(" \x1B[31m-\x1B[0m Hook script (~/.claude/hooks/genie-bash-hook.sh)");if(hasOrchestrationRules)console.log(" \x1B[31m-\x1B[0m Orchestration rules (~/.claude/rules/genie-orchestration.md)");if(hasGenieDir)console.log(` \x1B[31m-\x1B[0m Genie directory (${contractPath(genieDir)})`);if(existingSymlinks.length>0)console.log(` \x1B[31m-\x1B[0m Symlinks from ~/.local/bin: ${existingSymlinks.join(", ")}`);if(console.log(),!hasGenieDir&&!hasHookScript&&!hasOrchestrationRules&&existingSymlinks.length===0){console.log("\x1B[33mNothing to uninstall.\x1B[0m"),console.log();return}if(!await esm_default4({message:"Are you sure you want to uninstall Genie CLI?",default:!1})){console.log(),console.log("\x1B[2mUninstall cancelled.\x1B[0m"),console.log();return}console.log(),performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir),console.log(),console.log("\x1B[32m+\x1B[0m Genie CLI uninstalled."),console.log(),console.log("\x1B[2mNote: If you installed via npm/bun, also run:\x1B[0m"),console.log(" \x1B[36mbun remove -g @automagik/genie\x1B[0m"),console.log(" \x1B[2mor\x1B[0m"),console.log(" \x1B[36mnpm uninstall -g @automagik/genie\x1B[0m"),console.log()}init_genie_config2();init_version();import{execSync as execSync3,spawn as spawn3}from"child_process";import{chmodSync as chmodSync2,closeSync as closeSync3,copyFileSync as copyFileSync3,existsSync as existsSync29,mkdirSync as mkdirSync15,openSync as openSync3,readFileSync as readFileSync20,readSync as readSync2,readdirSync as readdirSync9,readlinkSync,rmSync as rmSync3,statSync as statSync7,writeFileSync as writeFileSync13}from"fs";import{chmod,copyFile,mkdir as mkdir5,unlink as unlink2}from"fs/promises";import{homedir as homedir28}from"os";import{join as join34}from"path";var REGISTRY=[];async function cleanupLegacyArtifacts(skipList,registry=REGISTRY){let entries=[];for(let artifact of registry){if(skipList.has(artifact.name)){entries.push({name:artifact.name,outcome:"skipped",removed:[],warnings:[]});continue}if(!await artifact.detect()){entries.push({name:artifact.name,outcome:"absent",removed:[],warnings:[]});continue}let result2=await artifact.cleanup();entries.push({name:artifact.name,outcome:"cleaned",removed:result2.removed,warnings:result2.warnings})}return{entries}}function parseSkipCleanupFlag(value){let skip=new Set;if(!value)return skip;for(let part of value.split(",")){let name=part.trim();if(name)skip.add(name)}return skip}var GENIE_HOME2=process.env.GENIE_HOME||join34(homedir28(),".genie"),GENIE_SRC=join34(GENIE_HOME2,"src"),GENIE_BIN=join34(GENIE_HOME2,"bin"),LOCAL_BIN2=join34(homedir28(),".local","bin"),TRUTHY=new Set(["1","true","yes","on"]),UPDATE_DIAGNOSTIC_SCHEMA_VERSION=2,VERIFY_PROBE_DEADLINE_MS=15000,VERIFY_PROBE_POLL_INTERVAL_MS=500,FETCH_LATEST_TIMEOUT_MS=5000;function normalizeVersion(value){let trimmed=value.trim(),plusIdx=trimmed.indexOf("+");return plusIdx===-1?trimmed:trimmed.slice(0,plusIdx)}function decideVerify(args){if(args.skipReason)return{kind:"skipped",reason:args.skipReason};if(args.serverHealthBody===null)return{kind:"health-unreachable",endpoint:args.endpoint};let cliVersion=normalizeVersion(args.cliVersion),rawServerVersion=args.serverHealthBody.version??null,serverVersion=rawServerVersion===null?null:normalizeVersion(rawServerVersion);if(args.serverHealthBody.daemonInodeStale===!0)return{kind:"daemon-stale-inode",cliVersion,diskVersion:serverVersion,pid:args.serverHealthBody.daemonPid??0,cwd:args.serverHealthBody.daemonCwd??""};if(serverVersion===null||serverVersion!==cliVersion)return{kind:"version-mismatch",cliVersion,serverVersion};return{kind:"ok",cliVersion,serverVersion}}function shortCircuitIfCurrent(currentVersion,latestVersion){if(!latestVersion)return!1;return normalizeVersion(currentVersion)===normalizeVersion(latestVersion)}async function fetchLatestVersion(channel){let candidates=[{cmd:"npm",args:["view",`@automagik/genie@${channel}`,"version"]},{cmd:"bunx",args:["npm","view",`@automagik/genie@${channel}`,"version"]}];for(let{cmd,args}of candidates){let result2=await runCommandSilent(cmd,args,void 0,FETCH_LATEST_TIMEOUT_MS);if(!result2.success)continue;let trimmed=result2.output.trim();if(!trimmed)continue;let lines=trimmed.split(/\r?\n/).filter(Boolean),tokens2=lines[lines.length-1].split(/\s+/),candidate=tokens2[tokens2.length-1].replace(/^['"]|['"]$/g,"");if(/^\d+\.\d+/.test(candidate))return candidate}return null}async function promptConfirm(question){if(!process.stdin.isTTY||!process.stdout.isTTY)return!0;return process.stdout.write(`${question} [Y/n] `),new Promise((resolve5)=>{let onData=(chunk)=>{process.stdin.removeListener("data",onData),process.stdin.pause();let answer=chunk.toString("utf-8").trim().toLowerCase();if(answer===""||answer==="y"||answer==="yes")resolve5(!0);else resolve5(!1)};process.stdin.resume(),process.stdin.once("data",onData)})}function shouldAutoConfirm(opts){if(opts.yes)return!0;return isTruthyEnv(process.env.GENIE_UPDATE_YES)}var VERIFY_PROBE_ENDPOINT="pgserve status --json + ~/.genie/serve.pid";function readDaemonCwd(pid){if(process.platform!=="linux")return null;try{let cwd=readlinkSync(`/proc/${pid}/cwd`);return{cwd,staleInode:cwd.endsWith(" (deleted)")}}catch{return null}}function readInstalledPackageVersion(){let candidates=[join34(homedir28(),".bun","install","global","node_modules","@automagik","genie","package.json")],npmPrefix=safeExec("npm prefix -g",1500);if(npmPrefix)candidates.push(join34(npmPrefix,"lib","node_modules","@automagik","genie","package.json"));for(let path3 of candidates)try{let pkg=JSON.parse(readFileSync20(path3,"utf-8"));if(typeof pkg.version==="string"&&/^\d+\.\d+/.test(pkg.version))return pkg.version}catch{}return null}async function readServerHealth(){if(!(await runCommandSilent("pgserve",["status","--json"],void 0,3000)).success)return null;let pidPath=join34(GENIE_HOME2,"serve.pid"),rawPid=safeRead(pidPath,32);if(!rawPid)return null;let pid=Number.parseInt(rawPid.trim(),10);if(!Number.isFinite(pid)||pid<=0)return null;try{process.kill(pid,0)}catch{return null}let cwdInfo=readDaemonCwd(pid);return{version:readInstalledPackageVersion()??VERSION,daemonInodeStale:cwdInfo?.staleInode??!1,daemonPid:pid,daemonCwd:cwdInfo?.cwd}}async function pollHealth(readHealth,deadlineMs,intervalMs){let startedAt=Date.now();while(Date.now()-startedAt<deadlineMs){let body=null;try{body=await readHealth()}catch{}if(body!==null)return body;await new Promise((r)=>setTimeout(r,intervalMs))}return null}async function runVerifyProbe(opts){if(opts.skipReason)return decideVerify({cliVersion:opts.cliVersion,serverHealthBody:null,endpoint:VERIFY_PROBE_ENDPOINT,skipReason:opts.skipReason});let reader=opts.readHealth??readServerHealth,deadline=opts.deadlineMs??VERIFY_PROBE_DEADLINE_MS,interval=opts.intervalMs??VERIFY_PROBE_POLL_INTERVAL_MS,body=await pollHealth(reader,deadline,interval);return decideVerify({cliVersion:opts.cliVersion,serverHealthBody:body,endpoint:VERIFY_PROBE_ENDPOINT})}async function pm2GenieServe(){let result2=await runCommandSilent("pm2",["jlist"],void 0,3000);if(!result2.success)return null;try{let entry2=JSON.parse(result2.output).find((p)=>p.name==="genie-serve");if(!entry2||typeof entry2.pid!=="number"||entry2.pid<=0)return null;if(entry2.pm2_env?.status!=="online")return null;return{pid:entry2.pid,restartCount:entry2.pm2_env?.restart_time??0}}catch{return null}}async function restartServeIfStale(){let before=await pm2GenieServe();if(!before)return null;let cwdInfo=readDaemonCwd(before.pid);if(!cwdInfo||!cwdInfo.staleInode)return null;if(log(`Restarting pm2 genie-serve (stale inode detected: ${cwdInfo.cwd})`),!(await runCommandSilent("pm2",["restart","genie-serve","--update-env"],void 0,1e4)).success)return error("pm2 restart genie-serve failed; daemon will keep serving pre-update bytes until manually restarted"),null;let deadline=Date.now()+1e4;while(Date.now()<deadline){let after=await pm2GenieServe();if(after&&(after.pid!==before.pid||after.restartCount>before.restartCount))return success(`pm2 genie-serve restarted (pid ${before.pid} \u2192 ${after.pid})`),{oldPid:before.pid,newPid:after.pid};await new Promise((r)=>setTimeout(r,500))}return error("pm2 genie-serve restart did not produce a new pid within 10s \u2014 verify probe will surface the stale state"),null}function formatVerifyBanner(result2){let lines=[];switch(result2.kind){case"ok":lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} CLI: v${result2.cliVersion}`),lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} Server: v${result2.serverVersion} (healthy)`);break;case"health-unreachable":lines.push(`${colorize("\x1B[33m","\x1B[0m","!")} CLI: v${VERSION}`),lines.push(`${colorize("\x1B[31m","\x1B[0m","\u2716")} Server: unreachable (probe: ${result2.endpoint})`);break;case"version-mismatch":lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} CLI: v${result2.cliVersion}`),lines.push(`${colorize("\x1B[31m","\x1B[0m","\u2716")} Server: v${result2.serverVersion??"unknown"} (mismatch)`);break;case"daemon-stale-inode":lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} CLI: v${result2.cliVersion}`),lines.push(`${colorize("\x1B[31m","\x1B[0m","\u2716")} Server: stale inode (pid ${result2.pid}, on-disk v${result2.diskVersion??"unknown"})`),lines.push(`${colorize("\x1B[2m","\x1B[0m",` cwd: ${result2.cwd}`)}`),lines.push(`${colorize("\x1B[2m","\x1B[0m"," fix: pm2 restart genie-serve --update-env")}`);break;case"auth-invalid":lines.push(`${colorize("\x1B[31m","\x1B[0m","\u2716")} Auth: invalid`);break;case"skipped":lines.push(`${colorize("\x1B[32m","\x1B[0m","\u2714")} CLI: v${VERSION}`),lines.push(`${colorize("\x1B[2m","\x1B[0m",`\xB7 Server: v\u2026 (skipped: ${result2.reason})`)}`);break}return lines}function colorEnabled(){if(process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0")return!0;return Boolean(process.stdout.isTTY)}function colorize(open4,close,text){return colorEnabled()?`${open4}${text}${close}`:text}function log(message){console.log(`${colorize("\x1B[32m","\x1B[0m","\u25B8")} ${message}`)}function success(message){console.log(`${colorize("\x1B[32m","\x1B[0m","\u2714")} ${message}`)}function error(message){console.log(`${colorize("\x1B[31m","\x1B[0m","\u2716")} ${message}`)}function formatDuration2(ms){if(ms<1000)return`${ms}ms`;return`${(ms/1000).toFixed(1)}s`}function isTruthyEnv(value){return value!==void 0&&TRUTHY.has(value.trim().toLowerCase())}async function withTemporaryEnv(key,value,fn){let previous=process.env[key];process.env[key]=value;try{return await fn()}finally{if(previous===void 0)delete process.env[key];else process.env[key]=previous}}function safeExec(command,timeoutMs=1500){try{return execSync3(command,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:timeoutMs}).trim()}catch(err){let stdout=err.stdout;if(typeof stdout==="string"&&stdout.trim())return stdout.trim();return""}}function safeRead(path3,maxChars=4000){try{let value=readFileSync20(path3,"utf-8");if(value.length<=maxChars)return value;return value.slice(value.length-maxChars)}catch{return null}}function tailLines(path3,maxBytes=64000,maxLines=200){let fd=null;try{let stat4=statSync7(path3),bytesToRead=Math.min(stat4.size,maxBytes),buffer2=Buffer.alloc(bytesToRead);return fd=openSync3(path3,"r"),readSync2(fd,buffer2,0,bytesToRead,Math.max(0,stat4.size-bytesToRead)),buffer2.toString("utf-8").split(/\r?\n/).map((line)=>line.trim()).filter(Boolean).slice(-maxLines)}catch{return[]}finally{if(fd!==null)try{closeSync3(fd)}catch{}}}function summarizeJsonlSignals(path3){let signals2=new Map;for(let line of tailLines(path3))try{let event=JSON.parse(line),level=typeof event.level==="string"?event.level:"unknown";if(level!=="error"&&level!=="warn")continue;let name=typeof event.event==="string"?event.event:"unknown",key=`${level}:${name}`,existing=signals2.get(key)??{level,event:name,count:0};if(existing.count++,typeof event.timestamp==="string")existing.lastTimestamp=event.timestamp;if(typeof event.error==="string")existing.lastError=event.error;signals2.set(key,existing)}catch{}return[...signals2.values()].sort((a,b2)=>b2.count-a.count).slice(0,10)}async function collectUpdateDiagnostics(ctx,maintenance,extras){let logsDir=join34(GENIE_HOME2,"logs");mkdirSync15(logsDir,{recursive:!0});let generatedAt=new Date().toISOString(),safeStamp=generatedAt.replace(/[:.]/g,"-"),path3=join34(logsDir,`update-diagnostics-${safeStamp}.json`),schedulerLog=join34(logsDir,"scheduler.log"),tuiCrashLog=join34(logsDir,"tui-crash.log"),signals2=summarizeJsonlSignals(schedulerLog),diagnostics={schemaVersion:UPDATE_DIAGNOSTIC_SCHEMA_VERSION,cli:"genie",generatedAt,verify:extras.verify,cleanups:extras.cleanups,update:ctx,runtime:{platform:process.platform,arch:process.arch,cwd:process.cwd(),node:process.version,bun:(await runCommandSilent("bun",["--version"])).output.trim()||null,npm:(await runCommandSilent("npm",["--version"])).output.trim()||null,genie:{which:(await runCommandSilent("which",["genie"])).output.trim()||null,tuiDisabled:isTruthyEnv(process.env.GENIE_TUI_DISABLE),updateSkipMaintenance:isTruthyEnv(process.env.GENIE_UPDATE_SKIP_MAINTENANCE)}},paths:{genieHome:GENIE_HOME2,logsDir,servePid:safeRead(join34(GENIE_HOME2,"serve.pid"),200),pgservePort:safeRead(join34(GENIE_HOME2,"pgserve.port"),200),schedulerLog,tuiCrashLog},processSnapshot:{genie:safeExec("ps -axo pid,ppid,pgid,stat,pcpu,pmem,etime,command -r | rg -i 'dist/genie.js|/src/genie.ts|pgserve|postgres -D .*\\.genie/data/pgserve|tmux -L genie-tui|bun' || true",2000)||null,tuiTmux:safeExec("tmux -L genie-tui ls 2>/dev/null || true",1000)||null},maintenance:{...maintenance,pgAutostartDisabled:!0,legend:{"[ok]":"healthy","[fix]":"fixed during maintenance","[--]":"skipped/non-blocking","[!!]":"operator action needed; update still completed"}},recentLogSignals:{scheduler:signals2,schedulerTail:tailLines(schedulerLog,32000,80),tuiCrashTail:tailLines(tuiCrashLog,32000,80)}};return writeFileSync13(path3,`${JSON.stringify(diagnostics,null,2)}
|
|
3989
|
+
`),{path:path3,signals:signals2}}async function runCommand(command,args,cwd){return new Promise((resolve5)=>{let output=[],child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}});child.stdout?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stdout.write(str2)}),child.stderr?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stderr.write(str2)}),child.on("close",(code)=>{resolve5({success:code===0,output:output.join("")})}),child.on("error",(err)=>{error(err.message),resolve5({success:!1,output:err.message})})})}async function getGitInfo(cwd){try{let branchResult=await runCommandSilent("git",["rev-parse","--abbrev-ref","HEAD"],cwd),commitResult=await runCommandSilent("git",["rev-parse","--short","HEAD"],cwd),dateResult=await runCommandSilent("git",["log","-1","--format=%ci"],cwd);if(branchResult.success&&commitResult.success&&dateResult.success)return{branch:branchResult.output.trim(),commit:commitResult.output.trim(),commitDate:dateResult.output.trim().split(" ")[0]}}catch{}return null}async function runCommandSilent(command,args,cwd,timeoutMs=4000){return new Promise((resolve5)=>{let output=[],settled=!1,child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"]}),timer2=setTimeout(()=>{if(settled)return;settled=!0,child.kill("SIGTERM"),resolve5({success:!1,output:`Timed out after ${timeoutMs}ms`})},timeoutMs);child.stdout?.on("data",(data)=>{output.push(data.toString())}),child.stderr?.on("data",(data)=>{output.push(data.toString())}),child.on("close",(code)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve5({success:code===0,output:output.join("")})}),child.on("error",(err)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve5({success:!1,output:err.message})})})}function detectFromBinaryPath(path3){let resolved=path3;try{resolved=__require("fs").realpathSync(path3)}catch{}if(resolved.includes(".bun"))return"bun";if(resolved.includes("node_modules"))return"npm";if(path3===join34(LOCAL_BIN2,"genie")||resolved.startsWith(GENIE_BIN))return"source";return null}async function detectInstallationType(){let whichResult=await runCommandSilent("which",["genie"]);if(whichResult.success){let detected=detectFromBinaryPath(whichResult.output.trim());if(detected)return detected}if(genieConfigExists())try{let config=await loadGenieConfig();if(config.installMethod)return config.installMethod}catch{}if(existsSync29(join34(GENIE_SRC,".git")))return"source";return(await runCommandSilent("which",["bun"])).success?"bun":"npm"}async function updateViaBun(channel){try{__require("fs").unlinkSync(join34(homedir28(),".bun","install","global","bun.lock"))}catch{}if(log(`Updating via bun (channel: ${channel})...`),!(await runCommand("bun",["add","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via bun"),!1;return console.log(),success(`Genie CLI updated via bun (${channel})!`),!0}async function updateViaNpm(channel){if(log(`Updating via npm (channel: ${channel})...`),!(await runCommand("npm",["install","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via npm"),!1;return console.log(),success(`Genie CLI updated via npm (${channel})!`),!0}async function detectGlobalInstalls(){let found=new Set,[npmResult,bunResult]=await Promise.all([runCommandSilent("npm",["list","-g","@automagik/genie"]),runCommandSilent("bun",["pm","ls","-g"])]);if(npmResult.success&&!npmResult.output.includes("(empty)"))found.add("npm");if(bunResult.success&&bunResult.output.includes("@automagik/genie"))found.add("bun");return found}async function updateSource(){if(!existsSync29(GENIE_SRC))error(`Source install path not found: ${GENIE_SRC}`),console.error(" Detection picked the source-install path, but the directory does not exist."),console.error(" This usually means a stale install hint (config or ~/.genie/src/.git) is"),console.error(" pointing somewhere genuine. Either:"),console.error(` 1. Re-clone the source: git clone https://github.com/automagik-dev/genie ${GENIE_SRC}`),console.error(" 2. Update via package manager instead: genie update --next --via bun"),console.error(" 3. Inspect detection: genie doctor --update-detection"),process.exit(1);if(!existsSync29(join34(GENIE_SRC,".git")))error(`Source install path is not a git checkout: ${GENIE_SRC}`),console.error(` ${GENIE_SRC} exists but has no .git/. Cannot run \`git fetch\` from it.`),console.error(` Either delete ${GENIE_SRC} and re-clone, or update via package manager:`),console.error(" genie update --next --via bun"),process.exit(1);let beforeInfo=await getGitInfo(GENIE_SRC);if(beforeInfo)console.log(`Current: \x1B[2m${beforeInfo.branch}@${beforeInfo.commit} (${beforeInfo.commitDate})\x1B[0m`),console.log();if(log("Fetching latest changes..."),!(await runCommand("git",["fetch","origin"],GENIE_SRC)).success)error("Failed to fetch from origin"),process.exit(1);if(log("Resetting to origin/main..."),!(await runCommand("git",["reset","--hard","origin/main"],GENIE_SRC)).success)error("Failed to reset to origin/main"),process.exit(1);console.log();let afterInfo=await getGitInfo(GENIE_SRC);if(beforeInfo&&afterInfo&&beforeInfo.commit===afterInfo.commit){success("Already up to date!"),console.log();return}if(log("Installing dependencies..."),!(await runCommand("bun",["install"],GENIE_SRC)).success)error("Failed to install dependencies"),process.exit(1);if(console.log(),log("Building..."),!(await runCommand("bun",["run","build"],GENIE_SRC)).success)error("Failed to build"),process.exit(1);console.log(),log("Installing binaries...");try{await mkdir5(GENIE_BIN,{recursive:!0}),await mkdir5(LOCAL_BIN2,{recursive:!0});let binaries=["genie.js","term.js"],names=["genie","term"];for(let i2=0;i2<binaries.length;i2++){let src=join34(GENIE_SRC,"dist",binaries[i2]),binDest=join34(GENIE_BIN,binaries[i2]),linkDest=join34(LOCAL_BIN2,names[i2]);await copyFile(src,binDest),await chmod(binDest,493),await symlinkOrCopy(binDest,linkDest)}for(let legacy of["claudio.js","claudio"]){let legacyBin=join34(GENIE_BIN,legacy),legacyLink=join34(LOCAL_BIN2,legacy);try{await unlink2(legacyBin)}catch{}try{await unlink2(legacyLink)}catch{}}success("Binaries installed")}catch(err){error(`Failed to install binaries: ${err}`),process.exit(1)}if(console.log(),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),success("Genie CLI updated successfully!"),console.log(),afterInfo)console.log(`Version: \x1B[36m${afterInfo.branch}@${afterInfo.commit}\x1B[0m (${afterInfo.commitDate})`),console.log()}async function symlinkOrCopy(src,dest){let{symlink:symlink2,unlink:unlink3}=await import("fs/promises");try{if(existsSync29(dest))await unlink3(dest);await symlink2(src,dest)}catch{await copyFile(src,dest)}}var FRAMEWORK_MARKER_FILES=new Set([".orphaned_at"]);function copyDirSync(src,dest){mkdirSync15(dest,{recursive:!0});for(let entry2 of readdirSync9(src,{withFileTypes:!0})){if(FRAMEWORK_MARKER_FILES.has(entry2.name))continue;let srcPath=join34(src,entry2.name),destPath=join34(dest,entry2.name);if(entry2.isDirectory())copyDirSync(srcPath,destPath);else copyFileSync3(srcPath,destPath)}}async function resolveGlobalPkgDir(installType){if(installType==="bun"){let bunPath=join34(homedir28(),".bun","install","global","node_modules","@automagik","genie");if(existsSync29(bunPath))return bunPath}if(installType==="npm"){let npmRootResult=await runCommandSilent("npm",["root","-g"]);if(npmRootResult.success){let npmPath=join34(npmRootResult.output.trim(),"@automagik","genie");if(existsSync29(npmPath))return npmPath}}let bunFallback=join34(homedir28(),".bun","install","global","node_modules","@automagik","genie");if(existsSync29(bunFallback))return bunFallback;let npmRootFallback=await runCommandSilent("npm",["root","-g"]);if(npmRootFallback.success){let npmPath=join34(npmRootFallback.output.trim(),"@automagik","genie");if(existsSync29(npmPath))return npmPath}return null}function updatePluginRegistry(claudePlugins,cacheDir,version){let registryPath=join34(claudePlugins,"installed_plugins.json");try{if(!existsSync29(registryPath))return;let registry=JSON.parse(readFileSync20(registryPath,"utf-8")),entries=registry.plugins?.["genie@automagik"];if(!Array.isArray(entries))return;for(let entry2 of entries)if(entry2.scope==="user")entry2.installPath=cacheDir,entry2.version=version,entry2.lastUpdated=new Date().toISOString();writeFileSync13(registryPath,JSON.stringify(registry,null,2))}catch(err){log(`Registry update failed (non-fatal): ${err}`)}}function syncTmuxConf(tmuxScriptsSrc){mkdirSync15(GENIE_HOME2,{recursive:!0});let tmuxConfSrc=join34(tmuxScriptsSrc,"genie.tmux.conf"),tmuxConfDest=join34(GENIE_HOME2,"tmux.conf");if(existsSync29(tmuxConfSrc))try{copyFileSync3(tmuxConfSrc,tmuxConfDest),success(`Installed tmux config to ${tmuxConfDest}`);try{let{tmuxBin:tmuxBin2}=(init_ensure_tmux(),__toCommonJS(exports_ensure_tmux));execSync3(`${tmuxBin2()} -L genie source-file '${tmuxConfDest}'`,{stdio:"ignore"}),success("Reloaded genie tmux server configuration")}catch{}}catch{}let tuiConfSrc=join34(tmuxScriptsSrc,"tui-tmux.conf"),tuiConfDest=join34(GENIE_HOME2,"tui-tmux.conf");if(existsSync29(tuiConfSrc))try{copyFileSync3(tuiConfSrc,tuiConfDest),success(`Installed TUI tmux config to ${tuiConfDest}`)}catch{}let themeSrc=join34(tmuxScriptsSrc,".generated.theme.conf"),themeDest=join34(GENIE_HOME2,".generated.theme.conf");if(existsSync29(themeSrc))try{copyFileSync3(themeSrc,themeDest),success(`Installed tmux theme to ${themeDest}`)}catch{}let osc52Src=join34(tmuxScriptsSrc,"osc52-copy.sh"),osc52Dest=join34(GENIE_HOME2,"scripts","osc52-copy.sh");if(existsSync29(osc52Src))try{copyFileSync3(osc52Src,osc52Dest),chmodSync2(osc52Dest,493),success(`Installed OSC 52 clipboard helper to ${osc52Dest}`)}catch{}}function syncTmuxScripts(globalPkgDir){let tmuxScriptsSrc=join34(globalPkgDir,"scripts","tmux");if(!existsSync29(tmuxScriptsSrc))return;let scriptsDir=join34(GENIE_HOME2,"scripts");mkdirSync15(scriptsDir,{recursive:!0});let scriptCount=0;for(let entry2 of readdirSync9(tmuxScriptsSrc))if(entry2.endsWith(".sh")||entry2==="genie.tmux.conf"||entry2==="tui-tmux.conf"||entry2===".generated.theme.conf"){let src=join34(tmuxScriptsSrc,entry2),dest=join34(scriptsDir,entry2);copyFileSync3(src,dest);try{chmodSync2(dest,entry2.endsWith(".sh")?493:420)}catch{}scriptCount++}if(scriptCount>0)success(`Refreshed ${scriptCount} tmux scripts at ${scriptsDir}`);syncTmuxConf(tmuxScriptsSrc)}function syncMarketplaceVersion(claudePlugins,version){let marketplacePath=join34(claudePlugins,"marketplaces","automagik",".claude-plugin","marketplace.json");try{if(!existsSync29(marketplacePath))return;let data=JSON.parse(readFileSync20(marketplacePath,"utf-8"));if(Array.isArray(data.plugins)){for(let plugin of data.plugins)if(plugin.name==="genie")plugin.version=version}writeFileSync13(marketplacePath,JSON.stringify(data,null,2)),success(`Updated marketplace.json to v${version}`)}catch(err){log(`Marketplace version update failed (non-fatal): ${err}`)}}function syncPluginPackageVersion(claudePlugins,version){let pkgPath=join34(claudePlugins,"marketplaces","automagik","plugins","genie","package.json");try{if(!existsSync29(pkgPath))return;let data=JSON.parse(readFileSync20(pkgPath,"utf-8"));data.version=version,writeFileSync13(pkgPath,JSON.stringify(data,null,2)),success(`Updated plugin package.json to v${version}`)}catch(err){log(`Plugin package.json update failed (non-fatal): ${err}`)}}function syncSkillsSymlink(claudePlugins,version){let skillsLink=join34(claudePlugins,"marketplaces","automagik","plugins","genie","skills"),cacheSkills=join34("..","..","..","..","cache","automagik","genie",version,"skills");try{let{symlinkSync,unlinkSync:unlinkSync9,lstatSync:lstatSync2}=__require("fs");try{lstatSync2(skillsLink),unlinkSync9(skillsLink)}catch{}symlinkSync(cacheSkills,skillsLink),success(`Skills symlink \u2192 cache/${version}/skills`)}catch(err){log(`Skills symlink update failed (non-fatal): ${err}`)}}async function syncPlugin(installType){log("Syncing Claude Code plugin...");let globalPkgDir=await resolveGlobalPkgDir(installType);if(!globalPkgDir)return log("Could not find installed package \u2014 skipping plugin sync"),{skippedReason:"installed package not found"};let pluginSrc=join34(globalPkgDir,"plugins","genie");if(!existsSync29(pluginSrc))return log("Plugin source not found in package \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"plugin source not found in package"};let version;try{version=JSON.parse(readFileSync20(join34(globalPkgDir,"package.json"),"utf-8")).version}catch{return log("Could not read package version \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"could not read package version"}}let claudePlugins=join34(homedir28(),".claude","plugins"),cacheDir=join34(claudePlugins,"cache","automagik","genie",version);try{if(existsSync29(cacheDir))rmSync3(cacheDir,{recursive:!0,force:!0});copyDirSync(pluginSrc,cacheDir);let skillsSrc=join34(globalPkgDir,"skills");if(existsSync29(skillsSrc)&&!existsSync29(join34(cacheDir,"skills")))copyDirSync(skillsSrc,join34(cacheDir,"skills"))}catch(err){return error(`Failed to copy plugin: ${err}`),{version,globalPkgDir,cacheDir,skippedReason:`failed to copy plugin: ${err}`}}return updatePluginRegistry(claudePlugins,cacheDir,version),syncMarketplaceVersion(claudePlugins,version),syncPluginPackageVersion(claudePlugins,version),syncSkillsSymlink(claudePlugins,version),syncTmuxScripts(globalPkgDir),success(`Plugin synced to v${version}`),{version,globalPkgDir,cacheDir}}async function resolveChannel(options){if(options.next)return"next";if(options.stable)return"latest";if(genieConfigExists())try{let config=await loadGenieConfig();if(config.updateChannel)return config.updateChannel}catch{}return"latest"}async function persistChannel(channel){try{let config=await loadGenieConfig();config.updateChannel=channel,await saveGenieConfig(config)}catch{}}async function updateCommand(options={}){console.log(),console.log(`${colorize("\x1B[1m","\x1B[0m","\uD83E\uDDDE Genie CLI Update")}`),console.log(`${colorize("\x1B[2m","\x1B[0m","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`),console.log();let cleanupSkipList=buildCleanupSkipList(options),noRestart=options.restart===!1||isTruthyEnv(process.env.GENIE_UPDATE_NO_RESTART),noVerify=options.verify===!1||isTruthyEnv(process.env.GENIE_UPDATE_NO_VERIFY),channel=await resolveChannel(options);if(options.next||options.stable)await persistChannel(channel);let latestVersion=await fetchLatestVersion(channel);if(shortCircuitIfCurrent(VERSION,latestVersion)){success(`Already up to date (v${normalizeVersion(VERSION)}, channel ${channel})`),console.log();return}let installType=await detectInstallationType();if(log(`Detected installation: ${installType}`),log(`Channel: ${channel}${channel==="next"?" (dev builds)":" (stable)"}`),latestVersion)log(`Update available: ${normalizeVersion(VERSION)} \u2192 ${normalizeVersion(latestVersion)}`);else log(`Registry version unavailable (proceeding with reinstall of channel ${channel})`);if(console.log(),installType==="unknown")error("No Genie CLI installation found"),console.log(),console.log("Install method not configured. Please reinstall genie:"),console.log(`${colorize("\x1B[36m","\x1B[0m"," curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash")}`),console.log(),process.exit(1);if(!shouldAutoConfirm(options)){let proceedQuestion=latestVersion?`Update v${normalizeVersion(VERSION)} \u2192 v${normalizeVersion(latestVersion)}?`:`Reinstall channel "${channel}"?`;if(!await promptConfirm(proceedQuestion)){console.log(),log("Update declined."),console.log();return}}if(installType==="source"){await updateSource();return}let globalInstalls=await detectGlobalInstalls(),primaryMethod=installType;if(!(primaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))process.exit(1);let secondaryMethod=primaryMethod==="bun"?"npm":"bun";if(globalInstalls.has(secondaryMethod)){if(console.log(),log(`Also updating ${secondaryMethod}-global install...`),!(secondaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))error(`Secondary update via ${secondaryMethod} failed (non-blocking)`)}let plugin=await syncPlugin(installType),cleanupReport=await runLegacyCleanupSafe(cleanupSkipList);await runPostUpdateMaintenanceSafe({...options,noRestart,noVerify},{channel,installType,primaryMethod,globalInstalls:[...globalInstalls].sort(),plugin,latestVersion,cliVersion:VERSION},cleanupReport)}function buildCleanupSkipList(options){let skipList=parseSkipCleanupFlag(options.skipCleanup);if(options.sidecarCleanup===!1)skipList.add("nats-reply-sidecar"),log("--no-sidecar-cleanup (no-op for genie, retained for cross-CLI portability)");return skipList}async function runLegacyCleanupSafe(skipList){try{return await cleanupLegacyArtifacts(skipList)}catch(err){let msg=err instanceof Error?err.message:String(err);return log(`Legacy artifact cleanup failed (non-fatal): ${msg}`),{entries:[]}}}function printPostUpdateMaintenanceIntro(){console.log(),log("Running post-update maintenance..."),console.log(" Purpose: make first launch after update fast and collect upgrade health signals."),console.log(" Checks: runtime partitions, watchdog status, session backfill drift, zombie rows, team config orphans."),console.log(" PG policy: read-only; uses an already-running pgserve when available and will not auto-start it."),console.log(" Legend: [ok]=healthy, [fix]=fixed, [--]=skipped/non-blocking, [!!]=operator action needed.")}async function runMaintenanceWithCapturedLines(maintenanceLines){let{runPostUpdateMaintenance:runPostUpdateMaintenance2}=await Promise.resolve().then(() => (init_doctor(),exports_doctor));await withTemporaryEnv("GENIE_PG_NO_AUTOSTART","1",()=>runPostUpdateMaintenance2({log:(line)=>{maintenanceLines.push(line),console.log(line)}}))}function printDiagnosticsSummary(diagnostics){if(log("Post-update diagnostics captured."),console.log(` Report: ${diagnostics.path}`),console.log(" Include this file when opening a GitHub issue; it contains install metadata, step output,"),console.log(" local process state, and recent scheduler/TUI log signals."),diagnostics.signals.length===0)return;console.log(" Recent scheduler signals:");for(let signal of diagnostics.signals.slice(0,3)){let errorDetail=signal.lastError?` \u2014 ${signal.lastError}`:"";console.log(` ${signal.level}:${signal.event} \xD7${signal.count}${errorDetail}`)}}async function capturePostUpdateDiagnostics(diagnosticsCtx,maintenance,extras){if(!diagnosticsCtx)return;try{let diagnostics=await collectUpdateDiagnostics(diagnosticsCtx,maintenance,extras);printDiagnosticsSummary(diagnostics)}catch(err){let msg=err instanceof Error?err.message:String(err);log(`Post-update diagnostics capture failed (non-fatal): ${msg}`)}}function printVerifyBanner(result2){console.log();for(let line of formatVerifyBanner(result2))console.log(` ${line}`);console.log()}async function runPostUpdateMaintenanceSafe(options,diagnosticsCtx,cleanupReport){if(options.noRestart){log("--no-restart: skipping maintenance and verify probe.");let verify2=await runVerifyProbe({cliVersion:VERSION,skipReason:"no-restart"});printVerifyBanner(verify2),await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome:"completed",durationMs:0,lines:[]},{verify:verify2,cleanups:cleanupReport});return}if(options.skipMaintenance||isTruthyEnv(process.env.GENIE_UPDATE_SKIP_MAINTENANCE)){log("Skipping post-update maintenance (requested).");let verify2=await runVerifyProbe({cliVersion:VERSION,skipReason:"no-restart"});printVerifyBanner(verify2),await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome:"completed",durationMs:0,lines:[]},{verify:verify2,cleanups:cleanupReport});return}let startedAt=Date.now(),maintenanceLines=[],outcome="completed",maintenanceError;try{printPostUpdateMaintenanceIntro(),await runMaintenanceWithCapturedLines(maintenanceLines),success(`Post-update maintenance complete (${formatDuration2(Date.now()-startedAt)}).`)}catch(err){outcome="failed",maintenanceError=err instanceof Error?err.message:String(err),error(`Post-update maintenance skipped: ${maintenanceError}`)}await restartServeIfStaleSafe();let verify=options.noVerify?await runVerifyProbe({cliVersion:VERSION,skipReason:"no-verify-flag"}):await runVerifyProbe({cliVersion:VERSION});if(printVerifyBanner(verify),await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome,durationMs:Date.now()-startedAt,lines:maintenanceLines,error:maintenanceError},{verify,cleanups:cleanupReport}),(verify.kind==="health-unreachable"||verify.kind==="daemon-stale-inode")&&!options.noVerify)process.exitCode=1}async function restartServeIfStaleSafe(){try{await restartServeIfStale()}catch(err){let msg=err instanceof Error?err.message:String(err);log(`Stale-serve restart skipped (non-fatal): ${msg}`)}}init_version();init_trust();init_trust();init_trust();import{execSync as execSync4}from"child_process";import{existsSync as existsSync31,mkdirSync as mkdirSync16,readFileSync as readFileSync22,renameSync as renameSync6,writeFileSync as writeFileSync14}from"fs";import{dirname as dirname13,isAbsolute,join as join36,resolve as resolve5}from"path";function resolveOriginUrl(repoRoot){try{return execSync4("git config --get remote.origin.url",{cwd:repoRoot,encoding:"utf-8"}).trim()||null}catch{return null}}function findRepoRoot(start){let current=start;while(current!=="/"){if(existsSync31(join36(current,".git")))return current;current=dirname13(current)}return null}function writeTrustFile(path3,file){let dir=dirname13(path3);if(!existsSync31(dir))mkdirSync16(dir,{recursive:!0});let sorted={version:1,entries:[...file.entries].sort((a,b2)=>a.path.localeCompare(b2.path))},serialized=`${JSON.stringify(sorted,null,2)}
|
|
3989
3990
|
`,tmpPath=`${path3}.tmp.${process.pid}`;writeFileSync14(tmpPath,serialized,"utf-8"),renameSync6(tmpPath,path3)}function runTrustList(trustPath){let current=readTrustFile(trustPath);if(current.entries.length===0){console.log(`(trust file empty: ${trustPath})`);return}console.log(`Trusted hooks (${current.entries.length}, from ${trustPath}):`);for(let entry2 of current.entries){let scope=entry2.scope==="repo"?`repo:${entry2.repoRemoteUrl??"?"}`:entry2.scope;if(console.log(` ${entry2.path}`),console.log(` scope: ${scope}`),console.log(` sha256: ${entry2.sha256}`),console.log(` trusted: ${entry2.trustedAt}`),entry2.capabilities&&entry2.capabilities.length>0)console.log(` caps: ${entry2.capabilities.join(", ")}`);if(entry2.note)console.log(` note: ${entry2.note}`)}}function resolveTrustScope(filePath,options){if(options.repo){let repoRoot=findRepoRoot(dirname13(filePath));if(!repoRoot)console.error(`Error: --repo passed but no .git directory found above ${filePath}`),process.exit(1);let remote=resolveOriginUrl(repoRoot);if(!remote)console.error(`Error: --repo passed but ${repoRoot} has no remote.origin.url`),process.exit(1);return{scope:"repo",repoRemoteUrl:remote}}if(options.team)return{scope:"team"};return{scope:"global"}}async function confirmTrustOrAbort(yes){if(yes||!process.stdin.isTTY)return;process.stdout.write("Confirm? (y/N) ");let buf=Buffer.alloc(8),read=0;try{read=(await import("fs")).readSync(0,buf,0,buf.length,null)}catch{console.error("Error: cannot read confirmation; pass --yes to trust non-interactively"),process.exit(1)}let answer=buf.subarray(0,read).toString().trim().toLowerCase();if(answer!=="y"&&answer!=="yes")console.log("Aborted."),process.exit(1)}async function runTrustAdd(target,options,trustPath){let filePath=isAbsolute(target)?target:resolve5(process.cwd(),target);if(!existsSync31(filePath))console.error(`Error: file not found: ${filePath}`),process.exit(1);if(!filePath.endsWith(".ts"))console.error(`Error: trust target must be a .ts file: ${filePath}`),process.exit(1);let{scope,repoRemoteUrl}=resolveTrustScope(filePath,options),sha=sha256OfFile(filePath),source=readFileSync22(filePath,"utf-8"),capabilities=parseCapabilities(source);if(console.log(`About to trust: ${filePath}`),console.log(` scope: ${scope==="repo"?`repo:${repoRemoteUrl}`:scope}`),console.log(` sha256: ${sha}`),capabilities.length>0)console.log(` caps: ${capabilities.join(", ")}`);if(options.note)console.log(` note: ${options.note}`);await confirmTrustOrAbort(options.yes??!1);let current=readTrustFile(trustPath),newEntry={path:filePath,sha256:sha,scope,repoRemoteUrl,trustedAt:new Date().toISOString(),note:options.note,capabilities:capabilities.length>0?capabilities:void 0},next={version:1,entries:[...current.entries.filter((e)=>e.path!==filePath),newEntry]};writeTrustFile(trustPath,next),console.log(`Trusted ${filePath} \u2192 ${trustPath}`)}async function trustAction(target,options){let trustPath=defaultTrustPath();if(!target)return runTrustList(trustPath);await runTrustAdd(target,options,trustPath)}function registerHookTrustCommand(parent){parent.command("trust [path]").description("Add a .ts hook file to the trust allowlist (or list current entries when [path] is omitted)").option("--repo","Scope to current repo (pinned to remote.origin.url)").option("--global","Scope globally (default)").option("--team <name>","Scope to a specific team directory").option("--note <text>","Free-form note saved with the entry").option("--yes","Skip the interactive confirmation prompt").action(trustAction)}import{appendFileSync as appendFileSync3,chmodSync as chmodSync3,mkdirSync as mkdirSync17,statSync as statSync8}from"fs";import{connect as connect2}from"net";import{homedir as homedir30}from"os";import{dirname as dirname14,join as join37}from"path";var PATTERNS=[{kind:"gh-token",re:/gh[ps]_[A-Za-z0-9]{30,}/g},{kind:"sk-token",re:/sk-[A-Za-z0-9-]{20,}/g},{kind:"glpat",re:/glpat-[A-Za-z0-9_-]{20,}/g},{kind:"hex",re:/\b[a-f0-9]{40,}\b/g}];function redactTokenShapes(text){if(text==null)return null;if(process.env.GENIE_HOOK_REDACTION==="off")return String(text);let out=String(text);for(let{kind,re}of PATTERNS)out=out.replace(re,`[REDACTED:${kind}]`);return out}function defaultSocketPath(){if(process.env.GENIE_HOOK_SOCK)return process.env.GENIE_HOOK_SOCK;let home=process.env.GENIE_HOME??join37(homedir30(),".genie");return join37(home,"hook.sock")}function fallbackLogPath2(){let home=process.env.GENIE_HOME??join37(homedir30(),".genie");return join37(home,"hook-fallback.log")}var MAX_FRAME_BYTES=1048576,FALLBACK_LOG_MAX_BYTES=104857600,DEFAULT_TIMEOUT_MS=5000;function readStdinSync(){let chunks=[],total=0,fd=0,buf=Buffer.alloc(65536);while(!0){let n;try{n=__require("fs").readSync(fd,buf,0,buf.length,null)}catch{break}if(n===0)break;if(chunks.push(Buffer.from(buf.subarray(0,n))),total+=n,total>MAX_FRAME_BYTES)break}return Buffer.concat(chunks,Math.min(total,MAX_FRAME_BYTES))}function summarizePayload(payload){try{let obj=JSON.parse(payload.toString("utf-8")),event=typeof obj.hook_event_name==="string"?obj.hook_event_name:null,tool=typeof obj.tool_name==="string"?obj.tool_name:null,command=null,ti=obj.tool_input;if(ti&&typeof ti.command==="string")command=ti.command.split(`
|
|
3990
3991
|
`)[0].slice(0,256);return{event,tool,command}}catch{return{event:null,tool:null,command:null}}}function ensureLogPermissions(path3){let st;try{st=statSync8(path3)}catch{return}let mode=st.mode&511;if(mode===384)return;try{chmodSync3(path3,384),process.stderr.write(`[genie-hook] tightened ${path3} permissions ${mode.toString(8)} -> 600
|
|
3991
3992
|
`)}catch{}}function appendFallback(record){let path3=fallbackLogPath2();try{mkdirSync17(dirname14(path3),{recursive:!0}),ensureLogPermissions(path3);let safe={...record,command:redactTokenShapes(record.command)},writeFresh=!1;try{if(statSync8(path3).size>=FALLBACK_LOG_MAX_BYTES)writeFresh=!0}catch{}let line=`${JSON.stringify(safe)}
|