@quantiya/codevibe-claude-plugin 1.0.41 → 1.0.42

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.41",
3
+ "version": "1.0.42",
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,18 +1,19 @@
1
- "use strict";var Ie=Object.create;var B=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Te=(f,e)=>{for(var t in e)B(f,t,{get:e[t],enumerable:!0})},pe=(f,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pe(e))!Ae.call(f,n)&&n!==t&&B(f,n,{get:()=>e[n],enumerable:!(i=ke(e,n))||i.enumerable});return f};var C=(f,e,t)=>(t=f!=null?Ie(be(f)):{},pe(e||!f||!f.__esModule?B(t,"default",{value:f,enumerable:!0}):t,f)),xe=f=>pe(B({},"__esModule",{value:!0}),f);var Re={};Te(Re,{McpServer:()=>J,parseInteractivePromptInput:()=>Se});module.exports=xe(Re);var M=C(require("fs")),N=C(require("path")),Y=C(require("os")),ve=require("child_process"),we=require("util"),Ee=require("child_process"),L=require("crypto");var ce=C(require("os")),de=C(require("path")),le=require("@quantiya/codevibe-core"),r=(0,le.createLogger)({name:"codevibe-claude",logFile:de.default.join(ce.default.tmpdir(),"codevibe-claude-mcp.log"),level:"info"});var a=require("@quantiya/codevibe-core");var te=C(require("express")),K=C(require("fs")),ne=C(require("path")),ie=C(require("os")),ue=require("@quantiya/codevibe-core");var v=require("@quantiya/codevibe-core");var H=class{constructor(){this.assignedPort=0;this.app=(0,te.default)(),this.setupMiddleware(),this.setupRoutes()}setSessionId(e){this.sessionId=e}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(te.default.json({limit:"1mb"})),this.app.use((e,t,i)=>{r.debug(`${e.method} ${e.path}`,{body:e.body,query:e.query}),i()}),this.app.use((e,t,i,n)=>{r.error("Express error:",e);let s={success:!1,error:e.message||"Internal server error"};i.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 i={success:!0,data:{status:"healthy",uptime:process.uptime(),version:"0.1.0",timestamp:new Date().toISOString()}};t.json(i)}async handleEvent(e,t){try{let i=e.body;if(!i.session_id){let o={success:!1,error:"Missing required field: session_id"};t.status(400).json(o);return}if(!i.hook_event_name){let o={success:!1,error:"Missing required field: hook_event_name"};t.status(400).json(o);return}let n=this.transformHookToEvent(i);r.info("Received event from hook",{sessionId:i.session_id,hookEvent:i.hook_event_name,type:n.type}),this.eventHandler?await this.eventHandler(n):r.warn("No event handler registered");let s={success:!0,message:"Event processed successfully"};t.json(s)}catch(i){r.error("Error handling event:",i);let n={success:!1,error:i instanceof Error?i.message:"Unknown error"};t.status(500).json(n)}}async handleTestExecute(e,t){try{let{sessionId:i,prompt:n}=e.body;if(!i||!n){let o={success:!1,error:"Missing required fields: sessionId, prompt"};t.status(400).json(o);return}r.info("Test execute request",{sessionId:i,prompt:n});let s={success:!0,message:"Test execution endpoint - not implemented yet",data:{sessionId:i,prompt:n}};t.json(s)}catch(i){r.error("Error in test execute:",i);let n={success:!1,error:i instanceof Error?i.message:"Unknown error"};t.status(500).json(n)}}transformHookToEvent(e){let t,i,n={cwd:e.cwd,hook_event_name:e.hook_event_name,...e.metadata||{}};if(e.type&&e.content!==void 0)t=e.type,i=e.content;else switch(e.hook_event_name){case"SessionStart":t=v.EventType.NOTIFICATION,i="Session started",n.source=e.source;break;case"SessionEnd":t=v.EventType.NOTIFICATION,i=`Session ended: ${e.reason||"unknown"}`,n.reason=e.reason;break;case"UserPromptSubmit":t=v.EventType.USER_PROMPT,i=e.prompt||"";break;case"PostToolUse":t=v.EventType.TOOL_USE,i=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=v.EventType.NOTIFICATION,i=e.message||"",n.notification_type=e.notification_type;break;default:t=v.EventType.NOTIFICATION,i=`Hook event: ${e.hook_event_name}`}return{session_id:e.session_id,hook_event_name:e.hook_event_name,type:t,source:v.EventSource.DESKTOP,content:i,metadata:n}}onEvent(e){this.eventHandler=e}async start(e){let t=e||this.sessionId;return t&&(this.sessionId=t),new Promise((i,n)=>{try{let s=(0,ue.getConfig)(),o=s.server.dynamicPort?0:s.server.port;this.server=this.app.listen(o,s.server.host,()=>{let p=this.server.address();this.assignedPort=p.port,r.info(`HTTP API listening on http://${s.server.host}:${this.assignedPort}`),this.sessionId&&this.writePortFile(this.sessionId,this.assignedPort),i(this.assignedPort)}),this.server.on("error",p=>{r.error("HTTP server error:",p),n(p)})}catch(s){n(s)}})}writePortFile(e,t){let i=ne.join(ie.tmpdir(),`codevibe-claude-${e}.port`);try{K.writeFileSync(i,t.toString()),r.info(`Port file written: ${i} -> ${t}`)}catch(n){r.error(`Failed to write port file: ${i}`,n)}}removePortFile(){if(this.sessionId){let e=ne.join(ie.tmpdir(),`codevibe-claude-${this.sessionId}.port`);try{K.existsSync(e)&&(K.unlinkSync(e),r.info(`Port file removed: ${e}`))}catch(t){r.warn(`Failed to remove port file: ${e}`,t)}}}async stop(e){return new Promise((t,i)=>{this.sessionId&&e?.protectedSessionIds?.has(this.sessionId)?r.info("Skipping port file removal \u2014 another daemon still serves this session",{sessionId:this.sessionId}):this.removePortFile(),this.server?this.server.close(n=>{n?(r.error("Error stopping HTTP server:",n),i(n)):(r.info("HTTP API stopped"),t())}):t()})}};var me=require("child_process"),ge=require("@quantiya/codevibe-core");var X=class{async executePrompt(e,t){let i=(0,ge.getConfig)(),n=i.claude.defaultTimeout;return r.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];r.debug("Spawning Claude command",{command:i.claude.command,args:o});let p=(0,me.spawn)(i.claude.command,o,{stdio:["pipe","pipe","pipe"],shell:!0}),c="",u="",l=!1,m=setTimeout(()=>{l=!0,r.warn("Command execution timed out",{sessionId:e,timeout:n}),p.kill("SIGTERM")},n);p.stdout?.on("data",d=>{let g=d.toString();c+=g,r.debug("Command stdout",{output:g.slice(0,200)})}),p.stderr?.on("data",d=>{let g=d.toString();u+=g,r.debug("Command stderr",{output:g.slice(0,200)})}),p.on("close",d=>{clearTimeout(m);let g={success:d===0&&!l,output:c,error:u,exitCode:d||void 0,timedOut:l};g.success?r.info("Command executed successfully",{sessionId:e,exitCode:d,outputLength:c.length}):r.error("Command execution failed",{sessionId:e,exitCode:d,timedOut:l,error:u.slice(0,500)}),s(g)}),p.on("error",d=>{clearTimeout(m),r.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(i=>i.test(e))}extractPromptText(e){let t=e.split(`
2
- `);for(let i=t.length-1;i>=0;i--){let n=t[i].trim();if(this.detectInteractivePrompt(n))return n}return null}};var fe=require("child_process"),he=require("util");var re=(0,he.promisify)(fe.exec),z=class{async answerInteractivePrompt(e,t,i={}){let{pressEnter:n=!0}=i;r.info("Attempting to answer interactive prompt",{sessionId:e,response:t,pressEnter:n});try{let s=process.env.CODEVIBE_TMUX_SESSION;return r.info("Checking tmux session environment",{tmuxSession:s||"(not set)",allEnvKeys:Object.keys(process.env).filter(o=>o.includes("CODEVIBE")||o.includes("TMUX"))}),s?(r.info("Using tmux send-keys",{tmuxSession:s,pressEnter:n}),await this.sendViaTmux(s,t,n),r.info("Successfully sent response to interactive prompt",{sessionId:e,response:t,pressEnter:n}),!0):(r.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 r.error("Failed to answer interactive prompt",{sessionId:e,error:s instanceof Error?s.message:String(s)}),!1}}async sendViaTmux(e,t,i){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");r.info("Sending via tmux",{sessionName:e,inputLength:t.length,pressEnter:i});try{let s=`tmux send-keys -t "${e}" -l "${n}"`,o=await re(s);if(r.info("tmux send-keys (text) completed",{stdout:o.stdout||"(empty)",stderr:o.stderr||"(empty)"}),i){await this.delay(500);let p=`tmux send-keys -t "${e}" Enter`,c=await re(p);r.info("tmux send-keys (Enter) completed",{stdout:c.stdout||"(empty)",stderr:c.stderr||"(empty)"})}else r.info("tmux send-keys: skipping Enter (caller requested digit-only)")}catch(s){throw r.error("tmux send-keys failed",{sessionName:e,error:s}),s}}async sendKey(e,t){let i=process.env.CODEVIBE_TMUX_SESSION;if(!i)return r.error("No tmux session found for sendKey",{sessionId:e,keyName:t}),!1;try{let n=`tmux send-keys -t "${i}" ${t}`,s=await re(n);return r.info("tmux send-keys (single key) completed",{sessionId:e,keyName:t,stdout:s.stdout||"(empty)",stderr:s.stderr||"(empty)"}),!0}catch(n){return r.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 Ce=(0,we.promisify)(Ee.exec),_e="/exit",ye="CODEVIBE_TMUX_SESSION";async function Fe(f,e){let t=async(i,n)=>{try{await Ce(i)}catch(s){r.warn("tmux send-keys failed during self-terminate",{sessionName:f,label:n,error:String(s)})}};await t(`tmux send-keys -t "${f}" C-c`,"ctrl-c"),await new Promise(i=>setTimeout(i,200)),await t(`tmux send-keys -t "${f}" -l "${e}"`,"quit-text"),await new Promise(i=>setTimeout(i,500)),await t(`tmux send-keys -t "${f}" Enter`,"enter")}var J=class f{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 H,this.commandExecutor=new X,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()}),r.debug("Tracking mobile prompt for deduplication",{sessionId:e,promptLength:t.length})}isRecentMobilePrompt(e,t){let i=this.pendingMobilePrompts.get(e);if(!i)return!1;let n=Date.now(),s=t.trim(),o=[],p=!1;for(let c of i)if(!(n-c.timestamp>f.MOBILE_PROMPT_EXPIRY_MS)){if(!p&&c.prompt===s){p=!0,r.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),p}writePortFile(e){let t=N.join(Y.tmpdir(),`codevibe-claude-${e}.port`);try{M.writeFileSync(t,this.assignedPort.toString()),r.info(`Port file written: ${t} -> ${this.assignedPort}`)}catch(i){r.error(`Failed to write port file: ${t}`,i)}}removePortFile(e){let t=N.join(Y.tmpdir(),`codevibe-claude-${e}.port`);try{M.existsSync(t)&&(M.unlinkSync(t),r.info(`Port file removed: ${t}`))}catch(i){r.warn(`Failed to remove port file: ${t}`,i)}}hasOtherLiveDaemonForSession(e){try{let t=(0,ve.execSync)("ps -eww -o pid= -o args=",{encoding:"utf8",timeout:2e3}),i=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 p=parseInt(s.substring(0,o),10);if(isNaN(p)||p===i)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 r.warn('hasOtherLiveDaemonForSession: ps query failed; falling back to "no other daemon"',{error:String(t)}),!1}}async start(){try{if(r.info("Starting CodeVibe MCP Server...",{environment:(0,a.getEnvironment)()}),this.appSyncClient=new a.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()){r.info("Authenticated with stored OAuth tokens",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,a.registerDeviceEncryptionKey)(this.appSyncClient,r),(0,a.startDeviceKeyWatcher)(this.appSyncClient,r);try{let t=await this.appSyncClient.sweepOrphanSessions({agentType:"CLAUDE"});t>0&&r.info("Orphan sweep: marked stale Claude sessions INACTIVE",{swept:t})}catch(t){r.warn("Orphan sweep failed, continuing startup",{error:t instanceof Error?t.message:String(t)})}}else r.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),r.info("MCP Server started successfully",{port:this.assignedPort,host:(0,a.getConfig)().server.host,dynamicPort:(0,a.getConfig)().server.dynamicPort,sessionId:this.initialSessionId,authenticated:this.appSyncClient.isAuthenticated(),userId:this.appSyncClient.getCurrentUserId()})}catch(e){throw r.error("Failed to start MCP Server:",e),e}}async stop(){r.info("Stopping MCP Server...");let e=Array.from(this.activeSessions.keys()),t=new Set;r.info(`Marking ${e.length} active session(s) as INACTIVE...`);for(let i of e){let n=this.activeSessions.get(i);n?.mobileEndWatcher&&(n.mobileEndWatcher.stop(),n.mobileEndWatcher=void 0)}for(let i of e)try{let n=this.activeSessions.get(i);if(n&&this.hasOtherLiveDaemonForSession(n.claudeSessionId)){r.info("Another daemon serves this session \u2014 skipping mark INACTIVE AND port file removal during shutdown",{sessionId:i,claudeSessionId:n.claudeSessionId,myPid:process.pid}),t.add(n.claudeSessionId);continue}await this.appSyncClient.updateSession({sessionId:i,status:a.SessionStatus.INACTIVE}),r.info("Session marked as INACTIVE during shutdown",{sessionId:i}),n&&this.removePortFile(n.claudeSessionId)}catch(n){r.warn("Failed to mark session as INACTIVE during shutdown",{sessionId:i,error:n})}this.appSyncClient.cleanupSubscriptions(),this.activeSessions.clear(),await this.httpApi.stop({protectedSessionIds:t}),r.info("MCP Server stopped")}async handleEventFromHook(e){let{session_id:t,hook_event_name:i,type:n,content:s}=e;r.info("Processing hook event",{sessionId:t,hookEvent:i,type:n});try{i==="SessionStart"?await this.handleSessionStart(e):i==="SessionEnd"&&await this.handleSessionEnd(e);let o=this.claudeToBackendSessionId.get(t)||this.generateBackendSessionId(t);if(i==="UserPromptSubmit"){let m=this.activeSessions.get(o);if(m?.completedAskUserQuestionFingerprints?.size){let d=m.completedAskUserQuestionFingerprints.size;m.completedAskUserQuestionFingerprints.clear(),r.info("Turn boundary \u2014 cleared closed-AskUserQuestion fingerprints",{sessionId:o,clearedCount:d})}}if(n===a.EventType.USER_PROMPT&&e.source===a.EventSource.DESKTOP&&i==="UserPromptSubmit"&&s&&this.isRecentMobilePrompt(o,s)){r.info("Skipping duplicate USER_PROMPT from mobile-originated prompt",{sessionId:o,contentLength:s.length});return}if(n===a.EventType.INTERACTIVE_PROMPT){(typeof e.prompt_id!="string"||e.prompt_id.length===0)&&(e.prompt_id=`synth-${(0,L.randomUUID)()}`,r.info("Synthesized prompt_id for INTERACTIVE_PROMPT (hook omitted it)",{sessionId:o,synthesizedPromptId:e.prompt_id}));let m=this.activeSessions.get(o),d;if(m&&e.metadata?.tool_name==="AskUserQuestion"&&(d=this.computeAskUserQuestionFingerprint(e.metadata.tool_input?.questions),d)){let g=m.activeAskUserQuestionFingerprint===d,_=m.completedAskUserQuestionFingerprints?.has(d)??!1;if(g||_){r.info("Dropping duplicate INTERACTIVE_PROMPT \u2014 AskUserQuestion already tracked",{sessionId:o,fingerprint:d.slice(0,16),status:g?"in-flight":"completed",hookEvent:e.hook_event_name,promptId:e.prompt_id});return}}if(m){this.clearPromptState(m),m.waitingForPromptResponse=!0,m.pendingPromptId=e.prompt_id;let g=this.nextPromptGen++;m.promptGenerationToken={promptId:e.prompt_id||"",gen:g},d&&(m.activeAskUserQuestionFingerprint=d),r.info("Interactive prompt detected - will parse options from tmux",{sessionId:o,promptId:e.prompt_id,tokenGen:g,askUserQuestionFingerprint:d?.slice(0,16)})}this.sendInteractivePromptAsync(o,e,s).catch(g=>{r.error("Failed to send interactive prompt with dynamic options",{error:g})});return}let p=s,c=e.metadata,u=!1;r.info("Hook event encryption state",{type:n,sessionId:o,hasSessionKey:!!this.sessionKey,sessionKeyLength:this.sessionKey?.length||0}),this.sessionKey?(p=a.cryptoService.encryptContent(s,this.sessionKey),c&&(c={encrypted:a.cryptoService.encryptMetadata(c,this.sessionKey)}),u=!0,r.info("Event encrypted for hook",{type:n,sessionId:o,isEncrypted:!0})):r.warn("No session key - event will NOT be encrypted",{type:n,sessionId:o});let l=await this.appSyncClient.createEvent({sessionId:o,type:n,source:e.source,content:p,metadata:c,promptId:e.prompt_id,timestamp:(0,a.prepareEventTimestamp)({orderingKey:o}),isEncrypted:u?!0:void 0});if(n===a.EventType.USER_PROMPT&&e.source===a.EventSource.DESKTOP){let m=this.activeSessions.get(o);m?.waitingForPromptResponse&&(this.promoteFingerprintAndClearPromptState(m),r.info("Clearing prompt wait state - new desktop prompt received",{sessionId:o}))}r.debug("Event sent to AppSync successfully")}catch(o){throw r.error("Failed to process hook event:",o),o}}async handleSessionStart(e){let t=e.session_id,i=this.generateBackendSessionId(t),n=e.metadata?.cwd||process.cwd();this.claudeToBackendSessionId.set(t,i),r.info("Session started",{claudeSessionId:t,sessionId:i,cwd:n});let s=Array.from(this.activeSessions.keys()).filter(u=>u!==i);if(s.length>0){r.info(`Marking ${s.length} previous session(s) as INACTIVE`);for(let u of s){let l=this.activeSessions.get(u);l?.mobileEndWatcher&&(l.mobileEndWatcher.stop(),l.mobileEndWatcher=void 0);try{await this.appSyncClient.updateSession({sessionId:u,status:a.SessionStatus.INACTIVE}),r.info("Previous session marked INACTIVE",{prevId:u,newSessionId:i})}catch(m){r.warn("Failed to mark previous session as INACTIVE",{prevId:u,error:m})}l&&this.removePortFile(l.claudeSessionId),this.activeSessions.delete(u)}}this.writePortFile(t);let o=this.appSyncClient.getCurrentUserId(),p={sessionId:i,claudeSessionId:t,userId:o,projectPath:n,cwd:n,createdAt:new Date,subscriptionActive:!1,waitingForPromptResponse:!1,metadata:e.metadata||{}};this.activeSessions.set(i,p);try{let u=await(0,a.resumeOrCreateSession)({sessionId:i,userId:p.userId,agentType:a.AgentType.CLAUDE,projectPath:n,metadata:e.metadata||{}},this.appSyncClient,r);if(this.sessionKey=u.sessionKey,u.resumed&&!u.sessionKey){let l=await a.keychainManager.getDeviceId();r.error("Device key not found in session encryptedKeys",{sessionId:i,pluginDeviceId:l}),console.error(`
4
- \u26A0\uFE0F E2E ENCRYPTION WARNING: Cannot decrypt this session!`),console.error(` Your device ID (${l.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(u){if(this.isSessionLimitExceeded(u)){this.displaySubscriptionLimitError(u,"session"),this.activeSessions.delete(i),this.removePortFile(t);return}r.error("Failed to create/resume session:",u)}this.subscribeToMobileEvents(i),this.appSyncClient.startHeartbeat(i);let c=this.activeSessions.get(i);c&&(c.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(i,async()=>{r.info("Mobile ended session \u2014 sending desktop quit",{sessionId:i});let u=process.env[ye];if(!u){r.warn("No tmux session set; skipping desktop self-terminate",{sessionId:i,expectedEnv:ye});return}await Fe(u,_e)}))}async handleSessionEnd(e){let t=e.session_id,i=this.claudeToBackendSessionId.get(t)||this.generateBackendSessionId(t);r.info("Session ended",{claudeSessionId:t,sessionId:i,reason:e.metadata?.reason});let n=this.activeSessions.get(i);if(n?.mobileEndWatcher&&(n.mobileEndWatcher.stop(),n.mobileEndWatcher=void 0),this.removePortFile(t),n?.waitingForPromptResponse&&(r.info("Clearing prompt wait state - session ending",{sessionId:i}),this.clearPromptState(n)),this.appSyncClient.stopHeartbeat(i),n)try{await this.appSyncClient.updateSession({sessionId:i,status:a.SessionStatus.INACTIVE}),r.info("Session marked as INACTIVE in AppSync",{sessionId:i})}catch(s){r.warn("Failed to update session in AppSync:",s)}else r.warn("Cannot update session - session state not found",{sessionId:i});this.activeSessions.delete(i),this.claudeToBackendSessionId.delete(t),r.debug("Session cleanup completed",{sessionId:i})}subscribeToMobileEvents(e){r.info("Subscribing to mobile events",{sessionId:e});let t=this.activeSessions.get(e);if(!t){r.error("Session not found",{sessionId:e});return}this.appSyncClient.subscribeToEvents(e,async i=>{await this.dispatchMobileEvent(e,i)},i=>{r.error("Subscription error",{sessionId:e,error:i})}),t.subscriptionActive=!0,r.info("Subscription active",{sessionId:e})}async dispatchMobileEvent(e,t){r.info("Received mobile event",{eventId:t.eventId,type:t.type,sessionId:t.sessionId,isEncrypted:t.isEncrypted});let i,n,s=!1,o,p,c;if(t.type===a.EventType.USER_PROMPT||t.type===a.EventType.PROMPT_RESPONSE)if(n=this.activeSessions.get(e),!n)i="no-session";else if(n.processedEventIds?.has(t.eventId))i="skip-dedup";else if(n.inFlightEventIds?.has(t.eventId))i="drop-event-redeliver";else if(n.waitingForPromptResponse){let d=n.promptGenerationToken;if(!d)i="regular";else if(t.type===a.EventType.USER_PROMPT&&n.hasReceivedPromptResponse&&(!t.promptId||t.promptId.length===0))i="drop-stale-answer";else if(t.promptId&&t.promptId.length>0&&d.promptId.length>0&&t.promptId!==d.promptId)i="drop-stale-answer";else{let g=d.promptId.length>0?d.promptId:`__prompt_gen_${d.gen}`;n.inFlightPromptIds?.has(g)?i="drop-in-flight":(n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightEventIds||(n.inFlightEventIds=new Set),n.inFlightPromptIds.add(g),n.inFlightEventIds.add(t.eventId),s=!0,p=g,c=t.eventId,o={promptId:d.promptId,gen:d.gen},i="walker")}}else i="regular";else i="not-user-prompt";let l=t.content||"";if(t.isEncrypted&&this.sessionKey)try{l=a.cryptoService.decryptContent(t.content,this.sessionKey),r.debug("Event decrypted successfully",{eventId:t.eventId})}catch(d){r.error("Failed to decrypt event:",{eventId:t.eventId,error:d}),l=t.content}let m={...t,content:l};if(i!=="skip-dedup")try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:a.DeliveryStatus.DELIVERED}),r.info("Event marked as DELIVERED",{eventId:t.eventId})}catch(d){r.warn("Failed to mark event as DELIVERED",{eventId:t.eventId,error:d})}if(i==="skip-dedup"){r.info("[walker] Subscription-level dedup hit (already processed) \u2014 skipping",{sessionId:e,eventId:t.eventId});return}if(i==="drop-stale-answer"){r.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){r.warn("[walker] markEventExecuted threw on stale-answer drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}if(i==="drop-in-flight"){r.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){r.warn("[walker] markEventExecuted threw on subscription-level duplicate drop \u2014 relying on processedEventIds Set",{sessionId:e,eventId:t.eventId,error:String(d)})}return}if(i==="drop-event-redeliver"){r.info("[walker] Subscription-level event-level redelivery \u2014 silent skip (original still in flight)",{sessionId:e,eventId:t.eventId});return}if(i==="walker"){t.type===a.EventType.PROMPT_RESPONSE&&n&&(n.hasReceivedPromptResponse=!0),await this.handleMobilePromptResponse(e,t,l,n,s,o,p,c);return}if(i==="regular"){if(t.type===a.EventType.PROMPT_RESPONSE){r.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){r.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,m);return}if(i==="no-session"){r.warn("Received mobile prompt input for unknown session \u2014 ignoring",{sessionId:e,eventId:t.eventId,type:t.type});return}}async handleMobilePromptResponse(e,t,i,n,s=!1,o,p,c){let u=o??n.promptGenerationToken,l=p,m=c;if(!s&&u){let d=u.promptId.length>0?u.promptId:`__prompt_gen_${u.gen}`;if(n.inFlightPromptIds?.has(d)){r.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),l=d,m=t.eventId}try{if(!s&&n.processedEventIds?.has(t.eventId)){r.info("[walker] Redelivered event already processed \u2014 skipping",{sessionId:e,eventId:t.eventId});return}let d=i.trim(),g=n.pendingPromptId,U=n.pendingSubmitMap,$=U?Object.keys(U).length:3,S=this.parseInteractivePromptInput(d,$);r.info("Parsed interactive prompt input",{sessionId:e,content:d,parsed:S,hasSubmitMap:!!U});let P=()=>{let T=n.promptGenerationToken,h=T?.gen,I=u?.gen;return h!==I?(r.warn("[walker] Token mismatch \u2014 external cleanup or new prompt during in-flight handler \u2014 aborting",{sessionId:e,eventId:t.eventId,entryToken:u,currentToken:T}),!0):!1};if(P()){await this.markEventExecutedIdempotent(n,t);return}{let T=n.pendingQuestionsQueue!==void 0,I=d.trim().match(/^(\d+)$/);if(T&&n.pendingCurrentQuestion&&I){let w=n.pendingCurrentQuestion.options?.length??0,E=I[1],y=parseInt(E,10),b=!Number.isFinite(y)||y<1||y>w,k=String(y)!==E;if(b||k){if(r.info("V2 walker \u2014 bare out-of-range or non-canonical option; routing to cancel",{sessionId:e,option:E,optionNum:y,realOptionCount:w,isOutOfRange:b,isNonCanonical:k,isSubmitStep:!!n.pendingCurrentQuestion._isSubmit,parsedAction:S.action}),await this.markEventExecutedIdempotent(n,t),P())return;await this.cancelV2WalkerAndExit(e,n,"invalid_option",!1,P);return}}}if(S.action==="select_option"){let T=U?.[S.option]||S.option,h=n.pendingQuestionsQueue!==void 0;r.info("User selected option",{option:S.option,terminalInput:T,isV2AskUserQuestion:h});let I=await this.promptResponder.answerInteractivePrompt(e,T,{pressEnter:!0});if(P()){await this.markEventExecutedIdempotent(n,t);return}if(I){if(await this.markEventExecutedIdempotent(n,t),P())return;if(!g){r.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"select_option",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}let w=(n.pendingQuestionsQueue?.length??0)===0;try{if(h){let A=parseInt(S.option,10)-1,Q=n.pendingCurrentQuestion?.options?.[A],O=typeof Q=="string"?Q:Q&&typeof Q=="object"?Q.label:`option ${S.option}`,oe=n.pendingCurrentQuestion?._isSubmit===!0,ae=O.toLowerCase(),W;oe&&ae==="cancel"?W="\u2192 Cancel \u2014 AskUserQuestion cancelled, no answers submitted":oe&&ae.startsWith("submit")?W="\u2192 Submit answers \u2014 AskUserQuestion completed":W=`\u2192 ${O}`,await this.emitUserChoice(e,W)}else await this.emitAnswerAck(e,`Selected option ${S.option}`,{promptId:g,questionIndex:0,isTerminal:w})}catch(A){r.warn("[walker] user-choice/ack emit failed \u2014 continuing to STEP 7/8",{sessionId:e,promptId:g,isV2AskUserQuestion:h,error:A instanceof Error?A.message:String(A)})}if(P())return;let E=n.pendingQuestionsQueue?.shift();if(E&&(n.pendingCurrentQuestion=E),!E){n.activeAskUserQuestionFingerprint&&(n.completedAskUserQuestionFingerprints||(n.completedAskUserQuestionFingerprints=new Set),n.completedAskUserQuestionFingerprints.add(n.activeAskUserQuestionFingerprint),r.info("AskUserQuestion V2 walker complete \u2014 fingerprint marked closed",{sessionId:e,fingerprint:n.activeAskUserQuestionFingerprint.slice(0,16)})),this.clearPromptState(n);return}let y=`synth-${(0,L.randomUUID)()}`;if(!y){this.promoteFingerprintAndClearPromptState(n),r.warn("Q[next] emit aborted: synthesized promptId was empty; promoted fingerprint + cleared prompt state",{sessionId:e,eventId:t.eventId});return}let b=n.pendingSynthTail??[],k=this.buildQuestionWireData(E,b),x=E.question,F={tool_name:"AskUserQuestion",tool_input:{questions:[E]},options:k.options,submitMap:k.submitMap,instructions:k.instructions},R=this.sessionKey,j=x,q=F,V=!1;R&&(j=a.cryptoService.encryptContent(x,R),q={encrypted:a.cryptoService.encryptMetadata(F,R)},V=!0);let Z=this.nextPromptGen++,ee={promptId:y,gen:Z};n.pendingPromptId=y,n.pendingSubmitMap=k.submitMap,n.promptGenerationToken=ee;let D=ee,G=this.activeSessions.get(e)?.promptGenerationToken;if(!G||G.gen!==D.gen||G.promptId!==D.promptId){r.warn("Q[next] emit aborted: token replaced before await dispatch",{sessionId:e,tokenAtAwait:D,currentToken:G});return}let se=y.length>0?y:`__prompt_gen_${ee.gen}`;n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightPromptIds.add(se);try{try{await this.appSyncClient.createEvent({sessionId:e,type:a.EventType.INTERACTIVE_PROMPT,source:a.EventSource.DESKTOP,content:j,metadata:q,promptId:y,timestamp:(0,a.prepareEventTimestamp)({orderingKey:e}),isEncrypted:V?!0:void 0}),r.info("Q[next] emit succeeded",{sessionId:e,promptId:y,remaining:n.pendingQuestionsQueue?.length??0})}catch(A){let Q=this.activeSessions.get(e),O=Q?.promptGenerationToken;O&&O.gen===D.gen&&O.promptId===D.promptId?(this.promoteFingerprintAndClearPromptState(Q),r.warn("Q[next] emit failed; promoted fingerprint + cleared prompt state. User must answer remaining questions on desktop terminal.",{sessionId:e,promptId:y,error:A instanceof Error?A.message:String(A)})):r.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:D,currentToken:O,error:A instanceof Error?A.message:String(A)})}}finally{n.inFlightPromptIds.delete(se)}}else try{await this.sendPromptError(e,"Failed to select option")}catch(w){r.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(w)})}finally{await this.markEventExecutedIdempotent(n,t)}}else if(S.action==="option_with_followup"){if(n.pendingQuestionsQueue!==void 0){if(r.info("V2 walker \u2014 option_with_followup \u2192 cancel + new prompt",{sessionId:e,option:S.option,followUpText:S.followUpText}),await this.markEventExecutedIdempotent(n,t),P())return;if(await this.cancelV2WalkerAndExit(e,n,"option_with_followup",!!S.followUpText,P)&&S.followUpText){await new Promise(b=>setTimeout(b,1500));let E=this.activeSessions.get(e);if(E?.pendingPromptId||E?.waitingForPromptResponse){r.warn("Post-cancel followup suppressed: new prompt B is active",{sessionId:e,bPromptId:E.pendingPromptId});return}let y={...t,content:S.followUpText};await this.executeMobilePrompt(e,y)}return}let h=U?.[S.option]||S.option;r.info("User selected option with follow-up",{option:S.option,terminalInput:h,followUpText:S.followUpText});let I=await this.promptResponder.answerInteractivePrompt(e,h);if(P()){await this.markEventExecutedIdempotent(n,t);return}if(I){if(await this.markEventExecutedIdempotent(n,t),P())return;if(!g){r.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 ${S.option}`,{promptId:g,questionIndex:0,isTerminal:!0})}catch(w){r.warn("[walker] emitAnswerAck (option_with_followup) failed \u2014 continuing to clearPromptState + executeMobilePrompt",{sessionId:e,promptId:g,error:w instanceof Error?w.message:String(w)})}if(P())return;if(this.promoteFingerprintAndClearPromptState(n),S.followUpText){await new Promise(E=>setTimeout(E,1e3));let w={...t,content:S.followUpText};await this.executeMobilePrompt(e,w)}}else try{await this.sendPromptError(e,"Failed to select option. Your reply (including the follow-up text) was not sent. Please retry.")}catch(w){r.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(w)})}finally{await this.markEventExecutedIdempotent(n,t)}}else{if(n.pendingQuestionsQueue!==void 0){if(r.info("V2 walker \u2014 send_as_response \u2192 cancel + new prompt",{sessionId:e,contentPreview:d.slice(0,80)}),await this.markEventExecutedIdempotent(n,t),P())return;if(await this.cancelV2WalkerAndExit(e,n,"send_as_response",!0,P)){await new Promise(E=>setTimeout(E,1500));let w=this.activeSessions.get(e);if(w?.pendingPromptId||w?.waitingForPromptResponse){r.warn("Post-cancel free-text suppressed: new prompt B is active",{sessionId:e,bPromptId:w.pendingPromptId});return}await this.executeMobilePrompt(e,t)}return}r.info("Sending as free-form response to interactive prompt",{response:d});let h=await this.promptResponder.answerInteractivePrompt(e,d);if(P()){await this.markEventExecutedIdempotent(n,t);return}if(h){if(await this.markEventExecutedIdempotent(n,t),P())return;if(!g){r.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:g,questionIndex:0,isTerminal:!0})}catch(I){r.warn("[walker] emitAnswerAck (send_as_response) failed \u2014 continuing to clearPromptState",{sessionId:e,promptId:g,error:I instanceof Error?I.message:String(I)})}if(P())return;this.promoteFingerprintAndClearPromptState(n)}else try{await this.sendPromptError(e,"Failed to send response")}catch(I){r.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(I)})}finally{await this.markEventExecutedIdempotent(n,t)}}}finally{l&&n.inFlightPromptIds&&n.inFlightPromptIds.delete(l),m&&n.inFlightEventIds&&n.inFlightEventIds.delete(m)}}async sendInteractivePromptAsync(e,t,i){let n=this.activeSessions.get(e),s=n?.promptGenerationToken?{...n.promptGenerationToken}:void 0,o=(0,a.prepareEventTimestamp)({orderingKey:e});await new Promise(h=>setTimeout(h,500));let p=process.env.CODEVIBE_TMUX_SESSION,c={...t.metadata||{}},u=t.metadata?.tool_name,l=t.metadata?.tool_input,m=u==="AskUserQuestion"&&Array.isArray(l?.questions)?l.questions:[],d=m.every(h=>!h.multiSelect),g=m.length>=1&&d;if(m.length>0&&Array.isArray(m[0]?.options)&&m[0].options.length>0){let h=m[0],I=[];if(p)try{let{exec:k}=await import("child_process"),x=R=>new Promise((j,q)=>{k(R,{timeout:5e3},(V,Z)=>{V?q(V):j({stdout:Z||""})})}),{stdout:F}=await x(`tmux capture-pane -p -e -S -30 -t '${p}'`);I=this.parseAskUserQuestionSynthTail(F),r.info("AskUserQuestion synth-tail parsed from tmux",{tailCount:I.length,tail:I.map(R=>R.label)})}catch(k){r.warn("Failed to capture tmux for AskUserQuestion synth-tail; emitting without synth tail",{error:k instanceof Error?k.message:String(k)})}else r.info("No tmux session \u2014 AskUserQuestion synth tail will be empty");let w=this.activeSessions.get(e);if(w){let k=w.promptGenerationToken;s&&k?.gen===s.gen?w.pendingSynthTail=I:r.warn("AskUserQuestion synth-tail: stale async \u2014 token gen mismatch, skipping pendingSynthTail write",{tokenAtEmit:s,currentToken:k,sessionId:e})}let E=this.buildQuestionWireData(h,I);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:[h]},i=h.question;let y=typeof t.prompt_id=="string"&&t.prompt_id.length>0,b=g&&y;if(b){let k=m.slice(1);k.push({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});let x=this.activeSessions.get(e);if(x){let F=x.promptGenerationToken;s&&F?.gen===s.gen?(x.pendingQuestionsQueue=k,x.pendingCurrentQuestion=h):r.warn("AskUserQuestion V2: stale async \u2014 token gen mismatch, skipping pendingQuestionsQueue write",{tokenAtEmit:s,currentToken:F,sessionId:e})}}else g&&!y&&r.warn("AskUserQuestion V2: empty prompt_id, degrading to single-Q legacy emit",{questionCount:m.length});r.info("AskUserQuestion V2: emitting Q1 only (Q2..QN queued)",{questionCount:m.length,v2SequentialEmit:b,queuedRemaining:b?m.length-1:0,optionCountFirst:E.options.length,anyMultiSelect:!d,questionPreview:h.question.slice(0,80)})}else if(p)try{let{exec:h}=await import("child_process"),I=b=>new Promise((k,x)=>{h(b,{timeout:5e3},(F,R)=>{F?x(F):k({stdout:R||""})})}),{stdout:w}=await I(`tmux capture-pane -p -e -S -30 -t '${p}'`),E=w.split(`
6
- `);r.info("tmux capture result",{tmuxSession:p,totalLines:E.length,lastLines:E.slice(-15).map(b=>b.replace(/\x1B[^m]*m/g,"").trim()).filter(Boolean)});let y=(0,a.parseInteractivePrompt)(w);y&&y.options.length>0?(c.options=y.options,c.submitMap=y.submitMap,c.instructions=this.buildPromptInstructions(y),r.info("Parsed dynamic options from tmux",{optionCount:y.options.length,kind:y.kind,options:y.options})):(r.info("No dynamic options parsed from tmux, using fallback",{parsedResult:y}),this.addFallbackOptions(c))}catch(h){r.warn("Failed to capture tmux pane for options",{error:h}),this.addFallbackOptions(c)}else r.warn("No tmux session \u2014 using fallback options"),this.addFallbackOptions(c);let _=this.activeSessions.get(e);if(_&&c.submitMap){let h=_.promptGenerationToken;s&&h?.gen===s.gen?_.pendingSubmitMap=c.submitMap:r.warn("Interactive prompt async: stale async \u2014 token gen mismatch, skipping pendingSubmitMap write",{tokenAtEmit:s,currentToken:h,sessionId:e})}let U=i,$=c,S=!1;this.sessionKey&&(U=a.cryptoService.encryptContent(i,this.sessionKey),$={encrypted:a.cryptoService.encryptMetadata($,this.sessionKey)},S=!0);let T=this.activeSessions.get(e)?.promptGenerationToken;if(s&&T?.gen!==s.gen){r.warn("Interactive prompt emit: stale token \u2014 newer INTERACTIVE_PROMPT replaced ours; skipping AppSync emit",{sessionId:e,tokenAtEmit:s,currentToken:T});return}await this.appSyncClient.createEvent({sessionId:e,type:a.EventType.INTERACTIVE_PROMPT,source:t.source,content:U,metadata:$,promptId:t.prompt_id,timestamp:o,isEncrypted:S?!0:void 0}),r.info("Interactive prompt sent to AppSync with dynamic options",{sessionId:e})}buildQuestionWireData(e,t=[]){let i=(e.options||[]).map((c,u)=>{let l=typeof c=="string",m=l?c:c.label||"",d=l?"":c.description||"",g=l?"":c.preview||"",_={number:String(u+1),text:m};return d&&(_.description=d),g&&(_.preview=g),_});if(!e._isSubmit)for(let c of t)i.push({number:String(i.length+1),text:c.label});let n=Object.fromEntries(i.map(c=>[c.number,c.number])),s=(e.options||[]).length,o=t.findIndex(c=>c.label==="Type something"),p;if(e._isSubmit)p="Reply with 1 to submit your answers or 2 to cancel.";else if(e.multiSelect)p=`Reply with comma-separated numbers (e.g., 1,3) for "${e.header||e.question}"`;else if(o>=0){let c=String(s+o+1);p=`Reply with the number of your choice. For option ${c} (Type something), reply "${c}, your answer".`}else p="Reply with the number of your choice.";return{options:i,submitMap:n,instructions:p}}parseAskUserQuestionSynthTail(e){let t=(0,a.normalizeSnapshot)(e);if(!t)return[];let i=t.split(`
7
- `).slice(-14),n=[],s=new Set,o=["Type something","Chat about this"];for(let p of i){let c=p.trim();for(let u of o)!s.has(u)&&c===u&&(n.push({label:u}),s.add(u))}return n}addFallbackOptions(e){e.options=[{number:"1",text:"Yes"},{number:"2",text:"Yes, and don't ask again"},{number:"3",text:"Reject and tell Claude what to do differently"}],e.submitMap={1:"1",2:"2",3:"3"},e.instructions="Reply with 1, 2, or 3. Append a message to provide alternative instructions."}buildPromptInstructions(e){return`Reply with ${e.options.map(i=>i.number).join(", ")}. Append a message to provide alternative instructions.`}parseInteractivePromptInput(e,t=3){return Se(e,t)}async markEventExecuted(e){try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:a.DeliveryStatus.EXECUTED}),r.info("Event marked as EXECUTED",{eventId:e.eventId})}catch(t){r.warn("Failed to mark event as EXECUTED",{eventId:e.eventId,error:t})}}async sendPromptError(e,t){let i={error:!0},n=t,s=i,o=!1;this.sessionKey&&(n=a.cryptoService.encryptContent(t,this.sessionKey),s={encrypted:a.cryptoService.encryptMetadata(i,this.sessionKey)},o=!0),await this.appSyncClient.createEvent({sessionId:e,type:a.EventType.NOTIFICATION,source:a.EventSource.DESKTOP,content:n,metadata:s,timestamp:(0,a.prepareEventTimestamp)({orderingKey:e}),isEncrypted:o?!0:void 0})}async emitUserChoice(e,t){let i=t,n={source:"codevibe_v2_user_choice"},s=!1;this.sessionKey&&(i=a.cryptoService.encryptContent(t,this.sessionKey),n={encrypted:a.cryptoService.encryptMetadata({source:"codevibe_v2_user_choice"},this.sessionKey)},s=!0),await this.appSyncClient.createEvent({sessionId:e,type:a.EventType.ASSISTANT_RESPONSE,source:a.EventSource.DESKTOP,content:i,metadata:n,timestamp:(0,a.prepareEventTimestamp)({orderingKey:e}),isEncrypted:s?!0:void 0})}async emitAnswerAck(e,t,i){let n={promptAnswered:!0,...i},s=t,o=n,p=!1;this.sessionKey&&(s=a.cryptoService.encryptContent(t,this.sessionKey),o={encrypted:a.cryptoService.encryptMetadata(n,this.sessionKey)},p=!0),await this.appSyncClient.createEvent({sessionId:e,type:a.EventType.NOTIFICATION,source:a.EventSource.DESKTOP,content:s,metadata:o,timestamp:(0,a.prepareEventTimestamp)({orderingKey:e}),isEncrypted:p?!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.activeAskUserQuestionFingerprint=void 0,e.promptGenerationToken=void 0}async cancelV2WalkerAndExit(e,t,i,n,s){let o=t.pendingQuestionsQueue?.length??0;r.info("V2 walker mid-walker bailout \u2014 navigating to Submit/Cancel",{sessionId:e,advanceCount:o,triggerReason:i,hasFollowupText:n});let p=!1;for(let l=0;l<o;l++){let m=await this.promptResponder.sendKey(e,"Enter");if(s())return r.warn("cancelV2WalkerAndExit: aborted mid-loop (token rotated); leaving session state for new prompt",{sessionId:e,attemptedAdvances:l,totalAdvances:o,triggerReason:i}),!1;if(!m){p=!0,r.warn("cancelV2WalkerAndExit: sendKey returned false; aborting cancel sequence",{sessionId:e,attemptedAdvances:l,totalAdvances:o,triggerReason:i});break}if(await new Promise(d=>setTimeout(d,200)),s())return r.warn("cancelV2WalkerAndExit: aborted post-delay (token rotated); leaving session state",{sessionId:e,attemptedAdvances:l+1,totalAdvances:o,triggerReason:i}),!1}if(p){this.promoteFingerprintAndClearPromptState(t);try{await this.emitUserChoice(e,"AskUserQuestion bailout \u2014 desktop walker state unknown (tmux unavailable); your reply was not sent")}catch(l){r.warn("emitUserChoice on V2 cancel (sendKey failed) failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}return!1}let c=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!0});if(s())return r.warn("cancelV2WalkerAndExit: aborted post-Cancel send (token rotated); leaving session state",{sessionId:e,triggerReason:i}),!1;if(!c){r.warn('cancelV2WalkerAndExit: final "2" Cancel send returned false; treating as bailout',{sessionId:e,triggerReason:i}),this.promoteFingerprintAndClearPromptState(t);try{await this.emitUserChoice(e,"AskUserQuestion bailout \u2014 Cancel keypress did not land (tmux unavailable); your reply was not sent")}catch(l){r.warn("emitUserChoice on V2 cancel (cancel send failed) failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}return!1}t.activeAskUserQuestionFingerprint&&(t.completedAskUserQuestionFingerprints||(t.completedAskUserQuestionFingerprints=new Set),t.completedAskUserQuestionFingerprints.add(t.activeAskUserQuestionFingerprint),r.info("V2 walker cancelled via mid-walker bailout \u2014 fingerprint marked closed",{sessionId:e,fingerprint:t.activeAskUserQuestionFingerprint.slice(0,16),triggerReason:i}));let u=n?"AskUserQuestion cancelled \u2014 sending your reply as a new prompt":"AskUserQuestion cancelled, no answers submitted";try{await this.emitUserChoice(e,u)}catch(l){r.warn("emitUserChoice on V2 cancel failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}return s()?(r.warn("cancelV2WalkerAndExit: aborted post-emitUserChoice (token rotated); leaving session state for new prompt",{sessionId:e,triggerReason:i}),!1):(this.clearPromptState(t),!0)}computeAskUserQuestionFingerprint(e){if(!(!e||typeof e!="object"))try{let t=this.stringifyCanonical(e);return(0,L.createHash)("sha256").update(t).digest("hex")}catch(t){r.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(i=>this.stringifyCanonical(i)).join(",")+"]":"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+this.stringifyCanonical(e[i])).join(",")+"}"}async markEventExecutedIdempotent(e,t){e.processedEventIds||(e.processedEventIds=new Set),e.processedEventIds.add(t.eventId);try{await this.markEventExecuted(t)}catch(i){r.warn("[walker] markEventExecuted threw \u2014 relying on processedEventIds set for dedup",{sessionId:t.sessionId,eventId:t.eventId,error:String(i)})}}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(i=>i.message||"").join(" ");if(typeof t.message=="string")return t.message}return String(e)}displaySubscriptionLimitError(e,t){let i=this.getErrorMessage(e),n="",s=i.match(/for your (\w+) plan/i);s&&(n=` (${s[1]} tier)`);let o="",p=i.match(/of (\d+)/);switch(p&&(o=` [Limit: ${p[1]}]`),console.log(`
1
+ "use strict";var Se=Object.create;var G=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var xe=(f,e)=>{for(var t in e)G(f,t,{get:e[t],enumerable:!0})},pe=(f,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pe(e))!Ae.call(f,n)&&n!==t&&G(f,n,{get:()=>e[n],enumerable:!(r=Ie(e,n))||r.enumerable});return f};var T=(f,e,t)=>(t=f!=null?Se(be(f)):{},pe(e||!f||!f.__esModule?G(t,"default",{value:f,enumerable:!0}):t,f)),Ce=f=>pe(G({},"__esModule",{value:!0}),f);var Re={};xe(Re,{McpServer:()=>J,parseInteractivePromptInput:()=>ke});module.exports=Ce(Re);var R=T(require("fs")),D=T(require("path")),Y=T(require("os")),ve=require("child_process"),we=require("util"),Ee=require("child_process"),L=require("crypto");var ce=T(require("os")),de=T(require("path")),le=require("@quantiya/codevibe-core"),i=(0,le.createLogger)({name:"codevibe-claude",logFile:de.default.join(ce.default.tmpdir(),"codevibe-claude-mcp.log"),level:"info"});var p=require("@quantiya/codevibe-core");var te=T(require("express")),$=T(require("fs")),ne=T(require("path")),re=T(require("os")),ue=require("@quantiya/codevibe-core");var k=require("@quantiya/codevibe-core");var H=class{constructor(){this.assignedPort=0;this.app=(0,te.default)(),this.setupMiddleware(),this.setupRoutes()}setSessionId(e){this.sessionId=e}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(te.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=k.EventType.NOTIFICATION,r="Session started",n.source=e.source;break;case"SessionEnd":t=k.EventType.NOTIFICATION,r=`Session ended: ${e.reason||"unknown"}`,n.reason=e.reason;break;case"UserPromptSubmit":t=k.EventType.USER_PROMPT,r=e.prompt||"";break;case"PostToolUse":t=k.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=k.EventType.NOTIFICATION,r=e.message||"",n.notification_type=e.notification_type;break;default:t=k.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:k.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,ue.getConfig)(),o=s.server.dynamicPort?0:s.server.port;this.server=this.app.listen(o,s.server.host,()=>{let c=this.server.address();this.assignedPort=c.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",c=>{i.error("HTTP server error:",c),n(c)})}catch(s){n(s)}})}writePortFile(e,t){let r=ne.join(re.tmpdir(),`codevibe-claude-${e}.port`);try{$.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=ne.join(re.tmpdir(),`codevibe-claude-${this.sessionId}.port`);try{$.existsSync(e)&&($.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 me=require("child_process"),ge=require("@quantiya/codevibe-core");var X=class{async executePrompt(e,t){let r=(0,ge.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 c=(0,me.spawn)(r.claude.command,o,{stdio:["pipe","pipe","pipe"],shell:!0}),a="",m="",g=!1,l=setTimeout(()=>{g=!0,i.warn("Command execution timed out",{sessionId:e,timeout:n}),c.kill("SIGTERM")},n);c.stdout?.on("data",d=>{let u=d.toString();a+=u,i.debug("Command stdout",{output:u.slice(0,200)})}),c.stderr?.on("data",d=>{let u=d.toString();m+=u,i.debug("Command stderr",{output:u.slice(0,200)})}),c.on("close",d=>{clearTimeout(l);let u={success:d===0&&!g,output:a,error:m,exitCode:d||void 0,timedOut:g};u.success?i.info("Command executed successfully",{sessionId:e,exitCode:d,outputLength:a.length}):i.error("Command execution failed",{sessionId:e,exitCode:d,timedOut:g,error:m.slice(0,500)}),s(u)}),c.on("error",d=>{clearTimeout(l),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"),he=require("util");var ie=(0,he.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 ie(s);if(i.info("tmux send-keys (text) completed",{stdout:o.stdout||"(empty)",stderr:o.stderr||"(empty)"}),r){await this.delay(500);let c=`tmux send-keys -t "${e}" Enter`,a=await ie(c);i.info("tmux send-keys (Enter) completed",{stdout:a.stdout||"(empty)",stderr:a.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 ie(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 Te=(0,we.promisify)(Ee.exec),_e="/exit",ye="CODEVIBE_TMUX_SESSION";async function Fe(f,e){let t=async(r,n)=>{try{await Te(r)}catch(s){i.warn("tmux send-keys failed during self-terminate",{sessionName:f,label:n,error:String(s)})}};await t(`tmux send-keys -t "${f}" C-c`,"ctrl-c"),await new Promise(r=>setTimeout(r,200)),await t(`tmux send-keys -t "${f}" -l "${e}"`,"quit-text"),await new Promise(r=>setTimeout(r,500)),await t(`tmux send-keys -t "${f}" Enter`,"enter")}var J=class f{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 H,this.commandExecutor=new X,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=[],c=!1;for(let a of r)if(!(n-a.timestamp>f.MOBILE_PROMPT_EXPIRY_MS)){if(!c&&a.prompt===s){c=!0,i.debug("Found matching mobile prompt, filtering duplicate",{sessionId:e});continue}o.push(a)}return o.length>0?this.pendingMobilePrompts.set(e,o):this.pendingMobilePrompts.delete(e),c}writePortFile(e){let t=D.join(Y.tmpdir(),`codevibe-claude-${e}.port`);try{R.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=D.join(Y.tmpdir(),`codevibe-claude-${e}.port`);try{R.existsSync(t)&&(R.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 c=parseInt(s.substring(0,o),10);if(isNaN(c)||c===r)continue;let a=s.substring(o+1);if(/node.*codevibe-claude.*server\.js/.test(a)&&a.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 l=this.activeSessions.get(o);if(l?.completedAskUserQuestionFingerprints?.size){let d=l.completedAskUserQuestionFingerprints.size;l.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,L.randomUUID)()}`,i.info("Synthesized prompt_id for INTERACTIVE_PROMPT (hook omitted it)",{sessionId:o,synthesizedPromptId:e.prompt_id}));let l=this.activeSessions.get(o),d;if(l&&e.metadata?.tool_name==="AskUserQuestion"&&(d=this.computeAskUserQuestionFingerprint(e.metadata.tool_input?.questions),d)){let u=l.activeAskUserQuestionFingerprint===d,b=l.completedAskUserQuestionFingerprints?.has(d)??!1;if(u||b){i.info("Dropping duplicate INTERACTIVE_PROMPT \u2014 AskUserQuestion already tracked",{sessionId:o,fingerprint:d.slice(0,16),status:u?"in-flight":"completed",hookEvent:e.hook_event_name,promptId:e.prompt_id});return}}if(l){this.clearPromptState(l),l.waitingForPromptResponse=!0,l.pendingPromptId=e.prompt_id;let u=this.nextPromptGen++;l.promptGenerationToken={promptId:e.prompt_id||"",gen:u},d&&(l.activeAskUserQuestionFingerprint=d),i.info("Interactive prompt detected - will parse options from tmux",{sessionId:o,promptId:e.prompt_id,tokenGen:u,askUserQuestionFingerprint:d?.slice(0,16)})}this.sendInteractivePromptAsync(o,e,s).catch(u=>{i.error("Failed to send interactive prompt with dynamic options",{error:u})});return}let c=s,a=e.metadata,m=!1;i.info("Hook event encryption state",{type:n,sessionId:o,hasSessionKey:!!this.sessionKey,sessionKeyLength:this.sessionKey?.length||0}),this.sessionKey?(c=p.cryptoService.encryptContent(s,this.sessionKey),a&&(a={encrypted:p.cryptoService.encryptMetadata(a,this.sessionKey)}),m=!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 g=await this.appSyncClient.createEvent({sessionId:o,type:n,source:e.source,content:c,metadata:a,promptId:e.prompt_id,timestamp:(0,p.prepareEventTimestamp)({orderingKey:o}),isEncrypted:m?!0:void 0});if(n===p.EventType.USER_PROMPT&&e.source===p.EventSource.DESKTOP){let l=this.activeSessions.get(o);l?.waitingForPromptResponse&&(this.promoteFingerprintAndClearPromptState(l),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(m=>m!==r);if(s.length>0){i.info(`Marking ${s.length} previous session(s) as INACTIVE`);for(let m of s){let g=this.activeSessions.get(m);g?.mobileEndWatcher&&(g.mobileEndWatcher.stop(),g.mobileEndWatcher=void 0);try{await this.appSyncClient.updateSession({sessionId:m,status:p.SessionStatus.INACTIVE}),i.info("Previous session marked INACTIVE",{prevId:m,newSessionId:r})}catch(l){i.warn("Failed to mark previous session as INACTIVE",{prevId:m,error:l})}g&&this.removePortFile(g.claudeSessionId),this.activeSessions.delete(m)}}this.writePortFile(t);let o=this.appSyncClient.getCurrentUserId(),c={sessionId:r,claudeSessionId:t,userId:o,projectPath:n,cwd:n,createdAt:new Date,subscriptionActive:!1,waitingForPromptResponse:!1,metadata:e.metadata||{}};this.activeSessions.set(r,c);try{let m=await(0,p.resumeOrCreateSession)({sessionId:r,userId:c.userId,agentType:p.AgentType.CLAUDE,projectPath:n,metadata:e.metadata||{}},this.appSyncClient,i);if(this.sessionKey=m.sessionKey,m.resumed&&!m.sessionKey){let g=await p.keychainManager.getDeviceId();i.error("Device key not found in session encryptedKeys",{sessionId:r,pluginDeviceId:g}),console.error(`
4
+ \u26A0\uFE0F E2E ENCRYPTION WARNING: Cannot decrypt this session!`),console.error(` Your device ID (${g.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(m){if(this.isSessionLimitExceeded(m)){this.displaySubscriptionLimitError(m,"session"),this.activeSessions.delete(r),this.removePortFile(t);return}i.error("Failed to create/resume session:",m)}this.subscribeToMobileEvents(r),this.appSyncClient.startHeartbeat(r);let a=this.activeSessions.get(r);a&&(a.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(r,async()=>{i.info("Mobile ended session \u2014 sending desktop quit",{sessionId:r});let m=process.env[ye];if(!m){i.warn("No tmux session set; skipping desktop self-terminate",{sessionId:r,expectedEnv:ye});return}await Fe(m,_e)}))}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),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,c,a;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 u=d.promptId.length>0?d.promptId:`__prompt_gen_${d.gen}`;n.inFlightPromptIds?.has(u)?r="drop-in-flight":(n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightEventIds||(n.inFlightEventIds=new Set),n.inFlightPromptIds.add(u),n.inFlightEventIds.add(t.eventId),s=!0,c=u,a=t.eventId,o={promptId:d.promptId,gen:d.gen},r="walker")}}else r="regular";else r="not-user-prompt";let g=t.content||"";if(t.isEncrypted&&this.sessionKey)try{g=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}),g=t.content}let l={...t,content:g};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,g,n,s,o,c,a);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,l);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,c,a){let m=o??n.promptGenerationToken,g=c,l=a;if(!s&&m){let d=m.promptId.length>0?m.promptId:`__prompt_gen_${m.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),g=d,l=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(),u=n.pendingPromptId,_=n.pendingSubmitMap,Q=_?Object.keys(_).length:3,w=this.parseInteractivePromptInput(d,Q);i.info("Parsed interactive prompt input",{sessionId:e,content:d,parsed:w,hasSubmitMap:!!_});let h=()=>{let A=n.promptGenerationToken,y=A?.gen,S=m?.gen;return y!==S?(i.warn("[walker] Token mismatch \u2014 external cleanup or new prompt during in-flight handler \u2014 aborting",{sessionId:e,eventId:t.eventId,entryToken:m,currentToken:A}),!0):!1};if(h()){await this.markEventExecutedIdempotent(n,t);return}{let A=n.pendingQuestionsQueue!==void 0,S=d.trim().match(/^(\d+)$/);if(A&&n.pendingCurrentQuestion&&S){let E=n.pendingCurrentQuestion.options?.length??0,I=S[1],v=parseInt(I,10),x=!Number.isFinite(v)||v<1||v>E,P=String(v)!==I;if(x||P){if(i.info("V2 walker \u2014 bare out-of-range or non-canonical option; routing to cancel",{sessionId:e,option:I,optionNum:v,realOptionCount:E,isOutOfRange:x,isNonCanonical:P,isSubmitStep:!!n.pendingCurrentQuestion._isSubmit,parsedAction:w.action}),await this.markEventExecutedIdempotent(n,t),h())return;await this.cancelV2WalkerAndExit(e,n,"invalid_option",!1,h);return}}}if(w.action==="select_option"){let A=_?.[w.option]||w.option,y=n.pendingQuestionsQueue!==void 0;i.info("User selected option",{option:w.option,terminalInput:A,isV2AskUserQuestion:y});let S=await this.promptResponder.answerInteractivePrompt(e,A,{pressEnter:!0});if(h()){await this.markEventExecutedIdempotent(n,t);return}if(S){if(await this.markEventExecutedIdempotent(n,t),h())return;if(!u){i.warn("emitAnswerAck called without promptId \u2014 clearing state + skipping ack",{sessionId:e,source:"select_option",eventId:t.eventId}),this.promoteFingerprintAndClearPromptState(n);return}let E=(n.pendingQuestionsQueue?.length??0)===0;try{if(y){let C=parseInt(w.option,10)-1,O=n.pendingCurrentQuestion?.options?.[C],N=typeof O=="string"?O:O&&typeof O=="object"?O.label:`option ${w.option}`,oe=n.pendingCurrentQuestion?._isSubmit===!0,ae=N.toLowerCase(),q;oe&&ae==="cancel"?q="\u2192 Cancel \u2014 AskUserQuestion cancelled, no answers submitted":oe&&ae.startsWith("submit")?q="\u2192 Submit answers \u2014 AskUserQuestion completed":q=`\u2192 ${N}`,await this.emitUserChoice(e,q)}else await this.emitAnswerAck(e,`Selected option ${w.option}`,{promptId:u,questionIndex:0,isTerminal:E})}catch(C){i.warn("[walker] user-choice/ack emit failed \u2014 continuing to STEP 7/8",{sessionId:e,promptId:u,isV2AskUserQuestion:y,error:C instanceof Error?C.message:String(C)})}if(h())return;let I=n.pendingQuestionsQueue?.shift();if(I&&(n.pendingCurrentQuestion=I),!I){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 v=`synth-${(0,L.randomUUID)()}`;if(!v){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 x=n.pendingSynthTail??[],P=this.buildQuestionWireData(I,x),F=I.question,M={tool_name:"AskUserQuestion",tool_input:{questions:[I]},options:P.options,submitMap:P.submitMap,instructions:P.instructions},U=this.sessionKey,W=F,B=M,V=!1;U&&(W=p.cryptoService.encryptContent(F,U),B={encrypted:p.cryptoService.encryptMetadata(M,U)},V=!0);let Z=this.nextPromptGen++,ee={promptId:v,gen:Z};n.pendingPromptId=v,n.pendingSubmitMap=P.submitMap,n.promptGenerationToken=ee;let K=ee,j=this.activeSessions.get(e)?.promptGenerationToken;if(!j||j.gen!==K.gen||j.promptId!==K.promptId){i.warn("Q[next] emit aborted: token replaced before await dispatch",{sessionId:e,tokenAtAwait:K,currentToken:j});return}let se=v.length>0?v:`__prompt_gen_${ee.gen}`;n.inFlightPromptIds||(n.inFlightPromptIds=new Set),n.inFlightPromptIds.add(se);try{try{await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.INTERACTIVE_PROMPT,source:p.EventSource.DESKTOP,content:W,metadata:B,promptId:v,timestamp:(0,p.prepareEventTimestamp)({orderingKey:e}),isEncrypted:V?!0:void 0}),i.info("Q[next] emit succeeded",{sessionId:e,promptId:v,remaining:n.pendingQuestionsQueue?.length??0})}catch(C){let O=this.activeSessions.get(e),N=O?.promptGenerationToken;N&&N.gen===K.gen&&N.promptId===K.promptId?(this.promoteFingerprintAndClearPromptState(O),i.warn("Q[next] emit failed; promoted fingerprint + cleared prompt state. User must answer remaining questions on desktop terminal.",{sessionId:e,promptId:v,error:C instanceof Error?C.message:String(C)})):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:K,currentToken:N,error:C instanceof Error?C.message:String(C)})}}finally{n.inFlightPromptIds.delete(se)}}else try{await this.sendPromptError(e,"Failed to select option")}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)}}else if(w.action==="option_with_followup"){if(n.pendingQuestionsQueue!==void 0){if(i.info("V2 walker \u2014 option_with_followup \u2192 cancel + new prompt",{sessionId:e,option:w.option,followUpText:w.followUpText}),await this.markEventExecutedIdempotent(n,t),h())return;if(await this.cancelV2WalkerAndExit(e,n,"option_with_followup",!!w.followUpText,h)&&w.followUpText){await new Promise(x=>setTimeout(x,1500));let I=this.activeSessions.get(e);if(I?.pendingPromptId||I?.waitingForPromptResponse){i.warn("Post-cancel followup suppressed: new prompt B is active",{sessionId:e,bPromptId:I.pendingPromptId});return}let v={...t,content:w.followUpText};await this.executeMobilePrompt(e,v)}return}let y=_?.[w.option]||w.option;i.info("User selected option with follow-up",{option:w.option,terminalInput:y,followUpText:w.followUpText});let S=await this.promptResponder.answerInteractivePrompt(e,y);if(h()){await this.markEventExecutedIdempotent(n,t);return}if(S){if(await this.markEventExecutedIdempotent(n,t),h())return;if(!u){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 ${w.option}`,{promptId:u,questionIndex:0,isTerminal:!0})}catch(E){i.warn("[walker] emitAnswerAck (option_with_followup) failed \u2014 continuing to clearPromptState + executeMobilePrompt",{sessionId:e,promptId:u,error:E instanceof Error?E.message:String(E)})}if(h())return;if(this.promoteFingerprintAndClearPromptState(n),w.followUpText){await new Promise(I=>setTimeout(I,1e3));let E={...t,content:w.followUpText};await this.executeMobilePrompt(e,E)}}else try{await this.sendPromptError(e,"Failed to select option. Your reply (including the follow-up text) was not sent. Please retry.")}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)}}else{if(n.pendingQuestionsQueue!==void 0){if(i.info("V2 walker \u2014 send_as_response \u2192 cancel + new prompt",{sessionId:e,contentPreview:d.slice(0,80)}),await this.markEventExecutedIdempotent(n,t),h())return;if(await this.cancelV2WalkerAndExit(e,n,"send_as_response",!0,h)){await new Promise(I=>setTimeout(I,1500));let E=this.activeSessions.get(e);if(E?.pendingPromptId||E?.waitingForPromptResponse){i.warn("Post-cancel free-text suppressed: new prompt B is active",{sessionId:e,bPromptId:E.pendingPromptId});return}await this.executeMobilePrompt(e,t)}return}i.info("Sending as free-form response to interactive prompt",{response:d});let y=await this.promptResponder.answerInteractivePrompt(e,d);if(h()){await this.markEventExecutedIdempotent(n,t);return}if(y){if(await this.markEventExecutedIdempotent(n,t),h())return;if(!u){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:u,questionIndex:0,isTerminal:!0})}catch(S){i.warn("[walker] emitAnswerAck (send_as_response) failed \u2014 continuing to clearPromptState",{sessionId:e,promptId:u,error:S instanceof Error?S.message:String(S)})}if(h())return;this.promoteFingerprintAndClearPromptState(n)}else try{await this.sendPromptError(e,"Failed to send response")}catch(S){i.warn("[walker] sendPromptError threw \u2014 relying on idempotent mark in finally",{sessionId:e,eventId:t.eventId,error:String(S)})}finally{await this.markEventExecutedIdempotent(n,t)}}}finally{g&&n.inFlightPromptIds&&n.inFlightPromptIds.delete(g),l&&n.inFlightEventIds&&n.inFlightEventIds.delete(l)}}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(y=>setTimeout(y,500));let c=process.env.CODEVIBE_TMUX_SESSION,a={...t.metadata||{}},m=t.metadata?.tool_name,g=t.metadata?.tool_input,l=m==="AskUserQuestion"&&Array.isArray(g?.questions)?g.questions:[],d=l.every(y=>!y.multiSelect),u=l.length>=1&&d;if(l.length>0&&Array.isArray(l[0]?.options)&&l[0].options.length>0){let y=l[0],S=[];if(c)try{let{exec:P}=await import("child_process"),F=U=>new Promise((W,B)=>{P(U,{timeout:5e3},(V,Z)=>{V?B(V):W({stdout:Z||""})})}),{stdout:M}=await F(`tmux capture-pane -p -e -S -30 -t '${c}'`);S=this.parseAskUserQuestionSynthTail(M),i.info("AskUserQuestion synth-tail parsed from tmux",{tailCount:S.length,tail:S.map(U=>U.label)})}catch(P){i.warn("Failed to capture tmux for AskUserQuestion synth-tail; emitting without synth tail",{error:P instanceof Error?P.message:String(P)})}else i.info("No tmux session \u2014 AskUserQuestion synth tail will be empty");let E=this.activeSessions.get(e);if(E){let P=E.promptGenerationToken;s&&P?.gen===s.gen?E.pendingSynthTail=S:i.warn("AskUserQuestion synth-tail: stale async \u2014 token gen mismatch, skipping pendingSynthTail write",{tokenAtEmit:s,currentToken:P,sessionId:e})}let I=this.buildQuestionWireData(y,S);a.options=JSON.parse(JSON.stringify(I.options)),a.submitMap=JSON.parse(JSON.stringify(I.submitMap)),a.instructions=I.instructions,a.tool_name="AskUserQuestion",a.tool_input={questions:[y]},r=y.question;let v=typeof t.prompt_id=="string"&&t.prompt_id.length>0,x=u&&v;if(x){let P=l.slice(1);P.push({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});let F=this.activeSessions.get(e);if(F){let M=F.promptGenerationToken;s&&M?.gen===s.gen?(F.pendingQuestionsQueue=P,F.pendingCurrentQuestion=y):i.warn("AskUserQuestion V2: stale async \u2014 token gen mismatch, skipping pendingQuestionsQueue write",{tokenAtEmit:s,currentToken:M,sessionId:e})}}else u&&!v&&i.warn("AskUserQuestion V2: empty prompt_id, degrading to single-Q legacy emit",{questionCount:l.length});i.info("AskUserQuestion V2: emitting Q1 only (Q2..QN queued)",{questionCount:l.length,v2SequentialEmit:x,queuedRemaining:x?l.length-1:0,optionCountFirst:I.options.length,anyMultiSelect:!d,questionPreview:y.question.slice(0,80)})}else if(c)try{let{exec:y}=await import("child_process"),S=x=>new Promise((P,F)=>{y(x,{timeout:5e3},(M,U)=>{M?F(M):P({stdout:U||""})})}),{stdout:E}=await S(`tmux capture-pane -p -e -S -30 -t '${c}'`),I=E.split(`
6
+ `);i.info("tmux capture result",{tmuxSession:c,totalLines:I.length,lastLines:I.slice(-15).map(x=>x.replace(/\x1B[^m]*m/g,"").trim()).filter(Boolean)});let v=(0,p.parseInteractivePrompt)(E);v&&v.options.length>0?(a.options=v.options,a.submitMap=v.submitMap,a.instructions=this.buildPromptInstructions(v),i.info("Parsed dynamic options from tmux",{optionCount:v.options.length,kind:v.kind,options:v.options})):(i.info("No dynamic options parsed from tmux, using fallback",{parsedResult:v}),this.addFallbackOptions(a))}catch(y){i.warn("Failed to capture tmux pane for options",{error:y}),this.addFallbackOptions(a)}else i.warn("No tmux session \u2014 using fallback options"),this.addFallbackOptions(a);let b=this.activeSessions.get(e);if(b&&a.submitMap){let y=b.promptGenerationToken;s&&y?.gen===s.gen?b.pendingSubmitMap=a.submitMap:i.warn("Interactive prompt async: stale async \u2014 token gen mismatch, skipping pendingSubmitMap write",{tokenAtEmit:s,currentToken:y,sessionId:e})}let _=r,Q=a,w=!1;this.sessionKey&&(_=p.cryptoService.encryptContent(r,this.sessionKey),Q={encrypted:p.cryptoService.encryptMetadata(Q,this.sessionKey)},w=!0);let A=this.activeSessions.get(e)?.promptGenerationToken;if(s&&A?.gen!==s.gen){i.warn("Interactive prompt emit: stale token \u2014 newer INTERACTIVE_PROMPT replaced ours; skipping AppSync emit",{sessionId:e,tokenAtEmit:s,currentToken:A});return}await this.appSyncClient.createEvent({sessionId:e,type:p.EventType.INTERACTIVE_PROMPT,source:t.source,content:_,metadata:Q,promptId:t.prompt_id,timestamp:o,isEncrypted:w?!0:void 0}),i.info("Interactive prompt sent to AppSync with dynamic options",{sessionId:e})}buildQuestionWireData(e,t=[]){let r=(e.options||[]).map((a,m)=>{let g=typeof a=="string",l=g?a:a.label||"",d=g?"":a.description||"",u=g?"":a.preview||"",b={number:String(m+1),text:l};return d&&(b.description=d),u&&(b.preview=u),b});if(!e._isSubmit)for(let a of t)r.push({number:String(r.length+1),text:a.label});let n=Object.fromEntries(r.map(a=>[a.number,a.number])),s=(e.options||[]).length,o=t.findIndex(a=>a.label==="Type something"),c;if(e._isSubmit)c="Reply with 1 to submit your answers or 2 to cancel.";else if(e.multiSelect)c=`Reply with comma-separated numbers (e.g., 1,3) for "${e.header||e.question}"`;else if(o>=0){let a=String(s+o+1);c=`Reply with the number of your choice. For option ${a} (Type something), reply "${a}, your answer".`}else c="Reply with the number of your choice.";return{options:r,submitMap:n,instructions:c}}parseAskUserQuestionSynthTail(e){let t=(0,p.normalizeSnapshot)(e);if(!t)return[];let r=t.split(`
7
+ `).slice(-14),n=[],s=new Set,o=["Type something","Chat about this"];for(let c of r){let a=c.trim();for(let m of o)!s.has(m)&&a===m&&(n.push({label:m}),s.add(m))}return n}addFallbackOptions(e){e.options=[{number:"1",text:"Yes"},{number:"2",text:"Yes, and don't ask again"},{number:"3",text:"Reject and tell Claude what to do differently"}],e.submitMap={1:"1",2:"2",3:"3"},e.instructions="Reply with 1, 2, or 3. Append a message to provide alternative instructions."}buildPromptInstructions(e){return`Reply with ${e.options.map(r=>r.number).join(", ")}. Append a message to provide alternative instructions.`}parseInteractivePromptInput(e,t=3){return ke(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,c=!1;this.sessionKey&&(s=p.cryptoService.encryptContent(t,this.sessionKey),o={encrypted:p.cryptoService.encryptMetadata(n,this.sessionKey)},c=!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:c?!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.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=h=>new Promise((A,y)=>{r(h,{timeout:3e3},(S,E)=>{S?y(S):A({stdout:E||""})})}),{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,c=s.split(`
8
+ `).map(h=>h.replace(o,"").trimEnd()),a=c.length-1;for(;a>=0&&c[a].trim()==="";)a-=1;if(a<0)return i.warn("detectWalkerActive: pane empty after ANSI strip \u2014 conservatively assuming walker active",{sessionId:e}),!0;let m=/(?:Esc to cancel|Enter to select|↑\/↓ to navigate|Tab to switch|shift\+tab|Chat about this|Type something|Notes: press|\(esc\)|\(shift\+tab\))/i,g=/^\s*(?:[›❯▸▶➜➤]\s*)?\d+\.\s+/,l=-1;for(let h=a;h>=0;h-=1)if(g.test(c[h])){l=h;break}let d=l>=0,u=-1;for(let h=a;h>=0;h-=1)if(m.test(c[h])){u=h;break}let b=u<0?1/0:a-u,_=u>=0&&b<=3,Q=u>=0&&l>=0&&u>=l&&u-l<=5,w=d&&_&&Q;return i.info("detectWalkerActive",{sessionId:e,walkerActive:w,hasParserBlock:d,chromeNearBottom:_,chromeFollowsBlock:Q,chromeDistanceFromBottom:Number.isFinite(b)?b:-1,parserBlockEndsAt:l,lastNonBlank:a,lastChromeLineAt:u,lastLineSample:c[a]?.slice(0,80)??""}),w}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}}async cancelV2WalkerAndExit(e,t,r,n,s){let o=t.pendingQuestionsQueue?.length??0;i.info("V2 walker mid-walker bailout \u2014 navigating to Submit/Cancel",{sessionId:e,advanceCount:o,triggerReason:r,hasFollowupText:n});let c=await this.detectWalkerActive(e);if(s())return i.warn("cancelV2WalkerAndExit: aborted post-detectWalkerActive (token rotated)",{sessionId:e,triggerReason:r}),!1;if(!c){i.warn('cancelV2WalkerAndExit: walker no longer rendering \u2014 skipping keystroke sequence to avoid stray "2"',{sessionId:e,triggerReason:r,hasFollowupText:n}),t.activeAskUserQuestionFingerprint&&(t.completedAskUserQuestionFingerprints||(t.completedAskUserQuestionFingerprints=new Set),t.completedAskUserQuestionFingerprints.add(t.activeAskUserQuestionFingerprint));let l=n?"AskUserQuestion already closed \u2014 sending your reply as a new prompt":"AskUserQuestion already closed, no answers submitted";try{await this.emitUserChoice(e,l)}catch(d){i.warn("emitUserChoice on early-exit (walker-gone) failed",{sessionId:e,error:d instanceof Error?d.message:String(d)})}return s()?(i.warn("cancelV2WalkerAndExit: aborted post-early-emit (token rotated)",{sessionId:e,triggerReason:r}),!1):(this.clearPromptState(t),!0)}let a=!1;for(let l=0;l<o;l++){let d=await this.promptResponder.sendKey(e,"Enter");if(s())return i.warn("cancelV2WalkerAndExit: aborted mid-loop (token rotated); leaving session state for new prompt",{sessionId:e,attemptedAdvances:l,totalAdvances:o,triggerReason:r}),!1;if(!d){a=!0,i.warn("cancelV2WalkerAndExit: sendKey returned false; aborting cancel sequence",{sessionId:e,attemptedAdvances:l,totalAdvances:o,triggerReason:r});break}if(await new Promise(u=>setTimeout(u,200)),s())return i.warn("cancelV2WalkerAndExit: aborted post-delay (token rotated); leaving session state",{sessionId:e,attemptedAdvances:l+1,totalAdvances:o,triggerReason:r}),!1}if(a){this.promoteFingerprintAndClearPromptState(t);try{await this.emitUserChoice(e,"AskUserQuestion bailout \u2014 desktop walker state unknown (tmux unavailable); your reply was not sent")}catch(l){i.warn("emitUserChoice on V2 cancel (sendKey failed) failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}return!1}let m=await this.promptResponder.answerInteractivePrompt(e,"2",{pressEnter:!0});if(s())return i.warn("cancelV2WalkerAndExit: aborted post-Cancel send (token rotated); leaving session state",{sessionId:e,triggerReason:r}),!1;if(!m){i.warn('cancelV2WalkerAndExit: final "2" Cancel send returned false; treating as bailout',{sessionId:e,triggerReason:r}),this.promoteFingerprintAndClearPromptState(t);try{await this.emitUserChoice(e,"AskUserQuestion bailout \u2014 Cancel keypress did not land (tmux unavailable); your reply was not sent")}catch(l){i.warn("emitUserChoice on V2 cancel (cancel send failed) failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}return!1}t.activeAskUserQuestionFingerprint&&(t.completedAskUserQuestionFingerprints||(t.completedAskUserQuestionFingerprints=new Set),t.completedAskUserQuestionFingerprints.add(t.activeAskUserQuestionFingerprint),i.info("V2 walker cancelled via mid-walker bailout \u2014 fingerprint marked closed",{sessionId:e,fingerprint:t.activeAskUserQuestionFingerprint.slice(0,16),triggerReason:r}));let g=n?"AskUserQuestion cancelled \u2014 sending your reply as a new prompt":"AskUserQuestion cancelled, no answers submitted";try{await this.emitUserChoice(e,g)}catch(l){i.warn("emitUserChoice on V2 cancel failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}return s()?(i.warn("cancelV2WalkerAndExit: aborted post-emitUserChoice (token rotated); leaving session state for new prompt",{sessionId:e,triggerReason:r}),!1):(this.clearPromptState(t),!0)}computeAskUserQuestionFingerprint(e){if(!(!e||typeof e!="object"))try{let t=this.stringifyCanonical(e);return(0,L.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="",c=r.match(/of (\d+)/);switch(c&&(o=` [Limit: ${c[1]}]`),console.log(`
8
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(`
9
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(`
10
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(`
11
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(`
12
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)+`
13
- `),r.error("Subscription limit exceeded",{limitType:t,errorMessage:i})}async downloadAttachment(e,t,i){try{let n=e.isEncrypted??i??!1;r.info("Downloading attachment - START",{id:e.id,type:e.type,filename:e.filename,s3Key:e.s3Key,attachmentIsEncrypted:e.isEncrypted,eventIsEncrypted:i,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 p=Buffer.from(await o.arrayBuffer());if(r.info("Attachment downloaded",{id:e.id,downloadedSize:p.length,first20Bytes:p.slice(0,20).toString("hex")}),r.info("Checking decryption conditions",{id:e.id,shouldDecrypt:n,hasSessionKey:!!this.sessionKey,willDecrypt:!!(n&&this.sessionKey)}),n&&this.sessionKey)try{r.info("Decrypting attachment",{id:e.id,encryptedSize:p.length}),p=a.cryptoService.decryptData(p,this.sessionKey),r.info("Attachment decrypted successfully",{id:e.id,decryptedSize:p.length,first20Bytes:p.slice(0,20).toString("hex")})}catch(g){throw r.error("Failed to decrypt attachment:",{id:e.id,error:g}),new Error("Failed to decrypt attachment")}else n&&!this.sessionKey?r.warn("Cannot decrypt attachment - no session key available",{id:e.id}):r.info("Skipping decryption - attachment not encrypted or no session key",{id:e.id,shouldDecrypt:n,hasSessionKey:!!this.sessionKey});let c=N.join(Y.tmpdir(),"codevibe-claude",t);M.existsSync(c)||M.mkdirSync(c,{recursive:!0});let u="",l=e.filename;if(n&&e.filename&&this.sessionKey)try{l=a.cryptoService.decryptContent(e.filename,this.sessionKey)}catch{l=e.filename}if(l){let g=N.extname(l);g&&(u=g)}u||(u={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[e.type]||".bin");let m=`attachment-${e.id}${u}`,d=N.join(c,m);return M.writeFileSync(d,p),r.info("Attachment saved to temp file",{id:e.id,filePath:d,size:p.length,wasDecrypted:n&&!!this.sessionKey}),d}catch(n){return r.error("Failed to download attachment:",{id:e.id,error:n}),null}}async executeMobilePrompt(e,t){let i=t.content||"",n=t.attachments||[];r.info("Executing mobile prompt via tmux",{sessionId:e,promptLength:i.length,attachmentCount:n.length});let s=[];if(n.length>0){r.info("Downloading attachments for prompt",{count:n.length});for(let o of n){let p=await this.downloadAttachment(o,e,t.isEncrypted);p&&s.push(p)}if(s.length>0){let o=s.map(p=>`[Attached file: ${p}]`).join(`
14
- `);i?i=`${o}
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 c=Buffer.from(await o.arrayBuffer());if(i.info("Attachment downloaded",{id:e.id,downloadedSize:c.length,first20Bytes:c.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:c.length}),c=p.cryptoService.decryptData(c,this.sessionKey),i.info("Attachment decrypted successfully",{id:e.id,decryptedSize:c.length,first20Bytes:c.slice(0,20).toString("hex")})}catch(u){throw i.error("Failed to decrypt attachment:",{id:e.id,error:u}),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 a=D.join(Y.tmpdir(),"codevibe-claude",t);R.existsSync(a)||R.mkdirSync(a,{recursive:!0});let m="",g=e.filename;if(n&&e.filename&&this.sessionKey)try{g=p.cryptoService.decryptContent(e.filename,this.sessionKey)}catch{g=e.filename}if(g){let u=D.extname(g);u&&(m=u)}m||(m={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[e.type]||".bin");let l=`attachment-${e.id}${m}`,d=D.join(a,l);return R.writeFileSync(d,c),i.info("Attachment saved to temp file",{id:e.id,filePath:d,size:c.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 c=await this.downloadAttachment(o,e,t.isEncrypted);c&&s.push(c)}if(s.length>0){let o=s.map(c=>`[Attached file: ${c}]`).join(`
15
+ `);r?r=`${o}
15
16
 
16
- ${i}`:i=`${o}
17
+ ${r}`:r=`${o}
17
18
 
18
- Please analyze the attached file(s).`,r.info("Prompt updated with attachment paths",{attachmentCount:s.length,newPromptLength:i.length})}}this.trackMobilePrompt(e,i);try{if(await this.promptResponder.answerInteractivePrompt(e,i)){try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:a.DeliveryStatus.EXECUTED}),r.info("Event marked as EXECUTED",{eventId:t.eventId})}catch(c){r.warn("Failed to mark event as EXECUTED",{eventId:t.eventId,error:c})}r.info("Mobile prompt sent successfully",{sessionId:e});let p=s.length>0?`Prompt with ${s.length} attachment(s) sent to Claude Code`:`Prompt "${i.substring(0,50)}${i.length>50?"...":""}" sent to Claude Code`;await this.appSyncClient.createEvent({sessionId:e,type:a.EventType.NOTIFICATION,source:a.EventSource.DESKTOP,content:p,metadata:{mobilePrompt:!0,attachmentCount:s.length},timestamp:(0,a.prepareEventTimestamp)({orderingKey:e})})}else r.error("Failed to send mobile prompt",{sessionId:e}),await this.appSyncClient.createEvent({sessionId:e,type:a.EventType.NOTIFICATION,source:a.EventSource.DESKTOP,content:"Failed to send prompt to Claude Code",metadata:{error:!0},timestamp:(0,a.prepareEventTimestamp)({orderingKey:e})})}catch(o){r.error("Failed to execute mobile prompt:",o)}}};async function Me(){let f=process.argv[2]||process.env.CLAUDE_SESSION_ID;f?r.info(`Starting MCP server for session: ${f}`):r.info("Starting MCP server without initial session ID (will be set on SessionStart)");let e=new J(f);try{await e.start();let t=e.getPort();console.log(`PORT=${t}`);let i=!1,n=async s=>{if(i){r.info("Shutdown already in progress, ignoring additional signal");return}i=!0,r.info(`Received ${s} signal, stopping server...`);try{await e.stop(),r.info("Graceful shutdown completed"),process.exit(0)}catch(o){r.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=>{r.error("Uncaught exception:",s),await n("uncaughtException")}),process.on("unhandledRejection",async s=>{r.error("Unhandled rejection:",s),await n("unhandledRejection")})}catch(t){r.error("Failed to start MCP Server:",t),process.exit(1)}}function Se(f,e=3){let t=f.trim(),i=t.match(/^(\d+)$/);if(i){let s=parseInt(i[1]);if(s>=1&&s<=e)return{action:"select_option",option:i[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||Me().catch(f=>{r.error("Unhandled error in main:",f),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(a){i.warn("Failed to mark event as EXECUTED",{eventId:t.eventId,error:a})}i.info("Mobile prompt sent successfully",{sessionId:e});let c=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:c,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 Me(){let f=process.argv[2]||process.env.CLAUDE_SESSION_ID;f?i.info(`Starting MCP server for session: ${f}`):i.info("Starting MCP server without initial session ID (will be set on SessionStart)");let e=new J(f);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 ke(f,e=3){let t=f.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||Me().catch(f=>{i.error("Unhandled error in main:",f),process.exit(1)});0&&(module.exports={McpServer,parseInteractivePromptInput});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantiya/codevibe-claude-plugin",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
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": {