@quantiya/codevibe-claude-plugin 1.0.20 → 1.0.21

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.20",
3
+ "version": "1.0.21",
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"
@@ -1,8 +1,8 @@
1
- "use strict";var rt=Object.create;var Z=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ke=(n,e)=>{for(var t in e)Z(n,t,{get:e[t],enumerable:!0})},xe=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of it(e))!ot.call(n,s)&&s!==t&&Z(n,s,{get:()=>e[s],enumerable:!(r=nt(e,s))||r.enumerable});return n};var f=(n,e,t)=>(t=n!=null?rt(st(n)):{},xe(e||!n||!n.__esModule?Z(t,"default",{value:n,enumerable:!0}):t,n)),at=n=>xe(Z({},"__esModule",{value:!0}),n);function ct(n,e){if(e instanceof Error){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);for(let r of Object.keys(e))r in t||(t[r]=e[r]);return t}return e}function ae(n){return new P(n)}var M,ee,Pe,Ce,P,a,Re=T(()=>{"use strict";M=f(require("fs")),ee=f(require("path")),Pe=f(require("os")),Ce={debug:0,info:1,warn:2,error:3};P=class{constructor(e){this.name=e.name,this.logFile=e.logFile,this.level=e.level||"info",this.enableConsole=e.console??!1,this.logFile&&this.ensureLogDir()}ensureLogDir(){if(this.logFile){let e=ee.dirname(this.logFile);M.existsSync(e)||M.mkdirSync(e,{recursive:!0})}}shouldLog(e){return Ce[e]>=Ce[this.level]}formatMessage(e,t,r){let s=new Date().toISOString(),i=e.toUpperCase().padEnd(5),o=`[${s}] [${i}] [${this.name}] ${t}`;return r!==void 0&&(r instanceof Error?(o+=` ${r.name}: ${r.message}`,r.stack&&(o+=`
1
+ "use strict";var rt=Object.create;var Z=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ke=(n,e)=>{for(var t in e)Z(n,t,{get:e[t],enumerable:!0})},xe=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of it(e))!ot.call(n,s)&&s!==t&&Z(n,s,{get:()=>e[s],enumerable:!(r=nt(e,s))||r.enumerable});return n};var m=(n,e,t)=>(t=n!=null?rt(st(n)):{},xe(e||!n||!n.__esModule?Z(t,"default",{value:n,enumerable:!0}):t,n)),at=n=>xe(Z({},"__esModule",{value:!0}),n);function ct(n,e){if(e instanceof Error){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);for(let r of Object.keys(e))r in t||(t[r]=e[r]);return t}return e}function ae(n){return new R(n)}var M,ee,Re,Ce,R,a,Pe=T(()=>{"use strict";M=m(require("fs")),ee=m(require("path")),Re=m(require("os")),Ce={debug:0,info:1,warn:2,error:3};R=class{constructor(e){this.name=e.name,this.logFile=e.logFile,this.level=e.level||"info",this.enableConsole=e.console??!1,this.logFile&&this.ensureLogDir()}ensureLogDir(){if(this.logFile){let e=ee.dirname(this.logFile);M.existsSync(e)||M.mkdirSync(e,{recursive:!0})}}shouldLog(e){return Ce[e]>=Ce[this.level]}formatMessage(e,t,r){let s=new Date().toISOString(),i=e.toUpperCase().padEnd(5),o=`[${s}] [${i}] [${this.name}] ${t}`;return r!==void 0&&(r instanceof Error?(o+=` ${r.name}: ${r.message}`,r.stack&&(o+=`
2
2
  ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,ct)}`:o+=` ${r}`),o}log(e,t,r){if(!this.shouldLog(e))return;let s=this.formatMessage(e,t,r);if(this.logFile)try{M.appendFileSync(this.logFile,s+`
3
- `)}catch{}if(this.enableConsole)switch(e){case"error":console.error(s);break;case"warn":console.warn(s);break;default:console.log(s)}}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}};a=new P({name:"codevibe-core",logFile:ee.join(Pe.tmpdir(),"codevibe-core.log"),level:"info"})});var R=T(()=>{"use strict";Re()});function dt(n){for(let e of n)try{process.stderr.write(e+`
3
+ `)}catch{}if(this.enableConsole)switch(e){case"error":console.error(s);break;case"warn":console.warn(s);break;default:console.log(s)}}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}};a=new R({name:"codevibe-core",logFile:ee.join(Re.tmpdir(),"codevibe-core.log"),level:"info"})});var P=T(()=>{"use strict";Pe()});function dt(n){for(let e of n)try{process.stderr.write(e+`
4
4
  `)}catch{}}function lt(){ce=le.join(Ne.homedir(),".codevibe");try{x.mkdirSync(ce,{recursive:!0,mode:448})}catch{}N="file"}function pt(){if(N!==null||de!==null)return;let optedIn=process.env.CODEVIBE_ALLOW_FILE_KEYCHAIN==="1";if(optedIn){dt(["","\u26A0 CodeVibe: file-based credential storage selected (CODEVIBE_ALLOW_FILE_KEYCHAIN=1).","\u26A0 Location: ~/.codevibe/ (directory 0700, files 0600)","\u26A0 Trust level: equivalent to ~/.ssh/id_rsa \u2014 weaker than OS keyring.","\u26A0 To use the OS keyring instead, unset CODEVIBE_ALLOW_FILE_KEYCHAIN and","\u26A0 install libsecret-1-0 + a running keyring daemon (Linux) or use the","\u26A0 native Keychain (macOS) / Credential Manager (Windows).",""]),a.warn("[keychain-backend] Using file-based storage at ~/.codevibe (CODEVIBE_ALLOW_FILE_KEYCHAIN=1 explicit opt-in)"),lt();return}let keytarLoadError=null;try{let nodeRequire=eval("require");A=nodeRequire("keytar")}catch(n){keytarLoadError=n instanceof Error?n.message:String(n),A=null}if(A){N="keytar",a.info("[keychain-backend] Using keytar (OS-native keyring)");return}de=new te(["CodeVibe could not load the OS-native keyring (keytar).",`Reason: ${keytarLoadError??"unknown"}`,"","Options to fix this:"," 1. (Linux) Install libsecret and a keyring daemon:"," sudo apt install libsecret-1-0 gnome-keyring"," Then unlock the keyring for your user session.",""," 2. (Headless / CI / Docker) Opt in to file-based credential"," storage at ~/.codevibe/ (0600 files). This is equivalent"," in trust to ~/.ssh/id_rsa \u2014 not the OS keyring:"," export CODEVIBE_ALLOW_FILE_KEYCHAIN=1"].join(`
5
- `))}function ut(n){return n.replace(/[^a-zA-Z0-9._-]/g,"_")}function Oe(n){return le.join(ce,`${ut(n)}.json`)}function pe(n){try{let e=x.readFileSync(Oe(n),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function $e(n,e){let t=Oe(n);x.writeFileSync(t,JSON.stringify(e,null,2),{mode:384});try{x.chmodSync(t,384)}catch{}}function ue(){if(pt(),N===null)throw de??new te("Keychain backend not initialized")}async function ye(n,e){return ue(),N==="keytar"&&A?A.getPassword(n,e):pe(n)[e]??null}async function ge(n,e,t){if(ue(),N==="keytar"&&A){await A.setPassword(n,e,t);return}let r=pe(n);r[e]=t,$e(n,r)}async function me(n,e){if(ue(),N==="keytar"&&A)return A.deletePassword(n,e);let t=pe(n);return e in t?(delete t[e],$e(n,t),!0):!1}var Ne,le,x,te,N,A,ce,de,Le=T(()=>{"use strict";Ne=f(require("os")),le=f(require("path")),x=f(require("fs"));R();te=class extends Error{constructor(e){super(e),this.name="KeychainBackendUnavailableError"}},N=null,A=null,ce="",de=null});var b,O,fe,gt,W,w,Ue=T(()=>{"use strict";b=f(require("crypto")),O=class extends Error{constructor(e){super(e),this.name="CryptoError"}},fe=1,gt="CodeVibe E2E v1",W=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}generateKeyPair(){let e=b.createECDH("prime256v1");e.generateKeys();let r=e.getPublicKey().subarray(1).toString("base64");return{privateKey:e.getPrivateKey().toString("base64"),publicKey:r}}generateSessionKey(){return b.randomBytes(32).toString("base64")}deriveSharedKey(e,t){try{let r=b.createECDH("prime256v1"),s=Buffer.from(e,"base64");r.setPrivateKey(s);let i=Buffer.concat([Buffer.from([4]),Buffer.from(t,"base64")]),o=r.computeSecret(i),c=b.hkdfSync("sha256",o,Buffer.alloc(0),Buffer.from(gt,"utf8"),32);return Buffer.from(c)}catch(r){throw new O(`Failed to derive shared key: ${r}`)}}encryptSessionKey(e,t){let r=this.generateKeyPair(),s=this.deriveSharedKey(r.privateKey,t),i=Buffer.from(e,"base64");return{encryptedKey:this.encrypt(i,s).toString("base64"),ephemeralPublicKey:r.publicKey}}decryptSessionKey(e,t){let r=this.deriveSharedKey(t,e.ephemeralPublicKey),s=Buffer.from(e.encryptedKey,"base64");return this.decrypt(s,r).toString("base64")}encryptContent(e,t){let r=Buffer.from(t,"base64"),s=Buffer.from(e,"utf8");return this.encrypt(s,r).toString("base64")}decryptContent(e,t){let r=Buffer.from(t,"base64"),s=Buffer.from(e,"base64");return this.decrypt(s,r).toString("utf8")}encryptMetadata(e,t){let r=JSON.stringify(e);return this.encryptContent(r,t)}decryptMetadata(e,t){let r=this.decryptContent(e,t);return JSON.parse(r)}encryptData(e,t){let r=Buffer.from(t,"base64");return this.encrypt(e,r)}decryptData(e,t){let r=Buffer.from(t,"base64");return this.decrypt(e,r)}encrypt(e,t){let r=b.randomBytes(12),s=b.createCipheriv("aes-256-gcm",t,r),i=Buffer.concat([s.update(e),s.final()]),o=s.getAuthTag();return Buffer.concat([r,i,o])}decrypt(e,t){let r=e.subarray(0,12),s=e.subarray(e.length-16),i=e.subarray(12,e.length-16),o=b.createDecipheriv("aes-256-gcm",t,r);o.setAuthTag(s);try{return Buffer.concat([o.update(i),o.final()])}catch{throw new O("Decryption failed: Invalid ciphertext or authentication tag")}}serializePrivateKey(e){return e}deserializePrivateKey(e){return e}},w=W.getInstance()});var J=T(()=>{"use strict";Ue()});function k(){let n=process.env.ENVIRONMENT;return n==="development"||n==="production"?n:"production"}function ne(n){let e=n||k();return re={...$[e],aws:{...$[e].aws,region:process.env.AWS_REGION||$[e].aws.region,appsyncUrl:process.env.APPSYNC_URL||$[e].aws.appsyncUrl,cognitoUserPoolId:process.env.COGNITO_USER_POOL_ID||$[e].aws.cognitoUserPoolId,cognitoClientId:process.env.COGNITO_CLIENT_ID||$[e].aws.cognitoClientId,cognitoDomain:process.env.COGNITO_DOMAIN||$[e].aws.cognitoDomain}},_e=!0,re}function h(){return(!_e||!re)&&ne(),re}var j,z,$,re,_e,Me=T(()=>{"use strict";j=f(require("os")),z=f(require("path")),$={development:{environment:"development",aws:{region:"us-east-1",appsyncUrl:"https://te6rjr37sbfpjc4fiunmb2tgy4.appsync-api.us-east-1.amazonaws.com/graphql",cognitoUserPoolId:"us-east-1_yVwWDPvvJ",cognitoClientId:"e9r5apv6v5uui3l928r2ris0r",cognitoDomain:"codevibe-development.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:z.default.join(j.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:z.default.join(j.default.homedir(),".gemini","tmp")}},production:{environment:"production",aws:{region:"us-east-1",appsyncUrl:"https://jwhyxq4sgrgcdosewp5k4ns5ca.appsync-api.us-east-1.amazonaws.com/graphql",cognitoUserPoolId:"us-east-1_mNRO0j5og",cognitoClientId:"5p04dbc9ojptc5r8n7605fg78f",cognitoDomain:"codevibe-production.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:z.default.join(j.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:z.default.join(j.default.homedir(),".gemini","tmp")}}},re=null,_e=!1});var B=T(()=>{"use strict";Me()});var ie,We,D,he,mt,L,y,Be=T(()=>{"use strict";ie=f(require("os")),We=require("uuid");Le();J();B();R();D=class extends Error{constructor(e){super(e),this.name="KeychainError"}},he="device-identity",mt="tokens-",L=class n{constructor(){this.deviceIdentity=null;this.sessionKeyCache=new Map;this.isRegistered=!1;this._serviceName=null}get serviceName(){return this._serviceName||(this._serviceName=h().keychain.serviceName),this._serviceName}static getInstance(){return n.instance||(n.instance=new n),n.instance}async getDeviceIdentity(){if(this.deviceIdentity)return this.deviceIdentity;let e=await ye(this.serviceName,he);return e?(this.deviceIdentity=JSON.parse(e),a.info(`[KeychainManager] Loaded device identity: ${this.deviceIdentity.deviceId}`),this.deviceIdentity):null}async setDeviceIdentity(e){try{await ge(this.serviceName,he,JSON.stringify(e)),this.deviceIdentity=e,a.info(`[KeychainManager] Saved device identity: ${e.deviceId}`)}catch(t){throw a.error(`[KeychainManager] Failed to save device identity: ${t}`),new D(`Failed to save device identity: ${t}`)}}async getOrCreateDeviceIdentity(){let e=await this.getDeviceIdentity();if(e)return e;let t=w.generateKeyPair();return e={deviceId:(0,We.v4)().toUpperCase(),privateKey:t.privateKey,publicKey:t.publicKey,createdAt:new Date().toISOString()},await this.setDeviceIdentity(e),a.info(`[KeychainManager] Generated new device identity: ${e.deviceId}`),e}async getDeviceId(){return(await this.getOrCreateDeviceIdentity()).deviceId}async getDevicePublicKey(){return(await this.getOrCreateDeviceIdentity()).publicKey}async getDevicePrivateKey(){return(await this.getOrCreateDeviceIdentity()).privateKey}async hasDeviceIdentity(){return await this.getDeviceIdentity()!==null}async deleteDeviceIdentity(){try{await me(this.serviceName,he),this.deviceIdentity=null,this.sessionKeyCache.clear(),this.isRegistered=!1,a.info("[KeychainManager] Deleted device identity")}catch(e){throw a.error(`[KeychainManager] Failed to delete device identity: ${e}`),new D(`Failed to delete device identity: ${e}`)}}getTokenAccount(e){return`${mt}${e}`}async getTokens(e="production"){let t=await ye(this.serviceName,this.getTokenAccount(e));if(!t)return null;let r=JSON.parse(t);return a.debug(`[KeychainManager] Loaded tokens for ${e}`),r}async setTokens(e,t="production"){try{await ge(this.serviceName,this.getTokenAccount(t),JSON.stringify(e)),a.info(`[KeychainManager] Saved tokens for ${t}`,{userId:e.userId,email:e.email})}catch(r){throw a.error(`[KeychainManager] Failed to save tokens: ${r}`),new D(`Failed to save tokens: ${r}`)}}async deleteTokens(e="production"){try{let t=await me(this.serviceName,this.getTokenAccount(e));return t&&a.info(`[KeychainManager] Deleted tokens for ${e}`),t}catch(t){return a.error(`[KeychainManager] Failed to delete tokens: ${t}`),!1}}isTokenExpired(e){return Date.now()>=e.expiresAt-3e5}async getSessionKey(e,t){let r=this.sessionKeyCache.get(e);if(r)return r;if(!t||t.length===0)return null;let s=await this.getDeviceId(),i=t.find(l=>l.deviceId===s);if(!i)return a.warn(`[KeychainManager] Device ${s} not found in encryptedKeys`),null;let o=await this.getDevicePrivateKey(),c=w.decryptSessionKey(i,o);return this.sessionKeyCache.set(e,c),a.info(`[KeychainManager] Decrypted and cached session key for ${e}`),c}createSessionKey(e){let t=w.generateSessionKey(),r=e.map(s=>{let i=w.encryptSessionKey(t,s.publicKey);return{deviceId:s.deviceId,encryptedKey:i.encryptedKey,ephemeralPublicKey:i.ephemeralPublicKey}});return a.info(`[KeychainManager] Created session key for ${e.length} devices`),{sessionKey:t,encryptedKeys:r}}cacheSessionKey(e,t){this.sessionKeyCache.set(e,t)}getCachedSessionKey(e){return this.sessionKeyCache.get(e)??null}getCachedSessionIds(){return Array.from(this.sessionKeyCache.keys())}clearSessionKey(e){this.sessionKeyCache.delete(e)}clearAllSessionKeys(){this.sessionKeyCache.clear()}getIsRegistered(){return this.isRegistered}setIsRegistered(e){this.isRegistered=e}getDeviceName(){return ie.hostname()||"CLI Client"}getDevicePlatform(){let e=ie.platform();return e==="darwin"?"MACOS":e==="linux"?"LINUX":e==="win32"?"WINDOWS":"CLI"}async clearAllData(){await this.deleteDeviceIdentity(),await this.deleteTokens("development"),await this.deleteTokens("production"),this.sessionKeyCache.clear(),this.isRegistered=!1,a.info("[KeychainManager] Cleared all data")}},y=L.getInstance()});var Fe={};Ke(Fe,{KeychainError:()=>D,KeychainManager:()=>L,keychainManager:()=>y});var C=T(()=>{"use strict";Be()});var Pt={};Ke(Pt,{AgentType:()=>je,AppSyncClient:()=>X,AuthService:()=>H,CryptoError:()=>O,CryptoService:()=>W,DeliveryStatus:()=>Je,ENCRYPTION_VERSION:()=>fe,EventSource:()=>ve,EventType:()=>Ve,KeychainError:()=>D,KeychainManager:()=>L,Logger:()=>P,SessionStatus:()=>Se,authService:()=>K,createLogger:()=>ae,cryptoService:()=>w,getConfig:()=>h,getEnvironment:()=>k,keychainManager:()=>y,loadConfig:()=>ne,logger:()=>a,mutations:()=>I,normalizeSnapshot:()=>Ee,parseInteractivePrompt:()=>Qe,prepareSessionEncryption:()=>oe,queries:()=>U,registerDeviceEncryptionKey:()=>De,rekeySessionForNewDevices:()=>_,resumeOrCreateSession:()=>Te,runAuthCli:()=>se,startDeviceKeyWatcher:()=>Ae,subscriptions:()=>q});module.exports=at(Pt);C();J();var G=f(require("ws")),Y=require("uuid");B();R();C();var qe=f(require("dns")),He=f(require("fs"));if(ft())try{qe.setDefaultResultOrder("ipv4first")}catch{}function ft(){if(process.platform!=="linux")return!1;try{let n=He.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(n)}catch{return!1}}async function F(n,e,t){try{return await fetch(n,e)}catch(r){let s=r?.cause?.code,i=r?.cause?.message,o=s||i||r?.message||"unknown",c=ht(s),l=t?`${t}: `:"",p=`Node ${process.version} on ${process.platform}`,g=[`${l}Cannot reach ${n}`,` Underlying error: ${o}`];c&&g.push(` Suggested fix: ${c}`),g.push(` Platform: ${p}`);let u=new Error(g.join(`
5
+ `))}function ut(n){return n.replace(/[^a-zA-Z0-9._-]/g,"_")}function Oe(n){return le.join(ce,`${ut(n)}.json`)}function pe(n){try{let e=x.readFileSync(Oe(n),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function $e(n,e){let t=Oe(n);x.writeFileSync(t,JSON.stringify(e,null,2),{mode:384});try{x.chmodSync(t,384)}catch{}}function ue(){if(pt(),N===null)throw de??new te("Keychain backend not initialized")}async function ge(n,e){return ue(),N==="keytar"&&A?A.getPassword(n,e):pe(n)[e]??null}async function ye(n,e,t){if(ue(),N==="keytar"&&A){await A.setPassword(n,e,t);return}let r=pe(n);r[e]=t,$e(n,r)}async function me(n,e){if(ue(),N==="keytar"&&A)return A.deletePassword(n,e);let t=pe(n);return e in t?(delete t[e],$e(n,t),!0):!1}var Ne,le,x,te,N,A,ce,de,Le=T(()=>{"use strict";Ne=m(require("os")),le=m(require("path")),x=m(require("fs"));P();te=class extends Error{constructor(e){super(e),this.name="KeychainBackendUnavailableError"}},N=null,A=null,ce="",de=null});var k,O,fe,yt,W,w,Ue=T(()=>{"use strict";k=m(require("crypto")),O=class extends Error{constructor(e){super(e),this.name="CryptoError"}},fe=1,yt="CodeVibe E2E v1",W=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}generateKeyPair(){let e=k.createECDH("prime256v1");e.generateKeys();let r=e.getPublicKey().subarray(1).toString("base64");return{privateKey:e.getPrivateKey().toString("base64"),publicKey:r}}generateSessionKey(){return k.randomBytes(32).toString("base64")}deriveSharedKey(e,t){try{let r=k.createECDH("prime256v1"),s=Buffer.from(e,"base64");r.setPrivateKey(s);let i=Buffer.concat([Buffer.from([4]),Buffer.from(t,"base64")]),o=r.computeSecret(i),c=k.hkdfSync("sha256",o,Buffer.alloc(0),Buffer.from(yt,"utf8"),32);return Buffer.from(c)}catch(r){throw new O(`Failed to derive shared key: ${r}`)}}encryptSessionKey(e,t){let r=this.generateKeyPair(),s=this.deriveSharedKey(r.privateKey,t),i=Buffer.from(e,"base64");return{encryptedKey:this.encrypt(i,s).toString("base64"),ephemeralPublicKey:r.publicKey}}decryptSessionKey(e,t){let r=this.deriveSharedKey(t,e.ephemeralPublicKey),s=Buffer.from(e.encryptedKey,"base64");return this.decrypt(s,r).toString("base64")}encryptContent(e,t){let r=Buffer.from(t,"base64"),s=Buffer.from(e,"utf8");return this.encrypt(s,r).toString("base64")}decryptContent(e,t){let r=Buffer.from(t,"base64"),s=Buffer.from(e,"base64");return this.decrypt(s,r).toString("utf8")}encryptMetadata(e,t){let r=JSON.stringify(e);return this.encryptContent(r,t)}decryptMetadata(e,t){let r=this.decryptContent(e,t);return JSON.parse(r)}encryptData(e,t){let r=Buffer.from(t,"base64");return this.encrypt(e,r)}decryptData(e,t){let r=Buffer.from(t,"base64");return this.decrypt(e,r)}encrypt(e,t){let r=k.randomBytes(12),s=k.createCipheriv("aes-256-gcm",t,r),i=Buffer.concat([s.update(e),s.final()]),o=s.getAuthTag();return Buffer.concat([r,i,o])}decrypt(e,t){let r=e.subarray(0,12),s=e.subarray(e.length-16),i=e.subarray(12,e.length-16),o=k.createDecipheriv("aes-256-gcm",t,r);o.setAuthTag(s);try{return Buffer.concat([o.update(i),o.final()])}catch{throw new O("Decryption failed: Invalid ciphertext or authentication tag")}}serializePrivateKey(e){return e}deserializePrivateKey(e){return e}},w=W.getInstance()});var J=T(()=>{"use strict";Ue()});function b(){let n=process.env.ENVIRONMENT;return n==="development"||n==="production"?n:"production"}function ne(n){let e=n||b();return re={...$[e],aws:{...$[e].aws,region:process.env.AWS_REGION||$[e].aws.region,appsyncUrl:process.env.APPSYNC_URL||$[e].aws.appsyncUrl,cognitoUserPoolId:process.env.COGNITO_USER_POOL_ID||$[e].aws.cognitoUserPoolId,cognitoClientId:process.env.COGNITO_CLIENT_ID||$[e].aws.cognitoClientId,cognitoDomain:process.env.COGNITO_DOMAIN||$[e].aws.cognitoDomain}},_e=!0,re}function h(){return(!_e||!re)&&ne(),re}var j,G,$,re,_e,Me=T(()=>{"use strict";j=m(require("os")),G=m(require("path")),$={development:{environment:"development",aws:{region:"us-east-1",appsyncUrl:"https://te6rjr37sbfpjc4fiunmb2tgy4.appsync-api.us-east-1.amazonaws.com/graphql",cognitoUserPoolId:"us-east-1_yVwWDPvvJ",cognitoClientId:"e9r5apv6v5uui3l928r2ris0r",cognitoDomain:"codevibe-development.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:G.default.join(j.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:G.default.join(j.default.homedir(),".gemini","tmp")}},production:{environment:"production",aws:{region:"us-east-1",appsyncUrl:"https://jwhyxq4sgrgcdosewp5k4ns5ca.appsync-api.us-east-1.amazonaws.com/graphql",cognitoUserPoolId:"us-east-1_mNRO0j5og",cognitoClientId:"5p04dbc9ojptc5r8n7605fg78f",cognitoDomain:"codevibe-production.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:G.default.join(j.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:G.default.join(j.default.homedir(),".gemini","tmp")}}},re=null,_e=!1});var B=T(()=>{"use strict";Me()});var ie,We,D,he,mt,L,g,Be=T(()=>{"use strict";ie=m(require("os")),We=require("uuid");Le();J();B();P();D=class extends Error{constructor(e){super(e),this.name="KeychainError"}},he="device-identity",mt="tokens-",L=class n{constructor(){this.deviceIdentity=null;this.sessionKeyCache=new Map;this.isRegistered=!1;this._serviceName=null}get serviceName(){return this._serviceName||(this._serviceName=h().keychain.serviceName),this._serviceName}static getInstance(){return n.instance||(n.instance=new n),n.instance}async getDeviceIdentity(){if(this.deviceIdentity)return this.deviceIdentity;let e=await ge(this.serviceName,he);return e?(this.deviceIdentity=JSON.parse(e),a.info(`[KeychainManager] Loaded device identity: ${this.deviceIdentity.deviceId}`),this.deviceIdentity):null}async setDeviceIdentity(e){try{await ye(this.serviceName,he,JSON.stringify(e)),this.deviceIdentity=e,a.info(`[KeychainManager] Saved device identity: ${e.deviceId}`)}catch(t){throw a.error(`[KeychainManager] Failed to save device identity: ${t}`),new D(`Failed to save device identity: ${t}`)}}async getOrCreateDeviceIdentity(){let e=await this.getDeviceIdentity();if(e)return e;let t=w.generateKeyPair();return e={deviceId:(0,We.v4)().toUpperCase(),privateKey:t.privateKey,publicKey:t.publicKey,createdAt:new Date().toISOString()},await this.setDeviceIdentity(e),a.info(`[KeychainManager] Generated new device identity: ${e.deviceId}`),e}async getDeviceId(){return(await this.getOrCreateDeviceIdentity()).deviceId}async getDevicePublicKey(){return(await this.getOrCreateDeviceIdentity()).publicKey}async getDevicePrivateKey(){return(await this.getOrCreateDeviceIdentity()).privateKey}async hasDeviceIdentity(){return await this.getDeviceIdentity()!==null}async deleteDeviceIdentity(){try{await me(this.serviceName,he),this.deviceIdentity=null,this.sessionKeyCache.clear(),this.isRegistered=!1,a.info("[KeychainManager] Deleted device identity")}catch(e){throw a.error(`[KeychainManager] Failed to delete device identity: ${e}`),new D(`Failed to delete device identity: ${e}`)}}getTokenAccount(e){return`${mt}${e}`}async getTokens(e="production"){let t=await ge(this.serviceName,this.getTokenAccount(e));if(!t)return null;let r=JSON.parse(t);return a.debug(`[KeychainManager] Loaded tokens for ${e}`),r}async setTokens(e,t="production"){try{await ye(this.serviceName,this.getTokenAccount(t),JSON.stringify(e)),a.info(`[KeychainManager] Saved tokens for ${t}`,{userId:e.userId,email:e.email})}catch(r){throw a.error(`[KeychainManager] Failed to save tokens: ${r}`),new D(`Failed to save tokens: ${r}`)}}async deleteTokens(e="production"){try{let t=await me(this.serviceName,this.getTokenAccount(e));return t&&a.info(`[KeychainManager] Deleted tokens for ${e}`),t}catch(t){return a.error(`[KeychainManager] Failed to delete tokens: ${t}`),!1}}isTokenExpired(e){return Date.now()>=e.expiresAt-3e5}async getSessionKey(e,t){let r=this.sessionKeyCache.get(e);if(r)return r;if(!t||t.length===0)return null;let s=await this.getDeviceId(),i=t.find(d=>d.deviceId===s);if(!i)return a.warn(`[KeychainManager] Device ${s} not found in encryptedKeys`),null;let o=await this.getDevicePrivateKey(),c=w.decryptSessionKey(i,o);return this.sessionKeyCache.set(e,c),a.info(`[KeychainManager] Decrypted and cached session key for ${e}`),c}createSessionKey(e){let t=w.generateSessionKey(),r=e.map(s=>{let i=w.encryptSessionKey(t,s.publicKey);return{deviceId:s.deviceId,encryptedKey:i.encryptedKey,ephemeralPublicKey:i.ephemeralPublicKey}});return a.info(`[KeychainManager] Created session key for ${e.length} devices`),{sessionKey:t,encryptedKeys:r}}cacheSessionKey(e,t){this.sessionKeyCache.set(e,t)}getCachedSessionKey(e){return this.sessionKeyCache.get(e)??null}getCachedSessionIds(){return Array.from(this.sessionKeyCache.keys())}clearSessionKey(e){this.sessionKeyCache.delete(e)}clearAllSessionKeys(){this.sessionKeyCache.clear()}getIsRegistered(){return this.isRegistered}setIsRegistered(e){this.isRegistered=e}getDeviceName(){return ie.hostname()||"CLI Client"}getDevicePlatform(){let e=ie.platform();return e==="darwin"?"MACOS":e==="linux"?"LINUX":e==="win32"?"WINDOWS":"CLI"}async clearAllData(){await this.deleteDeviceIdentity(),await this.deleteTokens("development"),await this.deleteTokens("production"),this.sessionKeyCache.clear(),this.isRegistered=!1,a.info("[KeychainManager] Cleared all data")}},g=L.getInstance()});var Fe={};Ke(Fe,{KeychainError:()=>D,KeychainManager:()=>L,keychainManager:()=>g});var C=T(()=>{"use strict";Be()});var Rt={};Ke(Rt,{AgentType:()=>je,AppSyncClient:()=>X,AuthService:()=>H,CryptoError:()=>O,CryptoService:()=>W,DeliveryStatus:()=>Je,ENCRYPTION_VERSION:()=>fe,EventSource:()=>ve,EventType:()=>Ve,KeychainError:()=>D,KeychainManager:()=>L,Logger:()=>R,SessionStatus:()=>Se,authService:()=>K,createLogger:()=>ae,cryptoService:()=>w,getConfig:()=>h,getEnvironment:()=>b,keychainManager:()=>g,loadConfig:()=>ne,logger:()=>a,mutations:()=>I,normalizeSnapshot:()=>Ee,parseInteractivePrompt:()=>Qe,prepareSessionEncryption:()=>oe,queries:()=>U,registerDeviceEncryptionKey:()=>De,rekeySessionForNewDevices:()=>_,resumeOrCreateSession:()=>Te,runAuthCli:()=>se,startDeviceKeyWatcher:()=>Ae,subscriptions:()=>q});module.exports=at(Rt);C();J();var z=m(require("ws")),Y=require("uuid");B();P();C();var qe=m(require("dns")),He=m(require("fs"));if(ft())try{qe.setDefaultResultOrder("ipv4first")}catch{}function ft(){if(process.platform!=="linux")return!1;try{let n=He.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(n)}catch{return!1}}async function F(n,e,t){try{return await fetch(n,e)}catch(r){let s=r?.cause?.code,i=r?.cause?.message,o=s||i||r?.message||"unknown",c=ht(s),d=t?`${t}: `:"",p=`Node ${process.version} on ${process.platform}`,y=[`${d}Cannot reach ${n}`,` Underlying error: ${o}`];c&&y.push(` Suggested fix: ${c}`),y.push(` Platform: ${p}`);let u=new Error(y.join(`
6
6
  `));throw u.cause=r,u}}function ht(n){if(!n)return null;switch(n){case"ENOTFOUND":case"EAI_AGAIN":return'DNS resolution failed. On WSL Ubuntu, check /etc/resolv.conf, or try running with NODE_OPTIONS="--dns-result-order=ipv4first".';case"ETIMEDOUT":case"ECONNREFUSED":case"ECONNRESET":case"EHOSTUNREACH":case"ENETUNREACH":return`Network unreachable. On WSL Ubuntu, try NODE_OPTIONS="--dns-result-order=ipv4first" (WSL's IPv6 is often broken). If behind a corporate proxy, set HTTPS_PROXY.`;case"CERT_HAS_EXPIRED":case"CERT_NOT_YET_VALID":return"TLS certificate time error \u2014 likely system clock drift. On WSL, run `sudo hwclock -s`, or shut down WSL from PowerShell with `wsl --shutdown` and restart.";case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":case"SELF_SIGNED_CERT_IN_CHAIN":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"DEPTH_ZERO_SELF_SIGNED_CERT":return"Corporate HTTPS proxy detected \u2014 the TLS cert is not trusted by Node. Set NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem, or configure HTTPS_PROXY if a proxy is required.";default:return null}}var U={getSession:`
7
7
  query GetSession($sessionId: ID!) {
8
8
  getSession(sessionId: $sessionId) {
@@ -182,7 +182,7 @@ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,ct)}`:o+=` ${r}`),o}log
182
182
  lastUsedAt
183
183
  }
184
184
  }
185
- `};var Ve=(c=>(c.USER_PROMPT="USER_PROMPT",c.ASSISTANT_RESPONSE="ASSISTANT_RESPONSE",c.TOOL_USE="TOOL_USE",c.NOTIFICATION="NOTIFICATION",c.INTERACTIVE_PROMPT="INTERACTIVE_PROMPT",c.PROMPT_RESPONSE="PROMPT_RESPONSE",c.REASONING="REASONING",c))(Ve||{}),ve=(t=>(t.DESKTOP="DESKTOP",t.MOBILE="MOBILE",t))(ve||{}),Je=(r=>(r.SENT="SENT",r.DELIVERED="DELIVERED",r.EXECUTED="EXECUTED",r))(Je||{});var Se=(r=>(r.ACTIVE="ACTIVE",r.INACTIVE="INACTIVE",r.PAUSED="PAUSED",r))(Se||{}),je=(r=>(r.CLAUDE="CLAUDE",r.GEMINI="GEMINI",r.CODEX="CODEX",r))(je||{});var E={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3},X=class{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.activeSubscriptions=new Map;this.deviceKeyWatcher=null;this.heartbeatTimers=new Map;this.environment=k(),a.info("[AppSyncClient] Initialized",{environment:this.environment})}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}async authenticateWithStoredTokens(){try{let e=await y.getTokens(this.environment);if(!e)return a.debug("[AppSyncClient] No stored tokens found"),!1;if(a.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:y.isTokenExpired(e)}),y.isTokenExpired(e)){if(a.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return a.warn("[AppSyncClient] Token refresh failed"),!1}else this.tokens=e;return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,a.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){return a.error("[AppSyncClient] Authentication failed:",e),!1}}async refreshTokens(e){try{let t=h(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e.refreshToken}),i=await F(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token refresh");if(!i.ok)return a.error("[AppSyncClient] Token refresh failed",{status:i.status}),!1;let o=await i.json(),c={...e,accessToken:o.access_token,idToken:o.id_token,expiresAt:Date.now()+o.expires_in*1e3};return await y.setTokens(c,this.environment),this.tokens=c,a.info("[AppSyncClient] Tokens refreshed",{expiresAt:new Date(c.expiresAt).toISOString()}),!0}catch(t){return a.error("[AppSyncClient] Token refresh error:",t),!1}}isAuthenticated(){return this.authenticated}signOut(){this.authenticated=!1,this.tokens=null,this.currentUserId=null,this.currentEmail=null,this.cleanupSubscriptions(),a.info("[AppSyncClient] Signed out")}async graphqlRequest(e,t,r=!1){let s=h();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let i={"Content-Type":"application/json",Authorization:this.tokens.idToken},o=await F(s.aws.appsyncUrl,{method:"POST",headers:i,body:JSON.stringify({query:e,variables:t})},"AppSync GraphQL request"),c=await o.json();if(o.status===401&&!r&&this.tokens){if(a.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),await this.refreshTokens(this.tokens))return this.graphqlRequest(e,t,!0);throw new Error("Token expired and refresh failed")}if(!o.ok)throw new Error(`GraphQL request failed: ${o.status}`);if(c.errors?.length)throw new Error(`GraphQL error: ${c.errors[0].message}`);return c}async createSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(I.createSession,{input:t});return a.info("[AppSyncClient] Session created",{sessionId:r.data.createSession.sessionId}),r.data.createSession}async updateSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(I.updateSession,{input:t});return a.debug("[AppSyncClient] Session updated",{sessionId:r.data.updateSession.sessionId}),r.data.updateSession}async getSession(e){return(await this.graphqlRequest(U.getSession,{sessionId:e})).data.getSession}async createEvent(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(I.createEvent,{input:t});return a.debug("[AppSyncClient] Event created",{eventId:r.data.createEvent.eventId,type:r.data.createEvent.type}),r.data.createEvent}async updateEventStatus(e){return(await this.graphqlRequest(I.updateEventStatus,{input:e})).data.updateEventStatus}async listEvents(e,t,r){return(await this.graphqlRequest(U.listEvents,{sessionId:e,source:t,limit:r})).data.listEvents.items}async listUserDeviceKeys(){return(await this.graphqlRequest(U.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async registerDeviceKey(e,t,r,s){let i={deviceId:e,publicKey:t,platform:r,deviceName:s};await this.graphqlRequest(I.registerDeviceKey,{input:i}),a.info("[AppSyncClient] Device key registered",{deviceId:e,platform:r})}async grantSessionKey(e){await this.graphqlRequest(I.grantSessionKey,{input:e}),a.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(I.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}subscribeToEvents(e,t,r){a.info("[AppSyncClient] Subscribing to events",{sessionId:e});let s=this.activeSubscriptions.get(e);s&&(this.cleanupSubscriptionState(s),this.activeSubscriptions.delete(e));let i={ws:null,subscriptionId:(0,Y.v4)(),sessionId:e,onEvent:t,onError:r,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,i),this.createSubscription(i),()=>{this.cleanupSubscriptionState(i),this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=h(),t=e.aws.appsyncUrl.replace("https://","wss://").replace("appsync-api","appsync-realtime-api"),r={host:new URL(e.aws.appsyncUrl).host};this.tokens?.idToken&&(r.Authorization=this.tokens.idToken);let s=Buffer.from(JSON.stringify(r)).toString("base64"),i=Buffer.from(JSON.stringify({})).toString("base64");return`${t}?header=${s}&payload=${i}`}createSubscription(e){let{sessionId:t,subscriptionId:r,onEvent:s,onError:i}=e;try{let o=this.buildRealtimeUrl(),c=new G.default(o,["graphql-ws"]);c.on("open",()=>{a.info("[AppSyncClient] WebSocket connected",{sessionId:t}),c.send(JSON.stringify({type:"connection_init"}))}),c.on("message",l=>{try{let p=JSON.parse(l.toString());switch(p.type){case"connection_ack":this.sendSubscriptionStart(c,e);break;case"start_ack":a.info("[AppSyncClient] Subscription started",{sessionId:t}),e.isReconnecting=!1,e.reconnectAttempts=0,this.startHeartbeat(t);break;case"data":this.resetKeepAliveTimer(e);let g=p.payload?.data?.onEventCreated;g&&g.source==="MOBILE"&&s(g);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let u=p.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(u));break}}catch(p){a.error("[AppSyncClient] Failed to parse message",{error:p})}}),c.on("error",l=>{a.error("[AppSyncClient] WebSocket error",{sessionId:t,error:l.message}),this.handleSubscriptionError(e,l)}),c.on("close",(l,p)=>{a.info("[AppSyncClient] WebSocket closed",{sessionId:t,code:l}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(t)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${l}`))}),e.ws=c,this.resetKeepAliveTimer(e)}catch(o){this.handleSubscriptionError(e,o)}}sendSubscriptionStart(e,t){let r=h(),{sessionId:s,subscriptionId:i}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:i,type:"start",payload:{data:JSON.stringify({query:q.onEventCreated,variables:{sessionId:s}}),extensions:{authorization:o}}}))}resetKeepAliveTimer(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSubscriptionError(e,new Error("Keep-alive timeout"))},300*1e3)}handleSubscriptionError(e,t){let{sessionId:r,onError:s}=e;if(e.isReconnecting||!this.activeSubscriptions.has(r))return;e.isReconnecting=!0,e.reconnectAttempts++,this.stopHeartbeat(r);let i=e.reconnectAttempts<=E.urgentMaxAttempts,o;if(i?o=Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):(o=E.persistentDelayMs,e.reconnectAttempts===E.urgentMaxAttempts+1&&a.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:r})),a.info("[AppSyncClient] Scheduling reconnect",{sessionId:r,attempt:e.reconnectAttempts,phase:i?"urgent":"persistent",delayMs:o}),e.ws){try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(r)!==e){a.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:r});return}try{let c=await y.getTokens(this.environment);c&&(y.isTokenExpired(c)?await this.refreshTokens(c)&&a.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:r}):this.tokens=c)}catch{a.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:r})}if(e.destroyed||this.activeSubscriptions.get(r)!==e){a.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:r});return}e.subscriptionId=(0,Y.v4)(),this.createSubscription(e)},o)}cleanupSubscriptionState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===G.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}subscribeToDeviceKeyRegistered(e,t,r,s){a.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let i={userId:e,subscriptionId:(0,Y.v4)(),ws:null,onNewDevice:t,onReconnect:r,onError:s,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.deviceKeyWatcher=i,this.createDeviceKeyWatcherConnection(i),()=>{this.stopDeviceKeyWatcherInternal()}}stopDeviceKeyWatcher(){this.stopDeviceKeyWatcherInternal()}stopDeviceKeyWatcherInternal(){let e=this.deviceKeyWatcher;if(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===G.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}this.deviceKeyWatcher=null,a.info("[AppSyncClient] Device key watcher stopped")}}createDeviceKeyWatcherConnection(e){try{let t=this.buildRealtimeUrl(),r=new G.default(t,["graphql-ws"]);r.on("open",()=>{a.info("[AppSyncClient] Device key watcher WebSocket connected",{userId:e.userId}),r.send(JSON.stringify({type:"connection_init"}))}),r.on("message",s=>{try{let i=JSON.parse(s.toString());switch(i.type){case"connection_ack":this.sendDeviceKeyWatcherStart(r,e);break;case"start_ack":a.info("[AppSyncClient] Device key watcher subscription started",{userId:e.userId});let o=e.isReconnecting;if(e.isReconnecting=!1,e.reconnectAttempts=0,o&&e.onReconnect)try{e.onReconnect()}catch(p){a.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:p})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let c=i.payload?.data?.onDeviceKeyRegistered;if(c){a.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:c.deviceId,platform:c.platform});try{e.onNewDevice(c)}catch(p){a.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:p})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let l=i.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(l));break}}catch(i){a.error("[AppSyncClient] Failed to parse device key watcher message",{error:i})}}),r.on("error",s=>{a.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:s.message}),this.handleDeviceKeyWatcherError(e,s)}),r.on("close",s=>{a.info("[AppSyncClient] Device key watcher WebSocket closed",{userId:e.userId,code:s}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.deviceKeyWatcher===e&&this.handleDeviceKeyWatcherError(e,new Error(`WebSocket closed: ${s}`))}),e.ws=r,this.resetDeviceKeyWatcherKeepAlive(e)}catch(t){this.handleDeviceKeyWatcherError(e,t)}}sendDeviceKeyWatcherStart(e,t){let r=h(),{userId:s,subscriptionId:i}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:i,type:"start",payload:{data:JSON.stringify({query:q.onDeviceKeyRegistered,variables:{userId:s}}),extensions:{authorization:o}}}))}resetDeviceKeyWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleDeviceKeyWatcherError(e,new Error("Device key watcher keep-alive timeout"))},300*1e3)}handleDeviceKeyWatcherError(e,t){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(t)}catch{}if(e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let s=e.reconnectAttempts<=E.urgentMaxAttempts?Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):E.persistentDelayMs;a.warn("[AppSyncClient] Device key watcher reconnect scheduled",{userId:e.userId,attempts:e.reconnectAttempts,delayMs:s,error:t.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.deviceKeyWatcher!==e){a.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}try{let i=await y.getTokens(this.environment);i&&(y.isTokenExpired(i)?await this.refreshTokens(i)&&a.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId}):this.tokens=i)}catch{a.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,Y.v4)(),this.createDeviceKeyWatcherConnection(e))},s)}startHeartbeat(e,t=120*1e3){this.stopHeartbeat(e),this.sendHeartbeat(e);let r=setInterval(()=>{this.sendHeartbeat(e)},t);this.heartbeatTimers.set(e,r),a.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:t})}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e),a.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async sendHeartbeat(e){try{await this.updateSession({sessionId:e,lastHeartbeatAt:new Date().toISOString()}),a.debug("[AppSyncClient] Heartbeat sent",{sessionId:e})}catch(t){a.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:t})}}cleanupSubscriptions(){this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear(),this.stopDeviceKeyWatcherInternal(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear()}};var ze=f(require("crypto")),Ge=f(require("fs")),ke=f(require("http")),Ye=require("child_process");B();C();R();var Q=8080,Xe="/callback",we=`http://localhost:${Q}${Xe}`,H=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}openBrowser(e){console.log(""),console.log("Opening your browser for sign-in..."),console.log("If your browser does not open automatically, visit this URL manually:"),console.log(` ${e}`),console.log("");let t=this.getBrowserCommands();this.tryBrowserCommand(t,e,0)}getBrowserCommands(){let e=process.platform;if(e==="darwin")return[{cmd:"open",fixedArgs:[]}];if(e==="win32")return[{cmd:"cmd",fixedArgs:["/c","start",""]}];let t=[];return this.isRunningInWSL()&&(t.push({cmd:"wslview",fixedArgs:[]}),t.push({cmd:"cmd.exe",fixedArgs:["/c","start",""]}),t.push({cmd:"powershell.exe",fixedArgs:["-NoProfile","-Command","Start-Process"]})),t.push({cmd:"xdg-open",fixedArgs:[]}),t}isRunningInWSL(){if(process.platform!=="linux")return!1;try{let e=Ge.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,t,r){if(r>=e.length){a.debug("[AuthService] No browser-opening command succeeded. User must open the sign-in URL manually (printed to stdout above).");return}let s=e[r],i=[...s.fixedArgs,t],o=!1,c=u=>{o||(o=!0,a.debug(`[AuthService] Browser command '${s.cmd}' ${u}; trying next fallback`),this.tryBrowserCommand(e,t,r+1))},l=u=>{o||(o=!0,a.debug(`[AuthService] Browser command '${s.cmd}' ${u}`))},p;try{p=(0,Ye.spawn)(s.cmd,i,{detached:!0,stdio:"ignore"})}catch(u){c(`threw synchronously: ${u?.message||u}`);return}p.on("error",u=>{c(`failed to spawn: ${u?.message||u}`)}),p.on("exit",(u,v)=>{u===0?l("exited successfully"):c(v?`terminated by signal ${v}`:`exited with code ${u}`)}),setTimeout(()=>{l("still running after 3s, assuming success")},3e3).unref(),p.unref()}generateState(){return ze.randomBytes(32).toString("hex")}buildAuthUrl(e){let t=h(),r=new URLSearchParams({client_id:t.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:we,state:e});return`https://${t.aws.cognitoDomain}/oauth2/authorize?${r.toString()}`}async exchangeCodeForTokens(e){let t=h(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"authorization_code",client_id:t.aws.cognitoClientId,code:e,redirect_uri:we}),i=await F(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token exchange");if(!i.ok){let c=await i.text();throw new Error(`Token exchange failed: ${i.status} ${c}`)}let o=await i.json();return{accessToken:o.access_token,idToken:o.id_token,refreshToken:o.refresh_token,expiresIn:o.expires_in}}decodeJwt(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT");return JSON.parse(Buffer.from(t[1],"base64").toString("utf-8"))}async refreshTokens(e){let t=h(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e}),i=await F(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token refresh");if(!i.ok)throw new Error(`Token refresh failed: ${i.status}`);let o=await i.json();return{accessToken:o.access_token,idToken:o.id_token,expiresIn:o.expires_in}}async login(){let e=await y.getTokens(k());if(e&&!y.isTokenExpired(e))return e;let t=this.generateState(),r=this.buildAuthUrl(t);return new Promise((s,i)=>{let o=ke.createServer(async(c,l)=>{if(!c.url?.startsWith(Xe)){l.writeHead(404),l.end("Not found");return}try{let p=new URL(c.url,`http://localhost:${Q}`),g=p.searchParams.get("code"),u=p.searchParams.get("state"),v=p.searchParams.get("error");if(v)throw new Error(`OAuth error: ${v}`);if(u!==t)throw new Error("State mismatch");if(!g)throw new Error("No authorization code");let S=await this.exchangeCodeForTokens(g),V=this.decodeJwt(S.idToken),m={accessToken:S.accessToken,idToken:S.idToken,refreshToken:S.refreshToken,expiresAt:Date.now()+S.expiresIn*1e3,userId:V.sub,email:V.email||"unknown"};await y.setTokens(m,k()),l.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),l.end(`
185
+ `};var Ve=(c=>(c.USER_PROMPT="USER_PROMPT",c.ASSISTANT_RESPONSE="ASSISTANT_RESPONSE",c.TOOL_USE="TOOL_USE",c.NOTIFICATION="NOTIFICATION",c.INTERACTIVE_PROMPT="INTERACTIVE_PROMPT",c.PROMPT_RESPONSE="PROMPT_RESPONSE",c.REASONING="REASONING",c))(Ve||{}),ve=(t=>(t.DESKTOP="DESKTOP",t.MOBILE="MOBILE",t))(ve||{}),Je=(r=>(r.SENT="SENT",r.DELIVERED="DELIVERED",r.EXECUTED="EXECUTED",r))(Je||{});var Se=(r=>(r.ACTIVE="ACTIVE",r.INACTIVE="INACTIVE",r.PAUSED="PAUSED",r))(Se||{}),je=(r=>(r.CLAUDE="CLAUDE",r.GEMINI="GEMINI",r.CODEX="CODEX",r))(je||{});var E={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3},X=class{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.activeSubscriptions=new Map;this.deviceKeyWatcher=null;this.heartbeatTimers=new Map;this.environment=b(),a.info("[AppSyncClient] Initialized",{environment:this.environment})}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}async authenticateWithStoredTokens(){try{let e=await g.getTokens(this.environment);if(!e)return a.debug("[AppSyncClient] No stored tokens found"),!1;if(a.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:g.isTokenExpired(e)}),g.isTokenExpired(e)){if(a.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return a.warn("[AppSyncClient] Token refresh failed"),!1}else this.tokens=e;return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,a.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){return a.error("[AppSyncClient] Authentication failed:",e),!1}}async refreshTokens(e){try{let t=h(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e.refreshToken}),i=await F(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token refresh");if(!i.ok)return a.error("[AppSyncClient] Token refresh failed",{status:i.status}),!1;let o=await i.json(),c={...e,accessToken:o.access_token,idToken:o.id_token,expiresAt:Date.now()+o.expires_in*1e3};return await g.setTokens(c,this.environment),this.tokens=c,a.info("[AppSyncClient] Tokens refreshed",{expiresAt:new Date(c.expiresAt).toISOString()}),!0}catch(t){return a.error("[AppSyncClient] Token refresh error:",t),!1}}isAuthenticated(){return this.authenticated}signOut(){this.authenticated=!1,this.tokens=null,this.currentUserId=null,this.currentEmail=null,this.cleanupSubscriptions(),a.info("[AppSyncClient] Signed out")}async graphqlRequest(e,t,r=!1){let s=h();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let i={"Content-Type":"application/json",Authorization:this.tokens.idToken},o=await F(s.aws.appsyncUrl,{method:"POST",headers:i,body:JSON.stringify({query:e,variables:t})},"AppSync GraphQL request"),c=await o.json();if(o.status===401&&!r&&this.tokens){if(a.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),await this.refreshTokens(this.tokens))return this.graphqlRequest(e,t,!0);throw new Error("Token expired and refresh failed")}if(!o.ok)throw new Error(`GraphQL request failed: ${o.status}`);if(c.errors?.length)throw new Error(`GraphQL error: ${c.errors[0].message}`);return c}async createSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(I.createSession,{input:t});return a.info("[AppSyncClient] Session created",{sessionId:r.data.createSession.sessionId}),r.data.createSession}async updateSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(I.updateSession,{input:t});return a.debug("[AppSyncClient] Session updated",{sessionId:r.data.updateSession.sessionId}),r.data.updateSession}async getSession(e){return(await this.graphqlRequest(U.getSession,{sessionId:e})).data.getSession}async createEvent(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},r=await this.graphqlRequest(I.createEvent,{input:t});return a.debug("[AppSyncClient] Event created",{eventId:r.data.createEvent.eventId,type:r.data.createEvent.type}),r.data.createEvent}async updateEventStatus(e){return(await this.graphqlRequest(I.updateEventStatus,{input:e})).data.updateEventStatus}async listEvents(e,t,r){return(await this.graphqlRequest(U.listEvents,{sessionId:e,source:t,limit:r})).data.listEvents.items}async listUserDeviceKeys(){return(await this.graphqlRequest(U.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async registerDeviceKey(e,t,r,s){let i={deviceId:e,publicKey:t,platform:r,deviceName:s};await this.graphqlRequest(I.registerDeviceKey,{input:i}),a.info("[AppSyncClient] Device key registered",{deviceId:e,platform:r})}async grantSessionKey(e){await this.graphqlRequest(I.grantSessionKey,{input:e}),a.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(I.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}subscribeToEvents(e,t,r){a.info("[AppSyncClient] Subscribing to events",{sessionId:e});let s=this.activeSubscriptions.get(e);s&&(this.cleanupSubscriptionState(s),this.activeSubscriptions.delete(e));let i={ws:null,subscriptionId:(0,Y.v4)(),sessionId:e,onEvent:t,onError:r,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,i),this.createSubscription(i),()=>{this.cleanupSubscriptionState(i),this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=h(),t=e.aws.appsyncUrl.replace("https://","wss://").replace("appsync-api","appsync-realtime-api"),r={host:new URL(e.aws.appsyncUrl).host};this.tokens?.idToken&&(r.Authorization=this.tokens.idToken);let s=Buffer.from(JSON.stringify(r)).toString("base64"),i=Buffer.from(JSON.stringify({})).toString("base64");return`${t}?header=${s}&payload=${i}`}createSubscription(e){let{sessionId:t,subscriptionId:r,onEvent:s,onError:i}=e;try{let o=this.buildRealtimeUrl(),c=new z.default(o,["graphql-ws"]);c.on("open",()=>{a.info("[AppSyncClient] WebSocket connected",{sessionId:t}),c.send(JSON.stringify({type:"connection_init"}))}),c.on("message",d=>{try{let p=JSON.parse(d.toString());switch(p.type){case"connection_ack":this.sendSubscriptionStart(c,e);break;case"start_ack":a.info("[AppSyncClient] Subscription started",{sessionId:t}),e.isReconnecting=!1,e.reconnectAttempts=0,this.startHeartbeat(t);break;case"data":this.resetKeepAliveTimer(e);let y=p.payload?.data?.onEventCreated;y&&y.source==="MOBILE"&&s(y);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let u=p.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(u));break}}catch(p){a.error("[AppSyncClient] Failed to parse message",{error:p})}}),c.on("error",d=>{a.error("[AppSyncClient] WebSocket error",{sessionId:t,error:d.message}),this.handleSubscriptionError(e,d)}),c.on("close",(d,p)=>{a.info("[AppSyncClient] WebSocket closed",{sessionId:t,code:d}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(t)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${d}`))}),e.ws=c,this.resetKeepAliveTimer(e)}catch(o){this.handleSubscriptionError(e,o)}}sendSubscriptionStart(e,t){let r=h(),{sessionId:s,subscriptionId:i}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:i,type:"start",payload:{data:JSON.stringify({query:q.onEventCreated,variables:{sessionId:s}}),extensions:{authorization:o}}}))}resetKeepAliveTimer(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSubscriptionError(e,new Error("Keep-alive timeout"))},300*1e3)}handleSubscriptionError(e,t){let{sessionId:r,onError:s}=e;if(e.isReconnecting||!this.activeSubscriptions.has(r))return;e.isReconnecting=!0,e.reconnectAttempts++,this.stopHeartbeat(r);let i=e.reconnectAttempts<=E.urgentMaxAttempts,o;if(i?o=Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):(o=E.persistentDelayMs,e.reconnectAttempts===E.urgentMaxAttempts+1&&a.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:r})),a.info("[AppSyncClient] Scheduling reconnect",{sessionId:r,attempt:e.reconnectAttempts,phase:i?"urgent":"persistent",delayMs:o}),e.ws){try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(r)!==e){a.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:r});return}try{let c=await g.getTokens(this.environment);c&&(g.isTokenExpired(c)?await this.refreshTokens(c)&&a.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:r}):this.tokens=c)}catch{a.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:r})}if(e.destroyed||this.activeSubscriptions.get(r)!==e){a.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:r});return}e.subscriptionId=(0,Y.v4)(),this.createSubscription(e)},o)}cleanupSubscriptionState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===z.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}subscribeToDeviceKeyRegistered(e,t,r,s){a.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let i={userId:e,subscriptionId:(0,Y.v4)(),ws:null,onNewDevice:t,onReconnect:r,onError:s,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.deviceKeyWatcher=i,this.createDeviceKeyWatcherConnection(i),()=>{this.stopDeviceKeyWatcherInternal()}}stopDeviceKeyWatcher(){this.stopDeviceKeyWatcherInternal()}stopDeviceKeyWatcherInternal(){let e=this.deviceKeyWatcher;if(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===z.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}this.deviceKeyWatcher=null,a.info("[AppSyncClient] Device key watcher stopped")}}createDeviceKeyWatcherConnection(e){try{let t=this.buildRealtimeUrl(),r=new z.default(t,["graphql-ws"]);r.on("open",()=>{a.info("[AppSyncClient] Device key watcher WebSocket connected",{userId:e.userId}),r.send(JSON.stringify({type:"connection_init"}))}),r.on("message",s=>{try{let i=JSON.parse(s.toString());switch(i.type){case"connection_ack":this.sendDeviceKeyWatcherStart(r,e);break;case"start_ack":a.info("[AppSyncClient] Device key watcher subscription started",{userId:e.userId});let o=e.isReconnecting;if(e.isReconnecting=!1,e.reconnectAttempts=0,o&&e.onReconnect)try{e.onReconnect()}catch(p){a.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:p})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let c=i.payload?.data?.onDeviceKeyRegistered;if(c){a.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:c.deviceId,platform:c.platform});try{e.onNewDevice(c)}catch(p){a.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:p})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let d=i.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(d));break}}catch(i){a.error("[AppSyncClient] Failed to parse device key watcher message",{error:i})}}),r.on("error",s=>{a.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:s.message}),this.handleDeviceKeyWatcherError(e,s)}),r.on("close",s=>{a.info("[AppSyncClient] Device key watcher WebSocket closed",{userId:e.userId,code:s}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.deviceKeyWatcher===e&&this.handleDeviceKeyWatcherError(e,new Error(`WebSocket closed: ${s}`))}),e.ws=r,this.resetDeviceKeyWatcherKeepAlive(e)}catch(t){this.handleDeviceKeyWatcherError(e,t)}}sendDeviceKeyWatcherStart(e,t){let r=h(),{userId:s,subscriptionId:i}=t,o={host:new URL(r.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:i,type:"start",payload:{data:JSON.stringify({query:q.onDeviceKeyRegistered,variables:{userId:s}}),extensions:{authorization:o}}}))}resetDeviceKeyWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleDeviceKeyWatcherError(e,new Error("Device key watcher keep-alive timeout"))},300*1e3)}handleDeviceKeyWatcherError(e,t){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(t)}catch{}if(e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let s=e.reconnectAttempts<=E.urgentMaxAttempts?Math.min(E.baseDelayMs*Math.pow(E.backoffMultiplier,e.reconnectAttempts-1),E.maxDelayMs):E.persistentDelayMs;a.warn("[AppSyncClient] Device key watcher reconnect scheduled",{userId:e.userId,attempts:e.reconnectAttempts,delayMs:s,error:t.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.deviceKeyWatcher!==e){a.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}try{let i=await g.getTokens(this.environment);i&&(g.isTokenExpired(i)?await this.refreshTokens(i)&&a.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId}):this.tokens=i)}catch{a.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,Y.v4)(),this.createDeviceKeyWatcherConnection(e))},s)}startHeartbeat(e,t=120*1e3){this.stopHeartbeat(e),this.sendHeartbeat(e);let r=setInterval(()=>{this.sendHeartbeat(e)},t);this.heartbeatTimers.set(e,r),a.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:t})}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e),a.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async sendHeartbeat(e){try{await this.updateSession({sessionId:e,lastHeartbeatAt:new Date().toISOString()}),a.debug("[AppSyncClient] Heartbeat sent",{sessionId:e})}catch(t){a.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:t})}}cleanupSubscriptions(){this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear(),this.stopDeviceKeyWatcherInternal(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear()}};var Ge=m(require("crypto")),ze=m(require("fs")),be=m(require("http")),Ye=require("child_process");B();C();P();var Q=8080,Xe="/callback",we=`http://localhost:${Q}${Xe}`,H=class n{constructor(){}static getInstance(){return n.instance||(n.instance=new n),n.instance}openBrowser(e){console.log(""),console.log("Opening your browser for sign-in..."),this.isRunningInWSL()?console.log("If your browser does not open, paste this URL in your Windows browser:"):console.log("If your browser does not open automatically, visit this URL:"),console.log(` ${e}`),console.log("");let t=this.getBrowserCommands();this.tryBrowserCommand(t,e,0)}getBrowserCommands(){let e=process.platform;if(e==="darwin")return[{cmd:"open",fixedArgs:[]}];if(e==="win32")return[{cmd:"cmd",fixedArgs:["/c","start",""]}];let t=[];return this.isRunningInWSL()&&(t.push({cmd:"wslview",fixedArgs:[]}),t.push({cmd:"cmd.exe",fixedArgs:["/c","start",""]}),t.push({cmd:"powershell.exe",fixedArgs:["-NoProfile","-Command","Start-Process"]})),t.push({cmd:"xdg-open",fixedArgs:[]}),t}isRunningInWSL(){if(process.platform!=="linux")return!1;try{let e=ze.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,t,r){if(r>=e.length){a.debug("[AuthService] No browser-opening command succeeded. User must open the sign-in URL manually (printed to stdout above)."),console.log(""),console.log("\u26A0\uFE0F Could not open browser automatically."),this.isRunningInWSL()?console.log(" WSL detected \u2014 paste this URL in your Windows browser:"):console.log(" Please copy and paste this URL into your browser:"),console.log(` ${t}`),console.log("");return}let s=e[r],i=[...s.fixedArgs,t],o=!1,c=u=>{o||(o=!0,a.debug(`[AuthService] Browser command '${s.cmd}' ${u}; trying next fallback`),this.tryBrowserCommand(e,t,r+1))},d=u=>{o||(o=!0,a.debug(`[AuthService] Browser command '${s.cmd}' ${u}`))},p;try{p=(0,Ye.spawn)(s.cmd,i,{detached:!0,stdio:"ignore"})}catch(u){c(`threw synchronously: ${u?.message||u}`);return}p.on("error",u=>{c(`failed to spawn: ${u?.message||u}`)}),p.on("exit",(u,v)=>{u===0?d("exited successfully"):c(v?`terminated by signal ${v}`:`exited with code ${u}`)}),setTimeout(()=>{d("still running after 3s, assuming success")},3e3).unref(),p.unref()}generateState(){return Ge.randomBytes(32).toString("hex")}buildAuthUrl(e){let t=h(),r=new URLSearchParams({client_id:t.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:we,state:e});return`https://${t.aws.cognitoDomain}/oauth2/authorize?${r.toString()}`}async exchangeCodeForTokens(e){let t=h(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"authorization_code",client_id:t.aws.cognitoClientId,code:e,redirect_uri:we}),i=await F(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token exchange");if(!i.ok){let c=await i.text();throw new Error(`Token exchange failed: ${i.status} ${c}`)}let o=await i.json();return{accessToken:o.access_token,idToken:o.id_token,refreshToken:o.refresh_token,expiresIn:o.expires_in}}decodeJwt(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT");return JSON.parse(Buffer.from(t[1],"base64").toString("utf-8"))}async refreshTokens(e){let t=h(),r=`https://${t.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e}),i=await F(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},"Token refresh");if(!i.ok)throw new Error(`Token refresh failed: ${i.status}`);let o=await i.json();return{accessToken:o.access_token,idToken:o.id_token,expiresIn:o.expires_in}}async login(){let e=await g.getTokens(b());if(e&&!g.isTokenExpired(e))return e;let t=this.generateState(),r=this.buildAuthUrl(t);return new Promise((s,i)=>{let o=be.createServer(async(c,d)=>{if(!c.url?.startsWith(Xe)){d.writeHead(404),d.end("Not found");return}try{let p=new URL(c.url,`http://localhost:${Q}`),y=p.searchParams.get("code"),u=p.searchParams.get("state"),v=p.searchParams.get("error");if(v)throw new Error(`OAuth error: ${v}`);if(u!==t)throw new Error("State mismatch");if(!y)throw new Error("No authorization code");let S=await this.exchangeCodeForTokens(y),V=this.decodeJwt(S.idToken),f={accessToken:S.accessToken,idToken:S.idToken,refreshToken:S.refreshToken,expiresAt:Date.now()+S.expiresIn*1e3,userId:V.sub,email:V.email||"unknown"};await g.setTokens(f,b()),d.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),d.end(`
186
186
  <!DOCTYPE html>
187
187
  <html>
188
188
  <head><title>Success</title></head>
@@ -191,17 +191,17 @@ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,ct)}`:o+=` ${r}`),o}log
191
191
  <p>You can close this window.</p>
192
192
  </body>
193
193
  </html>
194
- `),setTimeout(()=>{o.close(()=>s(m))},500)}catch(p){let g=String(p?.message||p).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");l.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),l.end(`
194
+ `),setTimeout(()=>{o.close(()=>s(f))},500)}catch(p){let y=String(p?.message||p).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");d.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),d.end(`
195
195
  <!DOCTYPE html>
196
196
  <html>
197
197
  <head><title>Error</title></head>
198
198
  <body style="font-family: system-ui; max-width: 720px; margin: 50px auto; padding: 0 16px;">
199
199
  <h1 style="color: #ef4444; text-align: center;">&#10007; Authentication Failed</h1>
200
- <pre style="background: #f4f4f5; padding: 16px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.5;">${g}</pre>
200
+ <pre style="background: #f4f4f5; padding: 16px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.5;">${y}</pre>
201
201
  <p style="text-align: center; color: #71717a; margin-top: 24px;">You can close this window and try again in your terminal.</p>
202
202
  </body>
203
203
  </html>
204
- `),setTimeout(()=>{o.close(()=>i(p))},500)}});o.on("error",c=>{c.code==="EADDRINUSE"?i(new Error(`Port ${Q} is in use`)):i(c)}),o.listen(Q,"localhost",()=>{a.info("[AuthService] Callback server started"),this.openBrowser(r)}),setTimeout(()=>{o.close(()=>i(new Error("Login timeout")))},120*1e3)})}async logout(){let e=h(),t=await y.deleteTokens(k());return t&&new Promise(r=>{let s=ke.createServer((i,o)=>{i.url?.startsWith("/signout")?(o.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),o.end(`
204
+ `),setTimeout(()=>{o.close(()=>i(p))},500)}});o.on("error",c=>{c.code==="EADDRINUSE"?i(new Error(`Port ${Q} is in use`)):i(c)}),o.listen(Q,"localhost",()=>{a.info("[AuthService] Callback server started"),this.openBrowser(r)}),setTimeout(()=>{o.close(()=>i(new Error("Login timeout")))},120*1e3)})}async logout(){let e=h(),t=await g.deleteTokens(b());return t&&new Promise(r=>{let s=be.createServer((i,o)=>{i.url?.startsWith("/signout")?(o.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),o.end(`
205
205
  <!DOCTYPE html>
206
206
  <html>
207
207
  <head><title>Signed Out</title></head>
@@ -210,27 +210,27 @@ ${r.stack}`)):typeof r=="object"?o+=` ${JSON.stringify(r,ct)}`:o+=` ${r}`),o}log
210
210
  <p>You can close this window.</p>
211
211
  </body>
212
212
  </html>
213
- `),setTimeout(()=>{s.close(()=>r(!0))},500)):(o.writeHead(404),o.end("Not found"))});s.on("error",()=>{r(!0)}),s.listen(Q,"localhost",()=>{let i=`https://${e.aws.cognitoDomain}/logout?client_id=${e.aws.cognitoClientId}&logout_uri=${encodeURIComponent(we.replace("/callback","/signout"))}`;this.openBrowser(i)}),setTimeout(()=>{s.close(()=>r(!0))},30*1e3)})}async getStatus(){let e=await y.getTokens(k());return e?{authenticated:!y.isTokenExpired(e),tokens:e}:{authenticated:!1}}},K=H.getInstance();B();var d={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function vt(){console.log(`${d.cyan}CodeVibe Login${d.reset}
214
- `);try{let n=await K.getStatus();if(n.authenticated&&n.tokens){console.log(`${d.yellow}Already logged in as: ${n.tokens.email}${d.reset}`),console.log(`Token expires: ${new Date(n.tokens.expiresAt).toLocaleString()}`),console.log(`
215
- Run '${d.dim}codevibe logout${d.reset}' to sign out first.`),process.exit(0);return}console.log("Opening browser for authentication..."),console.log(`${d.dim}Waiting for callback...${d.reset}
216
- `);let e=await K.login();e&&(console.log(`
217
- ${d.green}\u2713 Authentication successful!${d.reset}`),console.log(` User: ${e.email}`),console.log(` User ID: ${e.userId}`),console.log(` Expires: ${new Date(e.expiresAt).toLocaleString()}`)),process.exit(0)}catch(n){console.log(`
218
- ${d.red}\u2717 Authentication failed${d.reset}`),console.log(` Error: ${n.message}`),process.exit(1)}}async function St(){console.log(`${d.cyan}CodeVibe Logout${d.reset}
219
- `);try{let n=await K.getStatus();if(!n.authenticated){console.log(`${d.yellow}Not logged in.${d.reset}`),process.exit(0);return}let e=n.tokens?.email;await K.logout()?(console.log(`${d.green}\u2713 Logged out successfully.${d.reset}`),console.log(` Previous user: ${e}`),console.log(`
220
- ${d.dim}Clearing browser session...${d.reset}`)):console.log(`${d.red}\u2717 Failed to log out.${d.reset}`),process.exit(0)}catch(n){console.log(`${d.red}\u2717 Logout failed: ${n.message}${d.reset}`),process.exit(1)}}async function wt(){console.log(`${d.cyan}CodeVibe Auth Status${d.reset}
221
- `);try{let n=await K.getStatus();if(!n.tokens){console.log(`${d.yellow}Not authenticated.${d.reset}`),console.log(`
222
- Run '${d.dim}codevibe login${d.reset}' to sign in.`),process.exit(0);return}let e=!n.authenticated;console.log(e?`${d.yellow}\u26A0 Token expired${d.reset}`:`${d.green}\u2713 Authenticated${d.reset}`),console.log(` User: ${n.tokens.email}`),console.log(` User ID: ${n.tokens.userId}`),console.log(` Expires: ${new Date(n.tokens.expiresAt).toLocaleString()}`),e&&console.log(`
223
- ${d.dim}Token will be refreshed automatically.${d.reset}`),process.exit(0)}catch(n){console.log(`${d.red}\u2717 Status check failed: ${n.message}${d.reset}`),process.exit(1)}}async function kt(){console.log(`${d.cyan}CodeVibe Reset Device${d.reset}
224
- `),console.log(`${d.red}\u26A0 WARNING: This will delete your device identity.${d.reset}`),console.log(`${d.red} Old encrypted sessions will become inaccessible.${d.reset}
225
- `);let{keychainManager:n}=await Promise.resolve().then(()=>(C(),Fe));try{await n.clearAllData(),console.log(`${d.green}\u2713 Device reset complete.${d.reset}`),console.log(` Run '${d.dim}codevibe login${d.reset}' to set up again.`),process.exit(0)}catch(e){console.log(`${d.red}\u2717 Reset failed: ${e.message}${d.reset}`),process.exit(1)}}function bt(){console.log(`CodeVibe Authentication
213
+ `),setTimeout(()=>{s.close(()=>r(!0))},500)):(o.writeHead(404),o.end("Not found"))});s.on("error",()=>{r(!0)}),s.listen(Q,"localhost",()=>{let i=`https://${e.aws.cognitoDomain}/logout?client_id=${e.aws.cognitoClientId}&logout_uri=${encodeURIComponent(we.replace("/callback","/signout"))}`;this.openBrowser(i)}),setTimeout(()=>{s.close(()=>r(!0))},30*1e3)})}async getStatus(){let e=await g.getTokens(b());return e?{authenticated:!g.isTokenExpired(e),tokens:e}:{authenticated:!1}}},K=H.getInstance();B();var l={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function vt(){console.log(`${l.cyan}CodeVibe Login${l.reset}
214
+ `);try{let n=await K.getStatus();if(n.authenticated&&n.tokens){console.log(`${l.yellow}Already logged in as: ${n.tokens.email}${l.reset}`),console.log(`Token expires: ${new Date(n.tokens.expiresAt).toLocaleString()}`),console.log(`
215
+ Run '${l.dim}codevibe logout${l.reset}' to sign out first.`),process.exit(0);return}console.log("Opening browser for authentication..."),console.log(`${l.dim}Waiting for callback...${l.reset}
216
+ `);let e=await K.login();if(e){console.log(`
217
+ ${l.green}\u2713 Authentication successful!${l.reset}`),console.log(` User: ${e.email}`),console.log(` User ID: ${e.userId}`),console.log(` Expires: ${new Date(e.expiresAt).toLocaleString()}`);try{let t=await import("https"),r=await import("crypto"),s=await import("os"),i=r.createHash("sha256").update(`${s.hostname()}-${process.getuid?.()??0}`).digest("hex").substring(0,36),o=JSON.stringify({client_id:i,events:[{name:"auth_completed",params:{platform:process.platform,user_id:e.userId,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production"}}]});await new Promise(c=>{let d=t.request({hostname:"www.google-analytics.com",path:"/mp/collect?measurement_id=G-GS74YEQTB8&api_secret=lAfOF6OxRzSQ-NsLBRjhAg",method:"POST",headers:{"Content-Type":"application/json"}},()=>c());d.on("error",()=>c()),d.write(o),d.end(),setTimeout(c,2e3)})}catch{}}process.exit(0)}catch(n){console.log(`
218
+ ${l.red}\u2717 Authentication failed${l.reset}`),console.log(` Error: ${n.message}`),process.exit(1)}}async function St(){console.log(`${l.cyan}CodeVibe Logout${l.reset}
219
+ `);try{let n=await K.getStatus();if(!n.authenticated){console.log(`${l.yellow}Not logged in.${l.reset}`),process.exit(0);return}let e=n.tokens?.email;await K.logout()?(console.log(`${l.green}\u2713 Logged out successfully.${l.reset}`),console.log(` Previous user: ${e}`),console.log(`
220
+ ${l.dim}Clearing browser session...${l.reset}`)):console.log(`${l.red}\u2717 Failed to log out.${l.reset}`),process.exit(0)}catch(n){console.log(`${l.red}\u2717 Logout failed: ${n.message}${l.reset}`),process.exit(1)}}async function wt(){console.log(`${l.cyan}CodeVibe Auth Status${l.reset}
221
+ `);try{let n=await K.getStatus();if(!n.tokens){console.log(`${l.yellow}Not authenticated.${l.reset}`),console.log(`
222
+ Run '${l.dim}codevibe login${l.reset}' to sign in.`),process.exit(0);return}let e=!n.authenticated;console.log(e?`${l.yellow}\u26A0 Token expired${l.reset}`:`${l.green}\u2713 Authenticated${l.reset}`),console.log(` User: ${n.tokens.email}`),console.log(` User ID: ${n.tokens.userId}`),console.log(` Expires: ${new Date(n.tokens.expiresAt).toLocaleString()}`),e&&console.log(`
223
+ ${l.dim}Token will be refreshed automatically.${l.reset}`),process.exit(0)}catch(n){console.log(`${l.red}\u2717 Status check failed: ${n.message}${l.reset}`),process.exit(1)}}async function bt(){console.log(`${l.cyan}CodeVibe Reset Device${l.reset}
224
+ `),console.log(`${l.red}\u26A0 WARNING: This will delete your device identity.${l.reset}`),console.log(`${l.red} Old encrypted sessions will become inaccessible.${l.reset}
225
+ `);let{keychainManager:n}=await Promise.resolve().then(()=>(C(),Fe));try{await n.clearAllData(),console.log(`${l.green}\u2713 Device reset complete.${l.reset}`),console.log(` Run '${l.dim}codevibe login${l.reset}' to set up again.`),process.exit(0)}catch(e){console.log(`${l.red}\u2717 Reset failed: ${e.message}${l.reset}`),process.exit(1)}}function kt(){console.log(`CodeVibe Authentication
226
226
  `),console.log("Usage:"),console.log(" codevibe login - Sign in via browser"),console.log(" codevibe logout - Sign out"),console.log(" codevibe status - Show auth status"),console.log(" codevibe reset-device - Reset device identity (destructive)"),console.log(`
227
- Environment:`),console.log(' Set ENVIRONMENT env var to "development" or "production" (default)'),console.log(" Example: ENVIRONMENT=development codevibe login")}async function se(n){let e=k();console.log(`${d.dim}Environment: ${e}${d.reset}
228
- `);let r=n.slice(2).filter(s=>!s.startsWith("--"))[0];switch(r){case"login":await vt();break;case"logout":await St();break;case"status":await wt();break;case"reset-device":await kt();break;default:bt(),process.exit(r?1:0)}}require.main===module&&se(process.argv).catch(n=>{console.error("Error:",n),process.exit(1)});B();R();var It=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function Qe(n){let e=Ee(n);if(!e)return null;let t=Et(e);if(t)return t;let r=Tt(e);return r||null}function Ee(n){return n.replace(/\r/g,`
227
+ Environment:`),console.log(' Set ENVIRONMENT env var to "development" or "production" (default)'),console.log(" Example: ENVIRONMENT=development codevibe login")}async function se(n){let e=b();console.log(`${l.dim}Environment: ${e}${l.reset}
228
+ `);let r=n.slice(2).filter(s=>!s.startsWith("--"))[0];switch(r){case"login":await vt();break;case"logout":await St();break;case"status":await wt();break;case"reset-device":await bt();break;default:kt(),process.exit(r?1:0)}}require.main===module&&se(process.argv).catch(n=>{console.error("Error:",n),process.exit(1)});B();P();var It=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function Qe(n){let e=Ee(n);if(!e)return null;let t=Et(e);if(t)return t;let r=Tt(e);return r||null}function Ee(n){return n.replace(/\r/g,`
229
229
  `).replace(It,"").replace(/[│┌┐└┘─├┤┬┴┼╌╎╭╮╯╰║═╔╗╚╝╠╣╦╩╬]/g," ").replace(/[ \t]+\n/g,`
230
230
  `).replace(/\n{3,}/g,`
231
231
 
232
232
  `).trim()}function Et(n){let e=n.split(`
233
- `).map(g=>g.trim()),t=At(e,g=>/\[(?:y\/n|Y\/n|y\/N)\]/.test(g)),r=t>=0?e[t]:null;if(!r)return null;let s=et(e,t),i=s.length>0?s.join(`
233
+ `).map(y=>y.trim()),t=At(e,y=>/\[(?:y\/n|Y\/n|y\/N)\]/.test(y)),r=t>=0?e[t]:null;if(!r)return null;let s=et(e,t),i=s.length>0?s.join(`
234
234
  `):r,o=i.toLowerCase(),c=o.includes("what to change")||o.includes("what should")||o.includes("provide")||o.includes("instructions");return{kind:"yes_no",promptText:i,options:c?[{number:"1",text:"Yes"},{number:"2",text:"No, provide instructions"}]:[{number:"1",text:"Yes"},{number:"2",text:"No"}],submitMap:{1:"y",2:"n"},requiresFollowUpText:c}}function Tt(n){let e=n.split(`
235
- `).map(l=>l.trim()),t=Dt(e);if(t.length<2)return null;let r=t.map(({line:l})=>Ze(l)).filter(l=>!!l),s={};for(let l of r)s[l.number]=l.number;let i=t[0]?.index??-1,o=et(e,i-1);return{kind:"numbered",promptText:o.length>0?o.join(`
236
- `):"Select an option",options:r,submitMap:s}}function At(n,e){for(let t=n.length-1;t>=0;t-=1)if(e(n[t]))return t;return-1}function Ze(n){let e=n.match(/^(?:[>›❯▸▶➜➤*●]\s*)?(\d+)\.\s+(.*)$/);return e?{number:e[1],text:e[2]}:null}function Dt(n){let e=n.map((r,s)=>({index:s,line:r,parsed:Ze(r)})).filter(r=>!!r.parsed);if(e.length===0)return[];let t=[e[e.length-1]];for(let r=e.length-2;r>=0;r-=1){let s=e[r],i=t[0];if(s.index!==i.index-1)break;t.unshift(s)}return t.map(({index:r,line:s})=>({index:r,line:s}))}function et(n,e){if(e<0)return[];let t=be(n,e);if(t<0)return[];let{start:r,end:s}=Ie(n,t),i=n.slice(r,s+1).filter(Boolean);if(xt(i)){let u=Kt(n,r-1);return u.length>0?u:i}if(r<=1)return i;let o=r-1;if(o=be(n,o),o<0||o===r-1)return i;let{start:c,end:l}=Ie(n,o),p=n.slice(c,l+1).filter(Boolean);return p.some(tt)?[...p,...i]:i}function tt(n){return/^(?:would you like to|do you want to|the model would like to|action required|confirm)\b/i.test(n)}function be(n,e){let t=e;for(;t>=0&&!n[t];)t-=1;return t}function Ie(n,e){let t=e;for(;t>=0&&n[t];)t-=1;return{start:t+1,end:e}}function Kt(n,e){let t=[],r=e;for(;r>=0&&t.length<2&&(r=be(n,r),!(r<0));){let{start:i,end:o}=Ie(n,r),c=n.slice(i,o+1).filter(Boolean);c.length>0&&t.unshift(c),r=i-1}if(t.length===0)return[];let s=t.findIndex(i=>i.some(tt));return s>=0?t.slice(s).flat():t[t.length-1]}function xt(n){return n.length===0?!1:n.filter(Ct).length>=Math.max(2,Math.ceil(n.length/2))}function Ct(n){return/^\d+\s/.test(n)}J();C();J();R();async function _(n,e,t,r={}){let s;try{s=await t.getSession(n)}catch(u){return a.warn("[SessionRekey] Failed to fetch session state for re-key",{sessionId:n,error:u instanceof Error?u.message:String(u)}),0}if(!s)return a.warn("[SessionRekey] Session not found, skipping re-key",{sessionId:n}),0;if(!s.isEncrypted)return 0;let i=s.encryptedKeys||[],o=new Set(i.map(u=>u.deviceId)),c=r.forceDeviceIds??new Set,l;try{l=await t.listUserDeviceKeys()}catch(u){return a.warn("[SessionRekey] Failed to fetch user device keys",{sessionId:n,error:u instanceof Error?u.message:String(u)}),0}let p=l.filter(u=>!o.has(u.deviceId)||c.has(u.deviceId));if(p.length===0)return 0;a.info("[SessionRekey] Granting session key to devices",{sessionId:n,existingDeviceCount:i.length,grantCount:p.length,grantDeviceIds:p.map(u=>u.deviceId),forceCount:c.size});let g=0;for(let u of p)try{let v=w.encryptSessionKey(e,u.publicKey);await t.grantSessionKey({sessionId:n,deviceId:u.deviceId,encryptedKey:v.encryptedKey,ephemeralPublicKey:v.ephemeralPublicKey}),g++,a.info("[SessionRekey] Granted session key to device",{sessionId:n,deviceId:u.deviceId,platform:u.platform})}catch(v){a.warn("[SessionRekey] Failed to grant session key to device",{sessionId:n,deviceId:u.deviceId,error:v instanceof Error?v.message:String(v)})}return g>0&&a.info("[SessionRekey] Re-key complete",{sessionId:n,grantedCount:g,requestedCount:p.length}),g}async function oe(n,e,t){try{let r=await e.listUserDeviceKeys();if(r.length===0)return t.info("No device keys found, session will not be encrypted"),null;t.info("Preparing session encryption",{sessionId:n,deviceCount:r.length});let{sessionKey:s,encryptedKeys:i}=y.createSessionKey(r);return t.info("Session encryption prepared",{sessionId:n,deviceCount:i.length}),{sessionKey:s,encryptedKeys:i}}catch(r){return t.warn("Failed to prepare session encryption:",r),null}}async function Te(n,e,t){let{sessionId:r,userId:s,agentType:i,projectPath:o,metadata:c}=n,l=null;try{l=await e.getSession(r)}catch(S){t.warn("Failed to get session (will attempt to create new)",{sessionId:r,error:S})}if(l){t.info("Session exists in backend - reactivating",{sessionId:r,previousStatus:l.status});try{await e.updateSession({sessionId:r,status:"ACTIVE"})}catch(m){t.warn("Failed to reactivate existing session, will continue",{sessionId:r,error:m})}let S=null,V=l.encryptedKeys;if(l.isEncrypted&&V?.length)try{let m=await y.getSessionKey(r,V);m?(S=m,y.cacheSessionKey(r,m),t.info("Session key retrieved for resumed session",{sessionId:r})):t.warn("No encrypted key for this device; proceeding without decryption",{sessionId:r})}catch(m){t.warn("Failed to retrieve session key for resumed session",{sessionId:r,error:m})}if(S)try{let m=await _(r,S,e);m>0&&t.info("Session re-keyed for newly registered devices on resume",{sessionId:r,newDeviceCount:m})}catch(m){t.warn("Session re-key on resume failed (non-fatal)",{sessionId:r,error:m instanceof Error?m.message:String(m)})}return{resumed:!0,sessionKey:S}}let p=await oe(r,e,t),g=o,u=c;p&&(g=w.encryptContent(o,p.sessionKey),u&&Object.keys(u).length>0&&(u={encrypted:w.encryptMetadata(u,p.sessionKey)}),t.info("Session data encrypted",{sessionId:r})),t.info("Creating new session in backend",{sessionId:r,userId:s,agentType:i,isEncrypted:!!p}),await e.createSession({sessionId:r,userId:s,agentType:i,projectPath:g,status:"ACTIVE",metadata:u,isEncrypted:p?!0:void 0,creatorDeviceId:p?await y.getDeviceId():void 0,encryptionVersion:p?1:void 0,encryptedKeys:p?.encryptedKeys});let v=p?.sessionKey||null;return p&&y.cacheSessionKey(r,p.sessionKey),t.info("Session created",{sessionId:r,userId:s,isEncrypted:!!p}),{resumed:!1,sessionKey:v}}C();function Ae(n,e){let t=n.getCurrentUserId(),r=async(i,o)=>{let c=y.getCachedSessionIds();if(c.length===0){e.info("[DeviceKeyWatcher] No active sessions to re-key",{reason:i});return}e.info("[DeviceKeyWatcher] Running re-key pass",{reason:i,activeSessionCount:c.length,forceDeviceCount:o?.size??0});for(let l of c){let p=y.getCachedSessionKey(l);if(p)try{let g=await _(l,p,n,o?{forceDeviceIds:o}:void 0);g>0&&e.info("[DeviceKeyWatcher] Session re-keyed",{sessionId:l,newDeviceCount:g,reason:i})}catch(g){e.warn("[DeviceKeyWatcher] Re-key failed for session (non-fatal)",{sessionId:l,reason:i,error:g instanceof Error?g.message:String(g)})}}},s=n.subscribeToDeviceKeyRegistered(t,i=>{e.info("[DeviceKeyWatcher] New device observed, triggering re-key",{userId:t,newDeviceId:i.deviceId,platform:i.platform,deviceName:i.deviceName}),r(`new-device:${i.deviceId}`,new Set([i.deviceId]))},()=>{r("watcher-reconnect")},i=>{e.warn("[DeviceKeyWatcher] Subscription error (will retry)",{error:i instanceof Error?i.message:String(i)})});return e.info("[DeviceKeyWatcher] Started",{userId:t}),s}C();async function De(n,e){try{let t=await y.getDeviceId(),r=await y.getDevicePublicKey(),s=y.getDevicePlatform(),i=y.getDeviceName();e.info("Registering device encryption key",{deviceId:t,platform:s,deviceName:i}),await n.registerDeviceKey(t,r,s,i),y.setIsRegistered(!0),e.info("Device encryption key registered successfully",{deviceId:t})}catch(t){e.warn("Failed to register device encryption key (E2E encryption may not work):",t)}}0&&(module.exports={AgentType,AppSyncClient,AuthService,CryptoError,CryptoService,DeliveryStatus,ENCRYPTION_VERSION,EventSource,EventType,KeychainError,KeychainManager,Logger,SessionStatus,authService,createLogger,cryptoService,getConfig,getEnvironment,keychainManager,loadConfig,logger,mutations,normalizeSnapshot,parseInteractivePrompt,prepareSessionEncryption,queries,registerDeviceEncryptionKey,rekeySessionForNewDevices,resumeOrCreateSession,runAuthCli,startDeviceKeyWatcher,subscriptions});
235
+ `).map(d=>d.trim()),t=Dt(e);if(t.length<2)return null;let r=t.map(({line:d})=>Ze(d)).filter(d=>!!d),s={};for(let d of r)s[d.number]=d.number;let i=t[0]?.index??-1,o=et(e,i-1);return{kind:"numbered",promptText:o.length>0?o.join(`
236
+ `):"Select an option",options:r,submitMap:s}}function At(n,e){for(let t=n.length-1;t>=0;t-=1)if(e(n[t]))return t;return-1}function Ze(n){let e=n.match(/^(?:[>›❯▸▶➜➤*●]\s*)?(\d+)\.\s+(.*)$/);return e?{number:e[1],text:e[2]}:null}function Dt(n){let e=n.map((r,s)=>({index:s,line:r,parsed:Ze(r)})).filter(r=>!!r.parsed);if(e.length===0)return[];let t=[e[e.length-1]];for(let r=e.length-2;r>=0;r-=1){let s=e[r],i=t[0];if(s.index!==i.index-1)break;t.unshift(s)}return t.map(({index:r,line:s})=>({index:r,line:s}))}function et(n,e){if(e<0)return[];let t=ke(n,e);if(t<0)return[];let{start:r,end:s}=Ie(n,t),i=n.slice(r,s+1).filter(Boolean);if(xt(i)){let u=Kt(n,r-1);return u.length>0?u:i}if(r<=1)return i;let o=r-1;if(o=ke(n,o),o<0||o===r-1)return i;let{start:c,end:d}=Ie(n,o),p=n.slice(c,d+1).filter(Boolean);return p.some(tt)?[...p,...i]:i}function tt(n){return/^(?:would you like to|do you want to|the model would like to|action required|confirm)\b/i.test(n)}function ke(n,e){let t=e;for(;t>=0&&!n[t];)t-=1;return t}function Ie(n,e){let t=e;for(;t>=0&&n[t];)t-=1;return{start:t+1,end:e}}function Kt(n,e){let t=[],r=e;for(;r>=0&&t.length<2&&(r=ke(n,r),!(r<0));){let{start:i,end:o}=Ie(n,r),c=n.slice(i,o+1).filter(Boolean);c.length>0&&t.unshift(c),r=i-1}if(t.length===0)return[];let s=t.findIndex(i=>i.some(tt));return s>=0?t.slice(s).flat():t[t.length-1]}function xt(n){return n.length===0?!1:n.filter(Ct).length>=Math.max(2,Math.ceil(n.length/2))}function Ct(n){return/^\d+\s/.test(n)}J();C();J();P();async function _(n,e,t,r={}){let s;try{s=await t.getSession(n)}catch(u){return a.warn("[SessionRekey] Failed to fetch session state for re-key",{sessionId:n,error:u instanceof Error?u.message:String(u)}),0}if(!s)return a.warn("[SessionRekey] Session not found, skipping re-key",{sessionId:n}),0;if(!s.isEncrypted)return 0;let i=s.encryptedKeys||[],o=new Set(i.map(u=>u.deviceId)),c=r.forceDeviceIds??new Set,d;try{d=await t.listUserDeviceKeys()}catch(u){return a.warn("[SessionRekey] Failed to fetch user device keys",{sessionId:n,error:u instanceof Error?u.message:String(u)}),0}let p=d.filter(u=>!o.has(u.deviceId)||c.has(u.deviceId));if(p.length===0)return 0;a.info("[SessionRekey] Granting session key to devices",{sessionId:n,existingDeviceCount:i.length,grantCount:p.length,grantDeviceIds:p.map(u=>u.deviceId),forceCount:c.size});let y=0;for(let u of p)try{let v=w.encryptSessionKey(e,u.publicKey);await t.grantSessionKey({sessionId:n,deviceId:u.deviceId,encryptedKey:v.encryptedKey,ephemeralPublicKey:v.ephemeralPublicKey}),y++,a.info("[SessionRekey] Granted session key to device",{sessionId:n,deviceId:u.deviceId,platform:u.platform})}catch(v){a.warn("[SessionRekey] Failed to grant session key to device",{sessionId:n,deviceId:u.deviceId,error:v instanceof Error?v.message:String(v)})}return y>0&&a.info("[SessionRekey] Re-key complete",{sessionId:n,grantedCount:y,requestedCount:p.length}),y}async function oe(n,e,t){try{let r=await e.listUserDeviceKeys();if(r.length===0)return t.info("No device keys found, session will not be encrypted"),null;t.info("Preparing session encryption",{sessionId:n,deviceCount:r.length});let{sessionKey:s,encryptedKeys:i}=g.createSessionKey(r);return t.info("Session encryption prepared",{sessionId:n,deviceCount:i.length}),{sessionKey:s,encryptedKeys:i}}catch(r){return t.warn("Failed to prepare session encryption:",r),null}}async function Te(n,e,t){let{sessionId:r,userId:s,agentType:i,projectPath:o,metadata:c}=n,d=null;try{d=await e.getSession(r)}catch(S){t.warn("Failed to get session (will attempt to create new)",{sessionId:r,error:S})}if(d){t.info("Session exists in backend - reactivating",{sessionId:r,previousStatus:d.status});try{await e.updateSession({sessionId:r,status:"ACTIVE"})}catch(f){t.warn("Failed to reactivate existing session, will continue",{sessionId:r,error:f})}let S=null,V=d.encryptedKeys;if(d.isEncrypted&&V?.length)try{let f=await g.getSessionKey(r,V);f?(S=f,g.cacheSessionKey(r,f),t.info("Session key retrieved for resumed session",{sessionId:r})):t.warn("No encrypted key for this device; proceeding without decryption",{sessionId:r})}catch(f){t.warn("Failed to retrieve session key for resumed session",{sessionId:r,error:f})}if(S)try{let f=await _(r,S,e);f>0&&t.info("Session re-keyed for newly registered devices on resume",{sessionId:r,newDeviceCount:f})}catch(f){t.warn("Session re-key on resume failed (non-fatal)",{sessionId:r,error:f instanceof Error?f.message:String(f)})}return{resumed:!0,sessionKey:S}}let p=await oe(r,e,t),y=o,u=c;p&&(y=w.encryptContent(o,p.sessionKey),u&&Object.keys(u).length>0&&(u={encrypted:w.encryptMetadata(u,p.sessionKey)}),t.info("Session data encrypted",{sessionId:r})),t.info("Creating new session in backend",{sessionId:r,userId:s,agentType:i,isEncrypted:!!p}),await e.createSession({sessionId:r,userId:s,agentType:i,projectPath:y,status:"ACTIVE",metadata:u,isEncrypted:p?!0:void 0,creatorDeviceId:p?await g.getDeviceId():void 0,encryptionVersion:p?1:void 0,encryptedKeys:p?.encryptedKeys});let v=p?.sessionKey||null;return p&&g.cacheSessionKey(r,p.sessionKey),t.info("Session created",{sessionId:r,userId:s,isEncrypted:!!p}),{resumed:!1,sessionKey:v}}C();function Ae(n,e){let t=n.getCurrentUserId(),r=async(i,o)=>{let c=g.getCachedSessionIds();if(c.length===0){e.info("[DeviceKeyWatcher] No active sessions to re-key",{reason:i});return}e.info("[DeviceKeyWatcher] Running re-key pass",{reason:i,activeSessionCount:c.length,forceDeviceCount:o?.size??0});for(let d of c){let p=g.getCachedSessionKey(d);if(p)try{let y=await _(d,p,n,o?{forceDeviceIds:o}:void 0);y>0&&e.info("[DeviceKeyWatcher] Session re-keyed",{sessionId:d,newDeviceCount:y,reason:i})}catch(y){e.warn("[DeviceKeyWatcher] Re-key failed for session (non-fatal)",{sessionId:d,reason:i,error:y instanceof Error?y.message:String(y)})}}},s=n.subscribeToDeviceKeyRegistered(t,i=>{e.info("[DeviceKeyWatcher] New device observed, triggering re-key",{userId:t,newDeviceId:i.deviceId,platform:i.platform,deviceName:i.deviceName}),r(`new-device:${i.deviceId}`,new Set([i.deviceId]))},()=>{r("watcher-reconnect")},i=>{e.warn("[DeviceKeyWatcher] Subscription error (will retry)",{error:i instanceof Error?i.message:String(i)})});return e.info("[DeviceKeyWatcher] Started",{userId:t}),s}C();async function De(n,e){try{let t=await g.getDeviceId(),r=await g.getDevicePublicKey(),s=g.getDevicePlatform(),i=g.getDeviceName();e.info("Registering device encryption key",{deviceId:t,platform:s,deviceName:i}),await n.registerDeviceKey(t,r,s,i),g.setIsRegistered(!0),e.info("Device encryption key registered successfully",{deviceId:t})}catch(t){e.warn("Failed to register device encryption key (E2E encryption may not work):",t)}}0&&(module.exports={AgentType,AppSyncClient,AuthService,CryptoError,CryptoService,DeliveryStatus,ENCRYPTION_VERSION,EventSource,EventType,KeychainError,KeychainManager,Logger,SessionStatus,authService,createLogger,cryptoService,getConfig,getEnvironment,keychainManager,loadConfig,logger,mutations,normalizeSnapshot,parseInteractivePrompt,prepareSessionEncryption,queries,registerDeviceEncryptionKey,rekeySessionForNewDevices,resumeOrCreateSession,runAuthCli,startDeviceKeyWatcher,subscriptions});
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantiya/codevibe-core",
3
- "version": "1.0.10",
3
+ "version": "1.0.13",
4
4
  "description": "Core library for CodeVibe plugins - shared keychain, crypto, AppSync, and auth functionality",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantiya/codevibe-claude-plugin",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "description": "Control Claude Code from your iPhone and Android — real-time sync, approve file edits, send prompts by voice. Part of CodeVibe.",
5
5
  "main": "dist/server.js",
6
6
  "bin": {
@@ -47,7 +47,7 @@
47
47
  "node": ">=18.0.0"
48
48
  },
49
49
  "dependencies": {
50
- "@quantiya/codevibe-core": "^1.0.11",
50
+ "@quantiya/codevibe-core": "^1.0.13",
51
51
  "dotenv": "^16.6.1",
52
52
  "express": "^5.1.0",
53
53
  "graphql": "^16.12.0",