@quantiya/codevibe-claude-plugin 1.0.50 → 1.0.52

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codevibe-claude",
3
- "version": "1.0.50",
3
+ "version": "1.0.52",
4
4
  "description": "Sync Claude Code sessions with iOS mobile app via AWS backend. Control Claude Code from your phone with real-time bidirectional synchronization.",
5
5
  "author": {
6
6
  "name": "CodeVibe Team"
package/dist/server.js CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";var ke=Object.create;var X=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Te=(w,e)=>{for(var t in e)X(w,t,{get:e[t],enumerable:!0})},ce=(w,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ie(e))!Ae.call(w,n)&&n!==t&&X(w,n,{get:()=>e[n],enumerable:!(r=be(e,n))||r.enumerable});return w};var O=(w,e,t)=>(t=w!=null?ke(Ce(w)):{},ce(e||!w||!w.__esModule?X(t,"default",{value:w,enumerable:!0}):t,w)),xe=w=>ce(X({},"__esModule",{value:!0}),w);var Oe={};Te(Oe,{McpServer:()=>te,parseInteractivePromptInput:()=>Pe});module.exports=xe(Oe);var D=O(require("fs")),V=O(require("path")),ee=O(require("os")),ve=require("child_process"),Ee=require("util"),Se=require("child_process"),W=require("crypto");var de=O(require("os")),le=O(require("path")),ue=require("@quantiya/codevibe-core"),i=(0,ue.createLogger)({name:"codevibe-claude",logFile:le.default.join(de.default.tmpdir(),"codevibe-claude-mcp.log"),level:"info"});var p=require("@quantiya/codevibe-core");var ne=O(require("express")),j=O(require("fs")),re=O(require("path")),ie=O(require("os")),me=require("@quantiya/codevibe-core");var S=require("@quantiya/codevibe-core");var z=class{constructor(){this.assignedPort=0;this.app=(0,ne.default)(),this.setupMiddleware(),this.setupRoutes()}setSessionId(e){this.sessionId=e}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(ne.default.json({limit:"1mb"})),this.app.use((e,t,r)=>{i.debug(`${e.method} ${e.path}`,{body:e.body,query:e.query}),r()}),this.app.use((e,t,r,n)=>{i.error("Express error:",e);let s={success:!1,error:e.message||"Internal server error"};r.status(500).json(s)})}setupRoutes(){this.app.get("/health",this.handleHealth.bind(this)),this.app.post("/event",this.handleEvent.bind(this)),process.env.NODE_ENV!=="production"&&this.app.post("/test/execute",this.handleTestExecute.bind(this))}handleHealth(e,t){let r={success:!0,data:{status:"healthy",uptime:process.uptime(),version:"0.1.0",timestamp:new Date().toISOString()}};t.json(r)}async handleEvent(e,t){try{let r=e.body;if(!r.session_id){let o={success:!1,error:"Missing required field: session_id"};t.status(400).json(o);return}if(!r.hook_event_name){let o={success:!1,error:"Missing required field: hook_event_name"};t.status(400).json(o);return}let n=this.transformHookToEvent(r);i.info("Received event from hook",{sessionId:r.session_id,hookEvent:r.hook_event_name,type:n.type}),this.eventHandler?await this.eventHandler(n):i.warn("No event handler registered");let s={success:!0,message:"Event processed successfully"};t.json(s)}catch(r){i.error("Error handling event:",r);let n={success:!1,error:r instanceof Error?r.message:"Unknown error"};t.status(500).json(n)}}async handleTestExecute(e,t){try{let{sessionId:r,prompt:n}=e.body;if(!r||!n){let o={success:!1,error:"Missing required fields: sessionId, prompt"};t.status(400).json(o);return}i.info("Test execute request",{sessionId:r,prompt:n});let s={success:!0,message:"Test execution endpoint - not implemented yet",data:{sessionId:r,prompt:n}};t.json(s)}catch(r){i.error("Error in test execute:",r);let n={success:!1,error:r instanceof Error?r.message:"Unknown error"};t.status(500).json(n)}}transformHookToEvent(e){let t,r,n={cwd:e.cwd,hook_event_name:e.hook_event_name,...e.metadata||{}};if(e.type&&e.content!==void 0)t=e.type,r=e.content;else switch(e.hook_event_name){case"SessionStart":t=S.EventType.NOTIFICATION,r="Session started",n.source=e.source;break;case"SessionEnd":t=S.EventType.NOTIFICATION,r=`Session ended: ${e.reason||"unknown"}`,n.reason=e.reason;break;case"UserPromptSubmit":t=S.EventType.USER_PROMPT,r=e.prompt||"";break;case"PostToolUse":t=S.EventType.TOOL_USE,r=JSON.stringify({tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response}),n.tool_name=e.tool_name;break;case"Notification":t=S.EventType.NOTIFICATION,r=e.message||"",n.notification_type=e.notification_type;break;default:t=S.EventType.NOTIFICATION,r=`Hook event: ${e.hook_event_name}`}return{session_id:e.session_id,hook_event_name:e.hook_event_name,type:t,source:S.EventSource.DESKTOP,content:r,metadata:n}}onEvent(e){this.eventHandler=e}async start(e){let t=e||this.sessionId;return t&&(this.sessionId=t),new Promise((r,n)=>{try{let s=(0,me.getConfig)(),o=s.server.dynamicPort?0:s.server.port;this.server=this.app.listen(o,s.server.host,()=>{let a=this.server.address();this.assignedPort=a.port,i.info(`HTTP API listening on http://${s.server.host}:${this.assignedPort}`),this.sessionId&&this.writePortFile(this.sessionId,this.assignedPort),r(this.assignedPort)}),this.server.on("error",a=>{i.error("HTTP server error:",a),n(a)})}catch(s){n(s)}})}writePortFile(e,t){let r=re.join(ie.tmpdir(),`codevibe-claude-${e}.port`);try{j.writeFileSync(r,t.toString()),i.info(`Port file written: ${r} -> ${t}`)}catch(n){i.error(`Failed to write port file: ${r}`,n)}}removePortFile(){if(this.sessionId){let e=re.join(ie.tmpdir(),`codevibe-claude-${this.sessionId}.port`);try{j.existsSync(e)&&(j.unlinkSync(e),i.info(`Port file removed: ${e}`))}catch(t){i.warn(`Failed to remove port file: ${e}`,t)}}}async stop(e){return new Promise((t,r)=>{this.sessionId&&e?.protectedSessionIds?.has(this.sessionId)?i.info("Skipping port file removal \u2014 another daemon still serves this session",{sessionId:this.sessionId}):this.removePortFile(),this.server?this.server.close(n=>{n?(i.error("Error stopping HTTP server:",n),r(n)):(i.info("HTTP API stopped"),t())}):t()})}};var ge=require("child_process"),he=require("@quantiya/codevibe-core");var J=class{async executePrompt(e,t){let r=(0,he.getConfig)(),n=r.claude.defaultTimeout;return i.info("Executing prompt from mobile",{sessionId:e,promptLength:t.length,timeout:n}),new Promise(s=>{let o=["--resume",e,"--print","--output-format","stream-json",t];i.debug("Spawning Claude command",{command:r.claude.command,args:o});let a=(0,ge.spawn)(r.claude.command,o,{stdio:["pipe","pipe","pipe"],shell:!0}),c="",g="",u=!1,h=setTimeout(()=>{u=!0,i.warn("Command execution timed out",{sessionId:e,timeout:n}),a.kill("SIGTERM")},n);a.stdout?.on("data",d=>{let m=d.toString();c+=m,i.debug("Command stdout",{output:m.slice(0,200)})}),a.stderr?.on("data",d=>{let m=d.toString();g+=m,i.debug("Command stderr",{output:m.slice(0,200)})}),a.on("close",d=>{clearTimeout(h);let m={success:d===0&&!u,output:c,error:g,exitCode:d||void 0,timedOut:u};m.success?i.info("Command executed successfully",{sessionId:e,exitCode:d,outputLength:c.length}):i.error("Command execution failed",{sessionId:e,exitCode:d,timedOut:u,error:g.slice(0,500)}),s(m)}),a.on("error",d=>{clearTimeout(h),i.error("Failed to spawn command",{error:d.message}),s({success:!1,error:d.message,timedOut:!1})})})}detectInteractivePrompt(e){return[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/Continue\?/i,/Proceed\?/i].some(r=>r.test(e))}extractPromptText(e){let t=e.split(`
2
- `);for(let r=t.length-1;r>=0;r--){let n=t[r].trim();if(this.detectInteractivePrompt(n))return n}return null}};var fe=require("child_process"),ye=require("util");var se=(0,ye.promisify)(fe.exec),Z=class{async answerInteractivePrompt(e,t,r={}){let{pressEnter:n=!0}=r;i.info("Attempting to answer interactive prompt",{sessionId:e,response:t,pressEnter:n});try{let s=process.env.CODEVIBE_TMUX_SESSION;return i.info("Checking tmux session environment",{tmuxSession:s||"(not set)",allEnvKeys:Object.keys(process.env).filter(o=>o.includes("CODEVIBE")||o.includes("TMUX"))}),s?(i.info("Using tmux send-keys",{tmuxSession:s,pressEnter:n}),await this.sendViaTmux(s,t,n),i.info("Successfully sent response to interactive prompt",{sessionId:e,response:t,pressEnter:n}),!0):(i.error("No tmux session found - codevibe-claude wrapper is required",{sessionId:e,hint:"Start Claude Code using the codevibe-claude wrapper script"}),!1)}catch(s){return i.error("Failed to answer interactive prompt",{sessionId:e,error:s instanceof Error?s.message:String(s)}),!1}}async sendViaTmux(e,t,r){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");i.info("Sending via tmux",{sessionName:e,inputLength:t.length,pressEnter:r});try{let s=`tmux send-keys -t "${e}" -l "${n}"`,o=await se(s);if(i.info("tmux send-keys (text) completed",{stdout:o.stdout||"(empty)",stderr:o.stderr||"(empty)"}),r){await this.delay(500);let a=`tmux send-keys -t "${e}" Enter`,c=await se(a);i.info("tmux send-keys (Enter) completed",{stdout:c.stdout||"(empty)",stderr:c.stderr||"(empty)"})}else i.info("tmux send-keys: skipping Enter (caller requested digit-only)")}catch(s){throw i.error("tmux send-keys failed",{sessionName:e,error:s}),s}}async sendKey(e,t){let r=process.env.CODEVIBE_TMUX_SESSION;if(!r)return i.error("No tmux session found for sendKey",{sessionId:e,keyName:t}),!1;try{let n=`tmux send-keys -t "${r}" ${t}`,s=await se(n);return i.info("tmux send-keys (single key) completed",{sessionId:e,keyName:t,stdout:s.stdout||"(empty)",stderr:s.stderr||"(empty)"}),!0}catch(n){return i.error("tmux send-keys (single key) failed",{sessionId:e,keyName:t,error:n instanceof Error?n.message:String(n)}),!1}}delay(e){return new Promise(t=>setTimeout(t,e))}isPromptResponse(e){let t=e.trim().toLowerCase();return!!(t==="y"||t==="n"||t==="yes"||t==="no"||/^[0-9]+$/.test(t)||/^[a-z]$/.test(t)||["exit","quit","q","continue","skip","abort","retry","cancel"].includes(t))}};var _e=(0,Ee.promisify)(Se.exec),Re="/exit",we="CODEVIBE_TMUX_SESSION";async function Ue(w,e){let t=async(r,n)=>{try{await _e(r)}catch(s){i.warn("tmux send-keys failed during self-terminate",{sessionName:w,label:n,error:String(s)})}};await t(`tmux send-keys -t "${w}" C-c`,"ctrl-c"),await new Promise(r=>setTimeout(r,200)),await t(`tmux send-keys -t "${w}" -l "${e}"`,"quit-text"),await new Promise(r=>setTimeout(r,500)),await t(`tmux send-keys -t "${w}" Enter`,"enter")}var Fe={question:"Ready to submit your answers?",options:[{label:"Submit answers",description:"Send your selections to the assistant"},{label:"Cancel",description:"Discard your answers"}],multiSelect:!1,_isSubmit:!0};function Me(w){let e=w.length,t=e>=2,r=w.slice(1);return t&&r.push({...Fe}),{questionCount:e,hasReviewScreen:t,remainingQueue:r}}var te=class w{constructor(e){this.activeSessions=new Map;this.assignedPort=0;this.sessionKey=null;this.claudeToBackendSessionId=new Map;this.pendingMobilePrompts=new Map;this.nextPromptGen=1;this.httpApi=new z,this.commandExecutor=new J,this.promptResponder=new Z,this.initialSessionId=e}static{this.MOBILE_PROMPT_EXPIRY_MS=3e3}getPort(){return this.assignedPort}generateBackendSessionId(e){return`claude-${e}`}trackMobilePrompt(e,t){this.pendingMobilePrompts.has(e)||this.pendingMobilePrompts.set(e,[]),this.pendingMobilePrompts.get(e).push({prompt:t.trim(),timestamp:Date.now()}),i.debug("Tracking mobile prompt for deduplication",{sessionId:e,promptLength:t.length})}isRecentMobilePrompt(e,t){let r=this.pendingMobilePrompts.get(e);if(!r)return!1;let n=Date.now(),s=t.trim(),o=[],a=!1;for(let c of r)if(!(n-c.timestamp>w.MOBILE_PROMPT_EXPIRY_MS)){if(!a&&c.prompt===s){a=!0,i.debug("Found matching mobile prompt, filtering duplicate",{sessionId:e});continue}o.push(c)}return o.length>0?this.pendingMobilePrompts.set(e,o):this.pendingMobilePrompts.delete(e),a}writePortFile(e){let t=V.join(ee.tmpdir(),`codevibe-claude-${e}.port`);try{D.writeFileSync(t,this.assignedPort.toString()),i.info(`Port file written: ${t} -> ${this.assignedPort}`)}catch(r){i.error(`Failed to write port file: ${t}`,r)}}removePortFile(e){let t=V.join(ee.tmpdir(),`codevibe-claude-${e}.port`);try{D.existsSync(t)&&(D.unlinkSync(t),i.info(`Port file removed: ${t}`))}catch(r){i.warn(`Failed to remove port file: ${t}`,r)}}hasOtherLiveDaemonForSession(e){try{let t=(0,ve.execSync)("ps -eww -o pid= -o args=",{encoding:"utf8",timeout:2e3}),r=process.pid;for(let n of t.split(`
3
- `)){let s=n.trim();if(!s)continue;let o=s.indexOf(" ");if(o<0)continue;let a=parseInt(s.substring(0,o),10);if(isNaN(a)||a===r)continue;let c=s.substring(o+1);if(/node.*codevibe-claude.*server\.js/.test(c)&&c.includes(e))return!0}return!1}catch(t){return i.warn('hasOtherLiveDaemonForSession: ps query failed; falling back to "no other daemon"',{error:String(t)}),!1}}async start(){try{if(i.info("Starting CodeVibe MCP Server...",{environment:(0,p.getEnvironment)()}),this.appSyncClient=new p.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()){i.info("Authenticated with stored OAuth tokens",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,p.registerDeviceEncryptionKey)(this.appSyncClient,i),(0,p.startDeviceKeyWatcher)(this.appSyncClient,i);try{let t=await this.appSyncClient.sweepOrphanSessions({agentType:"CLAUDE"});t>0&&i.info("Orphan sweep: marked stale Claude sessions INACTIVE",{swept:t})}catch(t){i.warn("Orphan sweep failed, continuing startup",{error:t instanceof Error?t.message:String(t)})}}else i.error('Authentication failed. Run "codevibe-claude login" first.'),console.error('Not authenticated. Run "codevibe-claude login" to sign in.'),process.exit(1);this.httpApi.onEvent(this.handleEventFromHook.bind(this)),this.assignedPort=await this.httpApi.start(this.initialSessionId),i.info("MCP Server started successfully",{port:this.assignedPort,host:(0,p.getConfig)().server.host,dynamicPort:(0,p.getConfig)().server.dynamicPort,sessionId:this.initialSessionId,authenticated:this.appSyncClient.isAuthenticated(),userId:this.appSyncClient.getCurrentUserId()})}catch(e){throw i.error("Failed to start MCP Server:",e),e}}async stop(){i.info("Stopping MCP Server...");let e=Array.from(this.activeSessions.keys()),t=new Set;i.info(`Marking ${e.length} active session(s) as INACTIVE...`);for(let r of e){let n=this.activeSessions.get(r);n?.mobileEndWatcher&&(n.mobileEndWatcher.stop(),n.mobileEndWatcher=void 0)}for(let r of e)try{let n=this.activeSessions.get(r);if(n&&this.hasOtherLiveDaemonForSession(n.claudeSessionId)){i.info("Another daemon serves this session \u2014 skipping mark INACTIVE AND port file removal during shutdown",{sessionId:r,claudeSessionId:n.claudeSessionId,myPid:process.pid}),t.add(n.claudeSessionId);continue}await this.appSyncClient.updateSession({sessionId:r,status:p.SessionStatus.INACTIVE}),i.info("Session marked as INACTIVE during shutdown",{sessionId:r}),n&&this.removePortFile(n.claudeSessionId)}catch(n){i.warn("Failed to mark session as INACTIVE during shutdown",{sessionId:r,error:n})}this.appSyncClient.cleanupSubscriptions(),this.activeSessions.clear(),await this.httpApi.stop({protectedSessionIds:t}),i.info("MCP Server stopped")}async handleEventFromHook(e){let{session_id:t,hook_event_name:r,type:n,content:s}=e;i.info("Processing hook event",{sessionId:t,hookEvent:r,type:n});try{r==="SessionStart"?await this.handleSessionStart(e):r==="SessionEnd"&&await this.handleSessionEnd(e);let o=this.claudeToBackendSessionId.get(t)||this.generateBackendSessionId(t);if(r==="UserPromptSubmit"){let h=this.activeSessions.get(o);if(h?.completedAskUserQuestionFingerprints?.size){let d=h.completedAskUserQuestionFingerprints.size;h.completedAskUserQuestionFingerprints.clear(),i.info("Turn boundary \u2014 cleared closed-AskUserQuestion fingerprints",{sessionId:o,clearedCount:d})}}if(n===p.EventType.USER_PROMPT&&e.source===p.EventSource.DESKTOP&&r==="UserPromptSubmit"&&s&&this.isRecentMobilePrompt(o,s)){i.info("Skipping duplicate USER_PROMPT from mobile-originated prompt",{sessionId:o,contentLength:s.length});return}if(n===p.EventType.INTERACTIVE_PROMPT){(typeof e.prompt_id!="string"||e.prompt_id.length===0)&&(e.prompt_id=`synth-${(0,W.randomUUID)()}`,i.info("Synthesized prompt_id for INTERACTIVE_PROMPT (hook omitted it)",{sessionId:o,synthesizedPromptId:e.prompt_id}));let h=this.activeSessions.get(o),d;if(h&&e.metadata?.tool_name==="AskUserQuestion"){if(d=this.computeAskUserQuestionFingerprint(e.metadata.tool_input?.questions),d){let Q=h.activeAskUserQuestionFingerprint===d,v=h.completedAskUserQuestionFingerprints?.has(d)??!1;if(Q||v){i.info("Dropping duplicate INTERACTIVE_PROMPT \u2014 AskUserQuestion already tracked",{sessionId:o,fingerprint:d.slice(0,16),status:Q?"in-flight":"completed",hookEvent:e.hook_event_name,promptId:e.prompt_id});return}}let m=e.metadata.tool_input?.questions,x=Array.isArray(m)&&m.some(Q=>Q?.multiSelect===!0),R=Array.isArray(m)&&(m[0]?.options?.length??0)===0;if(d&&(x||R)){h.completedAskUserQuestionFingerprints||(h.completedAskUserQuestionFingerprints=new Set),h.completedAskUserQuestionFingerprints.add(d);let Q=x?"\u26A0\uFE0F This AskUserQuestion uses multi-select, which can't be answered from mobile. Please answer it on your desktop terminal.":"\u26A0\uFE0F This AskUserQuestion has no explicit options \u2014 please answer on your desktop terminal.";i.info("AUQ degraded at intercept \u2014 emitting notification, skipping walker setup",{sessionId:o,fingerprint:d.slice(0,16),hasMultiSelect:x,isZeroExplicitOption:R,questionCount:Array.isArray(m)?m.length:0}),setImmediate(()=>this.emitDegradedAUQNotification(o,Q));return}}if(h){this.clearPromptState(h),h.waitingForPromptResponse=!0,h.pendingPromptId=e.prompt_id;let m=this.nextPromptGen++;h.promptGenerationToken={promptId:e.prompt_id||"",gen:m},d&&(h.activeAskUserQuestionFingerprint=d),i.info("Interactive prompt detected - will parse options from tmux",{sessionId:o,promptId:e.prompt_id,tokenGen:m,askUserQuestionFingerprint:d?.slice(0,16)})}this.sendInteractivePromptAsync(o,e,s).catch(m=>{i.error("Failed to send interactive prompt with dynamic options",{error:m})});return}let a=s,c=e.metadata,g=!1;i.info("Hook event encryption state",{type:n,sessionId:o,hasSessionKey:!!this.sessionKey,sessionKeyLength:this.sessionKey?.length||0}),this.sessionKey?(a=p.cryptoService.encryptContent(s,this.sessionKey),c&&(c={encrypted:p.cryptoService.encryptMetadata(c,this.sessionKey)}),g=!0,i.info("Event encrypted for hook",{type:n,sessionId:o,isEncrypted:!0})):i.warn("No session key - event will NOT be encrypted",{type:n,sessionId:o});let u=await this.appSyncClient.createEvent({sessionId:o,type:n,source:e.source,content:a,metadata:c,promptId:e.prompt_id,timestamp:(0,p.prepareEventTimestamp)({orderingKey:o}),isEncrypted:g?!0:void 0});if(n===p.EventType.USER_PROMPT&&e.source===p.EventSource.DESKTOP){let h=this.activeSessions.get(o);h?.waitingForPromptResponse&&(this.promoteFingerprintAndClearPromptState(h),i.info("Clearing prompt wait state - new desktop prompt received",{sessionId:o}))}i.debug("Event sent to AppSync successfully")}catch(o){throw i.error("Failed to process hook event:",o),o}}async handleSessionStart(e){let t=e.session_id,r=this.generateBackendSessionId(t),n=e.metadata?.cwd||process.cwd();this.claudeToBackendSessionId.set(t,r),i.info("Session started",{claudeSessionId:t,sessionId:r,cwd:n});let s=Array.from(this.activeSessions.keys()).filter(g=>g!==r);if(s.length>0){i.info(`Marking ${s.length} previous session(s) as INACTIVE`);for(let g of s){let u=this.activeSessions.get(g);u?.mobileEndWatcher&&(u.mobileEndWatcher.stop(),u.mobileEndWatcher=void 0),this.appSyncClient.stopHeartbeat(g),this.appSyncClient.cleanupSubscription(g);try{await this.appSyncClient.updateSession({sessionId:g,status:p.SessionStatus.INACTIVE}),i.info("Previous session marked INACTIVE",{prevId:g,newSessionId:r})}catch(h){i.warn("Failed to mark previous session as INACTIVE",{prevId:g,error:h})}u&&this.removePortFile(u.claudeSessionId),this.activeSessions.delete(g)}}this.writePortFile(t);let o=this.appSyncClient.getCurrentUserId(),a={sessionId:r,claudeSessionId:t,userId:o,projectPath:n,cwd:n,createdAt:new Date,subscriptionActive:!1,waitingForPromptResponse:!1,metadata:e.metadata||{}};this.activeSessions.set(r,a);try{let g=await(0,p.resumeOrCreateSession)({sessionId:r,userId:a.userId,agentType:p.AgentType.CLAUDE,projectPath:n,metadata:e.metadata||{}},this.appSyncClient,i);if(this.sessionKey=g.sessionKey,g.resumed&&!g.sessionKey){let u=await p.keychainManager.getDeviceId();i.error("Device key not found in session encryptedKeys",{sessionId:r,pluginDeviceId:u}),console.error(`
1
+ "use strict";var ke=Object.create;var z=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var Ae=(w,e)=>{for(var t in e)z(w,t,{get:e[t],enumerable:!0})},de=(w,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of be(e))!Te.call(w,n)&&n!==t&&z(w,n,{get:()=>e[n],enumerable:!(r=Ie(e,n))||r.enumerable});return w};var N=(w,e,t)=>(t=w!=null?ke(Ce(w)):{},de(e||!w||!w.__esModule?z(t,"default",{value:w,enumerable:!0}):t,w)),xe=w=>de(z({},"__esModule",{value:!0}),w);var $e={};Ae($e,{McpServer:()=>te,parseInteractivePromptInput:()=>Pe});module.exports=xe($e);var U=N(require("fs")),$=N(require("path")),j=N(require("os")),ve=require("child_process"),Ee=require("util"),Se=require("child_process"),G=require("crypto");var le=N(require("os")),ue=N(require("path")),me=require("@quantiya/codevibe-core"),i=(0,me.createLogger)({name:"codevibe-claude",logFile:ue.default.join(le.default.tmpdir(),"codevibe-claude-mcp.log"),level:"info"});var p=require("@quantiya/codevibe-core");var ne=N(require("express")),B=N(require("fs")),re=N(require("path")),ie=N(require("os")),ge=require("@quantiya/codevibe-core");var S=require("@quantiya/codevibe-core");var J=class{constructor(){this.assignedPort=0;this.app=(0,ne.default)(),this.setupMiddleware(),this.setupRoutes()}setSessionId(e){this.sessionId=e}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(ne.default.json({limit:"1mb"})),this.app.use((e,t,r)=>{i.debug(`${e.method} ${e.path}`,{body:e.body,query:e.query}),r()}),this.app.use((e,t,r,n)=>{i.error("Express error:",e);let s={success:!1,error:e.message||"Internal server error"};r.status(500).json(s)})}setupRoutes(){this.app.get("/health",this.handleHealth.bind(this)),this.app.post("/event",this.handleEvent.bind(this)),process.env.NODE_ENV!=="production"&&this.app.post("/test/execute",this.handleTestExecute.bind(this))}handleHealth(e,t){let r={success:!0,data:{status:"healthy",uptime:process.uptime(),version:"0.1.0",timestamp:new Date().toISOString()}};t.json(r)}async handleEvent(e,t){try{let r=e.body;if(!r.session_id){let o={success:!1,error:"Missing required field: session_id"};t.status(400).json(o);return}if(!r.hook_event_name){let o={success:!1,error:"Missing required field: hook_event_name"};t.status(400).json(o);return}let n=this.transformHookToEvent(r);i.info("Received event from hook",{sessionId:r.session_id,hookEvent:r.hook_event_name,type:n.type}),this.eventHandler?await this.eventHandler(n):i.warn("No event handler registered");let s={success:!0,message:"Event processed successfully"};t.json(s)}catch(r){i.error("Error handling event:",r);let n={success:!1,error:r instanceof Error?r.message:"Unknown error"};t.status(500).json(n)}}async handleTestExecute(e,t){try{let{sessionId:r,prompt:n}=e.body;if(!r||!n){let o={success:!1,error:"Missing required fields: sessionId, prompt"};t.status(400).json(o);return}i.info("Test execute request",{sessionId:r,prompt:n});let s={success:!0,message:"Test execution endpoint - not implemented yet",data:{sessionId:r,prompt:n}};t.json(s)}catch(r){i.error("Error in test execute:",r);let n={success:!1,error:r instanceof Error?r.message:"Unknown error"};t.status(500).json(n)}}transformHookToEvent(e){let t,r,n={cwd:e.cwd,hook_event_name:e.hook_event_name,...e.metadata||{}};if(e.type&&e.content!==void 0)t=e.type,r=e.content;else switch(e.hook_event_name){case"SessionStart":t=S.EventType.NOTIFICATION,r="Session started",n.source=e.source;break;case"SessionEnd":t=S.EventType.NOTIFICATION,r=`Session ended: ${e.reason||"unknown"}`,n.reason=e.reason;break;case"UserPromptSubmit":t=S.EventType.USER_PROMPT,r=e.prompt||"";break;case"PostToolUse":t=S.EventType.TOOL_USE,r=JSON.stringify({tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response}),n.tool_name=e.tool_name;break;case"Notification":t=S.EventType.NOTIFICATION,r=e.message||"",n.notification_type=e.notification_type;break;default:t=S.EventType.NOTIFICATION,r=`Hook event: ${e.hook_event_name}`}return{session_id:e.session_id,hook_event_name:e.hook_event_name,type:t,source:S.EventSource.DESKTOP,content:r,metadata:n}}onEvent(e){this.eventHandler=e}async start(e){let t=e||this.sessionId;return t&&(this.sessionId=t),new Promise((r,n)=>{try{let s=(0,ge.getConfig)(),o=s.server.dynamicPort?0:s.server.port;this.server=this.app.listen(o,s.server.host,()=>{let a=this.server.address();this.assignedPort=a.port,i.info(`HTTP API listening on http://${s.server.host}:${this.assignedPort}`),this.sessionId&&this.writePortFile(this.sessionId,this.assignedPort),r(this.assignedPort)}),this.server.on("error",a=>{i.error("HTTP server error:",a),n(a)})}catch(s){n(s)}})}writePortFile(e,t){let r=re.join(ie.tmpdir(),`codevibe-claude-${e}.port`);try{B.writeFileSync(r,t.toString()),i.info(`Port file written: ${r} -> ${t}`)}catch(n){i.error(`Failed to write port file: ${r}`,n)}}removePortFile(){if(this.sessionId){let e=re.join(ie.tmpdir(),`codevibe-claude-${this.sessionId}.port`);try{B.existsSync(e)&&(B.unlinkSync(e),i.info(`Port file removed: ${e}`))}catch(t){i.warn(`Failed to remove port file: ${e}`,t)}}}async stop(e){return new Promise((t,r)=>{this.sessionId&&e?.protectedSessionIds?.has(this.sessionId)?i.info("Skipping port file removal \u2014 another daemon still serves this session",{sessionId:this.sessionId}):this.removePortFile(),this.server?this.server.close(n=>{n?(i.error("Error stopping HTTP server:",n),r(n)):(i.info("HTTP API stopped"),t())}):t()})}};var he=require("child_process"),fe=require("@quantiya/codevibe-core");var Z=class{async executePrompt(e,t){let r=(0,fe.getConfig)(),n=r.claude.defaultTimeout;return i.info("Executing prompt from mobile",{sessionId:e,promptLength:t.length,timeout:n}),new Promise(s=>{let o=["--resume",e,"--print","--output-format","stream-json",t];i.debug("Spawning Claude command",{command:r.claude.command,args:o});let a=(0,he.spawn)(r.claude.command,o,{stdio:["pipe","pipe","pipe"],shell:!0}),c="",g="",u=!1,h=setTimeout(()=>{u=!0,i.warn("Command execution timed out",{sessionId:e,timeout:n}),a.kill("SIGTERM")},n);a.stdout?.on("data",d=>{let m=d.toString();c+=m,i.debug("Command stdout",{output:m.slice(0,200)})}),a.stderr?.on("data",d=>{let m=d.toString();g+=m,i.debug("Command stderr",{output:m.slice(0,200)})}),a.on("close",d=>{clearTimeout(h);let m={success:d===0&&!u,output:c,error:g,exitCode:d||void 0,timedOut:u};m.success?i.info("Command executed successfully",{sessionId:e,exitCode:d,outputLength:c.length}):i.error("Command execution failed",{sessionId:e,exitCode:d,timedOut:u,error:g.slice(0,500)}),s(m)}),a.on("error",d=>{clearTimeout(h),i.error("Failed to spawn command",{error:d.message}),s({success:!1,error:d.message,timedOut:!1})})})}detectInteractivePrompt(e){return[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/Continue\?/i,/Proceed\?/i].some(r=>r.test(e))}extractPromptText(e){let t=e.split(`
2
+ `);for(let r=t.length-1;r>=0;r--){let n=t[r].trim();if(this.detectInteractivePrompt(n))return n}return null}};var ye=require("child_process"),we=require("util");var se=(0,we.promisify)(ye.exec),ee=class{async answerInteractivePrompt(e,t,r={}){let{pressEnter:n=!0}=r;i.info("Attempting to answer interactive prompt",{sessionId:e,response:t,pressEnter:n});try{let s=process.env.CODEVIBE_TMUX_SESSION;return i.info("Checking tmux session environment",{tmuxSession:s||"(not set)",allEnvKeys:Object.keys(process.env).filter(o=>o.includes("CODEVIBE")||o.includes("TMUX"))}),s?(i.info("Using tmux send-keys",{tmuxSession:s,pressEnter:n}),await this.sendViaTmux(s,t,n),i.info("Successfully sent response to interactive prompt",{sessionId:e,response:t,pressEnter:n}),!0):(i.error("No tmux session found - codevibe-claude wrapper is required",{sessionId:e,hint:"Start Claude Code using the codevibe-claude wrapper script"}),!1)}catch(s){return i.error("Failed to answer interactive prompt",{sessionId:e,error:s instanceof Error?s.message:String(s)}),!1}}async sendViaTmux(e,t,r){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");i.info("Sending via tmux",{sessionName:e,inputLength:t.length,pressEnter:r});try{let s=`tmux send-keys -t "${e}" -l "${n}"`,o=await se(s);if(i.info("tmux send-keys (text) completed",{stdout:o.stdout||"(empty)",stderr:o.stderr||"(empty)"}),r){await this.delay(500);let a=`tmux send-keys -t "${e}" Enter`,c=await se(a);i.info("tmux send-keys (Enter) completed",{stdout:c.stdout||"(empty)",stderr:c.stderr||"(empty)"})}else i.info("tmux send-keys: skipping Enter (caller requested digit-only)")}catch(s){throw i.error("tmux send-keys failed",{sessionName:e,error:s}),s}}async sendKey(e,t){let r=process.env.CODEVIBE_TMUX_SESSION;if(!r)return i.error("No tmux session found for sendKey",{sessionId:e,keyName:t}),!1;try{let n=`tmux send-keys -t "${r}" ${t}`,s=await se(n);return i.info("tmux send-keys (single key) completed",{sessionId:e,keyName:t,stdout:s.stdout||"(empty)",stderr:s.stderr||"(empty)"}),!0}catch(n){return i.error("tmux send-keys (single key) failed",{sessionId:e,keyName:t,error:n instanceof Error?n.message:String(n)}),!1}}delay(e){return new Promise(t=>setTimeout(t,e))}isPromptResponse(e){let t=e.trim().toLowerCase();return!!(t==="y"||t==="n"||t==="yes"||t==="no"||/^[0-9]+$/.test(t)||/^[a-z]$/.test(t)||["exit","quit","q","continue","skip","abort","retry","cancel"].includes(t))}};var _e=(0,Ee.promisify)(Se.exec),Re="/exit",oe="CODEVIBE_TMUX_SESSION",Fe=1800*1e3,Ue=60*1e3,Me=1440*60*1e3;async function Qe(w,e){let t=async(r,n)=>{try{await _e(r)}catch(s){i.warn("tmux send-keys failed during self-terminate",{sessionName:w,label:n,error:String(s)})}};await t(`tmux send-keys -t "${w}" C-c`,"ctrl-c"),await new Promise(r=>setTimeout(r,200)),await t(`tmux send-keys -t "${w}" -l "${e}"`,"quit-text"),await new Promise(r=>setTimeout(r,500)),await t(`tmux send-keys -t "${w}" Enter`,"enter")}var Oe={question:"Ready to submit your answers?",options:[{label:"Submit answers",description:"Send your selections to the assistant"},{label:"Cancel",description:"Discard your answers"}],multiSelect:!1,_isSubmit:!0};function Ne(w){let e=w.length,t=e>=2,r=w.slice(1);return t&&r.push({...Oe}),{questionCount:e,hasReviewScreen:t,remainingQueue:r}}var te=class w{constructor(e){this.activeSessions=new Map;this.assignedPort=0;this.portRefreshTimer=null;this.sessionKey=null;this.claudeToBackendSessionId=new Map;this.pendingMobilePrompts=new Map;this.nextPromptGen=1;this.httpApi=new J,this.commandExecutor=new Z,this.promptResponder=new ee,this.initialSessionId=e}static{this.MOBILE_PROMPT_EXPIRY_MS=3e3}getPort(){return this.assignedPort}generateBackendSessionId(e){return`claude-${e}`}trackMobilePrompt(e,t){this.pendingMobilePrompts.has(e)||this.pendingMobilePrompts.set(e,[]),this.pendingMobilePrompts.get(e).push({prompt:t.trim(),timestamp:Date.now()}),i.debug("Tracking mobile prompt for deduplication",{sessionId:e,promptLength:t.length})}isRecentMobilePrompt(e,t){let r=this.pendingMobilePrompts.get(e);if(!r)return!1;let n=Date.now(),s=t.trim(),o=[],a=!1;for(let c of r)if(!(n-c.timestamp>w.MOBILE_PROMPT_EXPIRY_MS)){if(!a&&c.prompt===s){a=!0,i.debug("Found matching mobile prompt, filtering duplicate",{sessionId:e});continue}o.push(c)}return o.length>0?this.pendingMobilePrompts.set(e,o):this.pendingMobilePrompts.delete(e),a}writePortFile(e){let t=$.join(j.tmpdir(),`codevibe-claude-${e}.port`);try{U.writeFileSync(t,this.assignedPort.toString()),i.info(`Port file written: ${t} -> ${this.assignedPort}`)}catch(r){i.error(`Failed to write port file: ${t}`,r)}}removePortFile(e){let t=$.join(j.tmpdir(),`codevibe-claude-${e}.port`);try{U.existsSync(t)&&(U.unlinkSync(t),i.info(`Port file removed: ${t}`))}catch(r){i.warn(`Failed to remove port file: ${t}`,r)}}hasOtherLiveDaemonForSession(e){try{let t=(0,ve.execSync)("ps -eww -o pid= -o args=",{encoding:"utf8",timeout:2e3}),r=process.pid;for(let n of t.split(`
3
+ `)){let s=n.trim();if(!s)continue;let o=s.indexOf(" ");if(o<0)continue;let a=parseInt(s.substring(0,o),10);if(isNaN(a)||a===r)continue;let c=s.substring(o+1);if(/node.*codevibe-claude.*server\.js/.test(c)&&c.includes(e))return!0}return!1}catch(t){return i.warn('hasOtherLiveDaemonForSession: ps query failed; falling back to "no other daemon"',{error:String(t)}),!1}}async start(){try{if(i.info("Starting CodeVibe MCP Server...",{environment:(0,p.getEnvironment)()}),this.appSyncClient=new p.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()){i.info("Authenticated with stored OAuth tokens",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,p.registerDeviceEncryptionKey)(this.appSyncClient,i),(0,p.startDeviceKeyWatcher)(this.appSyncClient,i);try{let t=await this.appSyncClient.sweepOrphanSessions({agentType:"CLAUDE"});t>0&&i.info("Orphan sweep: marked stale Claude sessions INACTIVE",{swept:t})}catch(t){i.warn("Orphan sweep failed, continuing startup",{error:t instanceof Error?t.message:String(t)})}}else i.error('Authentication failed. Run "codevibe-claude login" first.'),console.error('Not authenticated. Run "codevibe-claude login" to sign in.'),process.exit(1);this.httpApi.onEvent(this.handleEventFromHook.bind(this)),this.assignedPort=await this.httpApi.start(this.initialSessionId),this.startPortKeepalive(),i.info("MCP Server started successfully",{port:this.assignedPort,host:(0,p.getConfig)().server.host,dynamicPort:(0,p.getConfig)().server.dynamicPort,sessionId:this.initialSessionId,authenticated:this.appSyncClient.isAuthenticated(),userId:this.appSyncClient.getCurrentUserId()})}catch(e){throw i.error("Failed to start MCP Server:",e),e}}startPortKeepalive(){this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null);let e=Number(process.env.CODEVIBE_PORTFILE_REFRESH_MS),t=Number.isFinite(e)&&e>0?Math.min(Me,Math.max(Ue,e)):Fe;this.portRefreshTimer=setInterval(()=>this.refreshPortFiles(),t)}refreshPortFiles(){let e=new Date;for(let r of this.activeSessions.values()){let n=$.join(j.tmpdir(),`codevibe-claude-${r.claudeSessionId}.port`);try{U.utimesSync(n,e,e)}catch(o){o?.code==="ENOENT"?this.writePortFile(r.claudeSessionId):i.warn(`Port-file refresh failed: ${n}`,o)}let s=$.join(j.tmpdir(),`codevibe-claude-${r.claudeSessionId}.pid`);try{U.utimesSync(s,e,e)}catch(o){o?.code!=="ENOENT"&&i.warn(`Pid-file refresh failed: ${s}`,o)}}let t=process.env[oe];if(t){let r=$.join(j.tmpdir(),`codevibe-claude-instance-${t}.json`);try{U.utimesSync(r,e,e)}catch(n){n?.code!=="ENOENT"&&i.warn(`Instance-map refresh failed: ${r}`,n)}}}async stop(){i.info("Stopping MCP Server..."),this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null);let e=Array.from(this.activeSessions.keys()),t=new Set;i.info(`Marking ${e.length} active session(s) as INACTIVE...`);for(let r of e){let n=this.activeSessions.get(r);n?.mobileEndWatcher&&(n.mobileEndWatcher.stop(),n.mobileEndWatcher=void 0)}for(let r of e){let n=this.activeSessions.get(r);try{if(n&&this.hasOtherLiveDaemonForSession(n.claudeSessionId)){i.info("Another daemon serves this session \u2014 skipping mark INACTIVE AND port file removal during shutdown",{sessionId:r,claudeSessionId:n.claudeSessionId,myPid:process.pid}),t.add(n.claudeSessionId);continue}try{await this.appSyncClient.updateSession({sessionId:r,status:p.SessionStatus.INACTIVE}),i.info("Session marked as INACTIVE during shutdown",{sessionId:r})}catch(s){i.warn("Failed to mark session as INACTIVE during shutdown",{sessionId:r,error:s})}n&&this.removePortFile(n.claudeSessionId)}catch(s){i.warn("Failed during shutdown cleanup",{sessionId:r,error:s})}}this.appSyncClient.cleanupSubscriptions(),this.activeSessions.clear(),await this.httpApi.stop({protectedSessionIds:t}),i.info("MCP Server stopped")}async handleEventFromHook(e){let{session_id:t,hook_event_name:r,type:n,content:s}=e;i.info("Processing hook event",{sessionId:t,hookEvent:r,type:n});try{r==="SessionStart"?await this.handleSessionStart(e):r==="SessionEnd"&&await this.handleSessionEnd(e);let o=this.claudeToBackendSessionId.get(t)||this.generateBackendSessionId(t);if(r==="UserPromptSubmit"){let h=this.activeSessions.get(o);if(h?.completedAskUserQuestionFingerprints?.size){let d=h.completedAskUserQuestionFingerprints.size;h.completedAskUserQuestionFingerprints.clear(),i.info("Turn boundary \u2014 cleared closed-AskUserQuestion fingerprints",{sessionId:o,clearedCount:d})}}if(n===p.EventType.USER_PROMPT&&e.source===p.EventSource.DESKTOP&&r==="UserPromptSubmit"&&s&&this.isRecentMobilePrompt(o,s)){i.info("Skipping duplicate USER_PROMPT from mobile-originated prompt",{sessionId:o,contentLength:s.length});return}if(n===p.EventType.INTERACTIVE_PROMPT){(typeof e.prompt_id!="string"||e.prompt_id.length===0)&&(e.prompt_id=`synth-${(0,G.randomUUID)()}`,i.info("Synthesized prompt_id for INTERACTIVE_PROMPT (hook omitted it)",{sessionId:o,synthesizedPromptId:e.prompt_id}));let h=this.activeSessions.get(o),d;if(h&&e.metadata?.tool_name==="AskUserQuestion"){if(d=this.computeAskUserQuestionFingerprint(e.metadata.tool_input?.questions),d){let O=h.activeAskUserQuestionFingerprint===d,v=h.completedAskUserQuestionFingerprints?.has(d)??!1;if(O||v){i.info("Dropping duplicate INTERACTIVE_PROMPT \u2014 AskUserQuestion already tracked",{sessionId:o,fingerprint:d.slice(0,16),status:O?"in-flight":"completed",hookEvent:e.hook_event_name,promptId:e.prompt_id});return}}let m=e.metadata.tool_input?.questions,x=Array.isArray(m)&&m.some(O=>O?.multiSelect===!0),R=Array.isArray(m)&&(m[0]?.options?.length??0)===0;if(d&&(x||R)){h.completedAskUserQuestionFingerprints||(h.completedAskUserQuestionFingerprints=new Set),h.completedAskUserQuestionFingerprints.add(d);let O=x?"\u26A0\uFE0F This AskUserQuestion uses multi-select, which can't be answered from mobile. Please answer it on your desktop terminal.":"\u26A0\uFE0F This AskUserQuestion has no explicit options \u2014 please answer on your desktop terminal.";i.info("AUQ degraded at intercept \u2014 emitting notification, skipping walker setup",{sessionId:o,fingerprint:d.slice(0,16),hasMultiSelect:x,isZeroExplicitOption:R,questionCount:Array.isArray(m)?m.length:0}),setImmediate(()=>this.emitDegradedAUQNotification(o,O));return}}if(h){this.clearPromptState(h),h.waitingForPromptResponse=!0,h.pendingPromptId=e.prompt_id;let m=this.nextPromptGen++;h.promptGenerationToken={promptId:e.prompt_id||"",gen:m},d&&(h.activeAskUserQuestionFingerprint=d),i.info("Interactive prompt detected - will parse options from tmux",{sessionId:o,promptId:e.prompt_id,tokenGen:m,askUserQuestionFingerprint:d?.slice(0,16)})}this.sendInteractivePromptAsync(o,e,s).catch(m=>{i.error("Failed to send interactive prompt with dynamic options",{error:m})});return}let a=s,c=e.metadata,g=!1;i.info("Hook event encryption state",{type:n,sessionId:o,hasSessionKey:!!this.sessionKey,sessionKeyLength:this.sessionKey?.length||0}),this.sessionKey?(a=p.cryptoService.encryptContent(s,this.sessionKey),c&&(c={encrypted:p.cryptoService.encryptMetadata(c,this.sessionKey)}),g=!0,i.info("Event encrypted for hook",{type:n,sessionId:o,isEncrypted:!0})):i.warn("No session key - event will NOT be encrypted",{type:n,sessionId:o});let u=await this.appSyncClient.createEvent({sessionId:o,type:n,source:e.source,content:a,metadata:c,promptId:e.prompt_id,timestamp:(0,p.prepareEventTimestamp)({orderingKey:o}),isEncrypted:g?!0:void 0});if(n===p.EventType.USER_PROMPT&&e.source===p.EventSource.DESKTOP){let h=this.activeSessions.get(o);h?.waitingForPromptResponse&&(this.promoteFingerprintAndClearPromptState(h),i.info("Clearing prompt wait state - new desktop prompt received",{sessionId:o}))}i.debug("Event sent to AppSync successfully")}catch(o){throw i.error("Failed to process hook event:",o),o}}async handleSessionStart(e){let t=e.session_id,r=this.generateBackendSessionId(t),n=e.metadata?.cwd||process.cwd();this.claudeToBackendSessionId.set(t,r),i.info("Session started",{claudeSessionId:t,sessionId:r,cwd:n});let s=Array.from(this.activeSessions.keys()).filter(g=>g!==r);if(s.length>0){i.info(`Marking ${s.length} previous session(s) as INACTIVE`);for(let g of s){let u=this.activeSessions.get(g);u?.mobileEndWatcher&&(u.mobileEndWatcher.stop(),u.mobileEndWatcher=void 0),this.appSyncClient.stopHeartbeat(g),this.appSyncClient.cleanupSubscription(g);try{await this.appSyncClient.updateSession({sessionId:g,status:p.SessionStatus.INACTIVE}),i.info("Previous session marked INACTIVE",{prevId:g,newSessionId:r})}catch(h){i.warn("Failed to mark previous session as INACTIVE",{prevId:g,error:h})}u&&this.removePortFile(u.claudeSessionId),this.activeSessions.delete(g)}}this.writePortFile(t);let o=this.appSyncClient.getCurrentUserId(),a={sessionId:r,claudeSessionId:t,userId:o,projectPath:n,cwd:n,createdAt:new Date,subscriptionActive:!1,waitingForPromptResponse:!1,metadata:e.metadata||{}};this.activeSessions.set(r,a);try{let g=await(0,p.resumeOrCreateSession)({sessionId:r,userId:a.userId,agentType:p.AgentType.CLAUDE,projectPath:n,metadata:e.metadata||{}},this.appSyncClient,i);if(this.sessionKey=g.sessionKey,g.resumed&&!g.sessionKey){let u=await p.keychainManager.getDeviceId();i.error("Device key not found in session encryptedKeys",{sessionId:r,pluginDeviceId:u}),console.error(`
4
4
  \u26A0\uFE0F E2E ENCRYPTION WARNING: Cannot decrypt this session!`),console.error(` Your device ID (${u.substring(0,8)}...) is not in session's encryption keys.`),console.error(" This happens if your device key was regenerated after the session was created."),console.error(` SOLUTION: Start a new Claude Code session instead of resuming this one.
5
- `)}}catch(g){if(this.isSessionLimitExceeded(g)){this.displaySubscriptionLimitError(g,"session"),this.activeSessions.delete(r),this.removePortFile(t);return}i.error("Failed to create/resume session:",g)}this.subscribeToMobileEvents(r),this.appSyncClient.startHeartbeat(r);let c=this.activeSessions.get(r);c&&(c.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(r,async()=>{i.info("Mobile ended session \u2014 sending desktop quit",{sessionId:r});let g=process.env[we];if(!g){i.warn("No tmux session set; skipping desktop self-terminate",{sessionId:r,expectedEnv:we});return}await Ue(g,Re)}))}async handleSessionEnd(e){let t=e.session_id,r=this.claudeToBackendSessionId.get(t)||this.generateBackendSessionId(t);i.info("Session ended",{claudeSessionId:t,sessionId:r,reason:e.metadata?.reason});let n=this.activeSessions.get(r);if(n?.mobileEndWatcher&&(n.mobileEndWatcher.stop(),n.mobileEndWatcher=void 0),this.removePortFile(t),n?.waitingForPromptResponse&&(i.info("Clearing prompt wait state - session ending",{sessionId:r}),this.clearPromptState(n)),this.appSyncClient.stopHeartbeat(r),this.appSyncClient.cleanupSubscription(r),n)try{await this.appSyncClient.updateSession({sessionId:r,status:p.SessionStatus.INACTIVE}),i.info("Session marked as INACTIVE in AppSync",{sessionId:r})}catch(s){i.warn("Failed to update session in AppSync:",s)}else i.warn("Cannot update session - session state not found",{sessionId:r});this.activeSessions.delete(r),this.claudeToBackendSessionId.delete(t),i.debug("Session cleanup completed",{sessionId:r})}subscribeToMobileEvents(e){i.info("Subscribing to mobile events",{sessionId:e});let t=this.activeSessions.get(e);if(!t){i.error("Session not found",{sessionId:e});return}this.appSyncClient.subscribeToEvents(e,async r=>{await this.dispatchMobileEvent(e,r)},r=>{i.error("Subscription error",{sessionId:e,error:r})}),t.subscriptionActive=!0,i.info("Subscription active",{sessionId:e})}async dispatchMobileEvent(e,t){i.info("Received mobile event",{eventId:t.eventId,type:t.type,sessionId:t.sessionId,isEncrypted:t.isEncrypted});let r,n,s=!1,o,a,c;if(t.type===p.EventType.USER_PROMPT||t.type===p.EventType.PROMPT_RESPONSE)if(n=this.activeSessions.get(e),!n)r="no-session";else if(n.processedEventIds?.has(t.eventId))r="skip-dedup";else if(n.inFlightEventIds?.has(t.eventId))r="drop-event-redeliver";else if(n.waitingForPromptResponse){let d=n.promptGenerationToken;if(!d)r="regular";else if(t.type===p.EventType.USER_PROMPT&&n.hasReceivedPromptResponse&&(!t.promptId||t.promptId.length===0))r="drop-stale-answer";else if(t.promptId&&t.promptId.length>0&&d.promptId.length>0&&t.promptId!==d.promptId)r="drop-stale-answer";else{let m=d.promptId.length>0?d.promptId:`__prompt_gen_${d.gen}`;n.inFlightPromptIds?.has(m)?r="drop-in-flight":(n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightEventIds||(n.inFlightEventIds=new Set),n.inFlightPromptIds.add(m),n.inFlightEventIds.add(t.eventId),s=!0,a=m,c=t.eventId,o={promptId:d.promptId,gen:d.gen},r="walker")}}else r="regular";else r="not-user-prompt";let u=t.content||"";if(t.isEncrypted&&this.sessionKey)try{u=p.cryptoService.decryptContent(t.content,this.sessionKey),i.debug("Event decrypted successfully",{eventId:t.eventId})}catch(d){i.error("Failed to decrypt event:",{eventId:t.eventId,error:d}),u=t.content}let h={...t,content:u};if(r!=="skip-dedup")try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:p.DeliveryStatus.DELIVERED}),i.info("Event marked as DELIVERED",{eventId:t.eventId})}catch(d){i.warn("Failed to mark event as DELIVERED",{eventId:t.eventId,error:d})}if(r==="skip-dedup"){i.info("[walker] Subscription-level dedup hit (already processed) \u2014 skipping",{sessionId:e,eventId:t.eventId});return}if(r==="drop-stale-answer"){i.info("[walker] Stale answer dropped \u2014 event.promptId does not match current pending promptId",{sessionId:e,eventId:t.eventId,eventPromptId:t.promptId,currentPromptId:n?.promptGenerationToken?.promptId}),n&&(n.processedEventIds||(n.processedEventIds=new Set),n.processedEventIds.add(t.eventId));try{await this.markEventExecuted(t)}catch(d){i.warn("[walker] markEventExecuted threw on stale-answer drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}if(r==="drop-in-flight"){i.warn("[walker] Subscription-level in-flight guard \u2014 dropping duplicate USER_PROMPT (different eventId, same prompt)",{sessionId:e,eventId:t.eventId}),n&&(n.processedEventIds||(n.processedEventIds=new Set),n.processedEventIds.add(t.eventId));try{await this.markEventExecuted(t)}catch(d){i.warn("[walker] markEventExecuted threw on subscription-level duplicate drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}if(r==="drop-event-redeliver"){i.info("[walker] Subscription-level event-level redelivery \u2014 silent skip (original still in flight)",{sessionId:e,eventId:t.eventId});return}if(r==="walker"){t.type===p.EventType.PROMPT_RESPONSE&&n&&(n.hasReceivedPromptResponse=!0),await this.handleMobilePromptResponse(e,t,u,n,s,o,a,c);return}if(r==="regular"){if(t.type===p.EventType.PROMPT_RESPONSE){i.warn("Received PROMPT_RESPONSE with no active walker \u2014 dropping",{sessionId:e,eventId:t.eventId,promptId:t.promptId}),n&&(n.processedEventIds||(n.processedEventIds=new Set),n.processedEventIds.add(t.eventId));try{await this.markEventExecuted(t)}catch(d){i.warn("markEventExecuted threw on PROMPT_RESPONSE orphan drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}await this.executeMobilePrompt(e,h);return}if(r==="no-session"){i.warn("Received mobile prompt input for unknown session \u2014 ignoring",{sessionId:e,eventId:t.eventId,type:t.type});return}}async handleMobilePromptResponse(e,t,r,n,s=!1,o,a,c){let g=o??n.promptGenerationToken,u=a,h=c;if(!s&&g){let d=g.promptId.length>0?g.promptId:`__prompt_gen_${g.gen}`;if(n.inFlightPromptIds?.has(d)){i.warn("[walker] Duplicate mobile USER_PROMPT for same prompt \u2014 dropping",{sessionId:e,eventId:t.eventId,lockKey:d}),await this.markEventExecutedIdempotent(n,t);return}n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightEventIds||(n.inFlightEventIds=new Set),n.inFlightPromptIds.add(d),n.inFlightEventIds.add(t.eventId),u=d,h=t.eventId}try{if(!s&&n.processedEventIds?.has(t.eventId)){i.info("[walker] Redelivered event already processed \u2014 skipping",{sessionId:e,eventId:t.eventId});return}let d=r.trim(),m=n.pendingPromptId,R=n.pendingSubmitMap,Q=R?Object.keys(R).length:3,v=this.parseInteractivePromptInput(d,Q);i.info("Parsed interactive prompt input",{sessionId:e,content:d,parsed:v,hasSubmitMap:!!R});let l=()=>{let T=n.promptGenerationToken,I=T?.gen,E=g?.gen;return I!==E?(i.warn("[walker] Token mismatch \u2014 external cleanup or new prompt during in-flight handler \u2014 aborting",{sessionId:e,eventId:t.eventId,entryToken:g,currentToken:T}),!0):!1};if(l()){await this.markEventExecutedIdempotent(n,t);return}{let T=n.pendingQuestionsQueue!==void 0,I=d.trim(),E=I.match(/^(\d+)$/);if(T&&n.pendingCurrentQuestion&&E){let y=n.pendingCurrentQuestion.options?.length??0,P=E[1],f=parseInt(P,10),U=!Number.isFinite(f)||f<1||f>y,k=String(f)!==P;if(U||k){let _=this.getWalkerPosition(n);if(i.info("AUQ walker \u2014 bare out-of-range or non-canonical option; routing per dispatch matrix",{sessionId:e,option:P,optionNum:f,realOptionCount:y,isOutOfRange:U,isNonCanonical:k,walkerPosition:_,parsedAction:v.action}),await this.markEventExecutedIdempotent(n,t),l())return;if(_==="on_synth"){let $=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!1});if(l())return;if(!$){try{await this.emitUserChoice(e,"AskUserQuestion cancel keypress failed (tmux unavailable); your reply was not sent")}catch(A){i.warn("emitUserChoice on on-SYNTH Cancel failed",{sessionId:e,error:A instanceof Error?A.message:String(A)})}return}if(await new Promise(A=>setTimeout(A,1500)),l())return;let F=await this.promptResponder.answerInteractivePrompt(e,I,{pressEnter:!0});if(l())return;F||i.warn("on-SYNTH Cancel followup text-send failed; AUQ cancelled, no new prompt",{sessionId:e});try{await this.emitUserChoice(e,"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt")}catch(A){i.warn("emitUserChoice on on-SYNTH Cancel success failed",{sessionId:e,error:A instanceof Error?A.message:String(A)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}await this.handleMobileReplyAsDismissAndPrompt(e,n,I,l);return}}}if(v.action==="select_option"){let T=R?.[v.option]||v.option,I=n.pendingQuestionsQueue!==void 0;i.info("User selected option",{option:v.option,terminalInput:T,isV2AskUserQuestion:I});let E=await this.promptResponder.answerInteractivePrompt(e,T,{pressEnter:!I});if(l()){await this.markEventExecutedIdempotent(n,t);return}if(E){if(await this.markEventExecutedIdempotent(n,t),l())return;if(!m){i.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"select_option",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}let y=(n.pendingQuestionsQueue?.length??0)===0;try{if(I){let M=parseInt(v.option,10)-1,L=n.pendingCurrentQuestion?.options?.[M],q=typeof L=="string"?L:L&&typeof L=="object"?L.label:`option ${v.option}`,ae=n.pendingCurrentQuestion?._isSubmit===!0,pe=q.toLowerCase(),Y;ae&&pe==="cancel"?Y="\u2192 Cancel \u2014 AskUserQuestion cancelled, no answers submitted":ae&&pe.startsWith("submit")?Y="\u2192 Submit answers \u2014 AskUserQuestion completed":Y=`\u2192 ${q}`,await this.emitUserChoice(e,Y)}else await this.emitAnswerAck(e,`Selected option ${v.option}`,{promptId:m,questionIndex:0,isTerminal:y})}catch(M){i.warn("[walker] user-choice/ack emit failed \u2014 continuing to STEP 7/8",{sessionId:e,promptId:m,isV2AskUserQuestion:I,error:M instanceof Error?M.message:String(M)})}if(l())return;let P=n.pendingQuestionsQueue?.shift();if(P&&(n.pendingCurrentQuestion=P),!P){n.activeAskUserQuestionFingerprint&&(n.completedAskUserQuestionFingerprints||(n.completedAskUserQuestionFingerprints=new Set),n.completedAskUserQuestionFingerprints.add(n.activeAskUserQuestionFingerprint),i.info("AskUserQuestion V2 walker complete \u2014 fingerprint marked closed",{sessionId:e,fingerprint:n.activeAskUserQuestionFingerprint.slice(0,16)})),this.clearPromptState(n);return}let f=`synth-${(0,W.randomUUID)()}`;if(!f){this.promoteFingerprintAndClearPromptState(n),i.warn("Q[next] emit aborted: synthesized promptId was empty; promoted fingerprint + cleared prompt state",{sessionId:e,eventId:t.eventId});return}let U=n.pendingSynthTail??[],k=this.buildQuestionWireData(P,U),_=P.question,$={tool_name:"AskUserQuestion",tool_input:{questions:[P]},options:k.options,submitMap:k.submitMap,instructions:k.instructions},F=this.sessionKey,A=_,H=$,B=!1;F&&(A=p.cryptoService.encryptContent(_,F),H={encrypted:p.cryptoService.encryptMetadata($,F)},B=!0);let G=this.nextPromptGen++,K={promptId:f,gen:G};n.pendingPromptId=f,n.pendingSubmitMap=k.submitMap,n.promptGenerationToken=K;let C=K,N=this.activeSessions.get(e)?.promptGenerationToken;if(!N||N.gen!==C.gen||N.promptId!==C.promptId){i.warn("Q[next] emit aborted: token replaced before await dispatch",{sessionId:e,tokenAtAwait:C,currentToken:N});return}let oe=f.length>0?f:`__prompt_gen_${K.gen}`;n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightPromptIds.add(oe);try{try{await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.INTERACTIVE_PROMPT,source:p.EventSource.DESKTOP,content:A,metadata:H,promptId:f,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:B?!0:void 0}),i.info("Q[next] emit succeeded",{sessionId:e,promptId:f,remaining:n.pendingQuestionsQueue?.length??0})}catch(M){let L=this.activeSessions.get(e),q=L?.promptGenerationToken;q&&q.gen===C.gen&&q.promptId===C.promptId?(this.promoteFingerprintAndClearPromptState(L),i.warn("Q[next] emit failed; promoted fingerprint + cleared prompt state. User must answer remaining questions on desktop terminal.",{sessionId:e,promptId:f,error:M instanceof Error?M.message:String(M)})):i.warn("Q[next] emit failed but a NEW prompt replaced our token during await; not clearing state (would wipe new prompt). Q[next..QN] of the original AskUserQuestion are lost; new prompt continues normally.",{sessionId:e,tokenAtAwait:C,currentToken:q,error:M instanceof Error?M.message:String(M)})}}finally{n.inFlightPromptIds.delete(oe)}}else try{await this.sendPromptError(e,"Failed to select option")}catch(y){i.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(y)})}finally{await this.markEventExecutedIdempotent(n,t)}}else if(v.action==="option_with_followup"){if(n.pendingQuestionsQueue!==void 0){let y=this.getWalkerPosition(n),P=n.pendingCurrentQuestion?.options?.length??0,f=v.option?parseInt(v.option,10):NaN,U=Number.isFinite(f)&&f>P,k=v.followUpText??"";if(i.info("AUQ walker \u2014 option_with_followup dispatch",{sessionId:e,option:v.option,optionNum:f,explicitCount:P,isSynthDigit:U,walkerPosition:y,followUpTextLen:k.length}),await this.markEventExecutedIdempotent(n,t),l())return;if(U){if(y==="on_synth"){let C=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!1});if(l())return;if(!C){try{await this.emitUserChoice(e,"AskUserQuestion cancel keypress failed (tmux unavailable); your reply was not sent")}catch(b){i.warn("emitUserChoice on synth-digit on-SYNTH Cancel failed",{sessionId:e,error:b instanceof Error?b.message:String(b)})}return}if(await new Promise(b=>setTimeout(b,1500)),l())return;if(k){let b=await this.promptResponder.answerInteractivePrompt(e,k,{pressEnter:!0});if(l())return;b||i.warn("on-SYNTH Cancel followup text-send failed",{sessionId:e})}try{await this.emitUserChoice(e,"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt")}catch(b){i.warn("emitUserChoice on synth-digit on-SYNTH success failed",{sessionId:e,error:b instanceof Error?b.message:String(b)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}await this.handleMobileReplyAsDismissAndPrompt(e,n,k,l);return}let _=R?.[v.option]||v.option,$=f-1,F=n.pendingCurrentQuestion?.options?.[$],A=typeof F=="string"?F:F&&typeof F=="object"?F.label:`option ${v.option}`;if(y==="q1"){let C=await this.promptResponder.answerInteractivePrompt(e,_,{pressEnter:!1});if(l())return;if(!C){try{await this.sendPromptError(e,"Failed to select option. Your reply (including the follow-up text) was not sent. Please retry.")}catch(b){i.warn("sendPromptError on q1 option_with_followup failed",{sessionId:e,error:b instanceof Error?b.message:String(b)})}return}if(await new Promise(b=>setTimeout(b,1500)),l())return;if(k){let b=await this.promptResponder.answerInteractivePrompt(e,k,{pressEnter:!0});if(l())return;b||i.warn("q1 option_with_followup followup text-send failed",{sessionId:e})}try{await this.emitUserChoice(e,k?`\u2192 ${A} + sending your reply as a new prompt`:`\u2192 ${A}`)}catch(b){i.warn("emitUserChoice on q1 option_with_followup success failed",{sessionId:e,error:b instanceof Error?b.message:String(b)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}if(y==="nq_mid"){let C=await this.promptResponder.answerInteractivePrompt(e,_,{pressEnter:!1});if(l())return;if(!C){try{await this.sendPromptError(e,"Failed to commit Q[i]. Your reply was not sent. Please retry.")}catch(N){i.warn("sendPromptError on nq_mid option_with_followup failed",{sessionId:e,error:N instanceof Error?N.message:String(N)})}return}if(await new Promise(N=>setTimeout(N,200)),l())return;let b=n.pendingQuestionsQueue?.shift();b?n.pendingCurrentQuestion=b:i.warn("nq_mid option_with_followup: queue.shift returned undefined unexpectedly",{sessionId:e}),await this.handleMobileReplyAsDismissAndPrompt(e,n,k,l);return}if(y==="nq_last"){await this.handleOptionWithFollowupOnLastQ(e,n,_,A,k,l);return}let H=await this.promptResponder.answerInteractivePrompt(e,_,{pressEnter:!1});if(l())return;if(!H){try{await this.sendPromptError(e,"Failed to send SYNTH keypress. Your reply was not sent. Please retry.")}catch(C){i.warn("sendPromptError on on-SYNTH option_with_followup failed",{sessionId:e,error:C instanceof Error?C.message:String(C)})}return}if(await new Promise(C=>setTimeout(C,1500)),l())return;if(k){let C=await this.promptResponder.answerInteractivePrompt(e,k,{pressEnter:!0});if(l())return;C||i.warn("on-SYNTH option_with_followup text-send failed",{sessionId:e})}let B=n.pendingCurrentQuestion?._isSubmit===!0,G=A.toLowerCase(),K;B&&G==="cancel"?K=k?"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt":"\u2192 Cancel \u2014 AskUserQuestion cancelled, no answers submitted":B&&G.startsWith("submit")?K=k?"\u2192 Submit answers \u2014 AskUserQuestion completed, sending your reply as a new prompt":"\u2192 Submit answers \u2014 AskUserQuestion completed":K=k?`\u2192 ${A} + sending your reply as a new prompt`:`\u2192 ${A}`;try{await this.emitUserChoice(e,K)}catch(C){i.warn("emitUserChoice on on-SYNTH option_with_followup success failed",{sessionId:e,error:C instanceof Error?C.message:String(C)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}let I=R?.[v.option]||v.option;i.info("User selected option with follow-up",{option:v.option,terminalInput:I,followUpText:v.followUpText});let E=await this.promptResponder.answerInteractivePrompt(e,I);if(l()){await this.markEventExecutedIdempotent(n,t);return}if(E){if(await this.markEventExecutedIdempotent(n,t),l())return;if(!m){i.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"option_with_followup",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}try{await this.emitAnswerAck(e,`Selected option ${v.option}`,{promptId:m,questionIndex:0,isTerminal:!0})}catch(y){i.warn("[walker] emitAnswerAck (option_with_followup) failed \u2014 continuing to clearPromptState + executeMobilePrompt",{sessionId:e,promptId:m,error:y instanceof Error?y.message:String(y)})}if(l())return;if(this.promoteFingerprintAndClearPromptState(n),v.followUpText){await new Promise(P=>setTimeout(P,1e3));let y={...t,content:v.followUpText};await this.executeMobilePrompt(e,y)}}else try{await this.sendPromptError(e,"Failed to select option. Your reply (including the follow-up text) was not sent. Please retry.")}catch(y){i.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(y)})}finally{await this.markEventExecutedIdempotent(n,t)}}else{if(n.pendingQuestionsQueue!==void 0){let E=this.getWalkerPosition(n);if(i.info("AUQ walker \u2014 send_as_response dispatch",{sessionId:e,walkerPosition:E,contentPreview:d.slice(0,80)}),await this.markEventExecutedIdempotent(n,t),l())return;if(E==="on_synth"){let y=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!1});if(l())return;if(!y){try{await this.emitUserChoice(e,"AskUserQuestion cancel keypress failed (tmux unavailable); your reply was not sent")}catch(f){i.warn("emitUserChoice on send_as_response on-SYNTH Cancel failed",{sessionId:e,error:f instanceof Error?f.message:String(f)})}return}if(await new Promise(f=>setTimeout(f,1500)),l())return;let P=await this.promptResponder.answerInteractivePrompt(e,d,{pressEnter:!0});if(l())return;P||i.warn("send_as_response on-SYNTH text-send failed",{sessionId:e});try{await this.emitUserChoice(e,"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt")}catch(f){i.warn("emitUserChoice on send_as_response on-SYNTH success failed",{sessionId:e,error:f instanceof Error?f.message:String(f)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}await this.handleMobileReplyAsDismissAndPrompt(e,n,d,l);return}i.info("Sending as free-form response to interactive prompt",{response:d});let I=await this.promptResponder.answerInteractivePrompt(e,d);if(l()){await this.markEventExecutedIdempotent(n,t);return}if(I){if(await this.markEventExecutedIdempotent(n,t),l())return;if(!m){i.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"send_as_response",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}try{await this.emitAnswerAck(e,"Response sent to interactive prompt",{promptId:m,questionIndex:0,isTerminal:!0})}catch(E){i.warn("[walker] emitAnswerAck (send_as_response) failed \u2014 continuing to clearPromptState",{sessionId:e,promptId:m,error:E instanceof Error?E.message:String(E)})}if(l())return;this.promoteFingerprintAndClearPromptState(n)}else try{await this.sendPromptError(e,"Failed to send response")}catch(E){i.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(E)})}finally{await this.markEventExecutedIdempotent(n,t)}}}finally{u&&n.inFlightPromptIds&&n.inFlightPromptIds.delete(u),h&&n.inFlightEventIds&&n.inFlightEventIds.delete(h)}}async sendInteractivePromptAsync(e,t,r){let n=this.activeSessions.get(e),s=n?.promptGenerationToken?{...n.promptGenerationToken}:void 0,o=(0,p.prepareEventTimestamp)({orderingKey:e});await new Promise(l=>setTimeout(l,500));let a=process.env.CODEVIBE_TMUX_SESSION,c={...t.metadata||{}},g=t.metadata?.tool_name,u=t.metadata?.tool_input,h=g==="AskUserQuestion"&&Array.isArray(u?.questions)?u.questions:[];if(h.length>0&&Array.isArray(h[0]?.options)&&h[0].options.length>0){let l=h[0],T=[];if(a)try{let{exec:f}=await import("child_process"),U=_=>new Promise(($,F)=>{f(_,{timeout:5e3},(A,H)=>{A?F(A):$({stdout:H||""})})}),{stdout:k}=await U(`tmux capture-pane -p -e -S -30 -t '${a}'`);T=this.parseAskUserQuestionSynthTail(k),i.info("AskUserQuestion synth-tail parsed from tmux",{tailCount:T.length,tail:T.map(_=>_.label)})}catch(f){i.warn("Failed to capture tmux for AskUserQuestion synth-tail; emitting without synth tail",{error:f instanceof Error?f.message:String(f)})}else i.info("No tmux session \u2014 AskUserQuestion synth tail will be empty");let I=this.activeSessions.get(e);if(I){let f=I.promptGenerationToken;s&&f?.gen===s.gen?I.pendingSynthTail=T:i.warn("AskUserQuestion synth-tail: stale async \u2014 token gen mismatch, skipping pendingSynthTail write",{tokenAtEmit:s,currentToken:f,sessionId:e})}let E=this.buildQuestionWireData(l,T);c.options=JSON.parse(JSON.stringify(E.options)),c.submitMap=JSON.parse(JSON.stringify(E.submitMap)),c.instructions=E.instructions,c.tool_name="AskUserQuestion",c.tool_input={questions:[l]},r=l.question;let y=typeof t.prompt_id=="string"&&t.prompt_id.length>0,P=Me(h);if(y){let f=this.activeSessions.get(e);if(f){let U=f.promptGenerationToken;s&&U?.gen===s.gen?(f.pendingQuestionsQueue=P.remainingQueue,f.pendingCurrentQuestion=l,f.hasReviewScreen=P.hasReviewScreen):i.warn("AskUserQuestion: stale async \u2014 token gen mismatch, skipping walker-state write",{tokenAtEmit:s,currentToken:U,sessionId:e})}}else i.warn("AskUserQuestion: empty prompt_id, degrading to single-Q legacy emit",{questionCount:h.length});i.info("AskUserQuestion: emitting Q1 only (Q2..QN queued)",{questionCount:P.questionCount,hasReviewScreen:P.hasReviewScreen,queuedRemaining:y?P.remainingQueue.length:0,optionCountFirst:E.options.length,questionPreview:l.question.slice(0,80)})}else if(a)try{let{exec:l}=await import("child_process"),T=P=>new Promise((f,U)=>{l(P,{timeout:5e3},(k,_)=>{k?U(k):f({stdout:_||""})})}),{stdout:I}=await T(`tmux capture-pane -p -e -S -30 -t '${a}'`),E=I.split(`
6
- `);i.info("tmux capture result",{tmuxSession:a,totalLines:E.length,lastLines:E.slice(-15).map(P=>P.replace(/\x1B[^m]*m/g,"").trim()).filter(Boolean)});let y=(0,p.parseInteractivePrompt)(I);if(y&&y.options.length>0)c.options=y.options,c.submitMap=y.submitMap,c.instructions=this.buildPromptInstructions(y),i.info("Parsed dynamic options from tmux",{optionCount:y.options.length,kind:y.kind,options:y.options});else{this.suppressPromptOptionsUnavailable(e,s,"tmux parse returned no options");return}}catch(l){this.suppressPromptOptionsUnavailable(e,s,`tmux capture failed: ${l instanceof Error?l.message:String(l)}`);return}else{this.suppressPromptOptionsUnavailable(e,s,"no tmux session");return}let d=this.activeSessions.get(e);if(d&&c.submitMap){let l=d.promptGenerationToken;s&&l?.gen===s.gen?d.pendingSubmitMap=c.submitMap:i.warn("Interactive prompt async: stale async \u2014 token gen mismatch, skipping pendingSubmitMap write",{tokenAtEmit:s,currentToken:l,sessionId:e})}let m=r,x=c,R=!1;this.sessionKey&&(m=p.cryptoService.encryptContent(r,this.sessionKey),x={encrypted:p.cryptoService.encryptMetadata(x,this.sessionKey)},R=!0);let v=this.activeSessions.get(e)?.promptGenerationToken;if(s&&v?.gen!==s.gen){i.warn("Interactive prompt emit: stale token \u2014 newer INTERACTIVE_PROMPT replaced ours; skipping AppSync emit",{sessionId:e,tokenAtEmit:s,currentToken:v});return}await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.INTERACTIVE_PROMPT,source:t.source,content:m,metadata:x,promptId:t.prompt_id,timestamp:o,isEncrypted:R?!0:void 0}),i.info("Interactive prompt sent to AppSync with dynamic options",{sessionId:e})}buildQuestionWireData(e,t=[]){let r=(e.options||[]).map((c,g)=>{let u=typeof c=="string",h=u?c:c.label||"",d=u?"":c.description||"",m=u?"":c.preview||"",x={number:String(g+1),text:h};return d&&(x.description=d),m&&(x.preview=m),x});if(!e._isSubmit)for(let c of t)r.push({number:String(r.length+1),text:c.label});let n=Object.fromEntries(r.map(c=>[c.number,c.number])),s=(e.options||[]).length,o=t.findIndex(c=>c.label==="Type something"),a;if(e._isSubmit)a="Reply with 1 to submit your answers or 2 to cancel.";else if(e.multiSelect)a=`Reply with comma-separated numbers (e.g., 1,3) for "${e.header||e.question}"`;else if(o>=0){let c=String(s+o+1);a=`Reply with the number of your choice. For option ${c} (Type something), reply "${c}, your answer".`}else a="Reply with the number of your choice.";return{options:r,submitMap:n,instructions:a}}parseAskUserQuestionSynthTail(e){let t=(0,p.normalizeSnapshot)(e);if(!t)return[];let r=t.split(`
7
- `).slice(-14),n=[],s=new Set,o=/^\s*(?:[›❯▸▶➜➤]\s*)?(?:\d+\.\s+)?(Type something|Chat about this)\.?\s*$/i;for(let a of r){let c=a.match(o);if(!c)continue;let u=c[1].toLowerCase()==="type something"?"Type something":"Chat about this";s.has(u)||(n.push({label:u}),s.add(u))}return n}suppressPromptOptionsUnavailable(e,t,r){i.warn("Interactive prompt: real options unavailable \u2014 suppressing mobile prompt (no fabricated options)",{sessionId:e,reason:r});let n=this.activeSessions.get(e);n&&t&&n.promptGenerationToken?.gen===t.gen&&this.clearPromptState(n)}buildPromptInstructions(e){return`Reply with ${e.options.map(r=>r.number).join(", ")}. Append a message to provide alternative instructions.`}parseInteractivePromptInput(e,t=3){return Pe(e,t)}async markEventExecuted(e){try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:p.DeliveryStatus.EXECUTED}),i.info("Event marked as EXECUTED",{eventId:e.eventId})}catch(t){i.warn("Failed to mark event as EXECUTED",{eventId:e.eventId,error:t})}}async sendPromptError(e,t){let r={error:!0},n=t,s=r,o=!1;this.sessionKey&&(n=p.cryptoService.encryptContent(t,this.sessionKey),s={encrypted:p.cryptoService.encryptMetadata(r,this.sessionKey)},o=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:n,metadata:s,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:o?!0:void 0})}async emitUserChoice(e,t){let r=t,n={source:"codevibe_v2_user_choice"},s=!1;this.sessionKey&&(r=p.cryptoService.encryptContent(t,this.sessionKey),n={encrypted:p.cryptoService.encryptMetadata({source:"codevibe_v2_user_choice"},this.sessionKey)},s=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.ASSISTANT_RESPONSE,source:p.EventSource.DESKTOP,content:r,metadata:n,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:s?!0:void 0})}async emitAnswerAck(e,t,r){let n={promptAnswered:!0,...r},s=t,o=n,a=!1;this.sessionKey&&(s=p.cryptoService.encryptContent(t,this.sessionKey),o={encrypted:p.cryptoService.encryptMetadata(n,this.sessionKey)},a=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:s,metadata:o,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:a?!0:void 0})}promoteFingerprintAndClearPromptState(e){e.activeAskUserQuestionFingerprint&&(e.completedAskUserQuestionFingerprints||(e.completedAskUserQuestionFingerprints=new Set),e.completedAskUserQuestionFingerprints.add(e.activeAskUserQuestionFingerprint)),this.clearPromptState(e)}clearPromptState(e){e.waitingForPromptResponse=!1,e.pendingPromptId=void 0,e.pendingSubmitMap=void 0,e.pendingQuestionsQueue=void 0,e.pendingCurrentQuestion=void 0,e.pendingSynthTail=void 0,e.hasReviewScreen=void 0,e.activeAskUserQuestionFingerprint=void 0,e.promptGenerationToken=void 0}async detectWalkerActive(e){let t=process.env.CODEVIBE_TMUX_SESSION;if(!t)return i.debug("detectWalkerActive: no CODEVIBE_TMUX_SESSION env \u2014 conservatively assuming walker active",{sessionId:e}),!0;try{let{exec:r}=await import("child_process"),n=l=>new Promise((T,I)=>{r(l,{timeout:3e3},(E,y)=>{E?I(E):T({stdout:y||""})})}),{stdout:s}=await n(`tmux capture-pane -p -e -S -30 -t '${t}'`),o=/\x1B(?:\[[?!0-9;]*[A-Za-z]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[()][A-B012])/g,a=s.split(`
8
- `).map(l=>l.replace(o,"").trimEnd()),c=a.length-1;for(;c>=0&&a[c].trim()==="";)c-=1;if(c<0)return i.warn("detectWalkerActive: pane empty after ANSI strip \u2014 conservatively assuming walker active",{sessionId:e}),!0;let g=/(?:Esc to cancel|Enter to select|↑\/↓ to navigate|Tab to switch|shift\+tab|Chat about this|Type something|Notes: press|\(esc\)|\(shift\+tab\))/i,u=/^\s*(?:[›❯▸▶➜➤]\s*)?\d+\.\s+/,h=-1;for(let l=c;l>=0;l-=1)if(u.test(a[l])){h=l;break}let d=h>=0,m=-1;for(let l=c;l>=0;l-=1)if(g.test(a[l])){m=l;break}let x=m<0?1/0:c-m,R=m>=0&&x<=3,Q=m>=0&&h>=0&&m>=h&&m-h<=5,v=d&&R&&Q;return i.info("detectWalkerActive",{sessionId:e,walkerActive:v,hasParserBlock:d,chromeNearBottom:R,chromeFollowsBlock:Q,chromeDistanceFromBottom:Number.isFinite(x)?x:-1,parserBlockEndsAt:h,lastNonBlank:c,lastChromeLineAt:m,lastLineSample:a[c]?.slice(0,80)??""}),v}catch(r){return i.warn("detectWalkerActive: tmux capture/parse failed \u2014 conservatively assuming walker active",{sessionId:e,error:r instanceof Error?r.message:String(r)}),!0}}getWalkerPosition(e){return e.pendingCurrentQuestion?._isSubmit?"on_synth":e.hasReviewScreen?(e.pendingQuestionsQueue?.length??0)>=2?"nq_mid":"nq_last":"q1"}async emitDegradedAUQNotification(e,t){try{let r=t,n={source:"codevibe_auq_degraded"},s=!1;this.sessionKey&&(r=p.cryptoService.encryptContent(t,this.sessionKey),n={encrypted:p.cryptoService.encryptMetadata({source:"codevibe_auq_degraded"},this.sessionKey)},s=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.ASSISTANT_RESPONSE,source:p.EventSource.DESKTOP,content:r,metadata:n,isEncrypted:s?!0:void 0}),i.info("Emitted degraded-AUQ notification",{sessionId:e,textPreview:t.slice(0,60)})}catch(r){i.warn("emitDegradedAUQNotification failed",{sessionId:e,error:r instanceof Error?r.message:String(r)})}}async handleMobileReplyAsDismissAndPrompt(e,t,r,n){let s=await this.promptResponder.sendKey(e,"Escape");if(n())return!1;if(!s){try{await this.emitUserChoice(e,"AskUserQuestion dismissal failed (tmux unavailable)")}catch(a){i.warn("emitUserChoice on dismiss-ok1-failed failed",{sessionId:e,error:a instanceof Error?a.message:String(a)})}return!1}if(await new Promise(a=>setTimeout(a,200)),n())return!1;let o=await this.promptResponder.answerInteractivePrompt(e,r,{pressEnter:!0});if(n())return!1;if(!o){try{await this.emitUserChoice(e,"AskUserQuestion dismissed but text-send failed; please retry")}catch(a){i.warn("emitUserChoice on dismiss-ok2-failed failed",{sessionId:e,error:a instanceof Error?a.message:String(a)})}return n()||this.promoteFingerprintAndClearPromptState(t),!1}try{await this.emitUserChoice(e,"\u2192 AskUserQuestion dismissed, sending your reply as a new prompt")}catch(a){i.warn("emitUserChoice on dismiss-success failed \u2014 continuing to promote+clear",{sessionId:e,error:a instanceof Error?a.message:String(a)})}return n()?(i.warn("handleMobileReplyAsDismissAndPrompt: aborted post-emitUserChoice (token rotated); leaving session state for new prompt",{sessionId:e}),!1):(this.promoteFingerprintAndClearPromptState(t),!0)}async handleOptionWithFollowupOnLastQ(e,t,r,n,s,o){let a=await this.promptResponder.answerInteractivePrompt(e,r,{pressEnter:!1});if(o())return!1;if(!a){try{await this.emitUserChoice(e,"Failed to commit Q[N] (tmux unavailable); your reply was not sent")}catch(u){i.warn("emitUserChoice on lastQ-ok1-failed failed",{sessionId:e,error:u instanceof Error?u.message:String(u)})}return!1}if(await new Promise(u=>setTimeout(u,200)),o())return!1;let c=await this.promptResponder.answerInteractivePrompt(e,"1",{pressEnter:!1});if(o())return!1;if(!c){try{await this.emitUserChoice(e,"Q[N] committed but Submit failed (tmux unavailable); please retry on desktop")}catch(u){i.warn("emitUserChoice on lastQ-ok2-failed failed",{sessionId:e,error:u instanceof Error?u.message:String(u)})}return o()||this.promoteFingerprintAndClearPromptState(t),!1}if(await new Promise(u=>setTimeout(u,1500)),o())return!1;let g=await this.promptResponder.answerInteractivePrompt(e,s,{pressEnter:!0});if(o())return!1;g||i.warn("handleOptionWithFollowupOnLastQ: followup text send failed",{sessionId:e});try{await this.emitUserChoice(e,`\u2192 ${n} + sending your reply as a new prompt`)}catch(u){i.warn("emitUserChoice on lastQ-success failed \u2014 continuing to promote+clear",{sessionId:e,error:u instanceof Error?u.message:String(u)})}return o()?(i.warn("handleOptionWithFollowupOnLastQ: aborted post-emitUserChoice (token rotated); leaving session state for new prompt",{sessionId:e}),!1):(this.promoteFingerprintAndClearPromptState(t),!0)}computeAskUserQuestionFingerprint(e){if(!(!e||typeof e!="object"))try{let t=this.stringifyCanonical(e);return(0,W.createHash)("sha256").update(t).digest("hex")}catch(t){i.warn("Failed to fingerprint AskUserQuestion questions",{error:t instanceof Error?t.message:String(t)});return}}stringifyCanonical(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(r=>this.stringifyCanonical(r)).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+this.stringifyCanonical(e[r])).join(",")+"}"}async markEventExecutedIdempotent(e,t){e.processedEventIds||(e.processedEventIds=new Set),e.processedEventIds.add(t.eventId);try{await this.markEventExecuted(t)}catch(r){i.warn("[walker] markEventExecuted threw \u2014 relying on processedEventIds set for dedup",{sessionId:t.sessionId,eventId:t.eventId,error:String(r)})}}isSessionLimitExceeded(e){return this.getErrorMessage(e).includes("SESSION_LIMIT_EXCEEDED")}isUsageLimitExceeded(e){let t=this.getErrorMessage(e);return t.includes("MESSAGE_LIMIT_EXCEEDED")||t.includes("IMAGE_LIMIT_EXCEEDED")}getErrorMessage(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e;if(t.errors&&Array.isArray(t.errors))return t.errors.map(r=>r.message||"").join(" ");if(typeof t.message=="string")return t.message}return String(e)}displaySubscriptionLimitError(e,t){let r=this.getErrorMessage(e),n="",s=r.match(/for your (\w+) plan/i);s&&(n=` (${s[1]} tier)`);let o="",a=r.match(/of (\d+)/);switch(a&&(o=` [Limit: ${a[1]}]`),console.log(`
5
+ `)}}catch(g){if(this.isSessionLimitExceeded(g)){this.displaySubscriptionLimitError(g,"session"),this.activeSessions.delete(r),this.removePortFile(t);return}i.error("Failed to create/resume session:",g)}this.subscribeToMobileEvents(r),this.appSyncClient.startHeartbeat(r);let c=this.activeSessions.get(r);c&&(c.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(r,async()=>{i.info("Mobile ended session \u2014 sending desktop quit",{sessionId:r});let g=process.env[oe];if(!g){i.warn("No tmux session set; skipping desktop self-terminate",{sessionId:r,expectedEnv:oe});return}await Qe(g,Re)}))}async handleSessionEnd(e){let t=e.session_id,r=this.claudeToBackendSessionId.get(t)||this.generateBackendSessionId(t);i.info("Session ended",{claudeSessionId:t,sessionId:r,reason:e.metadata?.reason});let n=this.activeSessions.get(r);if(n?.mobileEndWatcher&&(n.mobileEndWatcher.stop(),n.mobileEndWatcher=void 0),this.activeSessions.delete(r),this.claudeToBackendSessionId.delete(t),this.removePortFile(t),n?.waitingForPromptResponse&&(i.info("Clearing prompt wait state - session ending",{sessionId:r}),this.clearPromptState(n)),this.appSyncClient.stopHeartbeat(r),this.appSyncClient.cleanupSubscription(r),n)try{await this.appSyncClient.updateSession({sessionId:r,status:p.SessionStatus.INACTIVE}),i.info("Session marked as INACTIVE in AppSync",{sessionId:r})}catch(s){i.warn("Failed to update session in AppSync:",s)}else i.warn("Cannot update session - session state not found",{sessionId:r});i.debug("Session cleanup completed",{sessionId:r})}subscribeToMobileEvents(e){i.info("Subscribing to mobile events",{sessionId:e});let t=this.activeSessions.get(e);if(!t){i.error("Session not found",{sessionId:e});return}this.appSyncClient.subscribeToEvents(e,async r=>{await this.dispatchMobileEvent(e,r)},r=>{i.error("Subscription error",{sessionId:e,error:r})}),t.subscriptionActive=!0,i.info("Subscription active",{sessionId:e})}async dispatchMobileEvent(e,t){i.info("Received mobile event",{eventId:t.eventId,type:t.type,sessionId:t.sessionId,isEncrypted:t.isEncrypted});let r,n,s=!1,o,a,c;if(t.type===p.EventType.USER_PROMPT||t.type===p.EventType.PROMPT_RESPONSE)if(n=this.activeSessions.get(e),!n)r="no-session";else if(n.processedEventIds?.has(t.eventId))r="skip-dedup";else if(n.inFlightEventIds?.has(t.eventId))r="drop-event-redeliver";else if(n.waitingForPromptResponse){let d=n.promptGenerationToken;if(!d)r="regular";else if(t.type===p.EventType.USER_PROMPT&&n.hasReceivedPromptResponse&&(!t.promptId||t.promptId.length===0))r="drop-stale-answer";else if(t.promptId&&t.promptId.length>0&&d.promptId.length>0&&t.promptId!==d.promptId)r="drop-stale-answer";else{let m=d.promptId.length>0?d.promptId:`__prompt_gen_${d.gen}`;n.inFlightPromptIds?.has(m)?r="drop-in-flight":(n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightEventIds||(n.inFlightEventIds=new Set),n.inFlightPromptIds.add(m),n.inFlightEventIds.add(t.eventId),s=!0,a=m,c=t.eventId,o={promptId:d.promptId,gen:d.gen},r="walker")}}else r="regular";else r="not-user-prompt";let u=t.content||"";if(t.isEncrypted&&this.sessionKey)try{u=p.cryptoService.decryptContent(t.content,this.sessionKey),i.debug("Event decrypted successfully",{eventId:t.eventId})}catch(d){i.error("Failed to decrypt event:",{eventId:t.eventId,error:d}),u=t.content}let h={...t,content:u};if(r!=="skip-dedup")try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:p.DeliveryStatus.DELIVERED}),i.info("Event marked as DELIVERED",{eventId:t.eventId})}catch(d){i.warn("Failed to mark event as DELIVERED",{eventId:t.eventId,error:d})}if(r==="skip-dedup"){i.info("[walker] Subscription-level dedup hit (already processed) \u2014 skipping",{sessionId:e,eventId:t.eventId});return}if(r==="drop-stale-answer"){i.info("[walker] Stale answer dropped \u2014 event.promptId does not match current pending promptId",{sessionId:e,eventId:t.eventId,eventPromptId:t.promptId,currentPromptId:n?.promptGenerationToken?.promptId}),n&&(n.processedEventIds||(n.processedEventIds=new Set),n.processedEventIds.add(t.eventId));try{await this.markEventExecuted(t)}catch(d){i.warn("[walker] markEventExecuted threw on stale-answer drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}if(r==="drop-in-flight"){i.warn("[walker] Subscription-level in-flight guard \u2014 dropping duplicate USER_PROMPT (different eventId, same prompt)",{sessionId:e,eventId:t.eventId}),n&&(n.processedEventIds||(n.processedEventIds=new Set),n.processedEventIds.add(t.eventId));try{await this.markEventExecuted(t)}catch(d){i.warn("[walker] markEventExecuted threw on subscription-level duplicate drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}if(r==="drop-event-redeliver"){i.info("[walker] Subscription-level event-level redelivery \u2014 silent skip (original still in flight)",{sessionId:e,eventId:t.eventId});return}if(r==="walker"){t.type===p.EventType.PROMPT_RESPONSE&&n&&(n.hasReceivedPromptResponse=!0),await this.handleMobilePromptResponse(e,t,u,n,s,o,a,c);return}if(r==="regular"){if(t.type===p.EventType.PROMPT_RESPONSE){i.warn("Received PROMPT_RESPONSE with no active walker \u2014 dropping",{sessionId:e,eventId:t.eventId,promptId:t.promptId}),n&&(n.processedEventIds||(n.processedEventIds=new Set),n.processedEventIds.add(t.eventId));try{await this.markEventExecuted(t)}catch(d){i.warn("markEventExecuted threw on PROMPT_RESPONSE orphan drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}await this.executeMobilePrompt(e,h);return}if(r==="no-session"){i.warn("Received mobile prompt input for unknown session \u2014 ignoring",{sessionId:e,eventId:t.eventId,type:t.type});return}}async handleMobilePromptResponse(e,t,r,n,s=!1,o,a,c){let g=o??n.promptGenerationToken,u=a,h=c;if(!s&&g){let d=g.promptId.length>0?g.promptId:`__prompt_gen_${g.gen}`;if(n.inFlightPromptIds?.has(d)){i.warn("[walker] Duplicate mobile USER_PROMPT for same prompt \u2014 dropping",{sessionId:e,eventId:t.eventId,lockKey:d}),await this.markEventExecutedIdempotent(n,t);return}n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightEventIds||(n.inFlightEventIds=new Set),n.inFlightPromptIds.add(d),n.inFlightEventIds.add(t.eventId),u=d,h=t.eventId}try{if(!s&&n.processedEventIds?.has(t.eventId)){i.info("[walker] Redelivered event already processed \u2014 skipping",{sessionId:e,eventId:t.eventId});return}let d=r.trim(),m=n.pendingPromptId,R=n.pendingSubmitMap,O=R?Object.keys(R).length:3,v=this.parseInteractivePromptInput(d,O);i.info("Parsed interactive prompt input",{sessionId:e,content:d,parsed:v,hasSubmitMap:!!R});let l=()=>{let A=n.promptGenerationToken,b=A?.gen,E=g?.gen;return b!==E?(i.warn("[walker] Token mismatch \u2014 external cleanup or new prompt during in-flight handler \u2014 aborting",{sessionId:e,eventId:t.eventId,entryToken:g,currentToken:A}),!0):!1};if(l()){await this.markEventExecutedIdempotent(n,t);return}{let A=n.pendingQuestionsQueue!==void 0,b=d.trim(),E=b.match(/^(\d+)$/);if(A&&n.pendingCurrentQuestion&&E){let y=n.pendingCurrentQuestion.options?.length??0,P=E[1],f=parseInt(P,10),F=!Number.isFinite(f)||f<1||f>y,k=String(f)!==P;if(F||k){let _=this.getWalkerPosition(n);if(i.info("AUQ walker \u2014 bare out-of-range or non-canonical option; routing per dispatch matrix",{sessionId:e,option:P,optionNum:f,realOptionCount:y,isOutOfRange:F,isNonCanonical:k,walkerPosition:_,parsedAction:v.action}),await this.markEventExecutedIdempotent(n,t),l())return;if(_==="on_synth"){let K=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!1});if(l())return;if(!K){try{await this.emitUserChoice(e,"AskUserQuestion cancel keypress failed (tmux unavailable); your reply was not sent")}catch(T){i.warn("emitUserChoice on on-SYNTH Cancel failed",{sessionId:e,error:T instanceof Error?T.message:String(T)})}return}if(await new Promise(T=>setTimeout(T,1500)),l())return;let M=await this.promptResponder.answerInteractivePrompt(e,b,{pressEnter:!0});if(l())return;M||i.warn("on-SYNTH Cancel followup text-send failed; AUQ cancelled, no new prompt",{sessionId:e});try{await this.emitUserChoice(e,"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt")}catch(T){i.warn("emitUserChoice on on-SYNTH Cancel success failed",{sessionId:e,error:T instanceof Error?T.message:String(T)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}await this.handleMobileReplyAsDismissAndPrompt(e,n,b,l);return}}}if(v.action==="select_option"){let A=R?.[v.option]||v.option,b=n.pendingQuestionsQueue!==void 0;i.info("User selected option",{option:v.option,terminalInput:A,isV2AskUserQuestion:b});let E=await this.promptResponder.answerInteractivePrompt(e,A,{pressEnter:!b});if(l()){await this.markEventExecutedIdempotent(n,t);return}if(E){if(await this.markEventExecutedIdempotent(n,t),l())return;if(!m){i.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"select_option",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}let y=(n.pendingQuestionsQueue?.length??0)===0;try{if(b){let Q=parseInt(v.option,10)-1,q=n.pendingCurrentQuestion?.options?.[Q],H=typeof q=="string"?q:q&&typeof q=="object"?q.label:`option ${v.option}`,pe=n.pendingCurrentQuestion?._isSubmit===!0,ce=H.toLowerCase(),X;pe&&ce==="cancel"?X="\u2192 Cancel \u2014 AskUserQuestion cancelled, no answers submitted":pe&&ce.startsWith("submit")?X="\u2192 Submit answers \u2014 AskUserQuestion completed":X=`\u2192 ${H}`,await this.emitUserChoice(e,X)}else await this.emitAnswerAck(e,`Selected option ${v.option}`,{promptId:m,questionIndex:0,isTerminal:y})}catch(Q){i.warn("[walker] user-choice/ack emit failed \u2014 continuing to STEP 7/8",{sessionId:e,promptId:m,isV2AskUserQuestion:b,error:Q instanceof Error?Q.message:String(Q)})}if(l())return;let P=n.pendingQuestionsQueue?.shift();if(P&&(n.pendingCurrentQuestion=P),!P){n.activeAskUserQuestionFingerprint&&(n.completedAskUserQuestionFingerprints||(n.completedAskUserQuestionFingerprints=new Set),n.completedAskUserQuestionFingerprints.add(n.activeAskUserQuestionFingerprint),i.info("AskUserQuestion V2 walker complete \u2014 fingerprint marked closed",{sessionId:e,fingerprint:n.activeAskUserQuestionFingerprint.slice(0,16)})),this.clearPromptState(n);return}let f=`synth-${(0,G.randomUUID)()}`;if(!f){this.promoteFingerprintAndClearPromptState(n),i.warn("Q[next] emit aborted: synthesized promptId was empty; promoted fingerprint + cleared prompt state",{sessionId:e,eventId:t.eventId});return}let F=n.pendingSynthTail??[],k=this.buildQuestionWireData(P,F),_=P.question,K={tool_name:"AskUserQuestion",tool_input:{questions:[P]},options:k.options,submitMap:k.submitMap,instructions:k.instructions},M=this.sessionKey,T=_,V=K,W=!1;M&&(T=p.cryptoService.encryptContent(_,M),V={encrypted:p.cryptoService.encryptMetadata(K,M)},W=!0);let Y=this.nextPromptGen++,L={promptId:f,gen:Y};n.pendingPromptId=f,n.pendingSubmitMap=k.submitMap,n.promptGenerationToken=L;let C=L,D=this.activeSessions.get(e)?.promptGenerationToken;if(!D||D.gen!==C.gen||D.promptId!==C.promptId){i.warn("Q[next] emit aborted: token replaced before await dispatch",{sessionId:e,tokenAtAwait:C,currentToken:D});return}let ae=f.length>0?f:`__prompt_gen_${L.gen}`;n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightPromptIds.add(ae);try{try{await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.INTERACTIVE_PROMPT,source:p.EventSource.DESKTOP,content:T,metadata:V,promptId:f,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:W?!0:void 0}),i.info("Q[next] emit succeeded",{sessionId:e,promptId:f,remaining:n.pendingQuestionsQueue?.length??0})}catch(Q){let q=this.activeSessions.get(e),H=q?.promptGenerationToken;H&&H.gen===C.gen&&H.promptId===C.promptId?(this.promoteFingerprintAndClearPromptState(q),i.warn("Q[next] emit failed; promoted fingerprint + cleared prompt state. User must answer remaining questions on desktop terminal.",{sessionId:e,promptId:f,error:Q instanceof Error?Q.message:String(Q)})):i.warn("Q[next] emit failed but a NEW prompt replaced our token during await; not clearing state (would wipe new prompt). Q[next..QN] of the original AskUserQuestion are lost; new prompt continues normally.",{sessionId:e,tokenAtAwait:C,currentToken:H,error:Q instanceof Error?Q.message:String(Q)})}}finally{n.inFlightPromptIds.delete(ae)}}else try{await this.sendPromptError(e,"Failed to select option")}catch(y){i.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(y)})}finally{await this.markEventExecutedIdempotent(n,t)}}else if(v.action==="option_with_followup"){if(n.pendingQuestionsQueue!==void 0){let y=this.getWalkerPosition(n),P=n.pendingCurrentQuestion?.options?.length??0,f=v.option?parseInt(v.option,10):NaN,F=Number.isFinite(f)&&f>P,k=v.followUpText??"";if(i.info("AUQ walker \u2014 option_with_followup dispatch",{sessionId:e,option:v.option,optionNum:f,explicitCount:P,isSynthDigit:F,walkerPosition:y,followUpTextLen:k.length}),await this.markEventExecutedIdempotent(n,t),l())return;if(F){if(y==="on_synth"){let C=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!1});if(l())return;if(!C){try{await this.emitUserChoice(e,"AskUserQuestion cancel keypress failed (tmux unavailable); your reply was not sent")}catch(I){i.warn("emitUserChoice on synth-digit on-SYNTH Cancel failed",{sessionId:e,error:I instanceof Error?I.message:String(I)})}return}if(await new Promise(I=>setTimeout(I,1500)),l())return;if(k){let I=await this.promptResponder.answerInteractivePrompt(e,k,{pressEnter:!0});if(l())return;I||i.warn("on-SYNTH Cancel followup text-send failed",{sessionId:e})}try{await this.emitUserChoice(e,"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt")}catch(I){i.warn("emitUserChoice on synth-digit on-SYNTH success failed",{sessionId:e,error:I instanceof Error?I.message:String(I)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}await this.handleMobileReplyAsDismissAndPrompt(e,n,k,l);return}let _=R?.[v.option]||v.option,K=f-1,M=n.pendingCurrentQuestion?.options?.[K],T=typeof M=="string"?M:M&&typeof M=="object"?M.label:`option ${v.option}`;if(y==="q1"){let C=await this.promptResponder.answerInteractivePrompt(e,_,{pressEnter:!1});if(l())return;if(!C){try{await this.sendPromptError(e,"Failed to select option. Your reply (including the follow-up text) was not sent. Please retry.")}catch(I){i.warn("sendPromptError on q1 option_with_followup failed",{sessionId:e,error:I instanceof Error?I.message:String(I)})}return}if(await new Promise(I=>setTimeout(I,1500)),l())return;if(k){let I=await this.promptResponder.answerInteractivePrompt(e,k,{pressEnter:!0});if(l())return;I||i.warn("q1 option_with_followup followup text-send failed",{sessionId:e})}try{await this.emitUserChoice(e,k?`\u2192 ${T} + sending your reply as a new prompt`:`\u2192 ${T}`)}catch(I){i.warn("emitUserChoice on q1 option_with_followup success failed",{sessionId:e,error:I instanceof Error?I.message:String(I)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}if(y==="nq_mid"){let C=await this.promptResponder.answerInteractivePrompt(e,_,{pressEnter:!1});if(l())return;if(!C){try{await this.sendPromptError(e,"Failed to commit Q[i]. Your reply was not sent. Please retry.")}catch(D){i.warn("sendPromptError on nq_mid option_with_followup failed",{sessionId:e,error:D instanceof Error?D.message:String(D)})}return}if(await new Promise(D=>setTimeout(D,200)),l())return;let I=n.pendingQuestionsQueue?.shift();I?n.pendingCurrentQuestion=I:i.warn("nq_mid option_with_followup: queue.shift returned undefined unexpectedly",{sessionId:e}),await this.handleMobileReplyAsDismissAndPrompt(e,n,k,l);return}if(y==="nq_last"){await this.handleOptionWithFollowupOnLastQ(e,n,_,T,k,l);return}let V=await this.promptResponder.answerInteractivePrompt(e,_,{pressEnter:!1});if(l())return;if(!V){try{await this.sendPromptError(e,"Failed to send SYNTH keypress. Your reply was not sent. Please retry.")}catch(C){i.warn("sendPromptError on on-SYNTH option_with_followup failed",{sessionId:e,error:C instanceof Error?C.message:String(C)})}return}if(await new Promise(C=>setTimeout(C,1500)),l())return;if(k){let C=await this.promptResponder.answerInteractivePrompt(e,k,{pressEnter:!0});if(l())return;C||i.warn("on-SYNTH option_with_followup text-send failed",{sessionId:e})}let W=n.pendingCurrentQuestion?._isSubmit===!0,Y=T.toLowerCase(),L;W&&Y==="cancel"?L=k?"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt":"\u2192 Cancel \u2014 AskUserQuestion cancelled, no answers submitted":W&&Y.startsWith("submit")?L=k?"\u2192 Submit answers \u2014 AskUserQuestion completed, sending your reply as a new prompt":"\u2192 Submit answers \u2014 AskUserQuestion completed":L=k?`\u2192 ${T} + sending your reply as a new prompt`:`\u2192 ${T}`;try{await this.emitUserChoice(e,L)}catch(C){i.warn("emitUserChoice on on-SYNTH option_with_followup success failed",{sessionId:e,error:C instanceof Error?C.message:String(C)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}let b=R?.[v.option]||v.option;i.info("User selected option with follow-up",{option:v.option,terminalInput:b,followUpText:v.followUpText});let E=await this.promptResponder.answerInteractivePrompt(e,b);if(l()){await this.markEventExecutedIdempotent(n,t);return}if(E){if(await this.markEventExecutedIdempotent(n,t),l())return;if(!m){i.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"option_with_followup",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}try{await this.emitAnswerAck(e,`Selected option ${v.option}`,{promptId:m,questionIndex:0,isTerminal:!0})}catch(y){i.warn("[walker] emitAnswerAck (option_with_followup) failed \u2014 continuing to clearPromptState + executeMobilePrompt",{sessionId:e,promptId:m,error:y instanceof Error?y.message:String(y)})}if(l())return;if(this.promoteFingerprintAndClearPromptState(n),v.followUpText){await new Promise(P=>setTimeout(P,1e3));let y={...t,content:v.followUpText};await this.executeMobilePrompt(e,y)}}else try{await this.sendPromptError(e,"Failed to select option. Your reply (including the follow-up text) was not sent. Please retry.")}catch(y){i.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(y)})}finally{await this.markEventExecutedIdempotent(n,t)}}else{if(n.pendingQuestionsQueue!==void 0){let E=this.getWalkerPosition(n);if(i.info("AUQ walker \u2014 send_as_response dispatch",{sessionId:e,walkerPosition:E,contentPreview:d.slice(0,80)}),await this.markEventExecutedIdempotent(n,t),l())return;if(E==="on_synth"){let y=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!1});if(l())return;if(!y){try{await this.emitUserChoice(e,"AskUserQuestion cancel keypress failed (tmux unavailable); your reply was not sent")}catch(f){i.warn("emitUserChoice on send_as_response on-SYNTH Cancel failed",{sessionId:e,error:f instanceof Error?f.message:String(f)})}return}if(await new Promise(f=>setTimeout(f,1500)),l())return;let P=await this.promptResponder.answerInteractivePrompt(e,d,{pressEnter:!0});if(l())return;P||i.warn("send_as_response on-SYNTH text-send failed",{sessionId:e});try{await this.emitUserChoice(e,"\u2192 Cancel \u2014 AskUserQuestion cancelled, sending your reply as a new prompt")}catch(f){i.warn("emitUserChoice on send_as_response on-SYNTH success failed",{sessionId:e,error:f instanceof Error?f.message:String(f)})}if(l())return;this.promoteFingerprintAndClearPromptState(n);return}await this.handleMobileReplyAsDismissAndPrompt(e,n,d,l);return}i.info("Sending as free-form response to interactive prompt",{response:d});let b=await this.promptResponder.answerInteractivePrompt(e,d);if(l()){await this.markEventExecutedIdempotent(n,t);return}if(b){if(await this.markEventExecutedIdempotent(n,t),l())return;if(!m){i.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"send_as_response",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}try{await this.emitAnswerAck(e,"Response sent to interactive prompt",{promptId:m,questionIndex:0,isTerminal:!0})}catch(E){i.warn("[walker] emitAnswerAck (send_as_response) failed \u2014 continuing to clearPromptState",{sessionId:e,promptId:m,error:E instanceof Error?E.message:String(E)})}if(l())return;this.promoteFingerprintAndClearPromptState(n)}else try{await this.sendPromptError(e,"Failed to send response")}catch(E){i.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(E)})}finally{await this.markEventExecutedIdempotent(n,t)}}}finally{u&&n.inFlightPromptIds&&n.inFlightPromptIds.delete(u),h&&n.inFlightEventIds&&n.inFlightEventIds.delete(h)}}async sendInteractivePromptAsync(e,t,r){let n=this.activeSessions.get(e),s=n?.promptGenerationToken?{...n.promptGenerationToken}:void 0,o=(0,p.prepareEventTimestamp)({orderingKey:e});await new Promise(l=>setTimeout(l,500));let a=process.env.CODEVIBE_TMUX_SESSION,c={...t.metadata||{}},g=t.metadata?.tool_name,u=t.metadata?.tool_input,h=g==="AskUserQuestion"&&Array.isArray(u?.questions)?u.questions:[];if(h.length>0&&Array.isArray(h[0]?.options)&&h[0].options.length>0){let l=h[0],A=[];if(a)try{let{exec:f}=await import("child_process"),F=_=>new Promise((K,M)=>{f(_,{timeout:5e3},(T,V)=>{T?M(T):K({stdout:V||""})})}),{stdout:k}=await F(`tmux capture-pane -p -e -S -30 -t '${a}'`);A=this.parseAskUserQuestionSynthTail(k),i.info("AskUserQuestion synth-tail parsed from tmux",{tailCount:A.length,tail:A.map(_=>_.label)})}catch(f){i.warn("Failed to capture tmux for AskUserQuestion synth-tail; emitting without synth tail",{error:f instanceof Error?f.message:String(f)})}else i.info("No tmux session \u2014 AskUserQuestion synth tail will be empty");let b=this.activeSessions.get(e);if(b){let f=b.promptGenerationToken;s&&f?.gen===s.gen?b.pendingSynthTail=A:i.warn("AskUserQuestion synth-tail: stale async \u2014 token gen mismatch, skipping pendingSynthTail write",{tokenAtEmit:s,currentToken:f,sessionId:e})}let E=this.buildQuestionWireData(l,A);c.options=JSON.parse(JSON.stringify(E.options)),c.submitMap=JSON.parse(JSON.stringify(E.submitMap)),c.instructions=E.instructions,c.tool_name="AskUserQuestion",c.tool_input={questions:[l]},r=l.question;let y=typeof t.prompt_id=="string"&&t.prompt_id.length>0,P=Ne(h);if(y){let f=this.activeSessions.get(e);if(f){let F=f.promptGenerationToken;s&&F?.gen===s.gen?(f.pendingQuestionsQueue=P.remainingQueue,f.pendingCurrentQuestion=l,f.hasReviewScreen=P.hasReviewScreen):i.warn("AskUserQuestion: stale async \u2014 token gen mismatch, skipping walker-state write",{tokenAtEmit:s,currentToken:F,sessionId:e})}}else i.warn("AskUserQuestion: empty prompt_id, degrading to single-Q legacy emit",{questionCount:h.length});i.info("AskUserQuestion: emitting Q1 only (Q2..QN queued)",{questionCount:P.questionCount,hasReviewScreen:P.hasReviewScreen,queuedRemaining:y?P.remainingQueue.length:0,optionCountFirst:E.options.length,questionPreview:l.question.slice(0,80)})}else if(a)try{let{exec:l}=await import("child_process"),A=P=>new Promise((f,F)=>{l(P,{timeout:5e3},(k,_)=>{k?F(k):f({stdout:_||""})})}),{stdout:b}=await A(`tmux capture-pane -p -e -S -30 -t '${a}'`),E=b.split(`
6
+ `);i.info("tmux capture result",{tmuxSession:a,totalLines:E.length,lastLines:E.slice(-15).map(P=>P.replace(/\x1B[^m]*m/g,"").trim()).filter(Boolean)});let y=(0,p.parseInteractivePrompt)(b);if(y&&y.options.length>0)c.options=y.options,c.submitMap=y.submitMap,c.instructions=this.buildPromptInstructions(y),i.info("Parsed dynamic options from tmux",{optionCount:y.options.length,kind:y.kind,options:y.options});else{this.suppressPromptOptionsUnavailable(e,s,"tmux parse returned no options");return}}catch(l){this.suppressPromptOptionsUnavailable(e,s,`tmux capture failed: ${l instanceof Error?l.message:String(l)}`);return}else{this.suppressPromptOptionsUnavailable(e,s,"no tmux session");return}let d=this.activeSessions.get(e);if(d&&c.submitMap){let l=d.promptGenerationToken;s&&l?.gen===s.gen?d.pendingSubmitMap=c.submitMap:i.warn("Interactive prompt async: stale async \u2014 token gen mismatch, skipping pendingSubmitMap write",{tokenAtEmit:s,currentToken:l,sessionId:e})}let m=r,x=c,R=!1;this.sessionKey&&(m=p.cryptoService.encryptContent(r,this.sessionKey),x={encrypted:p.cryptoService.encryptMetadata(x,this.sessionKey)},R=!0);let v=this.activeSessions.get(e)?.promptGenerationToken;if(s&&v?.gen!==s.gen){i.warn("Interactive prompt emit: stale token \u2014 newer INTERACTIVE_PROMPT replaced ours; skipping AppSync emit",{sessionId:e,tokenAtEmit:s,currentToken:v});return}await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.INTERACTIVE_PROMPT,source:t.source,content:m,metadata:x,promptId:t.prompt_id,timestamp:o,isEncrypted:R?!0:void 0}),i.info("Interactive prompt sent to AppSync with dynamic options",{sessionId:e})}buildQuestionWireData(e,t=[]){let r=(e.options||[]).map((c,g)=>{let u=typeof c=="string",h=u?c:c.label||"",d=u?"":c.description||"",m=u?"":c.preview||"",x={number:String(g+1),text:h};return d&&(x.description=d),m&&(x.preview=m),x});if(!e._isSubmit)for(let c of t)r.push({number:String(r.length+1),text:c.label});let n=Object.fromEntries(r.map(c=>[c.number,c.number])),s=(e.options||[]).length,o=t.findIndex(c=>c.label==="Type something"),a;if(e._isSubmit)a="Reply with 1 to submit your answers or 2 to cancel.";else if(e.multiSelect)a=`Reply with comma-separated numbers (e.g., 1,3) for "${e.header||e.question}"`;else if(o>=0){let c=String(s+o+1);a=`Reply with the number of your choice. For option ${c} (Type something), reply "${c}, your answer".`}else a="Reply with the number of your choice.";return{options:r,submitMap:n,instructions:a}}parseAskUserQuestionSynthTail(e){let t=(0,p.normalizeSnapshot)(e);if(!t)return[];let r=t.split(`
7
+ `).slice(-14),n=[],s=new Set,o=/^\s*(?:[›❯▸▶➜➤]\s*)?(?:\d+\.\s+)?(Type something|Chat about this)\.?\s*$/i;for(let a of r){let c=a.match(o);if(!c)continue;let u=c[1].toLowerCase()==="type something"?"Type something":"Chat about this";s.has(u)||(n.push({label:u}),s.add(u))}return n}suppressPromptOptionsUnavailable(e,t,r){i.warn("Interactive prompt: real options unavailable \u2014 suppressing mobile prompt (no fabricated options)",{sessionId:e,reason:r});let n=this.activeSessions.get(e);n&&t&&n.promptGenerationToken?.gen===t.gen&&this.clearPromptState(n)}buildPromptInstructions(e){return`Reply with ${e.options.map(r=>r.number).join(", ")}. Append a message to provide alternative instructions.`}parseInteractivePromptInput(e,t=3){return Pe(e,t)}async markEventExecuted(e){try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:p.DeliveryStatus.EXECUTED}),i.info("Event marked as EXECUTED",{eventId:e.eventId})}catch(t){i.warn("Failed to mark event as EXECUTED",{eventId:e.eventId,error:t})}}async sendPromptError(e,t){let r={error:!0},n=t,s=r,o=!1;this.sessionKey&&(n=p.cryptoService.encryptContent(t,this.sessionKey),s={encrypted:p.cryptoService.encryptMetadata(r,this.sessionKey)},o=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:n,metadata:s,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:o?!0:void 0})}async emitUserChoice(e,t){let r=t,n={source:"codevibe_v2_user_choice"},s=!1;this.sessionKey&&(r=p.cryptoService.encryptContent(t,this.sessionKey),n={encrypted:p.cryptoService.encryptMetadata({source:"codevibe_v2_user_choice"},this.sessionKey)},s=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.ASSISTANT_RESPONSE,source:p.EventSource.DESKTOP,content:r,metadata:n,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:s?!0:void 0})}async emitAnswerAck(e,t,r){let n={promptAnswered:!0,...r},s=t,o=n,a=!1;this.sessionKey&&(s=p.cryptoService.encryptContent(t,this.sessionKey),o={encrypted:p.cryptoService.encryptMetadata(n,this.sessionKey)},a=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:s,metadata:o,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:a?!0:void 0})}promoteFingerprintAndClearPromptState(e){e.activeAskUserQuestionFingerprint&&(e.completedAskUserQuestionFingerprints||(e.completedAskUserQuestionFingerprints=new Set),e.completedAskUserQuestionFingerprints.add(e.activeAskUserQuestionFingerprint)),this.clearPromptState(e)}clearPromptState(e){e.waitingForPromptResponse=!1,e.pendingPromptId=void 0,e.pendingSubmitMap=void 0,e.pendingQuestionsQueue=void 0,e.pendingCurrentQuestion=void 0,e.pendingSynthTail=void 0,e.hasReviewScreen=void 0,e.activeAskUserQuestionFingerprint=void 0,e.promptGenerationToken=void 0}async detectWalkerActive(e){let t=process.env.CODEVIBE_TMUX_SESSION;if(!t)return i.debug("detectWalkerActive: no CODEVIBE_TMUX_SESSION env \u2014 conservatively assuming walker active",{sessionId:e}),!0;try{let{exec:r}=await import("child_process"),n=l=>new Promise((A,b)=>{r(l,{timeout:3e3},(E,y)=>{E?b(E):A({stdout:y||""})})}),{stdout:s}=await n(`tmux capture-pane -p -e -S -30 -t '${t}'`),o=/\x1B(?:\[[?!0-9;]*[A-Za-z]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[()][A-B012])/g,a=s.split(`
8
+ `).map(l=>l.replace(o,"").trimEnd()),c=a.length-1;for(;c>=0&&a[c].trim()==="";)c-=1;if(c<0)return i.warn("detectWalkerActive: pane empty after ANSI strip \u2014 conservatively assuming walker active",{sessionId:e}),!0;let g=/(?:Esc to cancel|Enter to select|↑\/↓ to navigate|Tab to switch|shift\+tab|Chat about this|Type something|Notes: press|\(esc\)|\(shift\+tab\))/i,u=/^\s*(?:[›❯▸▶➜➤]\s*)?\d+\.\s+/,h=-1;for(let l=c;l>=0;l-=1)if(u.test(a[l])){h=l;break}let d=h>=0,m=-1;for(let l=c;l>=0;l-=1)if(g.test(a[l])){m=l;break}let x=m<0?1/0:c-m,R=m>=0&&x<=3,O=m>=0&&h>=0&&m>=h&&m-h<=5,v=d&&R&&O;return i.info("detectWalkerActive",{sessionId:e,walkerActive:v,hasParserBlock:d,chromeNearBottom:R,chromeFollowsBlock:O,chromeDistanceFromBottom:Number.isFinite(x)?x:-1,parserBlockEndsAt:h,lastNonBlank:c,lastChromeLineAt:m,lastLineSample:a[c]?.slice(0,80)??""}),v}catch(r){return i.warn("detectWalkerActive: tmux capture/parse failed \u2014 conservatively assuming walker active",{sessionId:e,error:r instanceof Error?r.message:String(r)}),!0}}getWalkerPosition(e){return e.pendingCurrentQuestion?._isSubmit?"on_synth":e.hasReviewScreen?(e.pendingQuestionsQueue?.length??0)>=2?"nq_mid":"nq_last":"q1"}async emitDegradedAUQNotification(e,t){try{let r=t,n={source:"codevibe_auq_degraded"},s=!1;this.sessionKey&&(r=p.cryptoService.encryptContent(t,this.sessionKey),n={encrypted:p.cryptoService.encryptMetadata({source:"codevibe_auq_degraded"},this.sessionKey)},s=!0),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.ASSISTANT_RESPONSE,source:p.EventSource.DESKTOP,content:r,metadata:n,isEncrypted:s?!0:void 0}),i.info("Emitted degraded-AUQ notification",{sessionId:e,textPreview:t.slice(0,60)})}catch(r){i.warn("emitDegradedAUQNotification failed",{sessionId:e,error:r instanceof Error?r.message:String(r)})}}async handleMobileReplyAsDismissAndPrompt(e,t,r,n){let s=await this.promptResponder.sendKey(e,"Escape");if(n())return!1;if(!s){try{await this.emitUserChoice(e,"AskUserQuestion dismissal failed (tmux unavailable)")}catch(a){i.warn("emitUserChoice on dismiss-ok1-failed failed",{sessionId:e,error:a instanceof Error?a.message:String(a)})}return!1}if(await new Promise(a=>setTimeout(a,200)),n())return!1;let o=await this.promptResponder.answerInteractivePrompt(e,r,{pressEnter:!0});if(n())return!1;if(!o){try{await this.emitUserChoice(e,"AskUserQuestion dismissed but text-send failed; please retry")}catch(a){i.warn("emitUserChoice on dismiss-ok2-failed failed",{sessionId:e,error:a instanceof Error?a.message:String(a)})}return n()||this.promoteFingerprintAndClearPromptState(t),!1}try{await this.emitUserChoice(e,"\u2192 AskUserQuestion dismissed, sending your reply as a new prompt")}catch(a){i.warn("emitUserChoice on dismiss-success failed \u2014 continuing to promote+clear",{sessionId:e,error:a instanceof Error?a.message:String(a)})}return n()?(i.warn("handleMobileReplyAsDismissAndPrompt: aborted post-emitUserChoice (token rotated); leaving session state for new prompt",{sessionId:e}),!1):(this.promoteFingerprintAndClearPromptState(t),!0)}async handleOptionWithFollowupOnLastQ(e,t,r,n,s,o){let a=await this.promptResponder.answerInteractivePrompt(e,r,{pressEnter:!1});if(o())return!1;if(!a){try{await this.emitUserChoice(e,"Failed to commit Q[N] (tmux unavailable); your reply was not sent")}catch(u){i.warn("emitUserChoice on lastQ-ok1-failed failed",{sessionId:e,error:u instanceof Error?u.message:String(u)})}return!1}if(await new Promise(u=>setTimeout(u,200)),o())return!1;let c=await this.promptResponder.answerInteractivePrompt(e,"1",{pressEnter:!1});if(o())return!1;if(!c){try{await this.emitUserChoice(e,"Q[N] committed but Submit failed (tmux unavailable); please retry on desktop")}catch(u){i.warn("emitUserChoice on lastQ-ok2-failed failed",{sessionId:e,error:u instanceof Error?u.message:String(u)})}return o()||this.promoteFingerprintAndClearPromptState(t),!1}if(await new Promise(u=>setTimeout(u,1500)),o())return!1;let g=await this.promptResponder.answerInteractivePrompt(e,s,{pressEnter:!0});if(o())return!1;g||i.warn("handleOptionWithFollowupOnLastQ: followup text send failed",{sessionId:e});try{await this.emitUserChoice(e,`\u2192 ${n} + sending your reply as a new prompt`)}catch(u){i.warn("emitUserChoice on lastQ-success failed \u2014 continuing to promote+clear",{sessionId:e,error:u instanceof Error?u.message:String(u)})}return o()?(i.warn("handleOptionWithFollowupOnLastQ: aborted post-emitUserChoice (token rotated); leaving session state for new prompt",{sessionId:e}),!1):(this.promoteFingerprintAndClearPromptState(t),!0)}computeAskUserQuestionFingerprint(e){if(!(!e||typeof e!="object"))try{let t=this.stringifyCanonical(e);return(0,G.createHash)("sha256").update(t).digest("hex")}catch(t){i.warn("Failed to fingerprint AskUserQuestion questions",{error:t instanceof Error?t.message:String(t)});return}}stringifyCanonical(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(r=>this.stringifyCanonical(r)).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+this.stringifyCanonical(e[r])).join(",")+"}"}async markEventExecutedIdempotent(e,t){e.processedEventIds||(e.processedEventIds=new Set),e.processedEventIds.add(t.eventId);try{await this.markEventExecuted(t)}catch(r){i.warn("[walker] markEventExecuted threw \u2014 relying on processedEventIds set for dedup",{sessionId:t.sessionId,eventId:t.eventId,error:String(r)})}}isSessionLimitExceeded(e){return this.getErrorMessage(e).includes("SESSION_LIMIT_EXCEEDED")}isUsageLimitExceeded(e){let t=this.getErrorMessage(e);return t.includes("MESSAGE_LIMIT_EXCEEDED")||t.includes("IMAGE_LIMIT_EXCEEDED")}getErrorMessage(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e;if(t.errors&&Array.isArray(t.errors))return t.errors.map(r=>r.message||"").join(" ");if(typeof t.message=="string")return t.message}return String(e)}displaySubscriptionLimitError(e,t){let r=this.getErrorMessage(e),n="",s=r.match(/for your (\w+) plan/i);s&&(n=` (${s[1]} tier)`);let o="",a=r.match(/of (\d+)/);switch(a&&(o=` [Limit: ${a[1]}]`),console.log(`
9
9
  `+"=".repeat(60)),console.log("\u26A0\uFE0F SUBSCRIPTION LIMIT REACHED"),console.log("=".repeat(60)),t){case"session":console.log(`You have reached the maximum number of active sessions${n}.`),console.log(`${o}`),console.log(`
10
10
  To continue, please:`),console.log(" \u2022 Close an existing Claude Code session, or"),console.log(" \u2022 Upgrade your subscription in the CodeVibe iOS app");break;case"message":console.log(`You have reached your monthly message limit${n}.`),console.log(`${o}`),console.log(`
11
11
  To continue, please:`),console.log(" \u2022 Wait until your usage resets next month, or"),console.log(" \u2022 Upgrade your subscription in the CodeVibe iOS app");break;case"image":console.log(`You have reached your monthly image attachment limit${n}.`),console.log(`${o}`),console.log(`
12
12
  To continue, please:`),console.log(" \u2022 Wait until your usage resets next month, or"),console.log(" \u2022 Upgrade your subscription in the CodeVibe iOS app");break}console.log(`
13
13
  Note: You can still use Claude Code normally from your desktop.`),console.log("This limit only affects syncing with the mobile app."),console.log("=".repeat(60)+`
14
- `),i.error("Subscription limit exceeded",{limitType:t,errorMessage:r})}async downloadAttachment(e,t,r){try{let n=e.isEncrypted??r??!1;i.info("Downloading attachment - START",{id:e.id,type:e.type,filename:e.filename,s3Key:e.s3Key,attachmentIsEncrypted:e.isEncrypted,eventIsEncrypted:r,shouldDecrypt:n,hasSessionKey:!!this.sessionKey});let{downloadUrl:s}=await this.appSyncClient.getAttachmentDownloadUrl(e.s3Key),o=await fetch(s);if(!o.ok)throw new Error(`Failed to download attachment: ${o.status} ${o.statusText}`);let a=Buffer.from(await o.arrayBuffer());if(i.info("Attachment downloaded",{id:e.id,downloadedSize:a.length,first20Bytes:a.slice(0,20).toString("hex")}),i.info("Checking decryption conditions",{id:e.id,shouldDecrypt:n,hasSessionKey:!!this.sessionKey,willDecrypt:!!(n&&this.sessionKey)}),n&&this.sessionKey)try{i.info("Decrypting attachment",{id:e.id,encryptedSize:a.length}),a=p.cryptoService.decryptData(a,this.sessionKey),i.info("Attachment decrypted successfully",{id:e.id,decryptedSize:a.length,first20Bytes:a.slice(0,20).toString("hex")})}catch(m){throw i.error("Failed to decrypt attachment:",{id:e.id,error:m}),new Error("Failed to decrypt attachment")}else n&&!this.sessionKey?i.warn("Cannot decrypt attachment - no session key available",{id:e.id}):i.info("Skipping decryption - attachment not encrypted or no session key",{id:e.id,shouldDecrypt:n,hasSessionKey:!!this.sessionKey});let c=V.join(ee.tmpdir(),"codevibe-claude",t);D.existsSync(c)||D.mkdirSync(c,{recursive:!0});let g="",u=e.filename;if(n&&e.filename&&this.sessionKey)try{u=p.cryptoService.decryptContent(e.filename,this.sessionKey)}catch{u=e.filename}if(u){let m=V.extname(u);m&&(g=m)}g||(g={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[e.type]||".bin");let h=`attachment-${e.id}${g}`,d=V.join(c,h);return D.writeFileSync(d,a),i.info("Attachment saved to temp file",{id:e.id,filePath:d,size:a.length,wasDecrypted:n&&!!this.sessionKey}),d}catch(n){return i.error("Failed to download attachment:",{id:e.id,error:n}),null}}async executeMobilePrompt(e,t){let r=t.content||"",n=t.attachments||[];i.info("Executing mobile prompt via tmux",{sessionId:e,promptLength:r.length,attachmentCount:n.length});let s=[];if(n.length>0){i.info("Downloading attachments for prompt",{count:n.length});for(let o of n){let a=await this.downloadAttachment(o,e,t.isEncrypted);a&&s.push(a)}if(s.length>0){let o=s.map(a=>`[Attached file: ${a}]`).join(`
14
+ `),i.error("Subscription limit exceeded",{limitType:t,errorMessage:r})}async downloadAttachment(e,t,r){try{let n=e.isEncrypted??r??!1;i.info("Downloading attachment - START",{id:e.id,type:e.type,filename:e.filename,s3Key:e.s3Key,attachmentIsEncrypted:e.isEncrypted,eventIsEncrypted:r,shouldDecrypt:n,hasSessionKey:!!this.sessionKey});let{downloadUrl:s}=await this.appSyncClient.getAttachmentDownloadUrl(e.s3Key),o=await fetch(s);if(!o.ok)throw new Error(`Failed to download attachment: ${o.status} ${o.statusText}`);let a=Buffer.from(await o.arrayBuffer());if(i.info("Attachment downloaded",{id:e.id,downloadedSize:a.length,first20Bytes:a.slice(0,20).toString("hex")}),i.info("Checking decryption conditions",{id:e.id,shouldDecrypt:n,hasSessionKey:!!this.sessionKey,willDecrypt:!!(n&&this.sessionKey)}),n&&this.sessionKey)try{i.info("Decrypting attachment",{id:e.id,encryptedSize:a.length}),a=p.cryptoService.decryptData(a,this.sessionKey),i.info("Attachment decrypted successfully",{id:e.id,decryptedSize:a.length,first20Bytes:a.slice(0,20).toString("hex")})}catch(m){throw i.error("Failed to decrypt attachment:",{id:e.id,error:m}),new Error("Failed to decrypt attachment")}else n&&!this.sessionKey?i.warn("Cannot decrypt attachment - no session key available",{id:e.id}):i.info("Skipping decryption - attachment not encrypted or no session key",{id:e.id,shouldDecrypt:n,hasSessionKey:!!this.sessionKey});let c=$.join(j.tmpdir(),"codevibe-claude",t);U.existsSync(c)||U.mkdirSync(c,{recursive:!0});let g="",u=e.filename;if(n&&e.filename&&this.sessionKey)try{u=p.cryptoService.decryptContent(e.filename,this.sessionKey)}catch{u=e.filename}if(u){let m=$.extname(u);m&&(g=m)}g||(g={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[e.type]||".bin");let h=`attachment-${e.id}${g}`,d=$.join(c,h);return U.writeFileSync(d,a),i.info("Attachment saved to temp file",{id:e.id,filePath:d,size:a.length,wasDecrypted:n&&!!this.sessionKey}),d}catch(n){return i.error("Failed to download attachment:",{id:e.id,error:n}),null}}async executeMobilePrompt(e,t){let r=t.content||"",n=t.attachments||[];i.info("Executing mobile prompt via tmux",{sessionId:e,promptLength:r.length,attachmentCount:n.length});let s=[];if(n.length>0){i.info("Downloading attachments for prompt",{count:n.length});for(let o of n){let a=await this.downloadAttachment(o,e,t.isEncrypted);a&&s.push(a)}if(s.length>0){let o=s.map(a=>`[Attached file: ${a}]`).join(`
15
15
  `);r?r=`${o}
16
16
 
17
17
  ${r}`:r=`${o}
18
18
 
19
- Please analyze the attached file(s).`,i.info("Prompt updated with attachment paths",{attachmentCount:s.length,newPromptLength:r.length})}}this.trackMobilePrompt(e,r);try{if(await this.promptResponder.answerInteractivePrompt(e,r)){try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:p.DeliveryStatus.EXECUTED}),i.info("Event marked as EXECUTED",{eventId:t.eventId})}catch(c){i.warn("Failed to mark event as EXECUTED",{eventId:t.eventId,error:c})}i.info("Mobile prompt sent successfully",{sessionId:e});let a=s.length>0?`Prompt with ${s.length} attachment(s) sent to Claude Code`:`Prompt "${r.substring(0,50)}${r.length>50?"...":""}" sent to Claude Code`;await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:a,metadata:{mobilePrompt:!0,attachmentCount:s.length},timestamp:(0,p.prepareEventTimestamp)({orderingKey:e})})}else i.error("Failed to send mobile prompt",{sessionId:e}),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:"Failed to send prompt to Claude Code",metadata:{error:!0},timestamp:(0,p.prepareEventTimestamp)({orderingKey:e})})}catch(o){i.error("Failed to execute mobile prompt:",o)}}};async function Qe(){let w=process.argv[2]||process.env.CLAUDE_SESSION_ID;w?i.info(`Starting MCP server for session: ${w}`):i.info("Starting MCP server without initial session ID (will be set on SessionStart)");let e=new te(w);try{await e.start();let t=e.getPort();console.log(`PORT=${t}`);let r=!1,n=async s=>{if(r){i.info("Shutdown already in progress, ignoring additional signal");return}r=!0,i.info(`Received ${s} signal, stopping server...`);try{await e.stop(),i.info("Graceful shutdown completed"),process.exit(0)}catch(o){i.error("Error during shutdown:",o),process.exit(1)}};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM")),process.on("SIGHUP",()=>n("SIGHUP")),process.on("uncaughtException",async s=>{i.error("Uncaught exception:",s),await n("uncaughtException")}),process.on("unhandledRejection",async s=>{i.error("Unhandled rejection:",s),await n("unhandledRejection")})}catch(t){i.error("Failed to start MCP Server:",t),process.exit(1)}}function Pe(w,e=3){let t=w.trim(),r=t.match(/^(\d+)$/);if(r){let s=parseInt(r[1]);if(s>=1&&s<=e)return{action:"select_option",option:r[1]}}let n=t.match(/^(\d+)[,.:;\-\s\n]+(.+)$/s);if(n){let s=parseInt(n[1]);if(s>=1&&s<=e)return{action:"option_with_followup",option:n[1],followUpText:n[2].trim()}}return{action:"send_as_response"}}process.env.JEST_WORKER_ID||Qe().catch(w=>{i.error("Unhandled error in main:",w),process.exit(1)});0&&(module.exports={McpServer,parseInteractivePromptInput});
19
+ Please analyze the attached file(s).`,i.info("Prompt updated with attachment paths",{attachmentCount:s.length,newPromptLength:r.length})}}this.trackMobilePrompt(e,r);try{if(await this.promptResponder.answerInteractivePrompt(e,r)){try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:p.DeliveryStatus.EXECUTED}),i.info("Event marked as EXECUTED",{eventId:t.eventId})}catch(c){i.warn("Failed to mark event as EXECUTED",{eventId:t.eventId,error:c})}i.info("Mobile prompt sent successfully",{sessionId:e});let a=s.length>0?`Prompt with ${s.length} attachment(s) sent to Claude Code`:`Prompt "${r.substring(0,50)}${r.length>50?"...":""}" sent to Claude Code`;await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:a,metadata:{mobilePrompt:!0,attachmentCount:s.length},timestamp:(0,p.prepareEventTimestamp)({orderingKey:e})})}else i.error("Failed to send mobile prompt",{sessionId:e}),await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.NOTIFICATION,source:p.EventSource.DESKTOP,content:"Failed to send prompt to Claude Code",metadata:{error:!0},timestamp:(0,p.prepareEventTimestamp)({orderingKey:e})})}catch(o){i.error("Failed to execute mobile prompt:",o)}}};async function De(){let w=process.argv[2]||process.env.CLAUDE_SESSION_ID;w?i.info(`Starting MCP server for session: ${w}`):i.info("Starting MCP server without initial session ID (will be set on SessionStart)");let e=new te(w);try{await e.start();let t=e.getPort();console.log(`PORT=${t}`);let r=!1,n=async s=>{if(r){i.info("Shutdown already in progress, ignoring additional signal");return}r=!0,i.info(`Received ${s} signal, stopping server...`);try{await e.stop(),i.info("Graceful shutdown completed"),process.exit(0)}catch(o){i.error("Error during shutdown:",o),process.exit(1)}};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM")),process.on("SIGHUP",()=>n("SIGHUP")),process.on("uncaughtException",async s=>{i.error("Uncaught exception:",s),await n("uncaughtException")}),process.on("unhandledRejection",async s=>{i.error("Unhandled rejection:",s),await n("unhandledRejection")})}catch(t){i.error("Failed to start MCP Server:",t),process.exit(1)}}function Pe(w,e=3){let t=w.trim(),r=t.match(/^(\d+)$/);if(r){let s=parseInt(r[1]);if(s>=1&&s<=e)return{action:"select_option",option:r[1]}}let n=t.match(/^(\d+)[,.:;\-\s\n]+(.+)$/s);if(n){let s=parseInt(n[1]);if(s>=1&&s<=e)return{action:"option_with_followup",option:n[1],followUpText:n[2].trim()}}return{action:"send_as_response"}}process.env.JEST_WORKER_ID||De().catch(w=>{i.error("Unhandled error in main:",w),process.exit(1)});0&&(module.exports={McpServer,parseInteractivePromptInput});
@@ -0,0 +1,28 @@
1
+ /** Exposed for the single log line in createEvent. */
2
+ export declare const CLIENT_THROTTLE_EVENTS_PER_WINDOW: number;
3
+ interface RateWindow {
4
+ windowStartMs: number;
5
+ count: number;
6
+ toolUseAboveThreshold: number;
7
+ suppressed: number;
8
+ logged: boolean;
9
+ }
10
+ /**
11
+ * Decide whether this outbound event should be suppressed (not sent).
12
+ * Deterministic given (sessionId, type, now) and prior counter state.
13
+ * Exported for unit tests; resetThrottleState() clears the module map.
14
+ */
15
+ export declare function shouldSuppressEvent(sessionId: string, type: string, now: number): boolean;
16
+ /**
17
+ * Returns the session's rate window exactly once per window — the first time the
18
+ * throttle engages — for a single log line; later calls in the same window
19
+ * return undefined. Keeps logging out of the hot path.
20
+ */
21
+ export declare function consumeThrottleLogOnce(sessionId: string): RateWindow | undefined;
22
+ /** Test-only: clears the per-process rate map. */
23
+ export declare function resetThrottleState(): void;
24
+ /** Test-only: current size of the per-process rate map (eviction-bound check). */
25
+ export declare function throttleMapSize(): number;
26
+ /** Test-only: whether a session is currently tracked (eviction assertions). */
27
+ export declare function throttleMapHas(sessionId: string): boolean;
28
+ export {};
@@ -1,11 +1,11 @@
1
- "use strict";var jt=Object.create;var ke=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var _=(n,e)=>()=>(n&&(e=n(n=0)),e);var nt=(n,e)=>{for(var t in e)ke(n,t,{get:e[t],enumerable:!0})},it=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jt(e))!Yt.call(n,i)&&i!==t&&ke(n,i,{get:()=>e[i],enumerable:!(r=Gt(e,i))||r.enumerable});return n};var v=(n,e,t)=>(t=n!=null?jt(zt(n)):{},it(e||!n||!n.__esModule?ke(t,"default",{value:n,enumerable:!0}):t,n)),Xt=n=>it(ke({},"__esModule",{value:!0}),n);function Zt(n,e){if(e instanceof Error){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);for(let r of Object.keys(e))r in t||(t[r]=e[r]);return t}return e}function Ke(n){return new H(n)}var Q,be,ot,st,H,c,at=_(()=>{"use strict";Q=v(require("fs")),be=v(require("path")),ot=v(require("os")),st={debug:0,info:1,warn:2,error:3};H=class{constructor(e){this.name=e.name,this.logFile=e.logFile,this.level=e.level||"info",this.enableConsole=e.console??!1,this.logFile&&this.ensureLogDir()}ensureLogDir(){if(this.logFile){let e=be.dirname(this.logFile);Q.existsSync(e)||Q.mkdirSync(e,{recursive:!0})}}shouldLog(e){return st[e]>=st[this.level]}formatMessage(e,t,r){let i=new Date().toISOString(),s=e.toUpperCase().padEnd(5),o=`[${i}] [${s}] [${this.name}] ${t}`;return r!==void 0&&(r instanceof Error?(o+=` ${r.name}: ${r.message}`,r.stack&&(o+=`
2
- ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,Zt)}`:o+=` ${r}`),o}log(e,t,r){if(!this.shouldLog(e))return;let i=this.formatMessage(e,t,r);if(this.logFile)try{Q.appendFileSync(this.logFile,i+`
3
- `)}catch{}if(this.enableConsole)switch(e){case"error":console.error(i);break;case"warn":console.warn(i);break;default:console.log(i)}}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}};c=new H({name:"codevibe-core",logFile:be.join(ot.tmpdir(),"codevibe-core.log"),level:"info"})});var q=_(()=>{"use strict";at()});function ir(){let n=typeof process.getuid=="function"?process.getuid():0;return Pe.createHash("sha256").update(`${dt.hostname()}-${n}`).digest("hex").substring(0,36)}function K(){return{platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production"}}async function P(n,e){try{let t=JSON.stringify({client_id:ir(),events:[{name:n,params:e}]});await new Promise(r=>{let i=ct.request({hostname:tr,path:rr,method:"POST",headers:{"Content-Type":"application/json"}},()=>r());i.on("error",()=>r()),i.write(t),i.end(),setTimeout(r,2e3)})}catch{}}async function de(n){await P("auth_completed",{...K(),user_id:n})}async function I(n,e){let t={...K(),reason:n,stage:e?.stage??nr[n]};if(typeof e?.httpStatus=="number"&&(t.http_status=e.httpStatus),e?.errorFragment){let{homedir:r}=await import("os"),i=e.errorFragment.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"").replace(/\\/g,"/").replace(/[\n\r\t"]/g," ").replace(/[^\x20-\x7E]/g,"").trim(),s=[process.env.HOME,process.env.USERPROFILE,(()=>{try{return r()}catch{return}})()].filter(d=>typeof d=="string"&&d.length>0).map(d=>d.replace(/\\/g,"/"));for(let d of s){let l=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(l,"g"),"~")}i=i.replace(/\/Users\/[^/ ]+/g,"/Users/<user>").replace(/\/home\/[^/ ]+/g,"/home/<user>").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"<email>");let o=i.substring(0,100),a=i.substring(100,200);o&&(t.error_fragment=o),a&&(t.error_fragment_2=a)}await P("auth_failed",t)}async function lt(n){await P("keychain_file_fallback",{...K(),reason:n})}function x(n,e){try{Object.defineProperty(n,Oe,{value:!0,enumerable:!1,configurable:!0,writable:!1}),Object.defineProperty(n,pt,{value:e,enumerable:!1,configurable:!0,writable:!1})}catch{}return n}function le(n){return!!(n&&typeof n=="object"&&n[Oe])}function Ne(n){if(n&&typeof n=="object"&&n[Oe]){let e=n[pt];if(typeof e=="string")return e}}function ee(n){return n<=0?"0":n===1?"1":n<=5?"2-5":"6+"}function we(n){return Pe.createHash("sha256").update(n).digest("hex").slice(0,8)}async function ut(n){return P("session_encryption_device_skipped",{...K(),...n})}async function ht(n){return P("session_encryption_partial_success",{...K(),...n})}async function yt(n){return P("session_encryption_catch_up_grant",{...K(),...n})}async function gt(n){return P("session_encryption_self_rekey_request",{...K(),...n})}async function ft(n){return P("session_encryption_self_rekey_success",{...K(),...n})}async function mt(n){return P("session_encryption_self_rekey_timeout",{...K(),...n})}var Pe,ct,dt,Qt,er,tr,rr,nr,Oe,pt,te=_(()=>{"use strict";Pe=v(require("crypto")),ct=v(require("https")),dt=v(require("os")),Qt="G-GS74YEQTB8",er="lAfOF6OxRzSQ-NsLBRjhAg",tr="www.google-analytics.com",rr=`/mp/collect?measurement_id=${Qt}&api_secret=${er}`,nr={port_in_use:"server_start",port_range_exhausted:"server_start",server_listen_failed:"server_start",browser_open_failed:"browser_open",login_timeout:"awaiting_callback",cognito_rejected:"awaiting_callback",state_mismatch:"awaiting_callback",no_authorization_code:"awaiting_callback",token_exchange_failed:"exchanging_code",token_exchange_network_error:"exchanging_code",keychain_write_failed:"storing_tokens",user_aborted:"unknown",unknown:"unknown"};Oe=Symbol.for("codevibe.auth.beaconed"),pt=Symbol.for("codevibe.auth.failureReason")});function bt(n){for(let e of n)try{process.stderr.write(e+`
4
- `)}catch{}}function $e(){Ue=V.join(ue.homedir(),".codevibe");try{w.mkdirSync(Ue,{recursive:!0,mode:448})}catch{}L="file"}function vt(){if(process.platform!=="linux"||process.env.DISPLAY||process.env.WAYLAND_DISPLAY||process.env.DBUS_SESSION_BUS_ADDRESS)return!1;try{let n=process.env.XDG_RUNTIME_DIR;if(n&&w.existsSync(V.join(n,"bus")))return!1;let e=typeof process.getuid=="function"?process.getuid():void 0;if(e!==void 0&&w.existsSync(`/run/user/${e}/bus`))return!1}catch{}return!0}function wt(){return V.join(ue.homedir(),".codevibe",".keyring-used")}function sr(){if(process.platform==="linux")try{w.mkdirSync(V.join(ue.homedir(),".codevibe"),{recursive:!0,mode:448}),w.writeFileSync(wt(),`keytar
5
- `,{mode:384})}catch{}}function or(){try{return w.existsSync(wt())}catch{return!1}}function ar(){try{let n=V.join(ue.homedir(),".codevibe");return w.readdirSync(n).some(e=>e.endsWith(".json"))}catch{return!1}}function cr(n){bt(["","\u26A0 CodeVibe: no OS keyring service detected on this machine.","\u26A0 Using file-based credential storage at ~/.codevibe/ instead","\u26A0 (directory 0700, files 0600 \u2014 trust level equivalent to ~/.ssh/id_rsa,","\u26A0 weaker than an OS keyring). This is expected on headless / SSH / Docker / CI.","\u26A0 For the OS keyring, run inside a desktop session with a keyring daemon","\u26A0 (Linux) or on macOS / Windows.",""]),c.warn(`[keychain-backend] No OS keyring service (${n}); auto-selected file storage at ~/.codevibe (headless fallback)`),kt=!0,$e(),lt(n)}function dr(){c.info("[keychain-backend] OS keyring is reachable, but durable file credentials already exist at ~/.codevibe; continuing on the file backend to avoid forking the device identity"),$e()}function St(n){if(or()){Ee=new pe(["CodeVibe used the OS keyring on this machine before, but it is not","reachable in this session (no desktop session / no D-Bus session bus \u2014","e.g. SSH without a forwarded bus).","","Auto-switching to file storage here would create a SEPARATE credential","identity and break your existing encrypted sessions, so we stop instead.","","Options:"," 1. Run inside the desktop session where the keyring is unlocked, or"," 2. Explicitly switch THIS machine to file-based storage (a new, separate"," credential identity):"," export CODEVIBE_ALLOW_FILE_KEYCHAIN=1"].join(`
6
- `)),c.warn("[keychain-backend] OS keyring used here before but unreachable now; refusing silent file fallback (set CODEVIBE_ALLOW_FILE_KEYCHAIN=1 to override)");return}cr(n)}function Hr(){return kt}function qr(){return L}function lr(){if(L!==null||Ee!==null)return;let optedIn=process.env.CODEVIBE_ALLOW_FILE_KEYCHAIN==="1";if(optedIn){bt(["","\u26A0 CodeVibe: file-based credential storage selected (CODEVIBE_ALLOW_FILE_KEYCHAIN=1).","\u26A0 Location: ~/.codevibe/ (directory 0700, files 0600)","\u26A0 Trust level: equivalent to ~/.ssh/id_rsa \u2014 weaker than OS keyring.","\u26A0 To use the OS keyring instead, unset CODEVIBE_ALLOW_FILE_KEYCHAIN and","\u26A0 install libsecret-1-0 + a running keyring daemon (Linux) or use the","\u26A0 native Keychain (macOS) / Credential Manager (Windows).",""]),c.warn("[keychain-backend] Using file-based storage at ~/.codevibe (CODEVIBE_ALLOW_FILE_KEYCHAIN=1 explicit opt-in)"),$e();return}if(ar()){dr();return}let keytarLoadError=null;try{let nodeRequire=eval("require");R=nodeRequire("keytar")}catch(n){keytarLoadError=n instanceof Error?n.message:String(n),R=null}if(R){if(vt()){R=null,St("no_keyring_service");return}L="keytar",c.info("[keychain-backend] Using keytar (OS-native keyring)"),sr();return}if(vt()){St("keytar_load_failed");return}Ee=new pe(["CodeVibe could not load the OS-native keyring (keytar).",`Reason: ${keytarLoadError??"unknown"}`,"","Options to fix this:"," 1. (Linux) Install libsecret and a keyring daemon:"," sudo apt install libsecret-1-0 gnome-keyring"," Then unlock the keyring for your user session.",""," 2. (Headless / CI / Docker) Opt in to file-based credential"," storage at ~/.codevibe/ (0600 files). This is equivalent"," in trust to ~/.ssh/id_rsa \u2014 not the OS keyring:"," export CODEVIBE_ALLOW_FILE_KEYCHAIN=1"].join(`
7
- `))}function pr(n){return n.replace(/[^a-zA-Z0-9._-]/g,"_")}function Et(n){return V.join(Ue,`${pr(n)}.json`)}function Le(n){try{let e=w.readFileSync(Et(n),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function It(n,e){let t=Et(n);w.writeFileSync(t,JSON.stringify(e,null,2),{mode:384});try{w.chmodSync(t,384)}catch{}}function Me(){if(lr(),L===null)throw Ee??new pe("Keychain backend not initialized")}async function We(n,e){return Me(),L==="keytar"&&R?R.getPassword(n,e):Le(n)[e]??null}async function Be(n,e,t){if(Me(),L==="keytar"&&R){await R.setPassword(n,e,t);return}let r=Le(n);r[e]=t,It(n,r)}async function Fe(n,e){if(Me(),L==="keytar"&&R)return R.deletePassword(n,e);let t=Le(n);return e in t?(delete t[e],It(n,t),!0):!1}var ue,V,w,pe,L,R,Ue,Ee,kt,At=_(()=>{"use strict";ue=v(require("os")),V=v(require("path")),w=v(require("fs"));q();te();pe=class extends Error{constructor(e){super(e),this.name="KeychainBackendUnavailableError"}},L=null,R=null,Ue="",Ee=null,kt=!1});var C,O,He,hr,re,A,Tt=_(()=>{"use strict";C=v(require("crypto")),O=class extends Error{constructor(e){super(e),this.name="CryptoError"}},He=1,hr="CodeVibe E2E v1",re=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}generateKeyPair(){let e=C.createECDH("prime256v1");e.generateKeys();let r=e.getPublicKey().subarray(1).toString("base64");return{privateKey:e.getPrivateKey().toString("base64"),publicKey:r}}generateSessionKey(){return C.randomBytes(32).toString("base64")}deriveSharedKey(e,t){try{let r=C.createECDH("prime256v1"),i=Buffer.from(e,"base64");r.setPrivateKey(i);let s=Buffer.from(t,"base64"),o=s.length===65&&s[0]===4?s:Buffer.concat([Buffer.from([4]),s]),a=r.computeSecret(o),d=C.hkdfSync("sha256",a,Buffer.alloc(0),Buffer.from(hr,"utf8"),32);return Buffer.from(d)}catch(r){throw new O(`Failed to derive shared key: ${r}`)}}encryptSessionKey(e,t){let r=this.generateKeyPair(),i=this.deriveSharedKey(r.privateKey,t),s=Buffer.from(e,"base64");return{encryptedKey:this.encrypt(s,i).toString("base64"),ephemeralPublicKey:r.publicKey}}decryptSessionKey(e,t){let r=this.deriveSharedKey(t,e.ephemeralPublicKey),i=Buffer.from(e.encryptedKey,"base64");return this.decrypt(i,r).toString("base64")}encryptContent(e,t){let r=Buffer.from(t,"base64"),i=Buffer.from(e,"utf8");return this.encrypt(i,r).toString("base64")}decryptContent(e,t){let r=Buffer.from(t,"base64"),i=Buffer.from(e,"base64");return this.decrypt(i,r).toString("utf8")}encryptMetadata(e,t){let r=JSON.stringify(e);return this.encryptContent(r,t)}decryptMetadata(e,t){let r=this.decryptContent(e,t);return JSON.parse(r)}encryptData(e,t){let r=Buffer.from(t,"base64");return this.encrypt(e,r)}decryptData(e,t){let r=Buffer.from(t,"base64");return this.decrypt(e,r)}encrypt(e,t){let r=C.randomBytes(12),i=C.createCipheriv("aes-256-gcm",t,r),s=Buffer.concat([i.update(e),i.final()]),o=i.getAuthTag();return Buffer.concat([r,s,o])}decrypt(e,t){let r=e.subarray(0,12),i=e.subarray(e.length-16),s=e.subarray(12,e.length-16),o=C.createDecipheriv("aes-256-gcm",t,r);o.setAuthTag(i);try{return Buffer.concat([o.update(s),o.final()])}catch{throw new O("Decryption failed: Invalid ciphertext or authentication tag")}}serializePrivateKey(e){return e}deserializePrivateKey(e){return e}},A=re.getInstance()});var he=_(()=>{"use strict";Tt()});function T(){let n=process.env.ENVIRONMENT;return n==="development"||n==="production"?n:"production"}function Ae(n){let e=n||T();return Ie={...j[e],aws:{...j[e].aws,region:process.env.AWS_REGION||j[e].aws.region,appsyncUrl:process.env.APPSYNC_URL||j[e].aws.appsyncUrl,cognitoUserPoolId:process.env.COGNITO_USER_POOL_ID||j[e].aws.cognitoUserPoolId,cognitoClientId:process.env.COGNITO_CLIENT_ID||j[e].aws.cognitoClientId,cognitoDomain:process.env.COGNITO_DOMAIN||j[e].aws.cognitoDomain}},xt=!0,Ie}function b(){return(!xt||!Ie)&&Ae(),Ie}var ye,ge,j,Ie,xt,Ct=_(()=>{"use strict";ye=v(require("os")),ge=v(require("path")),j={development:{environment:"development",aws:{region:"us-east-1",appsyncUrl:"https://api-dev.codevibe.quantiya.ai/graphql",cognitoUserPoolId:"us-east-1_yVwWDPvvJ",cognitoClientId:"e9r5apv6v5uui3l928r2ris0r",cognitoDomain:"codevibe-development.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:ge.default.join(ye.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:ge.default.join(ye.default.homedir(),".gemini","tmp")}},production:{environment:"production",aws:{region:"us-east-1",appsyncUrl:"https://api.codevibe.quantiya.ai/graphql",cognitoUserPoolId:"us-east-1_mNRO0j5og",cognitoClientId:"5p04dbc9ojptc5r8n7605fg78f",cognitoDomain:"codevibe-production.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:ge.default.join(ye.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:ge.default.join(ye.default.homedir(),".gemini","tmp")}}},Ie=null,xt=!1});var ne=_(()=>{"use strict";Ct()});var Te,Dt,N,qe,yr,G,y,_t=_(()=>{"use strict";Te=v(require("os")),Dt=require("uuid");At();he();ne();q();N=class extends Error{constructor(e){super(e),this.name="KeychainError"}},qe="device-identity",yr="tokens-",G=class n{constructor(){this.deviceIdentity=null;this.sessionKeyCache=new Map;this.isRegistered=!1;this._serviceName=null}get serviceName(){return this._serviceName||(this._serviceName=b().keychain.serviceName),this._serviceName}static getInstance(){return n.instance||(n.instance=new n),n.instance}async getDeviceIdentity(){if(this.deviceIdentity)return this.deviceIdentity;let e=await We(this.serviceName,qe);return e?(this.deviceIdentity=JSON.parse(e),c.info(`[KeychainManager] Loaded device identity: ${this.deviceIdentity.deviceId}`),this.deviceIdentity):null}async setDeviceIdentity(e){try{await Be(this.serviceName,qe,JSON.stringify(e)),this.deviceIdentity=e,c.info(`[KeychainManager] Saved device identity: ${e.deviceId}`)}catch(t){throw c.error(`[KeychainManager] Failed to save device identity: ${t}`),new N(`Failed to save device identity: ${t}`)}}async getOrCreateDeviceIdentity(){let e=await this.getDeviceIdentity();if(e)return e;let t=A.generateKeyPair();return e={deviceId:(0,Dt.v4)().toUpperCase(),privateKey:t.privateKey,publicKey:t.publicKey,createdAt:new Date().toISOString()},await this.setDeviceIdentity(e),c.info(`[KeychainManager] Generated new device identity: ${e.deviceId}`),e}async getDeviceId(){return(await this.getOrCreateDeviceIdentity()).deviceId}async getDevicePublicKey(){return(await this.getOrCreateDeviceIdentity()).publicKey}async getDevicePrivateKey(){return(await this.getOrCreateDeviceIdentity()).privateKey}async hasDeviceIdentity(){return await this.getDeviceIdentity()!==null}async deleteDeviceIdentity(){try{await Fe(this.serviceName,qe),this.deviceIdentity=null,this.sessionKeyCache.clear(),this.isRegistered=!1,c.info("[KeychainManager] Deleted device identity")}catch(e){throw c.error(`[KeychainManager] Failed to delete device identity: ${e}`),new N(`Failed to delete device identity: ${e}`)}}getTokenAccount(e){return`${yr}${e}`}async getTokens(e="production"){let t=await We(this.serviceName,this.getTokenAccount(e));if(!t)return null;let r=JSON.parse(t);return c.debug(`[KeychainManager] Loaded tokens for ${e}`),r}async setTokens(e,t="production"){try{await Be(this.serviceName,this.getTokenAccount(t),JSON.stringify(e)),c.info(`[KeychainManager] Saved tokens for ${t}`,{userId:e.userId,email:e.email})}catch(r){throw c.error(`[KeychainManager] Failed to save tokens: ${r}`),new N(`Failed to save tokens: ${r}`)}}async deleteTokens(e="production"){try{let t=await Fe(this.serviceName,this.getTokenAccount(e));return t&&c.info(`[KeychainManager] Deleted tokens for ${e}`),t}catch(t){return c.error(`[KeychainManager] Failed to delete tokens: ${t}`),!1}}isTokenExpired(e){return Date.now()>=e.expiresAt-3e5}async getSessionKey(e,t){let r=this.sessionKeyCache.get(e);if(r)return r;if(!t||t.length===0)return null;let i=await this.getDeviceId(),s=t.find(d=>d.deviceId===i);if(!s)return c.warn(`[KeychainManager] Device ${i} not found in encryptedKeys`),null;let o=await this.getDevicePrivateKey(),a=A.decryptSessionKey(s,o);return this.sessionKeyCache.set(e,a),c.info(`[KeychainManager] Decrypted and cached session key for ${e}`),a}createSessionKey(e,t){let r=A.generateSessionKey(),i=[],s=[];for(let o of e)try{let a=A.encryptSessionKey(r,o.publicKey);i.push({deviceId:o.deviceId,encryptedKey:a.encryptedKey,ephemeralPublicKey:a.ephemeralPublicKey})}catch(a){c.warn("[KeychainManager] Skipping device with invalid public key",{deviceId:o.deviceId,error:a instanceof Error?a.message:String(a)}),s.push(o.deviceId);try{t?.onDeviceSkipped?.(s.length)}catch{}}if(i.length===0)throw new O(`Failed to encrypt session key for any of ${e.length} devices`);return c.info("[KeychainManager] Created session key",{encryptedCount:i.length,skippedCount:s.length,totalCount:e.length}),{sessionKey:r,encryptedKeys:i,skippedDeviceIds:s}}cacheSessionKey(e,t){this.sessionKeyCache.set(e,t)}getCachedSessionKey(e){return this.sessionKeyCache.get(e)??null}getCachedSessionIds(){return Array.from(this.sessionKeyCache.keys())}clearSessionKey(e){this.sessionKeyCache.delete(e)}clearAllSessionKeys(){this.sessionKeyCache.clear()}getIsRegistered(){return this.isRegistered}setIsRegistered(e){this.isRegistered=e}getDeviceName(){return Te.hostname()||"CLI Client"}getDevicePlatform(){let e=Te.platform();return e==="darwin"?"MACOS":e==="linux"?"LINUX":e==="win32"?"WINDOWS":"CLI"}async clearAllData(){await this.deleteDeviceIdentity(),await this.deleteTokens("development"),await this.deleteTokens("production"),this.sessionKeyCache.clear(),this.isRegistered=!1,c.info("[KeychainManager] Cleared all data")}},y=G.getInstance()});var Rt={};nt(Rt,{KeychainError:()=>N,KeychainManager:()=>G,keychainManager:()=>y});var U=_(()=>{"use strict";_t()});var Or={};nt(Or,{AgentType:()=>Ut,AppSyncClient:()=>fe,AuthService:()=>ae,CryptoError:()=>O,CryptoService:()=>re,DeliveryStatus:()=>Nt,ENCRYPTION_VERSION:()=>He,EventSource:()=>Ve,EventType:()=>Ot,KeychainError:()=>N,KeychainManager:()=>G,Logger:()=>H,PORT_RANGE_SIZE:()=>oe,PRIMARY_PORT:()=>se,SessionStatus:()=>xe,_resetPrepareEventTimestampForTesting:()=>et,authService:()=>$,bindOAuthServer:()=>me,createLogger:()=>Ke,cryptoService:()=>A,errorWasBeaconed:()=>le,fireAuthCompletedBeacon:()=>de,fireAuthFailedBeacon:()=>I,getConfig:()=>b,getEnvironment:()=>T,getErrorReason:()=>Ne,keychainManager:()=>y,loadConfig:()=>Ae,logger:()=>c,markErrorBeaconed:()=>x,mutations:()=>D,normalizeSnapshot:()=>ze,parseInteractivePrompt:()=>Ft,prepareEventTimestamp:()=>Qe,prepareSessionEncryption:()=>De,queries:()=>M,registerDeviceEncryptionKey:()=>ve,rekeySessionForNewDevices:()=>X,resumeOrCreateSession:()=>Xe,runAuthCli:()=>Ce,startDeviceKeyWatcher:()=>Ze,subscriptions:()=>J});module.exports=Xt(Or);U();he();var z=v(require("ws")),Y=require("uuid");ne();q();U();var Kt=v(require("dns")),Pt=v(require("fs"));if(gr())try{Kt.setDefaultResultOrder("ipv4first")}catch{}function gr(){if(process.platform!=="linux")return!1;try{let n=Pt.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(n)}catch{return!1}}async function ie(n,e,t){try{return await fetch(n,e)}catch(r){let i=r?.cause?.code,s=r?.cause?.message,o=i||s||r?.message||"unknown",a=fr(i),d=t?`${t}: `:"",l=`Node ${process.version} on ${process.platform}`,g=[`${d}Cannot reach ${n}`,` Underlying error: ${o}`];a&&g.push(` Suggested fix: ${a}`),g.push(` Platform: ${l}`);let p=new Error(g.join(`
8
- `));throw p.cause=r,p}}function fr(n){if(!n)return null;switch(n){case"ENOTFOUND":case"EAI_AGAIN":return'DNS resolution failed. On WSL Ubuntu, check /etc/resolv.conf, or try running with NODE_OPTIONS="--dns-result-order=ipv4first".';case"ETIMEDOUT":case"ECONNREFUSED":case"ECONNRESET":case"EHOSTUNREACH":case"ENETUNREACH":return`Network unreachable. On WSL Ubuntu, try NODE_OPTIONS="--dns-result-order=ipv4first" (WSL's IPv6 is often broken). If behind a corporate proxy, set HTTPS_PROXY.`;case"CERT_HAS_EXPIRED":case"CERT_NOT_YET_VALID":return"TLS certificate time error \u2014 likely system clock drift. On WSL, run `sudo hwclock -s`, or shut down WSL from PowerShell with `wsl --shutdown` and restart.";case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":case"SELF_SIGNED_CERT_IN_CHAIN":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"DEPTH_ZERO_SELF_SIGNED_CERT":return"Corporate HTTPS proxy detected \u2014 the TLS cert is not trusted by Node. Set NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem, or configure HTTPS_PROXY if a proxy is required.";default:return null}}var M={getSession:`
1
+ "use strict";var Xt=Object.create;var ke=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var er=Object.getPrototypeOf,tr=Object.prototype.hasOwnProperty;var D=(n,e)=>()=>(n&&(e=n(n=0)),e);var st=(n,e)=>{for(var t in e)ke(n,t,{get:e[t],enumerable:!0})},ot=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Qt(e))!tr.call(n,i)&&i!==t&&ke(n,i,{get:()=>e[i],enumerable:!(r=Zt(e,i))||r.enumerable});return n};var v=(n,e,t)=>(t=n!=null?Xt(er(n)):{},ot(e||!n||!n.__esModule?ke(t,"default",{value:n,enumerable:!0}):t,n)),rr=n=>ot(ke({},"__esModule",{value:!0}),n);function nr(n,e){if(e instanceof Error){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);for(let r of Object.keys(e))r in t||(t[r]=e[r]);return t}return e}function Oe(n){return new H(n)}var ee,we,ct,at,H,c,dt=D(()=>{"use strict";ee=v(require("fs")),we=v(require("path")),ct=v(require("os")),at={debug:0,info:1,warn:2,error:3};H=class{constructor(e){this.name=e.name,this.logFile=e.logFile,this.level=e.level||"info",this.enableConsole=e.console??!1,this.logFile&&this.ensureLogDir()}ensureLogDir(){if(this.logFile){let e=we.dirname(this.logFile);ee.existsSync(e)||ee.mkdirSync(e,{recursive:!0})}}shouldLog(e){return at[e]>=at[this.level]}formatMessage(e,t,r){let i=new Date().toISOString(),s=e.toUpperCase().padEnd(5),o=`[${i}] [${s}] [${this.name}] ${t}`;return r!==void 0&&(r instanceof Error?(o+=` ${r.name}: ${r.message}`,r.stack&&(o+=`
2
+ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,nr)}`:o+=` ${r}`),o}log(e,t,r){if(!this.shouldLog(e))return;let i=this.formatMessage(e,t,r);if(this.logFile)try{ee.appendFileSync(this.logFile,i+`
3
+ `)}catch{}if(this.enableConsole)switch(e){case"error":console.error(i);break;case"warn":console.warn(i);break;default:console.log(i)}}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}};c=new H({name:"codevibe-core",logFile:we.join(ct.tmpdir(),"codevibe-core.log"),level:"info"})});var q=D(()=>{"use strict";dt()});function dr(){let n=typeof process.getuid=="function"?process.getuid():0;return Pe.createHash("sha256").update(`${pt.hostname()}-${n}`).digest("hex").substring(0,36)}function K(){return{platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production"}}async function O(n,e){try{let t=JSON.stringify({client_id:dr(),events:[{name:n,params:e}]});await new Promise(r=>{let i=lt.request({hostname:or,path:ar,method:"POST",headers:{"Content-Type":"application/json"}},()=>r());i.on("error",()=>r()),i.write(t),i.end(),setTimeout(r,2e3)})}catch{}}async function le(n){await O("auth_completed",{...K(),user_id:n})}async function I(n,e){let t={...K(),reason:n,stage:e?.stage??cr[n]};if(typeof e?.httpStatus=="number"&&(t.http_status=e.httpStatus),e?.errorFragment){let{homedir:r}=await import("os"),i=e.errorFragment.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"").replace(/\\/g,"/").replace(/[\n\r\t"]/g," ").replace(/[^\x20-\x7E]/g,"").trim(),s=[process.env.HOME,process.env.USERPROFILE,(()=>{try{return r()}catch{return}})()].filter(d=>typeof d=="string"&&d.length>0).map(d=>d.replace(/\\/g,"/"));for(let d of s){let l=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(l,"g"),"~")}i=i.replace(/\/Users\/[^/ ]+/g,"/Users/<user>").replace(/\/home\/[^/ ]+/g,"/home/<user>").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"<email>");let o=i.substring(0,100),a=i.substring(100,200);o&&(t.error_fragment=o),a&&(t.error_fragment_2=a)}await O("auth_failed",t)}async function ut(n){await O("keychain_file_fallback",{...K(),reason:n})}function _(n,e){try{Object.defineProperty(n,Ne,{value:!0,enumerable:!1,configurable:!0,writable:!1}),Object.defineProperty(n,ht,{value:e,enumerable:!1,configurable:!0,writable:!1})}catch{}return n}function pe(n){return!!(n&&typeof n=="object"&&n[Ne])}function Ue(n){if(n&&typeof n=="object"&&n[Ne]){let e=n[ht];if(typeof e=="string")return e}}function te(n){return n<=0?"0":n===1?"1":n<=5?"2-5":"6+"}function Ee(n){return Pe.createHash("sha256").update(n).digest("hex").slice(0,8)}async function gt(n){return O("session_encryption_device_skipped",{...K(),...n})}async function yt(n){return O("session_encryption_partial_success",{...K(),...n})}async function ft(n){return O("session_encryption_catch_up_grant",{...K(),...n})}async function mt(n){return O("session_encryption_self_rekey_request",{...K(),...n})}async function vt(n){return O("session_encryption_self_rekey_success",{...K(),...n})}async function St(n){return O("session_encryption_self_rekey_timeout",{...K(),...n})}var Pe,lt,pt,ir,sr,or,ar,cr,Ne,ht,re=D(()=>{"use strict";Pe=v(require("crypto")),lt=v(require("https")),pt=v(require("os")),ir="G-GS74YEQTB8",sr="lAfOF6OxRzSQ-NsLBRjhAg",or="www.google-analytics.com",ar=`/mp/collect?measurement_id=${ir}&api_secret=${sr}`,cr={port_in_use:"server_start",port_range_exhausted:"server_start",server_listen_failed:"server_start",browser_open_failed:"browser_open",login_timeout:"awaiting_callback",cognito_rejected:"awaiting_callback",state_mismatch:"awaiting_callback",no_authorization_code:"awaiting_callback",token_exchange_failed:"exchanging_code",token_exchange_network_error:"exchanging_code",keychain_write_failed:"storing_tokens",user_aborted:"unknown",unknown:"unknown"};Ne=Symbol.for("codevibe.auth.beaconed"),ht=Symbol.for("codevibe.auth.failureReason")});function Et(n){for(let e of n)try{process.stderr.write(e+`
4
+ `)}catch{}}function Le(){$e=V.join(he.homedir(),".codevibe");try{w.mkdirSync($e,{recursive:!0,mode:448})}catch{}L="file"}function bt(){if(process.platform!=="linux"||process.env.DISPLAY||process.env.WAYLAND_DISPLAY||process.env.DBUS_SESSION_BUS_ADDRESS)return!1;try{let n=process.env.XDG_RUNTIME_DIR;if(n&&w.existsSync(V.join(n,"bus")))return!1;let e=typeof process.getuid=="function"?process.getuid():void 0;if(e!==void 0&&w.existsSync(`/run/user/${e}/bus`))return!1}catch{}return!0}function It(){return V.join(he.homedir(),".codevibe",".keyring-used")}function lr(){if(process.platform==="linux")try{w.mkdirSync(V.join(he.homedir(),".codevibe"),{recursive:!0,mode:448}),w.writeFileSync(It(),`keytar
5
+ `,{mode:384})}catch{}}function pr(){try{return w.existsSync(It())}catch{return!1}}function ur(){try{let n=V.join(he.homedir(),".codevibe");return w.readdirSync(n).some(e=>e.endsWith(".json"))}catch{return!1}}function hr(n){Et(["","\u26A0 CodeVibe: no OS keyring service detected on this machine.","\u26A0 Using file-based credential storage at ~/.codevibe/ instead","\u26A0 (directory 0700, files 0600 \u2014 trust level equivalent to ~/.ssh/id_rsa,","\u26A0 weaker than an OS keyring). This is expected on headless / SSH / Docker / CI.","\u26A0 For the OS keyring, run inside a desktop session with a keyring daemon","\u26A0 (Linux) or on macOS / Windows.",""]),c.warn(`[keychain-backend] No OS keyring service (${n}); auto-selected file storage at ~/.codevibe (headless fallback)`),wt=!0,Le(),ut(n)}function gr(){c.info("[keychain-backend] OS keyring is reachable, but durable file credentials already exist at ~/.codevibe; continuing on the file backend to avoid forking the device identity"),Le()}function kt(n){if(pr()){Ie=new ue(["CodeVibe used the OS keyring on this machine before, but it is not","reachable in this session (no desktop session / no D-Bus session bus \u2014","e.g. SSH without a forwarded bus).","","Auto-switching to file storage here would create a SEPARATE credential","identity and break your existing encrypted sessions, so we stop instead.","","Options:"," 1. Run inside the desktop session where the keyring is unlocked, or"," 2. Explicitly switch THIS machine to file-based storage (a new, separate"," credential identity):"," export CODEVIBE_ALLOW_FILE_KEYCHAIN=1"].join(`
6
+ `)),c.warn("[keychain-backend] OS keyring used here before but unreachable now; refusing silent file fallback (set CODEVIBE_ALLOW_FILE_KEYCHAIN=1 to override)");return}hr(n)}function Qr(){return wt}function en(){return L}function yr(){if(L!==null||Ie!==null)return;let optedIn=process.env.CODEVIBE_ALLOW_FILE_KEYCHAIN==="1";if(optedIn){Et(["","\u26A0 CodeVibe: file-based credential storage selected (CODEVIBE_ALLOW_FILE_KEYCHAIN=1).","\u26A0 Location: ~/.codevibe/ (directory 0700, files 0600)","\u26A0 Trust level: equivalent to ~/.ssh/id_rsa \u2014 weaker than OS keyring.","\u26A0 To use the OS keyring instead, unset CODEVIBE_ALLOW_FILE_KEYCHAIN and","\u26A0 install libsecret-1-0 + a running keyring daemon (Linux) or use the","\u26A0 native Keychain (macOS) / Credential Manager (Windows).",""]),c.warn("[keychain-backend] Using file-based storage at ~/.codevibe (CODEVIBE_ALLOW_FILE_KEYCHAIN=1 explicit opt-in)"),Le();return}if(ur()){gr();return}let keytarLoadError=null;try{let nodeRequire=eval("require");R=nodeRequire("keytar")}catch(n){keytarLoadError=n instanceof Error?n.message:String(n),R=null}if(R){if(bt()){R=null,kt("no_keyring_service");return}L="keytar",c.info("[keychain-backend] Using keytar (OS-native keyring)"),lr();return}if(bt()){kt("keytar_load_failed");return}Ie=new ue(["CodeVibe could not load the OS-native keyring (keytar).",`Reason: ${keytarLoadError??"unknown"}`,"","Options to fix this:"," 1. (Linux) Install libsecret and a keyring daemon:"," sudo apt install libsecret-1-0 gnome-keyring"," Then unlock the keyring for your user session.",""," 2. (Headless / CI / Docker) Opt in to file-based credential"," storage at ~/.codevibe/ (0600 files). This is equivalent"," in trust to ~/.ssh/id_rsa \u2014 not the OS keyring:"," export CODEVIBE_ALLOW_FILE_KEYCHAIN=1"].join(`
7
+ `))}function fr(n){return n.replace(/[^a-zA-Z0-9._-]/g,"_")}function Tt(n){return V.join($e,`${fr(n)}.json`)}function Me(n){try{let e=w.readFileSync(Tt(n),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function At(n,e){let t=Tt(n);w.writeFileSync(t,JSON.stringify(e,null,2),{mode:384});try{w.chmodSync(t,384)}catch{}}function We(){if(yr(),L===null)throw Ie??new ue("Keychain backend not initialized")}async function Be(n,e){return We(),L==="keytar"&&R?R.getPassword(n,e):Me(n)[e]??null}async function Fe(n,e,t){if(We(),L==="keytar"&&R){await R.setPassword(n,e,t);return}let r=Me(n);r[e]=t,At(n,r)}async function He(n,e){if(We(),L==="keytar"&&R)return R.deletePassword(n,e);let t=Me(n);return e in t?(delete t[e],At(n,t),!0):!1}var he,V,w,ue,L,R,$e,Ie,wt,_t=D(()=>{"use strict";he=v(require("os")),V=v(require("path")),w=v(require("fs"));q();re();ue=class extends Error{constructor(e){super(e),this.name="KeychainBackendUnavailableError"}},L=null,R=null,$e="",Ie=null,wt=!1});var x,P,qe,vr,ne,T,xt=D(()=>{"use strict";x=v(require("crypto")),P=class extends Error{constructor(e){super(e),this.name="CryptoError"}},qe=1,vr="CodeVibe E2E v1",ne=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}generateKeyPair(){let e=x.createECDH("prime256v1");e.generateKeys();let r=e.getPublicKey().subarray(1).toString("base64");return{privateKey:e.getPrivateKey().toString("base64"),publicKey:r}}generateSessionKey(){return x.randomBytes(32).toString("base64")}deriveSharedKey(e,t){try{let r=x.createECDH("prime256v1"),i=Buffer.from(e,"base64");r.setPrivateKey(i);let s=Buffer.from(t,"base64"),o=s.length===65&&s[0]===4?s:Buffer.concat([Buffer.from([4]),s]),a=r.computeSecret(o),d=x.hkdfSync("sha256",a,Buffer.alloc(0),Buffer.from(vr,"utf8"),32);return Buffer.from(d)}catch(r){throw new P(`Failed to derive shared key: ${r}`)}}encryptSessionKey(e,t){let r=this.generateKeyPair(),i=this.deriveSharedKey(r.privateKey,t),s=Buffer.from(e,"base64");return{encryptedKey:this.encrypt(s,i).toString("base64"),ephemeralPublicKey:r.publicKey}}decryptSessionKey(e,t){let r=this.deriveSharedKey(t,e.ephemeralPublicKey),i=Buffer.from(e.encryptedKey,"base64");return this.decrypt(i,r).toString("base64")}encryptContent(e,t){let r=Buffer.from(t,"base64"),i=Buffer.from(e,"utf8");return this.encrypt(i,r).toString("base64")}decryptContent(e,t){let r=Buffer.from(t,"base64"),i=Buffer.from(e,"base64");return this.decrypt(i,r).toString("utf8")}encryptMetadata(e,t){let r=JSON.stringify(e);return this.encryptContent(r,t)}decryptMetadata(e,t){let r=this.decryptContent(e,t);return JSON.parse(r)}encryptData(e,t){let r=Buffer.from(t,"base64");return this.encrypt(e,r)}decryptData(e,t){let r=Buffer.from(t,"base64");return this.decrypt(e,r)}encrypt(e,t){let r=x.randomBytes(12),i=x.createCipheriv("aes-256-gcm",t,r),s=Buffer.concat([i.update(e),i.final()]),o=i.getAuthTag();return Buffer.concat([r,s,o])}decrypt(e,t){let r=e.subarray(0,12),i=e.subarray(e.length-16),s=e.subarray(12,e.length-16),o=x.createDecipheriv("aes-256-gcm",t,r);o.setAuthTag(i);try{return Buffer.concat([o.update(s),o.final()])}catch{throw new P("Decryption failed: Invalid ciphertext or authentication tag")}}serializePrivateKey(e){return e}deserializePrivateKey(e){return e}},T=ne.getInstance()});var ge=D(()=>{"use strict";xt()});function A(){let n=process.env.ENVIRONMENT;return n==="development"||n==="production"?n:"production"}function Ae(n){let e=n||A();return Te={...j[e],aws:{...j[e].aws,region:process.env.AWS_REGION||j[e].aws.region,appsyncUrl:process.env.APPSYNC_URL||j[e].aws.appsyncUrl,cognitoUserPoolId:process.env.COGNITO_USER_POOL_ID||j[e].aws.cognitoUserPoolId,cognitoClientId:process.env.COGNITO_CLIENT_ID||j[e].aws.cognitoClientId,cognitoDomain:process.env.COGNITO_DOMAIN||j[e].aws.cognitoDomain}},Ct=!0,Te}function k(){return(!Ct||!Te)&&Ae(),Te}var ye,fe,j,Te,Ct,Dt=D(()=>{"use strict";ye=v(require("os")),fe=v(require("path")),j={development:{environment:"development",aws:{region:"us-east-1",appsyncUrl:"https://api-dev.codevibe.quantiya.ai/graphql",cognitoUserPoolId:"us-east-1_yVwWDPvvJ",cognitoClientId:"e9r5apv6v5uui3l928r2ris0r",cognitoDomain:"codevibe-development.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:fe.default.join(ye.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:fe.default.join(ye.default.homedir(),".gemini","tmp")}},production:{environment:"production",aws:{region:"us-east-1",appsyncUrl:"https://api.codevibe.quantiya.ai/graphql",cognitoUserPoolId:"us-east-1_mNRO0j5og",cognitoClientId:"5p04dbc9ojptc5r8n7605fg78f",cognitoDomain:"codevibe-production.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:fe.default.join(ye.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:fe.default.join(ye.default.homedir(),".gemini","tmp")}}},Te=null,Ct=!1});var ie=D(()=>{"use strict";Dt()});var _e,Rt,N,Ve,Sr,G,g,Kt=D(()=>{"use strict";_e=v(require("os")),Rt=require("uuid");_t();ge();ie();q();N=class extends Error{constructor(e){super(e),this.name="KeychainError"}},Ve="device-identity",Sr="tokens-",G=class n{constructor(){this.deviceIdentity=null;this.sessionKeyCache=new Map;this.isRegistered=!1;this._serviceName=null}get serviceName(){return this._serviceName||(this._serviceName=k().keychain.serviceName),this._serviceName}static getInstance(){return n.instance||(n.instance=new n),n.instance}async getDeviceIdentity(){if(this.deviceIdentity)return this.deviceIdentity;let e=await Be(this.serviceName,Ve);return e?(this.deviceIdentity=JSON.parse(e),c.info(`[KeychainManager] Loaded device identity: ${this.deviceIdentity.deviceId}`),this.deviceIdentity):null}async setDeviceIdentity(e){try{await Fe(this.serviceName,Ve,JSON.stringify(e)),this.deviceIdentity=e,c.info(`[KeychainManager] Saved device identity: ${e.deviceId}`)}catch(t){throw c.error(`[KeychainManager] Failed to save device identity: ${t}`),new N(`Failed to save device identity: ${t}`)}}async getOrCreateDeviceIdentity(){let e=await this.getDeviceIdentity();if(e)return e;let t=T.generateKeyPair();return e={deviceId:(0,Rt.v4)().toUpperCase(),privateKey:t.privateKey,publicKey:t.publicKey,createdAt:new Date().toISOString()},await this.setDeviceIdentity(e),c.info(`[KeychainManager] Generated new device identity: ${e.deviceId}`),e}async getDeviceId(){return(await this.getOrCreateDeviceIdentity()).deviceId}async getDevicePublicKey(){return(await this.getOrCreateDeviceIdentity()).publicKey}async getDevicePrivateKey(){return(await this.getOrCreateDeviceIdentity()).privateKey}async hasDeviceIdentity(){return await this.getDeviceIdentity()!==null}async deleteDeviceIdentity(){try{await He(this.serviceName,Ve),this.deviceIdentity=null,this.sessionKeyCache.clear(),this.isRegistered=!1,c.info("[KeychainManager] Deleted device identity")}catch(e){throw c.error(`[KeychainManager] Failed to delete device identity: ${e}`),new N(`Failed to delete device identity: ${e}`)}}getTokenAccount(e){return`${Sr}${e}`}async getTokens(e="production"){let t=await Be(this.serviceName,this.getTokenAccount(e));if(!t)return null;let r=JSON.parse(t);return c.debug(`[KeychainManager] Loaded tokens for ${e}`),r}async setTokens(e,t="production"){try{await Fe(this.serviceName,this.getTokenAccount(t),JSON.stringify(e)),c.info(`[KeychainManager] Saved tokens for ${t}`,{userId:e.userId,email:e.email})}catch(r){throw c.error(`[KeychainManager] Failed to save tokens: ${r}`),new N(`Failed to save tokens: ${r}`)}}async deleteTokens(e="production"){try{let t=await He(this.serviceName,this.getTokenAccount(e));return t&&c.info(`[KeychainManager] Deleted tokens for ${e}`),t}catch(t){return c.error(`[KeychainManager] Failed to delete tokens: ${t}`),!1}}isTokenExpired(e){return Date.now()>=e.expiresAt-3e5}async getSessionKey(e,t){let r=this.sessionKeyCache.get(e);if(r)return r;if(!t||t.length===0)return null;let i=await this.getDeviceId(),s=t.find(d=>d.deviceId===i);if(!s)return c.warn(`[KeychainManager] Device ${i} not found in encryptedKeys`),null;let o=await this.getDevicePrivateKey(),a=T.decryptSessionKey(s,o);return this.sessionKeyCache.set(e,a),c.info(`[KeychainManager] Decrypted and cached session key for ${e}`),a}createSessionKey(e,t){let r=T.generateSessionKey(),i=[],s=[];for(let o of e)try{let a=T.encryptSessionKey(r,o.publicKey);i.push({deviceId:o.deviceId,encryptedKey:a.encryptedKey,ephemeralPublicKey:a.ephemeralPublicKey})}catch(a){c.warn("[KeychainManager] Skipping device with invalid public key",{deviceId:o.deviceId,error:a instanceof Error?a.message:String(a)}),s.push(o.deviceId);try{t?.onDeviceSkipped?.(s.length)}catch{}}if(i.length===0)throw new P(`Failed to encrypt session key for any of ${e.length} devices`);return c.info("[KeychainManager] Created session key",{encryptedCount:i.length,skippedCount:s.length,totalCount:e.length}),{sessionKey:r,encryptedKeys:i,skippedDeviceIds:s}}cacheSessionKey(e,t){this.sessionKeyCache.set(e,t)}getCachedSessionKey(e){return this.sessionKeyCache.get(e)??null}getCachedSessionIds(){return Array.from(this.sessionKeyCache.keys())}clearSessionKey(e){this.sessionKeyCache.delete(e)}clearAllSessionKeys(){this.sessionKeyCache.clear()}getIsRegistered(){return this.isRegistered}setIsRegistered(e){this.isRegistered=e}getDeviceName(){return _e.hostname()||"CLI Client"}getDevicePlatform(){let e=_e.platform();return e==="darwin"?"MACOS":e==="linux"?"LINUX":e==="win32"?"WINDOWS":"CLI"}async clearAllData(){await this.deleteDeviceIdentity(),await this.deleteTokens("development"),await this.deleteTokens("production"),this.sessionKeyCache.clear(),this.isRegistered=!1,c.info("[KeychainManager] Cleared all data")}},g=G.getInstance()});var Ot={};st(Ot,{KeychainError:()=>N,KeychainManager:()=>G,keychainManager:()=>g});var U=D(()=>{"use strict";Kt()});var qr={};st(qr,{AgentType:()=>Bt,AppSyncClient:()=>me,AuthService:()=>ce,CryptoError:()=>P,CryptoService:()=>ne,DeliveryStatus:()=>Pt,ENCRYPTION_VERSION:()=>qe,EventSource:()=>Ge,EventType:()=>je,KeychainError:()=>N,KeychainManager:()=>G,Logger:()=>H,PORT_RANGE_SIZE:()=>ae,PRIMARY_PORT:()=>oe,SessionStatus:()=>xe,_resetPrepareEventTimestampForTesting:()=>rt,authService:()=>$,bindOAuthServer:()=>ve,createLogger:()=>Oe,cryptoService:()=>T,errorWasBeaconed:()=>pe,fireAuthCompletedBeacon:()=>le,fireAuthFailedBeacon:()=>I,getConfig:()=>k,getEnvironment:()=>A,getErrorReason:()=>Ue,keychainManager:()=>g,loadConfig:()=>Ae,logger:()=>c,markErrorBeaconed:()=>_,mutations:()=>C,normalizeSnapshot:()=>Xe,parseInteractivePrompt:()=>Gt,prepareEventTimestamp:()=>tt,prepareSessionEncryption:()=>De,queries:()=>M,registerDeviceEncryptionKey:()=>Se,rekeySessionForNewDevices:()=>Z,resumeOrCreateSession:()=>Qe,runAuthCli:()=>Ce,startDeviceKeyWatcher:()=>et,subscriptions:()=>J});module.exports=rr(qr);U();ge();var Y=v(require("ws")),X=require("uuid");ie();q();var je=(a=>(a.USER_PROMPT="USER_PROMPT",a.ASSISTANT_RESPONSE="ASSISTANT_RESPONSE",a.TOOL_USE="TOOL_USE",a.NOTIFICATION="NOTIFICATION",a.INTERACTIVE_PROMPT="INTERACTIVE_PROMPT",a.PROMPT_RESPONSE="PROMPT_RESPONSE",a.REASONING="REASONING",a))(je||{}),Ge=(t=>(t.DESKTOP="DESKTOP",t.MOBILE="MOBILE",t))(Ge||{}),Pt=(r=>(r.SENT="SENT",r.DELIVERED="DELIVERED",r.EXECUTED="EXECUTED",r))(Pt||{});var br=Number(process.env.CODEVIBE_THROTTLE_WINDOW_MS)||1e4,Nt=Number(process.env.CODEVIBE_THROTTLE_EVENTS_PER_WINDOW)||50,kr=Number(process.env.CODEVIBE_THROTTLE_TOOL_USE_KEEP_EVERY)||10,wr=process.env.CODEVIBE_THROTTLE_DISABLED==="1",Ut=Nt,Er=new Set(["USER_PROMPT","ASSISTANT_RESPONSE","INTERACTIVE_PROMPT","PROMPT_RESPONSE","NOTIFICATION"]),z=new Map,Ir=2e3;function $t(n,e,t){if(wr)return!1;let r=z.get(n);if(!r||t-r.windowStartMs>=br||t<r.windowStartMs){if(z.delete(n),z.size>=Ir){let i=z.keys().next().value;i!==void 0&&z.delete(i)}r={windowStartMs:t,count:0,toolUseAboveThreshold:0,suppressed:0,logged:!1},z.set(n,r)}if(r.count+=1,r.count<=Nt||Er.has(e))return!1;if(e==="REASONING")return r.suppressed+=1,!0;if(e==="TOOL_USE"){r.toolUseAboveThreshold+=1;let i=r.toolUseAboveThreshold%kr===0;return i||(r.suppressed+=1),!i}return!1}function Lt(n){let e=z.get(n);if(e&&!e.logged)return e.logged=!0,e}U();var Mt=v(require("dns")),Wt=v(require("fs"));if(Tr())try{Mt.setDefaultResultOrder("ipv4first")}catch{}function Tr(){if(process.platform!=="linux")return!1;try{let n=Wt.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(n)}catch{return!1}}async function se(n,e,t){try{return await fetch(n,e)}catch(r){let i=r?.cause?.code,s=r?.cause?.message,o=i||s||r?.message||"unknown",a=Ar(i),d=t?`${t}: `:"",l=`Node ${process.version} on ${process.platform}`,y=[`${d}Cannot reach ${n}`,` Underlying error: ${o}`];a&&y.push(` Suggested fix: ${a}`),y.push(` Platform: ${l}`);let p=new Error(y.join(`
8
+ `));throw p.cause=r,p}}function Ar(n){if(!n)return null;switch(n){case"ENOTFOUND":case"EAI_AGAIN":return'DNS resolution failed. On WSL Ubuntu, check /etc/resolv.conf, or try running with NODE_OPTIONS="--dns-result-order=ipv4first".';case"ETIMEDOUT":case"ECONNREFUSED":case"ECONNRESET":case"EHOSTUNREACH":case"ENETUNREACH":return`Network unreachable. On WSL Ubuntu, try NODE_OPTIONS="--dns-result-order=ipv4first" (WSL's IPv6 is often broken). If behind a corporate proxy, set HTTPS_PROXY.`;case"CERT_HAS_EXPIRED":case"CERT_NOT_YET_VALID":return"TLS certificate time error \u2014 likely system clock drift. On WSL, run `sudo hwclock -s`, or shut down WSL from PowerShell with `wsl --shutdown` and restart.";case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":case"SELF_SIGNED_CERT_IN_CHAIN":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"DEPTH_ZERO_SELF_SIGNED_CERT":return"Corporate HTTPS proxy detected \u2014 the TLS cert is not trusted by Node. Set NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem, or configure HTTPS_PROXY if a proxy is required.";default:return null}}var M={getSession:`
9
9
  query GetSession($sessionId: ID!) {
10
10
  getSession(sessionId: $sessionId) {
11
11
  sessionId
@@ -80,7 +80,7 @@ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,Zt)}`:o+=` ${r}`),o}log
80
80
  nextToken
81
81
  }
82
82
  }
83
- `},D={createSession:`
83
+ `},C={createSession:`
84
84
  mutation CreateSession($input: CreateSessionInput!) {
85
85
  createSession(input: $input) {
86
86
  sessionId
@@ -204,7 +204,7 @@ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,Zt)}`:o+=` ${r}`),o}log
204
204
  updatedAt
205
205
  }
206
206
  }
207
- `};var Ot=(a=>(a.USER_PROMPT="USER_PROMPT",a.ASSISTANT_RESPONSE="ASSISTANT_RESPONSE",a.TOOL_USE="TOOL_USE",a.NOTIFICATION="NOTIFICATION",a.INTERACTIVE_PROMPT="INTERACTIVE_PROMPT",a.PROMPT_RESPONSE="PROMPT_RESPONSE",a.REASONING="REASONING",a))(Ot||{}),Ve=(t=>(t.DESKTOP="DESKTOP",t.MOBILE="MOBILE",t))(Ve||{}),Nt=(r=>(r.SENT="SENT",r.DELIVERED="DELIVERED",r.EXECUTED="EXECUTED",r))(Nt||{});var xe=(r=>(r.ACTIVE="ACTIVE",r.INACTIVE="INACTIVE",r.PAUSED="PAUSED",r))(xe||{}),Ut=(i=>(i.CLAUDE="CLAUDE",i.GEMINI="GEMINI",i.CODEX="CODEX",i.ANTIGRAVITY="ANTIGRAVITY",i))(Ut||{});var E={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3},fe=class n{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.activeSubscriptions=new Map;this.pendingRefresh=null;this.lastRefreshFailureAt=null;this.deviceKeyWatcher=null;this.sessionUpdateWatchers=new Map;this.statusWriteChains=new Map;this.heartbeatTimers=new Map;this.environment=T(),c.info("[AppSyncClient] Initialized",{environment:this.environment})}static{this.REFRESH_BACKOFF_MS=3e4}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}async authenticateWithStoredTokens(){try{let e=await y.getTokens(this.environment);if(!e)return c.debug("[AppSyncClient] No stored tokens found"),!1;if(c.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:y.isTokenExpired(e)}),y.isTokenExpired(e)){if(c.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return c.warn("[AppSyncClient] Token refresh failed"),!1}else this.tokens=e;return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,c.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){return c.error("[AppSyncClient] Authentication failed:",e),!1}}async refreshTokens(e){if(this.pendingRefresh)return this.pendingRefresh;if(this.lastRefreshFailureAt!==null&&Date.now()-this.lastRefreshFailureAt<n.REFRESH_BACKOFF_MS)return!1;this.pendingRefresh=this.performRefresh(e);try{return await this.pendingRefresh}finally{this.pendingRefresh=null}}async performRefresh(e){let t=await this.callCognitoRefresh(e.refreshToken);if(t!==null)return this.applyRefreshedTokens(e,t);let r=null;try{r=await y.getTokens(this.environment)}catch(i){c.warn("[AppSyncClient] Failed to re-read tokens from storage during refresh recovery",{error:i instanceof Error?i.message:String(i)})}if(r&&r.refreshToken&&r.refreshToken!==e.refreshToken){c.info("[AppSyncClient] In-memory refresh token rejected; retrying with storage-backed token (likely out-of-band re-auth)");let i=await this.callCognitoRefresh(r.refreshToken);if(i!==null)return this.applyRefreshedTokens(r,i)}return this.lastRefreshFailureAt=Date.now(),!1}async callCognitoRefresh(e){try{let t=b(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e}),s=await ie(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");return s.ok?await s.json():(c.error("[AppSyncClient] Token refresh failed",{status:s.status}),null)}catch(t){return c.error("[AppSyncClient] Token refresh error:",t),null}}async applyRefreshedTokens(e,t){let r={...e,accessToken:t.access_token,idToken:t.id_token,expiresAt:Date.now()+t.expires_in*1e3};this.tokens=r,this.lastRefreshFailureAt=null;try{await y.setTokens(r,this.environment),c.info("[AppSyncClient] Tokens refreshed",{expiresAt:new Date(r.expiresAt).toISOString()})}catch(i){c.warn("[AppSyncClient] Tokens refreshed but persistence failed; daemon keeps using fresh tokens in memory. A restart while persistence is still broken would lose them.",{error:i instanceof Error?i.message:String(i),expiresAt:new Date(r.expiresAt).toISOString()})}return!0}isAuthenticated(){return this.authenticated}signOut(){this.authenticated=!1,this.tokens=null,this.currentUserId=null,this.currentEmail=null,this.cleanupSubscriptions(),c.info("[AppSyncClient] Signed out")}async graphqlRequest(e,t,r=!1){let i=b();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let s={"Content-Type":"application/json",Authorization:this.tokens.idToken},o=await ie(i.aws.appsyncUrl,{method:"POST",headers:s,body:JSON.stringify({query:e,variables:t})},"AppSync GraphQL request"),a=await o.json();if(o.status===401&&!r&&this.tokens){if(c.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),await this.refreshTokens(this.tokens))return this.graphqlRequest(e,t,!0);throw new Error("Token expired and refresh failed")}if(!o.ok)throw new Error(`GraphQL request failed: ${o.status}`);if(a.errors?.length)throw new Error(`GraphQL error: ${a.errors[0].message}`);return a}async createSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(D.createSession,{input:t});return c.info("[AppSyncClient] Session created",{sessionId:r.data.createSession.sessionId}),r.data.createSession}async updateSession(e){if(e.status===void 0)return this.doUpdateSession(e);let r=(this.statusWriteChains.get(e.sessionId)??Promise.resolve()).catch(()=>{}).then(()=>this.doUpdateSession(e));return this.statusWriteChains.set(e.sessionId,r.catch(()=>{})),r}async doUpdateSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(D.updateSession,{input:t});return c.debug("[AppSyncClient] Session updated",{sessionId:r.data.updateSession.sessionId}),r.data.updateSession}async getSession(e){return(await this.graphqlRequest(M.getSession,{sessionId:e})).data.getSession}async createEvent(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(D.createEvent,{input:t});return c.debug("[AppSyncClient] Event created",{eventId:r.data.createEvent.eventId,type:r.data.createEvent.type}),r.data.createEvent}async updateEventStatus(e){return(await this.graphqlRequest(D.updateEventStatus,{input:e})).data.updateEventStatus}async listEvents(e,t,r){return(await this.graphqlRequest(M.listEvents,{sessionId:e,source:t,limit:r})).data.listEvents.items}async listSessions(e=100){if(!this.currentUserId)throw new Error("Not authenticated");let t=[],r=null;do{let s=(await this.graphqlRequest(M.listSessions,{userId:this.currentUserId,limit:e,nextToken:r})).data?.listSessions;s?.items&&t.push(...s.items),r=s?.nextToken??null}while(r);return t}async sweepOrphanSessions(e){let t=e.staleThresholdMs??9e5,r=new Set(e.excludeSessionIds??[]),i=Date.now(),s;try{s=await this.listSessions()}catch(a){return c.warn("[AppSyncClient] OrphanSweep: listSessions failed, skipping sweep",{agentType:e.agentType,error:a instanceof Error?a.message:String(a)}),0}let o=0;for(let a of s){if(a.agentType!==e.agentType||a.status!=="ACTIVE"||r.has(a.sessionId)||!a.lastHeartbeatAt)continue;let d=i-new Date(a.lastHeartbeatAt).getTime();if(!(d<t)){c.warn("[AppSyncClient] OrphanSweep: marking stale session INACTIVE",{sessionId:a.sessionId,agentType:a.agentType,lastHeartbeatAt:a.lastHeartbeatAt,heartbeatAgeMinutes:Math.round(d/6e4)});try{await this.updateSession({sessionId:a.sessionId,status:"INACTIVE"}),o++}catch(l){c.warn("[AppSyncClient] OrphanSweep: updateSession failed, leaving row as-is",{sessionId:a.sessionId,error:l instanceof Error?l.message:String(l)})}}}return o>0&&c.info("[AppSyncClient] OrphanSweep complete",{agentType:e.agentType,swept:o}),o}async listUserDeviceKeys(){return(await this.graphqlRequest(M.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async registerDeviceKey(e,t,r,i){let s={deviceId:e,publicKey:t,platform:r,deviceName:i};await this.graphqlRequest(D.registerDeviceKey,{input:s}),c.info("[AppSyncClient] Device key registered",{deviceId:e,platform:r})}async grantSessionKey(e){await this.graphqlRequest(D.grantSessionKey,{input:e}),c.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(D.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}subscribeToEvents(e,t,r){c.info("[AppSyncClient] Subscribing to events",{sessionId:e});let i=this.activeSubscriptions.get(e);i&&(this.cleanupSubscriptionState(i),this.activeSubscriptions.delete(e));let s={ws:null,subscriptionId:(0,Y.v4)(),sessionId:e,onEvent:t,onError:r,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,s),this.createSubscription(s),()=>{this.cleanupSubscriptionState(s),this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=b(),t=new URL(e.aws.appsyncUrl),i=/\.appsync-api\.[^.]+\.amazonaws\.com$/.test(t.host)?e.aws.appsyncUrl.replace("https://","wss://").replace("appsync-api","appsync-realtime-api"):`wss://${t.host}/graphql/realtime`,s={host:t.host};this.tokens?.idToken&&(s.Authorization=this.tokens.idToken);let o=Buffer.from(JSON.stringify(s)).toString("base64"),a=Buffer.from(JSON.stringify({})).toString("base64");return`${i}?header=${o}&payload=${a}`}createSubscription(e){let{sessionId:t,subscriptionId:r,onEvent:i,onError:s}=e;try{let o=this.buildRealtimeUrl(),a=new z.default(o,["graphql-ws"]);a.on("open",()=>{c.info("[AppSyncClient] WebSocket connected",{sessionId:t}),a.send(JSON.stringify({type:"connection_init"}))}),a.on("message",d=>{try{let l=JSON.parse(d.toString());switch(l.type){case"connection_ack":this.sendSubscriptionStart(a,e);break;case"start_ack":if(e.destroyed)break;c.info("[AppSyncClient] Subscription started",{sessionId:t});let g=e.reconnectAttempts>0;e.isReconnecting=!1,e.reconnectAttempts=0,this.startHeartbeat(t),g&&this.updateSession({sessionId:t,status:"ACTIVE"}).then(()=>c.info("[AppSyncClient] Re-asserted session ACTIVE after reconnect",{sessionId:t})).catch(f=>c.warn("[AppSyncClient] Re-assert ACTIVE after reconnect failed",{sessionId:t,error:f instanceof Error?f.message:String(f)}));break;case"data":this.resetKeepAliveTimer(e);let p=l.payload?.data?.onEventCreated;p&&p.source==="MOBILE"&&i(p);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let h=l.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(h));break}}catch(l){c.error("[AppSyncClient] Failed to parse message",{error:l})}}),a.on("error",d=>{c.error("[AppSyncClient] WebSocket error",{sessionId:t,error:d.message}),this.handleSubscriptionError(e,d)}),a.on("close",(d,l)=>{c.info("[AppSyncClient] WebSocket closed",{sessionId:t,code:d}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(t)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${d}`))}),e.ws=a,this.resetKeepAliveTimer(e)}catch(o){this.handleSubscriptionError(e,o)}}sendSubscriptionStart(e,t){let r=b(),{sessionId:i,subscriptionId:s}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:J.onEventCreated,variables:{sessionId:i}}),extensions:{authorization:o}}}))}resetKeepAliveTimer(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSubscriptionError(e,new Error("Keep-alive timeout"))},300*1e3)}handleSubscriptionError(e,t){let{sessionId:r,onError:i}=e;if(e.isReconnecting||!this.activeSubscriptions.has(r))return;e.isReconnecting=!0,e.reconnectAttempts++,this.stopHeartbeat(r);let s=e.reconnectAttempts<=E.urgentMaxAttempts,o;if(s?o=Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):(o=E.persistentDelayMs,e.reconnectAttempts===E.urgentMaxAttempts+1&&c.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:r})),c.info("[AppSyncClient] Scheduling reconnect",{sessionId:r,attempt:e.reconnectAttempts,phase:s?"urgent":"persistent",delayMs:o}),e.ws){try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(r)!==e){c.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:r});return}try{let a=await y.getTokens(this.environment);a&&(y.isTokenExpired(a)?await this.refreshTokens(a)&&c.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:r}):this.tokens=a)}catch{c.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:r})}if(e.destroyed||this.activeSubscriptions.get(r)!==e){c.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:r});return}e.subscriptionId=(0,Y.v4)(),this.createSubscription(e)},o)}cleanupSubscriptionState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===z.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}subscribeToDeviceKeyRegistered(e,t,r,i){c.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let s={userId:e,subscriptionId:(0,Y.v4)(),ws:null,onNewDevice:t,onReconnect:r,onError:i,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.deviceKeyWatcher=s,this.createDeviceKeyWatcherConnection(s),()=>{this.stopDeviceKeyWatcherInternal()}}stopDeviceKeyWatcher(){this.stopDeviceKeyWatcherInternal()}stopDeviceKeyWatcherInternal(){let e=this.deviceKeyWatcher;if(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===z.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}this.deviceKeyWatcher=null,c.info("[AppSyncClient] Device key watcher stopped")}}createDeviceKeyWatcherConnection(e){try{let t=this.buildRealtimeUrl(),r=new z.default(t,["graphql-ws"]);r.on("open",()=>{c.info("[AppSyncClient] Device key watcher WebSocket connected",{userId:e.userId}),r.send(JSON.stringify({type:"connection_init"}))}),r.on("message",i=>{try{let s=JSON.parse(i.toString());switch(s.type){case"connection_ack":this.sendDeviceKeyWatcherStart(r,e);break;case"start_ack":c.info("[AppSyncClient] Device key watcher subscription started",{userId:e.userId});let o=e.isReconnecting;if(e.isReconnecting=!1,e.reconnectAttempts=0,o&&e.onReconnect)try{e.onReconnect()}catch(l){c.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:l})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let a=s.payload?.data?.onDeviceKeyRegistered;if(a){c.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:a.deviceId,platform:a.platform});try{e.onNewDevice(a)}catch(l){c.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:l})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let d=s.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(d));break}}catch(s){c.error("[AppSyncClient] Failed to parse device key watcher message",{error:s})}}),r.on("error",i=>{c.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleDeviceKeyWatcherError(e,i)}),r.on("close",i=>{c.info("[AppSyncClient] Device key watcher WebSocket closed",{userId:e.userId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.deviceKeyWatcher===e&&this.handleDeviceKeyWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=r,this.resetDeviceKeyWatcherKeepAlive(e)}catch(t){this.handleDeviceKeyWatcherError(e,t)}}sendDeviceKeyWatcherStart(e,t){let r=b(),{userId:i,subscriptionId:s}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:J.onDeviceKeyRegistered,variables:{userId:i}}),extensions:{authorization:o}}}))}resetDeviceKeyWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleDeviceKeyWatcherError(e,new Error("Device key watcher keep-alive timeout"))},300*1e3)}handleDeviceKeyWatcherError(e,t){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(t)}catch{}if(e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=E.urgentMaxAttempts?Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):E.persistentDelayMs;c.warn("[AppSyncClient] Device key watcher reconnect scheduled",{userId:e.userId,attempts:e.reconnectAttempts,delayMs:i,error:t.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.deviceKeyWatcher!==e){c.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}try{let s=await y.getTokens(this.environment);s&&(y.isTokenExpired(s)?await this.refreshTokens(s)&&c.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId}):this.tokens=s)}catch{c.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,Y.v4)(),this.createDeviceKeyWatcherConnection(e))},i)}watchForMobileEnd(e,t){c.info("[AppSyncClient] Starting mobile-end watcher",{sessionId:e});let r=this.sessionUpdateWatchers.get(e);r&&(c.info("[AppSyncClient] Replacing existing mobile-end watcher",{sessionId:e}),this.cleanupSessionUpdateWatcherState(r),this.sessionUpdateWatchers.delete(e));let i={sessionId:e,subscriptionId:(0,Y.v4)(),ws:null,onMobileEndRequested:t,priorStatus:"ACTIVE",firedOnce:!1,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.sessionUpdateWatchers.set(e,i),this.createSessionUpdateWatcherConnection(i),{stop:()=>{this.sessionUpdateWatchers.get(e)===i&&(this.cleanupSessionUpdateWatcherState(i),this.sessionUpdateWatchers.delete(e),c.info("[AppSyncClient] Mobile-end watcher stopped",{sessionId:e}))}}}createSessionUpdateWatcherConnection(e){try{let t=this.buildRealtimeUrl(),r=new z.default(t,["graphql-ws"]);r.on("open",()=>{c.info("[AppSyncClient] Mobile-end watcher WebSocket connected",{sessionId:e.sessionId}),r.send(JSON.stringify({type:"connection_init"}))}),r.on("message",i=>{try{let s=JSON.parse(i.toString());switch(s.type){case"connection_ack":this.sendSessionUpdateWatcherStart(r,e);break;case"start_ack":c.info("[AppSyncClient] Mobile-end watcher subscription started",{sessionId:e.sessionId}),e.isReconnecting=!1,e.reconnectAttempts=0;break;case"data":this.resetSessionUpdateWatcherKeepAlive(e),this.handleSessionUpdatePayload(e,s.payload);break;case"ka":this.resetSessionUpdateWatcherKeepAlive(e);break;case"error":let o=s.payload?.errors?.[0]?.message||"Unknown error";this.handleSessionUpdateWatcherError(e,new Error(o));break}}catch(s){c.error("[AppSyncClient] Failed to parse mobile-end watcher message",{error:s})}}),r.on("error",i=>{c.error("[AppSyncClient] Mobile-end watcher WebSocket error",{sessionId:e.sessionId,error:i.message}),this.handleSessionUpdateWatcherError(e,i)}),r.on("close",i=>{c.info("[AppSyncClient] Mobile-end watcher WebSocket closed",{sessionId:e.sessionId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.sessionUpdateWatchers.get(e.sessionId)===e&&this.handleSessionUpdateWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=r,this.resetSessionUpdateWatcherKeepAlive(e)}catch(t){this.handleSessionUpdateWatcherError(e,t)}}handleSessionUpdatePayload(e,t){let r=t?.data?.onSessionUpdated;if(!r){c.warn("[AppSyncClient] Mobile-end watcher received malformed payload",{sessionId:e.sessionId});return}if(e.firedOnce)return;let i=r.status;if(i==null){c.debug("[AppSyncClient] Mobile-end watcher skipped non-status payload",{sessionId:e.sessionId});return}if(e.priorStatus==="ACTIVE"&&i==="INACTIVE"){e.firedOnce=!0,e.priorStatus="INACTIVE",c.info("[AppSyncClient] Mobile end requested for session",{sessionId:e.sessionId}),Promise.resolve().then(()=>e.onMobileEndRequested()).catch(s=>{c.warn("[AppSyncClient] Mobile-end callback threw",{sessionId:e.sessionId,error:s})});return}e.priorStatus=i}sendSessionUpdateWatcherStart(e,t){let r=b(),{sessionId:i,subscriptionId:s}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:J.onSessionUpdated,variables:{sessionId:i}}),extensions:{authorization:o}}}))}resetSessionUpdateWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSessionUpdateWatcherError(e,new Error("Mobile-end watcher keep-alive timeout"))},300*1e3)}handleSessionUpdateWatcherError(e,t){if(e.isReconnecting||e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=E.urgentMaxAttempts?Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):E.persistentDelayMs;c.warn("[AppSyncClient] Mobile-end watcher reconnect scheduled",{sessionId:e.sessionId,attempts:e.reconnectAttempts,delayMs:i,error:t.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,!(e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e)){try{let s=await y.getTokens(this.environment);s&&(y.isTokenExpired(s)?await this.refreshTokens(s):this.tokens=s)}catch{c.warn("[AppSyncClient] Token refresh failed before mobile-end watcher reconnect",{sessionId:e.sessionId})}e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Y.v4)(),this.createSessionUpdateWatcherConnection(e))}},i)}cleanupSessionUpdateWatcherState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===z.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}startHeartbeat(e,t=120*1e3){this.stopHeartbeat(e),this.sendHeartbeat(e);let r=setInterval(()=>{this.sendHeartbeat(e)},t);this.heartbeatTimers.set(e,r),c.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:t})}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e),c.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async sendHeartbeat(e){try{await this.updateSession({sessionId:e,lastHeartbeatAt:new Date().toISOString()}),c.debug("[AppSyncClient] Heartbeat sent",{sessionId:e})}catch(t){c.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:t})}}cleanupSubscription(e){let t=this.activeSubscriptions.get(e);t&&(this.cleanupSubscriptionState(t),this.activeSubscriptions.get(e)===t&&this.activeSubscriptions.delete(e))}cleanupSubscriptions(){this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear(),this.stopDeviceKeyWatcherInternal(),this.sessionUpdateWatchers.forEach(e=>{this.cleanupSessionUpdateWatcherState(e)}),this.sessionUpdateWatchers.clear(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear()}};var $t=v(require("crypto")),Lt=v(require("fs")),Mt=v(require("http")),Wt=require("child_process");ne();U();q();te();var se=8080,oe=20,je="/callback";async function me(n){let e=null;for(let t=0;t<oe;t++){let r=se+t;try{let i=await new Promise((s,o)=>{let a=Mt.createServer(n),d=g=>{a.removeListener("listening",l),o(g)},l=()=>{a.removeListener("error",d),a.on("error",g=>{c.error("[AuthService] OAuth server post-bind error",{port:r,code:g?.code,message:g?.message})}),s(a)};a.once("error",d),a.once("listening",l),a.listen(r,"localhost")});return c.info(`[AuthService] OAuth server bound on port ${r} (attempt ${t+1}/${oe})`),{server:i,port:r}}catch(i){if(e=i,i?.code==="EADDRINUSE")continue;throw i}}throw Object.assign(new Error(`All ports ${se}-${se+oe-1} are in use. Free at least one for OAuth callback or quit a conflicting service (common collisions: Vite, Webpack, Spring Boot, Docker exposed ports). Underlying: ${e?.message??"EADDRINUSE"}`),{code:"EADDRINUSE_ALL"})}var ae=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}openBrowser(e){console.error(""),console.error("Opening your browser for sign-in..."),this.isRunningInWSL()?console.error("If your browser does not open, paste this URL in your Windows browser:"):console.error("If your browser does not open automatically, visit this URL:"),console.error(` ${e}`),console.error("");let t=this.getBrowserCommands();this.tryBrowserCommand(t,e,0)}getBrowserCommands(){let e=process.platform;if(e==="darwin")return[{cmd:"open",fixedArgs:[]}];if(e==="win32")return[{cmd:"cmd",fixedArgs:["/c","start",""]}];let t=[];return this.isRunningInWSL()&&(t.push({cmd:"wslview",fixedArgs:[]}),t.push({cmd:"cmd.exe",fixedArgs:["/c","start",""]}),t.push({cmd:"powershell.exe",fixedArgs:["-NoProfile","-Command","Start-Process"]})),t.push({cmd:"xdg-open",fixedArgs:[]}),t}isRunningInWSL(){if(process.platform!=="linux")return!1;try{let e=Lt.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,t,r){if(r>=e.length){c.debug("[AuthService] No browser-opening command succeeded. User must open the sign-in URL manually (printed to stderr above)."),console.error(""),console.error("\u26A0\uFE0F Could not open browser automatically."),this.isRunningInWSL()?console.error(" WSL detected \u2014 paste this URL in your Windows browser:"):console.error(" Please copy and paste this URL into your browser:"),console.error(` ${t}`),console.error("");return}let i=e[r],s=[...i.fixedArgs,t],o=!1,a=p=>{o||(o=!0,c.debug(`[AuthService] Browser command '${i.cmd}' ${p}; trying next fallback`),this.tryBrowserCommand(e,t,r+1))},d=p=>{o||(o=!0,c.debug(`[AuthService] Browser command '${i.cmd}' ${p}`))},l;try{l=(0,Wt.spawn)(i.cmd,s,{detached:!0,stdio:"ignore"})}catch(p){a(`threw synchronously: ${p?.message||p}`);return}l.on("error",p=>{a(`failed to spawn: ${p?.message||p}`)}),l.on("exit",(p,h)=>{p===0?d("exited successfully"):a(h?`terminated by signal ${h}`:`exited with code ${p}`)}),setTimeout(()=>{d("still running after 3s, assuming success")},3e3).unref(),l.unref()}generateState(){return $t.randomBytes(32).toString("hex")}buildAuthUrl(e,t){let r=b(),i=new URLSearchParams({client_id:r.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:t,state:e});return`https://${r.aws.cognitoDomain}/oauth2/authorize?${i.toString()}`}async exchangeCodeForTokens(e,t){let r=b(),i=`https://${r.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"authorization_code",client_id:r.aws.cognitoClientId,code:e,redirect_uri:t}),o;try{o=await ie(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token exchange")}catch(d){throw await I("token_exchange_network_error"),x(d,"token_exchange_network_error"),d}if(!o.ok){let d=await o.text(),l=new Error(`Token exchange failed: ${o.status} ${d}`);throw await I("token_exchange_failed",{httpStatus:o.status}),x(l,"token_exchange_failed"),l}let a=await o.json();return{accessToken:a.access_token,idToken:a.id_token,refreshToken:a.refresh_token,expiresIn:a.expires_in}}decodeJwt(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT");return JSON.parse(Buffer.from(t[1],"base64").toString("utf-8"))}async refreshTokens(e){let t=b(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e}),s=await ie(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");if(!s.ok)throw new Error(`Token refresh failed: ${s.status}`);let o=await s.json();return{accessToken:o.access_token,idToken:o.id_token,expiresIn:o.expires_in}}async login(){let e=await y.getTokens(T());if(e&&!y.isTokenExpired(e))return e;let t=this.generateState();return new Promise((r,i)=>{let s={},o=null,a=!1,d=!1,l=h=>{h.closeAllConnections?.()},g=h=>{if(a)return;a=!0,o&&(clearTimeout(o),o=null);let f=s.server;f?(l(f),f.close(()=>r(h))):r(h)},p=h=>{if(a)return;a=!0,o&&(clearTimeout(o),o=null);let f=s.server;f?(l(f),f.close(()=>i(h))):i(h)};(async()=>{let h;try{h=await me(async(m,S)=>{if(d||a){S.writeHead(200,{Connection:"close"}),S.end();return}let tt=`http://localhost:${m.socket?.localPort??h.port}${je}`,Se=new URL(m.url||"",tt);if(Se.pathname!==je){S.writeHead(404,{Connection:"close"}),S.end("Not found");return}try{let F=Se.searchParams.get("code"),_e=Se.searchParams.get("state"),Z=Se.searchParams.get("error");if(Z){let k=new Error(`OAuth error: ${Z}`);throw await I("cognito_rejected"),x(k,"cognito_rejected"),k}if(_e!==t){let k=new Error("State mismatch");throw await I("state_mismatch"),x(k,"state_mismatch"),k}if(!F){let k=new Error("No authorization code");throw await I("no_authorization_code"),x(k,"no_authorization_code"),k}d=!0;let ce=await this.exchangeCodeForTokens(F,tt),rt=this.decodeJwt(ce.idToken),Re={accessToken:ce.accessToken,idToken:ce.idToken,refreshToken:ce.refreshToken,expiresAt:Date.now()+ce.expiresIn*1e3,userId:rt.sub,email:rt.email||"unknown"};try{await y.setTokens(Re,T())}catch(k){throw await I("keychain_write_failed",{errorFragment:k?.message?String(k.message):String(k)}),x(k,"keychain_write_failed"),k}S.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),S.end(`
207
+ `};var xe=(r=>(r.ACTIVE="ACTIVE",r.INACTIVE="INACTIVE",r.PAUSED="PAUSED",r))(xe||{}),Bt=(i=>(i.CLAUDE="CLAUDE",i.GEMINI="GEMINI",i.CODEX="CODEX",i.ANTIGRAVITY="ANTIGRAVITY",i))(Bt||{});var E={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3},me=class n{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.activeSubscriptions=new Map;this.pendingRefresh=null;this.lastRefreshFailureAt=null;this.deviceKeyWatcher=null;this.sessionUpdateWatchers=new Map;this.statusWriteChains=new Map;this.heartbeatTimers=new Map;this.environment=A(),c.info("[AppSyncClient] Initialized",{environment:this.environment})}static{this.REFRESH_BACKOFF_MS=3e4}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}async authenticateWithStoredTokens(){try{let e=await g.getTokens(this.environment);if(!e)return c.debug("[AppSyncClient] No stored tokens found"),!1;if(c.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:g.isTokenExpired(e)}),g.isTokenExpired(e)){if(c.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return c.warn("[AppSyncClient] Token refresh failed"),!1}else this.tokens=e;return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,c.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){return c.error("[AppSyncClient] Authentication failed:",e),!1}}async refreshTokens(e){if(this.pendingRefresh)return this.pendingRefresh;if(this.lastRefreshFailureAt!==null&&Date.now()-this.lastRefreshFailureAt<n.REFRESH_BACKOFF_MS)return!1;this.pendingRefresh=this.performRefresh(e);try{return await this.pendingRefresh}finally{this.pendingRefresh=null}}async performRefresh(e){let t=await this.callCognitoRefresh(e.refreshToken);if(t!==null)return this.applyRefreshedTokens(e,t);let r=null;try{r=await g.getTokens(this.environment)}catch(i){c.warn("[AppSyncClient] Failed to re-read tokens from storage during refresh recovery",{error:i instanceof Error?i.message:String(i)})}if(r&&r.refreshToken&&r.refreshToken!==e.refreshToken){c.info("[AppSyncClient] In-memory refresh token rejected; retrying with storage-backed token (likely out-of-band re-auth)");let i=await this.callCognitoRefresh(r.refreshToken);if(i!==null)return this.applyRefreshedTokens(r,i)}return this.lastRefreshFailureAt=Date.now(),!1}async callCognitoRefresh(e){try{let t=k(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e}),s=await se(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");return s.ok?await s.json():(c.error("[AppSyncClient] Token refresh failed",{status:s.status}),null)}catch(t){return c.error("[AppSyncClient] Token refresh error:",t),null}}async applyRefreshedTokens(e,t){let r={...e,accessToken:t.access_token,idToken:t.id_token,expiresAt:Date.now()+t.expires_in*1e3};this.tokens=r,this.lastRefreshFailureAt=null;try{await g.setTokens(r,this.environment),c.info("[AppSyncClient] Tokens refreshed",{expiresAt:new Date(r.expiresAt).toISOString()})}catch(i){c.warn("[AppSyncClient] Tokens refreshed but persistence failed; daemon keeps using fresh tokens in memory. A restart while persistence is still broken would lose them.",{error:i instanceof Error?i.message:String(i),expiresAt:new Date(r.expiresAt).toISOString()})}return!0}isAuthenticated(){return this.authenticated}signOut(){this.authenticated=!1,this.tokens=null,this.currentUserId=null,this.currentEmail=null,this.cleanupSubscriptions(),c.info("[AppSyncClient] Signed out")}async graphqlRequest(e,t,r=!1){let i=k();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let s={"Content-Type":"application/json",Authorization:this.tokens.idToken},o=await se(i.aws.appsyncUrl,{method:"POST",headers:s,body:JSON.stringify({query:e,variables:t})},"AppSync GraphQL request"),a=await o.json();if(o.status===401&&!r&&this.tokens){if(c.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),await this.refreshTokens(this.tokens))return this.graphqlRequest(e,t,!0);throw new Error("Token expired and refresh failed")}if(!o.ok)throw new Error(`GraphQL request failed: ${o.status}`);if(a.errors?.length)throw new Error(`GraphQL error: ${a.errors[0].message}`);return a}async createSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(C.createSession,{input:t});return c.info("[AppSyncClient] Session created",{sessionId:r.data.createSession.sessionId}),r.data.createSession}async updateSession(e){if(e.status===void 0)return this.doUpdateSession(e);let r=(this.statusWriteChains.get(e.sessionId)??Promise.resolve()).catch(()=>{}).then(()=>this.doUpdateSession(e));return this.statusWriteChains.set(e.sessionId,r.catch(()=>{})),r}async doUpdateSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(C.updateSession,{input:t});return c.debug("[AppSyncClient] Session updated",{sessionId:r.data.updateSession.sessionId}),r.data.updateSession}async getSession(e){return(await this.graphqlRequest(M.getSession,{sessionId:e})).data.getSession}async createEvent(e){let t=Date.now();if(e.sessionId&&$t(e.sessionId,e.type,t)){let s=Lt(e.sessionId);return s&&c.info("[AppSyncClient] client event throttle engaged",{sessionId:e.sessionId,type:e.type,windowCount:s.count,threshold:Ut}),{eventId:`local-throttled-${t}-${Math.random().toString(36).slice(2,11)}`,sessionId:e.sessionId,type:e.type,source:e.source,content:e.content,timestamp:e.timestamp??new Date(t).toISOString(),...e.promptId!==void 0?{promptId:e.promptId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{},...e.isEncrypted!==void 0?{isEncrypted:e.isEncrypted}:{}}}let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},i=await this.graphqlRequest(C.createEvent,{input:r});return c.debug("[AppSyncClient] Event created",{eventId:i.data.createEvent.eventId,type:i.data.createEvent.type}),i.data.createEvent}async updateEventStatus(e){return(await this.graphqlRequest(C.updateEventStatus,{input:e})).data.updateEventStatus}async listEvents(e,t,r){return(await this.graphqlRequest(M.listEvents,{sessionId:e,source:t,limit:r})).data.listEvents.items}async listSessions(e=100){if(!this.currentUserId)throw new Error("Not authenticated");let t=[],r=null;do{let s=(await this.graphqlRequest(M.listSessions,{userId:this.currentUserId,limit:e,nextToken:r})).data?.listSessions;s?.items&&t.push(...s.items),r=s?.nextToken??null}while(r);return t}async sweepOrphanSessions(e){let t=e.staleThresholdMs??9e5,r=new Set(e.excludeSessionIds??[]),i=Date.now(),s;try{s=await this.listSessions()}catch(a){return c.warn("[AppSyncClient] OrphanSweep: listSessions failed, skipping sweep",{agentType:e.agentType,error:a instanceof Error?a.message:String(a)}),0}let o=0;for(let a of s){if(a.agentType!==e.agentType||a.status!=="ACTIVE"||r.has(a.sessionId)||!a.lastHeartbeatAt)continue;let d=i-new Date(a.lastHeartbeatAt).getTime();if(!(d<t)){c.warn("[AppSyncClient] OrphanSweep: marking stale session INACTIVE",{sessionId:a.sessionId,agentType:a.agentType,lastHeartbeatAt:a.lastHeartbeatAt,heartbeatAgeMinutes:Math.round(d/6e4)});try{await this.updateSession({sessionId:a.sessionId,status:"INACTIVE"}),o++}catch(l){c.warn("[AppSyncClient] OrphanSweep: updateSession failed, leaving row as-is",{sessionId:a.sessionId,error:l instanceof Error?l.message:String(l)})}}}return o>0&&c.info("[AppSyncClient] OrphanSweep complete",{agentType:e.agentType,swept:o}),o}async listUserDeviceKeys(){return(await this.graphqlRequest(M.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async registerDeviceKey(e,t,r,i){let s={deviceId:e,publicKey:t,platform:r,deviceName:i};await this.graphqlRequest(C.registerDeviceKey,{input:s}),c.info("[AppSyncClient] Device key registered",{deviceId:e,platform:r})}async grantSessionKey(e){await this.graphqlRequest(C.grantSessionKey,{input:e}),c.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(C.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}subscribeToEvents(e,t,r){c.info("[AppSyncClient] Subscribing to events",{sessionId:e});let i=this.activeSubscriptions.get(e);i&&(this.cleanupSubscriptionState(i),this.activeSubscriptions.delete(e));let s={ws:null,subscriptionId:(0,X.v4)(),sessionId:e,onEvent:t,onError:r,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,s),this.createSubscription(s),()=>{this.cleanupSubscriptionState(s),this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=k(),t=new URL(e.aws.appsyncUrl),i=/\.appsync-api\.[^.]+\.amazonaws\.com$/.test(t.host)?e.aws.appsyncUrl.replace("https://","wss://").replace("appsync-api","appsync-realtime-api"):`wss://${t.host}/graphql/realtime`,s={host:t.host};this.tokens?.idToken&&(s.Authorization=this.tokens.idToken);let o=Buffer.from(JSON.stringify(s)).toString("base64"),a=Buffer.from(JSON.stringify({})).toString("base64");return`${i}?header=${o}&payload=${a}`}createSubscription(e){let{sessionId:t,subscriptionId:r,onEvent:i,onError:s}=e;try{let o=this.buildRealtimeUrl(),a=new Y.default(o,["graphql-ws"]);a.on("open",()=>{c.info("[AppSyncClient] WebSocket connected",{sessionId:t}),a.send(JSON.stringify({type:"connection_init"}))}),a.on("message",d=>{try{let l=JSON.parse(d.toString());switch(l.type){case"connection_ack":this.sendSubscriptionStart(a,e);break;case"start_ack":if(e.destroyed)break;c.info("[AppSyncClient] Subscription started",{sessionId:t});let y=e.reconnectAttempts>0;e.isReconnecting=!1,e.reconnectAttempts=0,this.startHeartbeat(t),y&&this.updateSession({sessionId:t,status:"ACTIVE"}).then(()=>c.info("[AppSyncClient] Re-asserted session ACTIVE after reconnect",{sessionId:t})).catch(f=>c.warn("[AppSyncClient] Re-assert ACTIVE after reconnect failed",{sessionId:t,error:f instanceof Error?f.message:String(f)}));break;case"data":this.resetKeepAliveTimer(e);let p=l.payload?.data?.onEventCreated;p&&p.source==="MOBILE"&&i(p);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let h=l.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(h));break}}catch(l){c.error("[AppSyncClient] Failed to parse message",{error:l})}}),a.on("error",d=>{c.error("[AppSyncClient] WebSocket error",{sessionId:t,error:d.message}),this.handleSubscriptionError(e,d)}),a.on("close",(d,l)=>{c.info("[AppSyncClient] WebSocket closed",{sessionId:t,code:d}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(t)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${d}`))}),e.ws=a,this.resetKeepAliveTimer(e)}catch(o){this.handleSubscriptionError(e,o)}}sendSubscriptionStart(e,t){let r=k(),{sessionId:i,subscriptionId:s}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:J.onEventCreated,variables:{sessionId:i}}),extensions:{authorization:o}}}))}resetKeepAliveTimer(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSubscriptionError(e,new Error("Keep-alive timeout"))},300*1e3)}handleSubscriptionError(e,t){let{sessionId:r,onError:i}=e;if(e.isReconnecting||!this.activeSubscriptions.has(r))return;e.isReconnecting=!0,e.reconnectAttempts++,this.stopHeartbeat(r);let s=e.reconnectAttempts<=E.urgentMaxAttempts,o;if(s?o=Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):(o=E.persistentDelayMs,e.reconnectAttempts===E.urgentMaxAttempts+1&&c.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:r})),c.info("[AppSyncClient] Scheduling reconnect",{sessionId:r,attempt:e.reconnectAttempts,phase:s?"urgent":"persistent",delayMs:o}),e.ws){try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(r)!==e){c.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:r});return}try{let a=await g.getTokens(this.environment);a&&(g.isTokenExpired(a)?await this.refreshTokens(a)&&c.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:r}):this.tokens=a)}catch{c.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:r})}if(e.destroyed||this.activeSubscriptions.get(r)!==e){c.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:r});return}e.subscriptionId=(0,X.v4)(),this.createSubscription(e)},o)}cleanupSubscriptionState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===Y.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}subscribeToDeviceKeyRegistered(e,t,r,i){c.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let s={userId:e,subscriptionId:(0,X.v4)(),ws:null,onNewDevice:t,onReconnect:r,onError:i,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.deviceKeyWatcher=s,this.createDeviceKeyWatcherConnection(s),()=>{this.stopDeviceKeyWatcherInternal()}}stopDeviceKeyWatcher(){this.stopDeviceKeyWatcherInternal()}stopDeviceKeyWatcherInternal(){let e=this.deviceKeyWatcher;if(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===Y.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}this.deviceKeyWatcher=null,c.info("[AppSyncClient] Device key watcher stopped")}}createDeviceKeyWatcherConnection(e){try{let t=this.buildRealtimeUrl(),r=new Y.default(t,["graphql-ws"]);r.on("open",()=>{c.info("[AppSyncClient] Device key watcher WebSocket connected",{userId:e.userId}),r.send(JSON.stringify({type:"connection_init"}))}),r.on("message",i=>{try{let s=JSON.parse(i.toString());switch(s.type){case"connection_ack":this.sendDeviceKeyWatcherStart(r,e);break;case"start_ack":c.info("[AppSyncClient] Device key watcher subscription started",{userId:e.userId});let o=e.isReconnecting;if(e.isReconnecting=!1,e.reconnectAttempts=0,o&&e.onReconnect)try{e.onReconnect()}catch(l){c.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:l})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let a=s.payload?.data?.onDeviceKeyRegistered;if(a){c.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:a.deviceId,platform:a.platform});try{e.onNewDevice(a)}catch(l){c.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:l})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let d=s.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(d));break}}catch(s){c.error("[AppSyncClient] Failed to parse device key watcher message",{error:s})}}),r.on("error",i=>{c.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleDeviceKeyWatcherError(e,i)}),r.on("close",i=>{c.info("[AppSyncClient] Device key watcher WebSocket closed",{userId:e.userId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.deviceKeyWatcher===e&&this.handleDeviceKeyWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=r,this.resetDeviceKeyWatcherKeepAlive(e)}catch(t){this.handleDeviceKeyWatcherError(e,t)}}sendDeviceKeyWatcherStart(e,t){let r=k(),{userId:i,subscriptionId:s}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:J.onDeviceKeyRegistered,variables:{userId:i}}),extensions:{authorization:o}}}))}resetDeviceKeyWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleDeviceKeyWatcherError(e,new Error("Device key watcher keep-alive timeout"))},300*1e3)}handleDeviceKeyWatcherError(e,t){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(t)}catch{}if(e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=E.urgentMaxAttempts?Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):E.persistentDelayMs;c.warn("[AppSyncClient] Device key watcher reconnect scheduled",{userId:e.userId,attempts:e.reconnectAttempts,delayMs:i,error:t.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.deviceKeyWatcher!==e){c.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}try{let s=await g.getTokens(this.environment);s&&(g.isTokenExpired(s)?await this.refreshTokens(s)&&c.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId}):this.tokens=s)}catch{c.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,X.v4)(),this.createDeviceKeyWatcherConnection(e))},i)}watchForMobileEnd(e,t){c.info("[AppSyncClient] Starting mobile-end watcher",{sessionId:e});let r=this.sessionUpdateWatchers.get(e);r&&(c.info("[AppSyncClient] Replacing existing mobile-end watcher",{sessionId:e}),this.cleanupSessionUpdateWatcherState(r),this.sessionUpdateWatchers.delete(e));let i={sessionId:e,subscriptionId:(0,X.v4)(),ws:null,onMobileEndRequested:t,priorStatus:"ACTIVE",firedOnce:!1,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.sessionUpdateWatchers.set(e,i),this.createSessionUpdateWatcherConnection(i),{stop:()=>{this.sessionUpdateWatchers.get(e)===i&&(this.cleanupSessionUpdateWatcherState(i),this.sessionUpdateWatchers.delete(e),c.info("[AppSyncClient] Mobile-end watcher stopped",{sessionId:e}))}}}createSessionUpdateWatcherConnection(e){try{let t=this.buildRealtimeUrl(),r=new Y.default(t,["graphql-ws"]);r.on("open",()=>{c.info("[AppSyncClient] Mobile-end watcher WebSocket connected",{sessionId:e.sessionId}),r.send(JSON.stringify({type:"connection_init"}))}),r.on("message",i=>{try{let s=JSON.parse(i.toString());switch(s.type){case"connection_ack":this.sendSessionUpdateWatcherStart(r,e);break;case"start_ack":c.info("[AppSyncClient] Mobile-end watcher subscription started",{sessionId:e.sessionId}),e.isReconnecting=!1,e.reconnectAttempts=0;break;case"data":this.resetSessionUpdateWatcherKeepAlive(e),this.handleSessionUpdatePayload(e,s.payload);break;case"ka":this.resetSessionUpdateWatcherKeepAlive(e);break;case"error":let o=s.payload?.errors?.[0]?.message||"Unknown error";this.handleSessionUpdateWatcherError(e,new Error(o));break}}catch(s){c.error("[AppSyncClient] Failed to parse mobile-end watcher message",{error:s})}}),r.on("error",i=>{c.error("[AppSyncClient] Mobile-end watcher WebSocket error",{sessionId:e.sessionId,error:i.message}),this.handleSessionUpdateWatcherError(e,i)}),r.on("close",i=>{c.info("[AppSyncClient] Mobile-end watcher WebSocket closed",{sessionId:e.sessionId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.sessionUpdateWatchers.get(e.sessionId)===e&&this.handleSessionUpdateWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=r,this.resetSessionUpdateWatcherKeepAlive(e)}catch(t){this.handleSessionUpdateWatcherError(e,t)}}handleSessionUpdatePayload(e,t){let r=t?.data?.onSessionUpdated;if(!r){c.warn("[AppSyncClient] Mobile-end watcher received malformed payload",{sessionId:e.sessionId});return}if(e.firedOnce)return;let i=r.status;if(i==null){c.debug("[AppSyncClient] Mobile-end watcher skipped non-status payload",{sessionId:e.sessionId});return}if(e.priorStatus==="ACTIVE"&&i==="INACTIVE"){e.firedOnce=!0,e.priorStatus="INACTIVE",c.info("[AppSyncClient] Mobile end requested for session",{sessionId:e.sessionId}),Promise.resolve().then(()=>e.onMobileEndRequested()).catch(s=>{c.warn("[AppSyncClient] Mobile-end callback threw",{sessionId:e.sessionId,error:s})});return}e.priorStatus=i}sendSessionUpdateWatcherStart(e,t){let r=k(),{sessionId:i,subscriptionId:s}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:J.onSessionUpdated,variables:{sessionId:i}}),extensions:{authorization:o}}}))}resetSessionUpdateWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSessionUpdateWatcherError(e,new Error("Mobile-end watcher keep-alive timeout"))},300*1e3)}handleSessionUpdateWatcherError(e,t){if(e.isReconnecting||e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=E.urgentMaxAttempts?Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):E.persistentDelayMs;c.warn("[AppSyncClient] Mobile-end watcher reconnect scheduled",{sessionId:e.sessionId,attempts:e.reconnectAttempts,delayMs:i,error:t.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,!(e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e)){try{let s=await g.getTokens(this.environment);s&&(g.isTokenExpired(s)?await this.refreshTokens(s):this.tokens=s)}catch{c.warn("[AppSyncClient] Token refresh failed before mobile-end watcher reconnect",{sessionId:e.sessionId})}e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,X.v4)(),this.createSessionUpdateWatcherConnection(e))}},i)}cleanupSessionUpdateWatcherState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===Y.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}startHeartbeat(e,t=120*1e3){this.stopHeartbeat(e),this.sendHeartbeat(e);let r=setInterval(()=>{this.sendHeartbeat(e)},t);this.heartbeatTimers.set(e,r),c.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:t})}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e),c.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async sendHeartbeat(e){try{await this.updateSession({sessionId:e,lastHeartbeatAt:new Date().toISOString()}),c.debug("[AppSyncClient] Heartbeat sent",{sessionId:e})}catch(t){c.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:t})}}cleanupSubscription(e){let t=this.activeSubscriptions.get(e);t&&(this.cleanupSubscriptionState(t),this.activeSubscriptions.get(e)===t&&this.activeSubscriptions.delete(e))}cleanupSubscriptions(){this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear(),this.stopDeviceKeyWatcherInternal(),this.sessionUpdateWatchers.forEach(e=>{this.cleanupSessionUpdateWatcherState(e)}),this.sessionUpdateWatchers.clear(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear()}};var Ft=v(require("crypto")),Ht=v(require("fs")),qt=v(require("http")),Vt=require("child_process");ie();U();q();re();var oe=8080,ae=20,ze="/callback";async function ve(n){let e=null;for(let t=0;t<ae;t++){let r=oe+t;try{let i=await new Promise((s,o)=>{let a=qt.createServer(n),d=y=>{a.removeListener("listening",l),o(y)},l=()=>{a.removeListener("error",d),a.on("error",y=>{c.error("[AuthService] OAuth server post-bind error",{port:r,code:y?.code,message:y?.message})}),s(a)};a.once("error",d),a.once("listening",l),a.listen(r,"localhost")});return c.info(`[AuthService] OAuth server bound on port ${r} (attempt ${t+1}/${ae})`),{server:i,port:r}}catch(i){if(e=i,i?.code==="EADDRINUSE")continue;throw i}}throw Object.assign(new Error(`All ports ${oe}-${oe+ae-1} are in use. Free at least one for OAuth callback or quit a conflicting service (common collisions: Vite, Webpack, Spring Boot, Docker exposed ports). Underlying: ${e?.message??"EADDRINUSE"}`),{code:"EADDRINUSE_ALL"})}var ce=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}openBrowser(e){console.error(""),console.error("Opening your browser for sign-in..."),this.isRunningInWSL()?console.error("If your browser does not open, paste this URL in your Windows browser:"):console.error("If your browser does not open automatically, visit this URL:"),console.error(` ${e}`),console.error("");let t=this.getBrowserCommands();this.tryBrowserCommand(t,e,0)}getBrowserCommands(){let e=process.platform;if(e==="darwin")return[{cmd:"open",fixedArgs:[]}];if(e==="win32")return[{cmd:"cmd",fixedArgs:["/c","start",""]}];let t=[];return this.isRunningInWSL()&&(t.push({cmd:"wslview",fixedArgs:[]}),t.push({cmd:"cmd.exe",fixedArgs:["/c","start",""]}),t.push({cmd:"powershell.exe",fixedArgs:["-NoProfile","-Command","Start-Process"]})),t.push({cmd:"xdg-open",fixedArgs:[]}),t}isRunningInWSL(){if(process.platform!=="linux")return!1;try{let e=Ht.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,t,r){if(r>=e.length){c.debug("[AuthService] No browser-opening command succeeded. User must open the sign-in URL manually (printed to stderr above)."),console.error(""),console.error("\u26A0\uFE0F Could not open browser automatically."),this.isRunningInWSL()?console.error(" WSL detected \u2014 paste this URL in your Windows browser:"):console.error(" Please copy and paste this URL into your browser:"),console.error(` ${t}`),console.error("");return}let i=e[r],s=[...i.fixedArgs,t],o=!1,a=p=>{o||(o=!0,c.debug(`[AuthService] Browser command '${i.cmd}' ${p}; trying next fallback`),this.tryBrowserCommand(e,t,r+1))},d=p=>{o||(o=!0,c.debug(`[AuthService] Browser command '${i.cmd}' ${p}`))},l;try{l=(0,Vt.spawn)(i.cmd,s,{detached:!0,stdio:"ignore"})}catch(p){a(`threw synchronously: ${p?.message||p}`);return}l.on("error",p=>{a(`failed to spawn: ${p?.message||p}`)}),l.on("exit",(p,h)=>{p===0?d("exited successfully"):a(h?`terminated by signal ${h}`:`exited with code ${p}`)}),setTimeout(()=>{d("still running after 3s, assuming success")},3e3).unref(),l.unref()}generateState(){return Ft.randomBytes(32).toString("hex")}buildAuthUrl(e,t){let r=k(),i=new URLSearchParams({client_id:r.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:t,state:e});return`https://${r.aws.cognitoDomain}/oauth2/authorize?${i.toString()}`}async exchangeCodeForTokens(e,t){let r=k(),i=`https://${r.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"authorization_code",client_id:r.aws.cognitoClientId,code:e,redirect_uri:t}),o;try{o=await se(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token exchange")}catch(d){throw await I("token_exchange_network_error"),_(d,"token_exchange_network_error"),d}if(!o.ok){let d=await o.text(),l=new Error(`Token exchange failed: ${o.status} ${d}`);throw await I("token_exchange_failed",{httpStatus:o.status}),_(l,"token_exchange_failed"),l}let a=await o.json();return{accessToken:a.access_token,idToken:a.id_token,refreshToken:a.refresh_token,expiresIn:a.expires_in}}decodeJwt(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT");return JSON.parse(Buffer.from(t[1],"base64").toString("utf-8"))}async refreshTokens(e){let t=k(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e}),s=await se(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");if(!s.ok)throw new Error(`Token refresh failed: ${s.status}`);let o=await s.json();return{accessToken:o.access_token,idToken:o.id_token,expiresIn:o.expires_in}}async login(){let e=await g.getTokens(A());if(e&&!g.isTokenExpired(e))return e;let t=this.generateState();return new Promise((r,i)=>{let s={},o=null,a=!1,d=!1,l=h=>{h.closeAllConnections?.()},y=h=>{if(a)return;a=!0,o&&(clearTimeout(o),o=null);let f=s.server;f?(l(f),f.close(()=>r(h))):r(h)},p=h=>{if(a)return;a=!0,o&&(clearTimeout(o),o=null);let f=s.server;f?(l(f),f.close(()=>i(h))):i(h)};(async()=>{let h;try{h=await ve(async(m,S)=>{if(d||a){S.writeHead(200,{Connection:"close"}),S.end();return}let nt=`http://localhost:${m.socket?.localPort??h.port}${ze}`,be=new URL(m.url||"",nt);if(be.pathname!==ze){S.writeHead(404,{Connection:"close"}),S.end("Not found");return}try{let F=be.searchParams.get("code"),Re=be.searchParams.get("state"),Q=be.searchParams.get("error");if(Q){let b=new Error(`OAuth error: ${Q}`);throw await I("cognito_rejected"),_(b,"cognito_rejected"),b}if(Re!==t){let b=new Error("State mismatch");throw await I("state_mismatch"),_(b,"state_mismatch"),b}if(!F){let b=new Error("No authorization code");throw await I("no_authorization_code"),_(b,"no_authorization_code"),b}d=!0;let de=await this.exchangeCodeForTokens(F,nt),it=this.decodeJwt(de.idToken),Ke={accessToken:de.accessToken,idToken:de.idToken,refreshToken:de.refreshToken,expiresAt:Date.now()+de.expiresIn*1e3,userId:it.sub,email:it.email||"unknown"};try{await g.setTokens(Ke,A())}catch(b){throw await I("keychain_write_failed",{errorFragment:b?.message?String(b.message):String(b)}),_(b,"keychain_write_failed"),b}S.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),S.end(`
208
208
  <!DOCTYPE html>
209
209
  <html>
210
210
  <head><title>Success</title></head>
@@ -213,17 +213,17 @@ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,Zt)}`:o+=` ${r}`),o}log
213
213
  <p>You can close this window.</p>
214
214
  </body>
215
215
  </html>
216
- `),a=!0,o&&(clearTimeout(o),o=null),setTimeout(()=>{let k=s.server;k?(l(k),k.close(()=>r(Re))):r(Re)},500)}catch(F){let _e=String(F?.message||F).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");S.writeHead(400,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),S.end(`
216
+ `),a=!0,o&&(clearTimeout(o),o=null),setTimeout(()=>{let b=s.server;b?(l(b),b.close(()=>r(Ke))):r(Ke)},500)}catch(F){let Re=String(F?.message||F).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");S.writeHead(400,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),S.end(`
217
217
  <!DOCTYPE html>
218
218
  <html>
219
219
  <head><title>Error</title></head>
220
220
  <body style="font-family: system-ui; max-width: 720px; margin: 50px auto; padding: 0 16px;">
221
221
  <h1 style="color: #ef4444; text-align: center;">&#10007; Authentication Failed</h1>
222
- <pre style="background: #f4f4f5; padding: 16px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.5;">${_e}</pre>
222
+ <pre style="background: #f4f4f5; padding: 16px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.5;">${Re}</pre>
223
223
  <p style="text-align: center; color: #71717a; margin-top: 24px;">You can close this window and try again in your terminal.</p>
224
224
  </body>
225
225
  </html>
226
- `),a=!0,o&&(clearTimeout(o),o=null),setTimeout(()=>{let Z=s.server;Z?(l(Z),Z.close(()=>i(F))):i(F)},500)}})}catch(m){let S=m?.code==="EADDRINUSE_ALL"?"port_range_exhausted":"server_listen_failed";return await I(S),x(m,S),p(m)}s.server=h.server;let f=`http://localhost:${h.port}${je}`,B=this.buildAuthUrl(t,f);this.openBrowser(B),o=setTimeout(async()=>{let m=new Error("Login timeout");await I("login_timeout"),x(m,"login_timeout"),p(m)},120*1e3)})().catch(h=>{p(h)})})}async logout(){let e=b(),t=await y.deleteTokens(T());return t&&new Promise(r=>{let i={},s=null,o=!1,a=d=>{if(o)return;o=!0,s&&(clearTimeout(s),s=null);let l=i.server;l?(l.closeAllConnections?.(),l.close(()=>r(d))):r(d)};(async()=>{try{let d=await me((h,f)=>{h.url?.startsWith("/signout")?(f.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),f.end(`
226
+ `),a=!0,o&&(clearTimeout(o),o=null),setTimeout(()=>{let Q=s.server;Q?(l(Q),Q.close(()=>i(F))):i(F)},500)}})}catch(m){let S=m?.code==="EADDRINUSE_ALL"?"port_range_exhausted":"server_listen_failed";return await I(S),_(m,S),p(m)}s.server=h.server;let f=`http://localhost:${h.port}${ze}`,B=this.buildAuthUrl(t,f);this.openBrowser(B),o=setTimeout(async()=>{let m=new Error("Login timeout");await I("login_timeout"),_(m,"login_timeout"),p(m)},120*1e3)})().catch(h=>{p(h)})})}async logout(){let e=k(),t=await g.deleteTokens(A());return t&&new Promise(r=>{let i={},s=null,o=!1,a=d=>{if(o)return;o=!0,s&&(clearTimeout(s),s=null);let l=i.server;l?(l.closeAllConnections?.(),l.close(()=>r(d))):r(d)};(async()=>{try{let d=await ve((h,f)=>{h.url?.startsWith("/signout")?(f.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),f.end(`
227
227
  <!DOCTYPE html>
228
228
  <html>
229
229
  <head><title>Signed Out</title></head>
@@ -232,27 +232,27 @@ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,Zt)}`:o+=` ${r}`),o}log
232
232
  <p>You can close this window.</p>
233
233
  </body>
234
234
  </html>
235
- `),setTimeout(()=>a(!0),500)):(f.writeHead(404,{Connection:"close"}),f.end("Not found"))});i.server=d.server;let l=`http://localhost:${d.port}/signout`,g=new URLSearchParams({client_id:e.aws.cognitoClientId,logout_uri:l}),p=`https://${e.aws.cognitoDomain}/logout?${g.toString()}`;this.openBrowser(p),s=setTimeout(()=>a(!0),30*1e3)}catch(d){c.warn("[AuthService] Logout server bind failed; tokens deleted but Cognito session may persist",{code:d?.code,message:d?.message}),a(!0)}})()})}async getStatus(){let e=await y.getTokens(T());return e?{authenticated:!y.isTokenExpired(e),tokens:e}:{authenticated:!1}}},$=ae.getInstance();ne();te();var u={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function mr(){console.log(`${u.cyan}CodeVibe Login${u.reset}
235
+ `),setTimeout(()=>a(!0),500)):(f.writeHead(404,{Connection:"close"}),f.end("Not found"))});i.server=d.server;let l=`http://localhost:${d.port}/signout`,y=new URLSearchParams({client_id:e.aws.cognitoClientId,logout_uri:l}),p=`https://${e.aws.cognitoDomain}/logout?${y.toString()}`;this.openBrowser(p),s=setTimeout(()=>a(!0),30*1e3)}catch(d){c.warn("[AuthService] Logout server bind failed; tokens deleted but Cognito session may persist",{code:d?.code,message:d?.message}),a(!0)}})()})}async getStatus(){let e=await g.getTokens(A());return e?{authenticated:!g.isTokenExpired(e),tokens:e}:{authenticated:!1}}},$=ce.getInstance();ie();re();var u={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function _r(){console.log(`${u.cyan}CodeVibe Login${u.reset}
236
236
  `);try{let n=await $.getStatus();if(n.authenticated&&n.tokens){console.log(`${u.yellow}Already logged in as: ${n.tokens.email}${u.reset}`),console.log(`Token expires: ${new Date(n.tokens.expiresAt).toLocaleString()}`),console.log(`
237
237
  Run '${u.dim}codevibe logout${u.reset}' to sign out first.`),process.exit(0);return}console.log("Opening browser for authentication..."),console.log(`${u.dim}Waiting for callback...${u.reset}
238
238
  `);let e=await $.login();e&&(console.log(`
239
- ${u.green}\u2713 Authentication successful!${u.reset}`),console.log(` User: ${e.email}`),console.log(` User ID: ${e.userId}`),console.log(` Expires: ${new Date(e.expiresAt).toLocaleString()}`),await de(e.userId)),process.exit(0)}catch(n){let e=(()=>{let t=n?.message;return typeof t=="string"&&t.length>0?t:n==null?"(null/undefined error)":`[no_message ctor=${n?.constructor?.name??typeof n}] ${String(n).substring(0,80)}`})();console.error(`
240
- ${u.red}\u2717 Authentication failed${u.reset}`),console.error(` Error: ${e}`),le(n)||await I("unknown",{errorFragment:e}),process.exit(1)}}async function vr(){console.log(`${u.cyan}CodeVibe Logout${u.reset}
239
+ ${u.green}\u2713 Authentication successful!${u.reset}`),console.log(` User: ${e.email}`),console.log(` User ID: ${e.userId}`),console.log(` Expires: ${new Date(e.expiresAt).toLocaleString()}`),await le(e.userId)),process.exit(0)}catch(n){let e=(()=>{let t=n?.message;return typeof t=="string"&&t.length>0?t:n==null?"(null/undefined error)":`[no_message ctor=${n?.constructor?.name??typeof n}] ${String(n).substring(0,80)}`})();console.error(`
240
+ ${u.red}\u2717 Authentication failed${u.reset}`),console.error(` Error: ${e}`),pe(n)||await I("unknown",{errorFragment:e}),process.exit(1)}}async function xr(){console.log(`${u.cyan}CodeVibe Logout${u.reset}
241
241
  `);try{let n=await $.getStatus();if(!n.authenticated){console.log(`${u.yellow}Not logged in.${u.reset}`),process.exit(0);return}let e=n.tokens?.email;await $.logout()?(console.log(`${u.green}\u2713 Logged out successfully.${u.reset}`),console.log(` Previous user: ${e}`),console.log(`
242
- ${u.dim}Clearing browser session...${u.reset}`)):console.log(`${u.red}\u2717 Failed to log out.${u.reset}`),process.exit(0)}catch(n){console.error(`${u.red}\u2717 Logout failed: ${n.message}${u.reset}`),process.exit(1)}}async function Sr(){console.log(`${u.cyan}CodeVibe Auth Status${u.reset}
242
+ ${u.dim}Clearing browser session...${u.reset}`)):console.log(`${u.red}\u2717 Failed to log out.${u.reset}`),process.exit(0)}catch(n){console.error(`${u.red}\u2717 Logout failed: ${n.message}${u.reset}`),process.exit(1)}}async function Cr(){console.log(`${u.cyan}CodeVibe Auth Status${u.reset}
243
243
  `);try{let n=await $.getStatus();if(!n.tokens){console.log(`${u.yellow}Not authenticated.${u.reset}`),console.log(`
244
244
  Run '${u.dim}codevibe login${u.reset}' to sign in.`),process.exit(0);return}let e=!n.authenticated;console.log(e?`${u.yellow}\u26A0 Token expired${u.reset}`:`${u.green}\u2713 Authenticated${u.reset}`),console.log(` User: ${n.tokens.email}`),console.log(` User ID: ${n.tokens.userId}`),console.log(` Expires: ${new Date(n.tokens.expiresAt).toLocaleString()}`),e&&console.log(`
245
- ${u.dim}Token will be refreshed automatically.${u.reset}`),process.exit(0)}catch(n){console.error(`${u.red}\u2717 Status check failed: ${n.message}${u.reset}`),process.exit(1)}}async function kr(){console.log(`${u.cyan}CodeVibe Reset Device${u.reset}
245
+ ${u.dim}Token will be refreshed automatically.${u.reset}`),process.exit(0)}catch(n){console.error(`${u.red}\u2717 Status check failed: ${n.message}${u.reset}`),process.exit(1)}}async function Dr(){console.log(`${u.cyan}CodeVibe Reset Device${u.reset}
246
246
  `),console.log(`${u.red}\u26A0 WARNING: This will delete your device identity.${u.reset}`),console.log(`${u.red} Old encrypted sessions will become inaccessible.${u.reset}
247
- `);let{keychainManager:n}=await Promise.resolve().then(()=>(U(),Rt));try{await n.clearAllData(),console.log(`${u.green}\u2713 Device reset complete.${u.reset}`),console.log(` Run '${u.dim}codevibe login${u.reset}' to set up again.`),process.exit(0)}catch(e){console.error(`${u.red}\u2717 Reset failed: ${e.message}${u.reset}`),process.exit(1)}}function br(){console.log(`CodeVibe Authentication
247
+ `);let{keychainManager:n}=await Promise.resolve().then(()=>(U(),Ot));try{await n.clearAllData(),console.log(`${u.green}\u2713 Device reset complete.${u.reset}`),console.log(` Run '${u.dim}codevibe login${u.reset}' to set up again.`),process.exit(0)}catch(e){console.error(`${u.red}\u2717 Reset failed: ${e.message}${u.reset}`),process.exit(1)}}function Rr(){console.log(`CodeVibe Authentication
248
248
  `),console.log("Usage:"),console.log(" codevibe login - Sign in via browser"),console.log(" codevibe logout - Sign out"),console.log(" codevibe status - Show auth status"),console.log(" codevibe reset-device - Reset device identity (destructive)"),console.log(`
249
- Environment:`),console.log(' Set ENVIRONMENT env var to "development" or "production" (default)'),console.log(" Example: ENVIRONMENT=development codevibe login")}async function Ce(n){let e=T();console.log(`${u.dim}Environment: ${e}${u.reset}
250
- `);let r=n.slice(2).filter(i=>!i.startsWith("--"))[0];switch(r){case"login":await mr();break;case"logout":await vr();break;case"status":await Sr();break;case"reset-device":await kr();break;default:br(),process.exit(r?1:0)}}require.main===module&&Ce(process.argv).catch(n=>{console.error("Error:",n),process.exit(1)});te();ne();q();var wr=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function Ft(n){let e=ze(n);if(!e)return null;let t=Er(e);if(t)return t;let r=Ir(e);return r||null}function ze(n){return n.replace(/\r/g,`
251
- `).replace(wr,"").replace(/[│┌┐└┘─├┤┬┴┼╌╎╭╮╯╰║═╔╗╚╝╠╣╦╩╬]/g," ").replace(/[ \t]+\n/g,`
249
+ Environment:`),console.log(' Set ENVIRONMENT env var to "development" or "production" (default)'),console.log(" Example: ENVIRONMENT=development codevibe login")}async function Ce(n){let e=A();console.log(`${u.dim}Environment: ${e}${u.reset}
250
+ `);let r=n.slice(2).filter(i=>!i.startsWith("--"))[0];switch(r){case"login":await _r();break;case"logout":await xr();break;case"status":await Cr();break;case"reset-device":await Dr();break;default:Rr(),process.exit(r?1:0)}}require.main===module&&Ce(process.argv).catch(n=>{console.error("Error:",n),process.exit(1)});re();ie();q();var Kr=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function Gt(n){let e=Xe(n);if(!e)return null;let t=Or(e);if(t)return t;let r=Pr(e);return r||null}function Xe(n){return n.replace(/\r/g,`
251
+ `).replace(Kr,"").replace(/[│┌┐└┘─├┤┬┴┼╌╎╭╮╯╰║═╔╗╚╝╠╣╦╩╬]/g," ").replace(/[ \t]+\n/g,`
252
252
  `).replace(/\n{3,}/g,`
253
253
 
254
- `).trim()}function Er(n){let e=n.split(`
255
- `).map(g=>g.trim()),t=Ar(e,g=>/\[(?:y\/n|Y\/n|y\/N)\]/.test(g)),r=t>=0?e[t]:null;if(!r)return null;let i=Ht(e,t),s=i.length>0?i.join(`
256
- `):r,o=s.toLowerCase(),a=o.includes("what to change")||o.includes("what should")||o.includes("provide")||o.includes("instructions");return{kind:"yes_no",promptText:s,options:a?[{number:"1",text:"Yes"},{number:"2",text:"No, provide instructions"}]:[{number:"1",text:"Yes"},{number:"2",text:"No"}],submitMap:{1:"y",2:"n"},requiresFollowUpText:a}}function Ir(n){let e=n.split(`
257
- `).map(d=>d.trim()),t=xr(e);if(t.length<2)return null;let r=t.map(({line:d})=>Ye(d)).filter(d=>!!d),i={};for(let d of r)i[d.number]=d.number;let s=t[0]?.index??-1,o=Ht(e,s-1);return{kind:"numbered",promptText:o.length>0?o.join(`
258
- `):"Select an option",options:r,submitMap:i}}function Ar(n,e){for(let t=n.length-1;t>=0;t-=1)if(e(n[t]))return t;return-1}function Ye(n){let e=n.match(/^(?:[>›❯▸▶➜➤*●]\s*)?(\d+)\.\s+(.*)$/);return e?{number:e[1],text:e[2]}:null}function Tr(n){return Ye(n)!==null}function xr(n){let e=[];for(let r=0;r<n.length;r+=1){let i=Ye(n[r]);i&&e.push({index:r,number:Number(i.number)})}if(e.length===0)return[];let t=[e[e.length-1]];for(let r=e.length-2;r>=0;r-=1){let i=e[r],s=t[0];if(Cr(n,i.index,s.index))break;i.number===s.number-1&&t.unshift(i)}return t.map((r,i)=>{let s=i+1<t.length?t[i+1].index-1:Dr(n,r.index);return{index:r.index,line:_r(n,r.index,s)}})}function Cr(n,e,t){for(let r=e+1;r<t;r+=1)if(!n[r])return!0;return!1}var Bt=/\((?:[a-z0-9]|esc|escape)\)\s*$/i;function Dr(n,e){let t=Bt.test(n[e])?e:-1;for(let r=e+1;r<n.length&&!(!n[r]||Tr(n[r]));r+=1)Bt.test(n[r])&&(t=r);return t>=0?t:e}function _r(n,e,t){let r=n[e];for(let i=e+1;i<=t;i+=1)r+=n[i];return r}function Ht(n,e){if(e<0)return[];let t=Ge(n,e);if(t<0)return[];let{start:r,end:i}=Je(n,t),s=n.slice(r,i+1).filter(Boolean);if(Kr(s)){let p=Rr(n,r-1);return p.length>0?p:s}if(r<=1)return s;let o=r-1;if(o=Ge(n,o),o<0||o===r-1)return s;let{start:a,end:d}=Je(n,o),l=n.slice(a,d+1).filter(Boolean);return l.some(qt)?[...l,...s]:s}function qt(n){return/^(?:would you like to|do you want to|the model would like to|action required|confirm)\b/i.test(n)}function Ge(n,e){let t=e;for(;t>=0&&!n[t];)t-=1;return t}function Je(n,e){let t=e;for(;t>=0&&n[t];)t-=1;return{start:t+1,end:e}}function Rr(n,e){let t=[],r=e;for(;r>=0&&t.length<2&&(r=Ge(n,r),!(r<0));){let{start:s,end:o}=Je(n,r),a=n.slice(s,o+1).filter(Boolean);a.length>0&&t.unshift(a),r=s-1}if(t.length===0)return[];let i=t.findIndex(s=>s.some(qt));return i>=0?t.slice(i).flat():t[t.length-1]}function Kr(n){return n.length===0?!1:n.filter(Pr).length>=Math.max(2,Math.ceil(n.length/2))}function Pr(n){return/^\d+\s/.test(n)}he();U();he();U();q();async function X(n,e,t,r={}){let i;try{i=await t.getSession(n)}catch(p){return c.warn("[SessionRekey] Failed to fetch session state for re-key",{sessionId:n,error:p instanceof Error?p.message:String(p)}),0}if(!i)return c.warn("[SessionRekey] Session not found, skipping re-key",{sessionId:n}),0;if(!i.isEncrypted)return 0;let s=i.encryptedKeys||[],o=new Set(s.map(p=>p.deviceId)),a=r.forceDeviceIds??new Set,d;try{d=await t.listUserDeviceKeys()}catch(p){return c.warn("[SessionRekey] Failed to fetch user device keys",{sessionId:n,error:p instanceof Error?p.message:String(p)}),0}let l=d.filter(p=>!o.has(p.deviceId)||a.has(p.deviceId));if(l.length===0)return 0;c.info("[SessionRekey] Granting session key to devices",{sessionId:n,existingDeviceCount:s.length,grantCount:l.length,grantDeviceIds:l.map(p=>p.deviceId),forceCount:a.size});let g=0;for(let p of l)try{let h=A.encryptSessionKey(e,p.publicKey);await t.grantSessionKey({sessionId:n,deviceId:p.deviceId,encryptedKey:h.encryptedKey,ephemeralPublicKey:h.ephemeralPublicKey}),g++,c.info("[SessionRekey] Granted session key to device",{sessionId:n,deviceId:p.deviceId,platform:p.platform})}catch(h){c.warn("[SessionRekey] Failed to grant session key to device",{sessionId:n,deviceId:p.deviceId,error:h instanceof Error?h.message:String(h)})}return g>0&&c.info("[SessionRekey] Re-key complete",{sessionId:n,grantedCount:g,requestedCount:l.length}),g}async function Vt(n,e){let t=e.pollIntervalMs??5e3,r=e.maxAttempts??6,i,s;try{i=await y.getDeviceId(),s=await y.getDevicePrivateKey()}catch(o){c.warn("[SessionRekey] A1 pre-loop keychain read failed",{sessionId:n,error:o instanceof Error?o.message:String(o)});try{e.onTimeout?.(0)}catch{}return null}for(let o=1;o<=r;o++){o>1&&await new Promise(h=>setTimeout(h,t));let a;try{a=await e.appSyncClient.getSession(n)}catch(h){c.warn("[SessionRekey] A1 getSession failed during poll, will retry",{sessionId:n,attempt:o,error:h instanceof Error?h.message:String(h)});continue}let d=a?.encryptedKeys??[],l=d.filter(h=>h.deviceId===i);if(l.length===0){c.info("[SessionRekey] A1 our deviceId still not in encryptedKeys",{sessionId:n,attempt:o,freshDeviceCount:d.length});continue}let g=null,p=[];for(let h=l.length-1;h>=0;h--)try{g=A.decryptSessionKey(l[h],s);break}catch(f){p.push(f instanceof Error?f.message:String(f))}if(g){y.cacheSessionKey(n,g);try{e.onSuccess?.(o)}catch{}return c.info("[SessionRekey] A1 self-rekey successful",{sessionId:n,attempt:o,entriesTriedToDecrypt:l.length}),g}c.warn("[SessionRekey] A1 found entries but all decrypt-failed, will retry",{sessionId:n,attempt:o,entriesTried:l.length,errors:p})}try{e.onTimeout?.(r)}catch{}return c.warn("[SessionRekey] A1 self-rekey exhausted maxAttempts",{sessionId:n,maxAttempts:r}),null}U();async function ve(n,e){try{let t=await y.getDeviceId(),r=await y.getDevicePublicKey(),i=y.getDevicePlatform(),s=y.getDeviceName();e.info("Registering device encryption key",{deviceId:t,platform:i,deviceName:s}),await n.registerDeviceKey(t,r,i,s),y.setIsRegistered(!0),e.info("Device encryption key registered successfully",{deviceId:t})}catch(t){e.warn("Failed to register device encryption key (E2E encryption may not work):",t)}}te();async function De(n,e,t){try{let r=await e.listUserDeviceKeys();if(r.length===0)return t.info("No device keys found, session will not be encrypted"),null;t.info("Preparing session encryption",{sessionId:n,deviceCount:r.length});let i=we(n),{sessionKey:s,encryptedKeys:o,skippedDeviceIds:a}=y.createSessionKey(r,{onDeviceSkipped:d=>{ut({skipped_count_bucket:ee(d),session_hash:i}).catch(()=>{})}});return a.length>0&&ht({session_hash:i,encrypted_count_bucket:ee(o.length),skipped_count_bucket:ee(a.length)}).catch(()=>{}),t.info("Session encryption prepared",{sessionId:n,deviceCount:o.length,skippedCount:a.length}),{sessionKey:s,encryptedKeys:o,skippedDeviceIds:a}}catch(r){return t.warn("Failed to prepare session encryption:",r),null}}async function Xe(n,e,t){let{sessionId:r,userId:i,agentType:s,projectPath:o,metadata:a}=n,d=null;try{d=await e.getSession(r)}catch(f){t.warn("Failed to get session (will attempt to create new)",{sessionId:r,error:f})}if(d){t.info("Session exists in backend - reactivating",{sessionId:r,previousStatus:d.status});try{await e.updateSession({sessionId:r,status:"ACTIVE"})}catch(m){t.warn("Failed to reactivate existing session, will continue",{sessionId:r,error:m})}let f=null,B=d.encryptedKeys??[];if(d.isEncrypted){if(B.length>0){try{let m=await y.getSessionKey(r,B);m&&(f=m,y.cacheSessionKey(r,m),t.info("Session key retrieved for resumed session",{sessionId:r}))}catch(m){t.warn("Failed to retrieve session key for resumed session",{sessionId:r,error:m})}if(!f){let m=we(r);t.info("Self-rekey: re-registering device key + awaiting grant",{sessionId:r,otherDeviceCount:B.length}),gt({session_hash:m,other_device_count_bucket:ee(B.length)}).catch(()=>{});try{await ve(e,t),f=await Vt(r,{appSyncClient:e,onSuccess:S=>{ft({session_hash:m,attempt_count:S}).catch(()=>{})},onTimeout:S=>{mt({session_hash:m,attempt_count:S}).catch(()=>{})}})}catch(S){t.warn("Self-rekey path failed",{sessionId:r,error:S instanceof Error?S.message:String(S)})}}}else t.warn("Encrypted session has empty encryptedKeys; cannot self-rekey",{sessionId:r});if(!f){let m=new Error(`Cannot resume encrypted session ${r}: `+(B.length===0?"session is marked encrypted but session.encryptedKeys is empty (corrupt state). Cannot self-rekey without a peer device. Start a new session.":"this device's key is not in session.encryptedKeys and self-rekey did not complete within 30s. This typically means the device key was rotated and mobile has not yet granted access to this device. Open the mobile app to refresh device keys, then retry."));throw m.code="ENCRYPTED_SESSION_NO_KEY",m}}if(f)try{let m=await X(r,f,e);m>0&&(t.info("Session re-keyed for newly registered devices on resume",{sessionId:r,newDeviceCount:m}),yt({session_hash:we(r),granted_count_bucket:ee(m)}).catch(()=>{}))}catch(m){t.warn("Session re-key on resume failed (non-fatal)",{sessionId:r,error:m instanceof Error?m.message:String(m)})}return{resumed:!0,sessionKey:f}}let l=await De(r,e,t),g=o,p=a;l&&(g=A.encryptContent(o,l.sessionKey),p&&Object.keys(p).length>0&&(p={encrypted:A.encryptMetadata(p,l.sessionKey)}),t.info("Session data encrypted",{sessionId:r})),t.info("Creating new session in backend",{sessionId:r,userId:i,agentType:s,isEncrypted:!!l}),await e.createSession({sessionId:r,userId:i,agentType:s,projectPath:g,status:"ACTIVE",metadata:p,isEncrypted:l?!0:void 0,creatorDeviceId:l?await y.getDeviceId():void 0,encryptionVersion:l?1:void 0,encryptedKeys:l?.encryptedKeys});let h=l?.sessionKey||null;return l&&y.cacheSessionKey(r,l.sessionKey),t.info("Session created",{sessionId:r,userId:i,isEncrypted:!!l}),{resumed:!1,sessionKey:h}}U();function Ze(n,e){let t=n.getCurrentUserId(),r=async(s,o)=>{let a=y.getCachedSessionIds();if(a.length===0){e.info("[DeviceKeyWatcher] No active sessions to re-key",{reason:s});return}e.info("[DeviceKeyWatcher] Running re-key pass",{reason:s,activeSessionCount:a.length,forceDeviceCount:o?.size??0});for(let d of a){let l=y.getCachedSessionKey(d);if(l)try{let g=await X(d,l,n,o?{forceDeviceIds:o}:void 0);g>0&&e.info("[DeviceKeyWatcher] Session re-keyed",{sessionId:d,newDeviceCount:g,reason:s})}catch(g){e.warn("[DeviceKeyWatcher] Re-key failed for session (non-fatal)",{sessionId:d,reason:s,error:g instanceof Error?g.message:String(g)})}}},i=n.subscribeToDeviceKeyRegistered(t,s=>{e.info("[DeviceKeyWatcher] New device observed, triggering re-key",{userId:t,newDeviceId:s.deviceId,platform:s.platform,deviceName:s.deviceName}),r(`new-device:${s.deviceId}`,new Set([s.deviceId]))},()=>{r("watcher-reconnect")},s=>{e.warn("[DeviceKeyWatcher] Subscription error (will retry)",{error:s instanceof Error?s.message:String(s)})});return e.info("[DeviceKeyWatcher] Started",{userId:t}),i}var W=new Map;function Qe(n){let e=Date.now(),t=n.agentClock?Date.parse(n.agentClock):NaN,r=Number.isNaN(t)?e:t,i=W.get(n.orderingKey)??0,s=typeof n.notBeforeMs=="number"&&Number.isFinite(n.notBeforeMs)?n.notBeforeMs+1:0,o=Math.max(r,i+1,s);if(W.has(n.orderingKey)&&W.delete(n.orderingKey),W.set(n.orderingKey,o),W.size>1024){let a=W.keys().next().value;a!==void 0&&W.delete(a)}return new Date(o).toISOString()}function et(){W.clear()}0&&(module.exports={AgentType,AppSyncClient,AuthService,CryptoError,CryptoService,DeliveryStatus,ENCRYPTION_VERSION,EventSource,EventType,KeychainError,KeychainManager,Logger,PORT_RANGE_SIZE,PRIMARY_PORT,SessionStatus,_resetPrepareEventTimestampForTesting,authService,bindOAuthServer,createLogger,cryptoService,errorWasBeaconed,fireAuthCompletedBeacon,fireAuthFailedBeacon,getConfig,getEnvironment,getErrorReason,keychainManager,loadConfig,logger,markErrorBeaconed,mutations,normalizeSnapshot,parseInteractivePrompt,prepareEventTimestamp,prepareSessionEncryption,queries,registerDeviceEncryptionKey,rekeySessionForNewDevices,resumeOrCreateSession,runAuthCli,startDeviceKeyWatcher,subscriptions});
254
+ `).trim()}function Or(n){let e=n.split(`
255
+ `).map(y=>y.trim()),t=Nr(e,y=>/\[(?:y\/n|Y\/n|y\/N)\]/.test(y)),r=t>=0?e[t]:null;if(!r)return null;let i=zt(e,t),s=i.length>0?i.join(`
256
+ `):r,o=s.toLowerCase(),a=o.includes("what to change")||o.includes("what should")||o.includes("provide")||o.includes("instructions");return{kind:"yes_no",promptText:s,options:a?[{number:"1",text:"Yes"},{number:"2",text:"No, provide instructions"}]:[{number:"1",text:"Yes"},{number:"2",text:"No"}],submitMap:{1:"y",2:"n"},requiresFollowUpText:a}}function Pr(n){let e=n.split(`
257
+ `).map(d=>d.trim()),t=$r(e);if(t.length<2)return null;let r=t.map(({line:d})=>Ze(d)).filter(d=>!!d),i={};for(let d of r)i[d.number]=d.number;let s=t[0]?.index??-1,o=zt(e,s-1);return{kind:"numbered",promptText:o.length>0?o.join(`
258
+ `):"Select an option",options:r,submitMap:i}}function Nr(n,e){for(let t=n.length-1;t>=0;t-=1)if(e(n[t]))return t;return-1}function Ze(n){let e=n.match(/^(?:[>›❯▸▶➜➤*●]\s*)?(\d+)\.\s+(.*)$/);return e?{number:e[1],text:e[2]}:null}function Ur(n){return Ze(n)!==null}function $r(n){let e=[];for(let r=0;r<n.length;r+=1){let i=Ze(n[r]);i&&e.push({index:r,number:Number(i.number)})}if(e.length===0)return[];let t=[e[e.length-1]];for(let r=e.length-2;r>=0;r-=1){let i=e[r],s=t[0];if(Lr(n,i.index,s.index))break;i.number===s.number-1&&t.unshift(i)}return t.map((r,i)=>{let s=i+1<t.length?t[i+1].index-1:Mr(n,r.index);return{index:r.index,line:Wr(n,r.index,s)}})}function Lr(n,e,t){for(let r=e+1;r<t;r+=1)if(!n[r])return!0;return!1}var jt=/\((?:[a-z0-9]|esc|escape)\)\s*$/i;function Mr(n,e){let t=jt.test(n[e])?e:-1;for(let r=e+1;r<n.length&&!(!n[r]||Ur(n[r]));r+=1)jt.test(n[r])&&(t=r);return t>=0?t:e}function Wr(n,e,t){let r=n[e];for(let i=e+1;i<=t;i+=1)r+=n[i];return r}function zt(n,e){if(e<0)return[];let t=Je(n,e);if(t<0)return[];let{start:r,end:i}=Ye(n,t),s=n.slice(r,i+1).filter(Boolean);if(Fr(s)){let p=Br(n,r-1);return p.length>0?p:s}if(r<=1)return s;let o=r-1;if(o=Je(n,o),o<0||o===r-1)return s;let{start:a,end:d}=Ye(n,o),l=n.slice(a,d+1).filter(Boolean);return l.some(Jt)?[...l,...s]:s}function Jt(n){return/^(?:would you like to|do you want to|the model would like to|action required|confirm)\b/i.test(n)}function Je(n,e){let t=e;for(;t>=0&&!n[t];)t-=1;return t}function Ye(n,e){let t=e;for(;t>=0&&n[t];)t-=1;return{start:t+1,end:e}}function Br(n,e){let t=[],r=e;for(;r>=0&&t.length<2&&(r=Je(n,r),!(r<0));){let{start:s,end:o}=Ye(n,r),a=n.slice(s,o+1).filter(Boolean);a.length>0&&t.unshift(a),r=s-1}if(t.length===0)return[];let i=t.findIndex(s=>s.some(Jt));return i>=0?t.slice(i).flat():t[t.length-1]}function Fr(n){return n.length===0?!1:n.filter(Hr).length>=Math.max(2,Math.ceil(n.length/2))}function Hr(n){return/^\d+\s/.test(n)}ge();U();ge();U();q();async function Z(n,e,t,r={}){let i;try{i=await t.getSession(n)}catch(p){return c.warn("[SessionRekey] Failed to fetch session state for re-key",{sessionId:n,error:p instanceof Error?p.message:String(p)}),0}if(!i)return c.warn("[SessionRekey] Session not found, skipping re-key",{sessionId:n}),0;if(!i.isEncrypted)return 0;let s=i.encryptedKeys||[],o=new Set(s.map(p=>p.deviceId)),a=r.forceDeviceIds??new Set,d;try{d=await t.listUserDeviceKeys()}catch(p){return c.warn("[SessionRekey] Failed to fetch user device keys",{sessionId:n,error:p instanceof Error?p.message:String(p)}),0}let l=d.filter(p=>!o.has(p.deviceId)||a.has(p.deviceId));if(l.length===0)return 0;c.info("[SessionRekey] Granting session key to devices",{sessionId:n,existingDeviceCount:s.length,grantCount:l.length,grantDeviceIds:l.map(p=>p.deviceId),forceCount:a.size});let y=0;for(let p of l)try{let h=T.encryptSessionKey(e,p.publicKey);await t.grantSessionKey({sessionId:n,deviceId:p.deviceId,encryptedKey:h.encryptedKey,ephemeralPublicKey:h.ephemeralPublicKey}),y++,c.info("[SessionRekey] Granted session key to device",{sessionId:n,deviceId:p.deviceId,platform:p.platform})}catch(h){c.warn("[SessionRekey] Failed to grant session key to device",{sessionId:n,deviceId:p.deviceId,error:h instanceof Error?h.message:String(h)})}return y>0&&c.info("[SessionRekey] Re-key complete",{sessionId:n,grantedCount:y,requestedCount:l.length}),y}async function Yt(n,e){let t=e.pollIntervalMs??5e3,r=e.maxAttempts??6,i,s;try{i=await g.getDeviceId(),s=await g.getDevicePrivateKey()}catch(o){c.warn("[SessionRekey] A1 pre-loop keychain read failed",{sessionId:n,error:o instanceof Error?o.message:String(o)});try{e.onTimeout?.(0)}catch{}return null}for(let o=1;o<=r;o++){o>1&&await new Promise(h=>setTimeout(h,t));let a;try{a=await e.appSyncClient.getSession(n)}catch(h){c.warn("[SessionRekey] A1 getSession failed during poll, will retry",{sessionId:n,attempt:o,error:h instanceof Error?h.message:String(h)});continue}let d=a?.encryptedKeys??[],l=d.filter(h=>h.deviceId===i);if(l.length===0){c.info("[SessionRekey] A1 our deviceId still not in encryptedKeys",{sessionId:n,attempt:o,freshDeviceCount:d.length});continue}let y=null,p=[];for(let h=l.length-1;h>=0;h--)try{y=T.decryptSessionKey(l[h],s);break}catch(f){p.push(f instanceof Error?f.message:String(f))}if(y){g.cacheSessionKey(n,y);try{e.onSuccess?.(o)}catch{}return c.info("[SessionRekey] A1 self-rekey successful",{sessionId:n,attempt:o,entriesTriedToDecrypt:l.length}),y}c.warn("[SessionRekey] A1 found entries but all decrypt-failed, will retry",{sessionId:n,attempt:o,entriesTried:l.length,errors:p})}try{e.onTimeout?.(r)}catch{}return c.warn("[SessionRekey] A1 self-rekey exhausted maxAttempts",{sessionId:n,maxAttempts:r}),null}U();async function Se(n,e){try{let t=await g.getDeviceId(),r=await g.getDevicePublicKey(),i=g.getDevicePlatform(),s=g.getDeviceName();e.info("Registering device encryption key",{deviceId:t,platform:i,deviceName:s}),await n.registerDeviceKey(t,r,i,s),g.setIsRegistered(!0),e.info("Device encryption key registered successfully",{deviceId:t})}catch(t){e.warn("Failed to register device encryption key (E2E encryption may not work):",t)}}re();async function De(n,e,t){try{let r=await e.listUserDeviceKeys();if(r.length===0)return t.info("No device keys found, session will not be encrypted"),null;t.info("Preparing session encryption",{sessionId:n,deviceCount:r.length});let i=Ee(n),{sessionKey:s,encryptedKeys:o,skippedDeviceIds:a}=g.createSessionKey(r,{onDeviceSkipped:d=>{gt({skipped_count_bucket:te(d),session_hash:i}).catch(()=>{})}});return a.length>0&&yt({session_hash:i,encrypted_count_bucket:te(o.length),skipped_count_bucket:te(a.length)}).catch(()=>{}),t.info("Session encryption prepared",{sessionId:n,deviceCount:o.length,skippedCount:a.length}),{sessionKey:s,encryptedKeys:o,skippedDeviceIds:a}}catch(r){return t.warn("Failed to prepare session encryption:",r),null}}async function Qe(n,e,t){let{sessionId:r,userId:i,agentType:s,projectPath:o,metadata:a}=n,d=null;try{d=await e.getSession(r)}catch(f){t.warn("Failed to get session (will attempt to create new)",{sessionId:r,error:f})}if(d){t.info("Session exists in backend - reactivating",{sessionId:r,previousStatus:d.status});try{await e.updateSession({sessionId:r,status:"ACTIVE"})}catch(m){t.warn("Failed to reactivate existing session, will continue",{sessionId:r,error:m})}let f=null,B=d.encryptedKeys??[];if(d.isEncrypted){if(B.length>0){try{let m=await g.getSessionKey(r,B);m&&(f=m,g.cacheSessionKey(r,m),t.info("Session key retrieved for resumed session",{sessionId:r}))}catch(m){t.warn("Failed to retrieve session key for resumed session",{sessionId:r,error:m})}if(!f){let m=Ee(r);t.info("Self-rekey: re-registering device key + awaiting grant",{sessionId:r,otherDeviceCount:B.length}),mt({session_hash:m,other_device_count_bucket:te(B.length)}).catch(()=>{});try{await Se(e,t),f=await Yt(r,{appSyncClient:e,onSuccess:S=>{vt({session_hash:m,attempt_count:S}).catch(()=>{})},onTimeout:S=>{St({session_hash:m,attempt_count:S}).catch(()=>{})}})}catch(S){t.warn("Self-rekey path failed",{sessionId:r,error:S instanceof Error?S.message:String(S)})}}}else t.warn("Encrypted session has empty encryptedKeys; cannot self-rekey",{sessionId:r});if(!f){let m=new Error(`Cannot resume encrypted session ${r}: `+(B.length===0?"session is marked encrypted but session.encryptedKeys is empty (corrupt state). Cannot self-rekey without a peer device. Start a new session.":"this device's key is not in session.encryptedKeys and self-rekey did not complete within 30s. This typically means the device key was rotated and mobile has not yet granted access to this device. Open the mobile app to refresh device keys, then retry."));throw m.code="ENCRYPTED_SESSION_NO_KEY",m}}if(f)try{let m=await Z(r,f,e);m>0&&(t.info("Session re-keyed for newly registered devices on resume",{sessionId:r,newDeviceCount:m}),ft({session_hash:Ee(r),granted_count_bucket:te(m)}).catch(()=>{}))}catch(m){t.warn("Session re-key on resume failed (non-fatal)",{sessionId:r,error:m instanceof Error?m.message:String(m)})}return{resumed:!0,sessionKey:f}}let l=await De(r,e,t),y=o,p=a;l&&(y=T.encryptContent(o,l.sessionKey),p&&Object.keys(p).length>0&&(p={encrypted:T.encryptMetadata(p,l.sessionKey)}),t.info("Session data encrypted",{sessionId:r})),t.info("Creating new session in backend",{sessionId:r,userId:i,agentType:s,isEncrypted:!!l}),await e.createSession({sessionId:r,userId:i,agentType:s,projectPath:y,status:"ACTIVE",metadata:p,isEncrypted:l?!0:void 0,creatorDeviceId:l?await g.getDeviceId():void 0,encryptionVersion:l?1:void 0,encryptedKeys:l?.encryptedKeys});let h=l?.sessionKey||null;return l&&g.cacheSessionKey(r,l.sessionKey),t.info("Session created",{sessionId:r,userId:i,isEncrypted:!!l}),{resumed:!1,sessionKey:h}}U();function et(n,e){let t=n.getCurrentUserId(),r=async(s,o)=>{let a=g.getCachedSessionIds();if(a.length===0){e.info("[DeviceKeyWatcher] No active sessions to re-key",{reason:s});return}e.info("[DeviceKeyWatcher] Running re-key pass",{reason:s,activeSessionCount:a.length,forceDeviceCount:o?.size??0});for(let d of a){let l=g.getCachedSessionKey(d);if(l)try{let y=await Z(d,l,n,o?{forceDeviceIds:o}:void 0);y>0&&e.info("[DeviceKeyWatcher] Session re-keyed",{sessionId:d,newDeviceCount:y,reason:s})}catch(y){e.warn("[DeviceKeyWatcher] Re-key failed for session (non-fatal)",{sessionId:d,reason:s,error:y instanceof Error?y.message:String(y)})}}},i=n.subscribeToDeviceKeyRegistered(t,s=>{e.info("[DeviceKeyWatcher] New device observed, triggering re-key",{userId:t,newDeviceId:s.deviceId,platform:s.platform,deviceName:s.deviceName}),r(`new-device:${s.deviceId}`,new Set([s.deviceId]))},()=>{r("watcher-reconnect")},s=>{e.warn("[DeviceKeyWatcher] Subscription error (will retry)",{error:s instanceof Error?s.message:String(s)})});return e.info("[DeviceKeyWatcher] Started",{userId:t}),i}var W=new Map;function tt(n){let e=Date.now(),t=n.agentClock?Date.parse(n.agentClock):NaN,r=Number.isNaN(t)?e:t,i=W.get(n.orderingKey)??0,s=typeof n.notBeforeMs=="number"&&Number.isFinite(n.notBeforeMs)?n.notBeforeMs+1:0,o=Math.max(r,i+1,s);if(W.has(n.orderingKey)&&W.delete(n.orderingKey),W.set(n.orderingKey,o),W.size>1024){let a=W.keys().next().value;a!==void 0&&W.delete(a)}return new Date(o).toISOString()}function rt(){W.clear()}0&&(module.exports={AgentType,AppSyncClient,AuthService,CryptoError,CryptoService,DeliveryStatus,ENCRYPTION_VERSION,EventSource,EventType,KeychainError,KeychainManager,Logger,PORT_RANGE_SIZE,PRIMARY_PORT,SessionStatus,_resetPrepareEventTimestampForTesting,authService,bindOAuthServer,createLogger,cryptoService,errorWasBeaconed,fireAuthCompletedBeacon,fireAuthFailedBeacon,getConfig,getEnvironment,getErrorReason,keychainManager,loadConfig,logger,markErrorBeaconed,mutations,normalizeSnapshot,parseInteractivePrompt,prepareEventTimestamp,prepareSessionEncryption,queries,registerDeviceEncryptionKey,rekeySessionForNewDevices,resumeOrCreateSession,runAuthCli,startDeviceKeyWatcher,subscriptions});
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantiya/codevibe-core",
3
- "version": "1.0.31",
3
+ "version": "1.0.32",
4
4
  "description": "Core library for CodeVibe plugins - shared keychain, crypto, AppSync, and auth functionality",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantiya/codevibe-claude-plugin",
3
- "version": "1.0.50",
3
+ "version": "1.0.52",
4
4
  "description": "Control Claude Code from your iPhone and Android — real-time sync, approve file edits, send prompts by voice. Part of CodeVibe.",
5
5
  "main": "dist/server.js",
6
6
  "bin": {
@@ -47,7 +47,7 @@
47
47
  "node": ">=18.0.0"
48
48
  },
49
49
  "dependencies": {
50
- "@quantiya/codevibe-core": "^1.0.31",
50
+ "@quantiya/codevibe-core": "^1.0.32",
51
51
  "dotenv": "^16.6.1",
52
52
  "express": "^5.1.0",
53
53
  "graphql": "^16.12.0",