@quantiya/codevibe-codex-plugin 2.0.110 → 2.0.112

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.
Files changed (37) hide show
  1. package/dist/native-launch.js +1 -1
  2. package/dist/server.js +1 -1
  3. package/node_modules/@quantiya/codevibe-core/dist/appsync/sync-mobile-echo.d.ts +12 -12
  4. package/node_modules/@quantiya/codevibe-core/dist/appsync/sync-shell-source.d.ts +14 -14
  5. package/node_modules/@quantiya/codevibe-core/dist/index.d.ts +1 -0
  6. package/node_modules/@quantiya/codevibe-core/dist/index.js +692 -664
  7. package/node_modules/@quantiya/codevibe-core/dist/local-executor/binary-classifier.d.ts +8 -0
  8. package/node_modules/@quantiya/codevibe-core/dist/local-executor/blob-store.d.ts +5 -0
  9. package/node_modules/@quantiya/codevibe-core/dist/local-executor/change-manifest.d.ts +5 -0
  10. package/node_modules/@quantiya/codevibe-core/dist/local-executor/local-executor-impl.d.ts +3 -0
  11. package/node_modules/@quantiya/codevibe-core/dist/local-executor/media-metadata.d.ts +16 -0
  12. package/node_modules/@quantiya/codevibe-core/dist/local-executor/shadow-protocol.d.ts +22 -0
  13. package/node_modules/@quantiya/codevibe-core/dist/local-executor/shadow-slice3-cleanups.d.ts +15 -0
  14. package/node_modules/@quantiya/codevibe-core/dist/local-executor/snapshot-merge.d.ts +4 -0
  15. package/node_modules/@quantiya/codevibe-core/dist/local-executor/task-group-types.d.ts +3 -1
  16. package/node_modules/@quantiya/codevibe-core/dist/local-executor/team-media-approval.d.ts +78 -0
  17. package/node_modules/@quantiya/codevibe-core/dist/local-executor/withheld-media.d.ts +14 -0
  18. package/node_modules/@quantiya/codevibe-core/dist/local-executor/workspace-shadow.d.ts +11 -6
  19. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/advisory-fingerprint/git-availability.d.ts +30 -0
  20. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/advisory-fingerprint/git-classify.d.ts +34 -0
  21. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/advisory-fingerprint/git-runner.d.ts +24 -0
  22. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/advisory-fingerprint/repo-record.d.ts +47 -0
  23. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/advisory-fingerprint/walk.d.ts +34 -0
  24. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/agent-turn-degrade.d.ts +14 -0
  25. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/binary-retry-brief.d.ts +8 -0
  26. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/brainstorm-quorum.d.ts +17 -5
  27. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/cli.js +6352 -3265
  28. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/context-store.d.ts +3 -58
  29. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/engine-projection.d.ts +9 -0
  30. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/media-approval.d.ts +112 -0
  31. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/quorum-loop.d.ts +3 -0
  32. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/review-bundle.d.ts +40 -0
  33. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/review-receipts.d.ts +22 -1
  34. package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/types.d.ts +6 -0
  35. package/node_modules/@quantiya/codevibe-core/dist/tool-activity/types.d.ts +12 -12
  36. package/node_modules/@quantiya/codevibe-core/package.json +1 -1
  37. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- "use strict";var Zt=Object.create;var Ae=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ti=Object.getOwnPropertyNames;var ii=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var ni=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),oi=(i,e)=>{for(var t in e)Ae(i,t,{get:e[t],enumerable:!0})},at=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ti(e))!ri.call(i,n)&&n!==t&&Ae(i,n,{get:()=>e[n],enumerable:!(r=ei(e,n))||r.enumerable});return i};var K=(i,e,t)=>(t=i!=null?Zt(ii(i)):{},at(e||!i||!i.__esModule?Ae(t,"default",{value:i,enumerable:!0}):t,i)),si=i=>at(Ae({},"__esModule",{value:!0}),i);var Ut=ni((Wi,fi)=>{fi.exports={name:"@quantiya/codevibe-codex-plugin",version:"2.0.110",description:"Control OpenAI Codex CLI from your iPhone and Android \u2014 real-time sync, approve file edits, send prompts by voice. Part of CodeVibe.",main:"dist/server.js",codevibe:{companionLauncher:"./libexec/companion-launcher"},files:["dist/**/*.js","libexec","hooks","README.md",".env.example"],scripts:{typecheck:"tsc --noEmit",build:"rm -rf dist && npm run typecheck && esbuild src/server.ts src/native-launch.ts --bundle --platform=node --target=node18 --minify --packages=external --outdir=dist",prepack:"node scripts/prepare-publish.js && npm run build",postpack:"node scripts/restore-dev.js",dev:"ts-node src/server.ts",start:"node dist/server.js",test:"jest --config jest.config.js"},keywords:["codex","codex-cli","openai","plugin","extension","mobile","ios","android","codevibe","companion","remote-control","ai","developer-tools"],author:"Quantiya <support@quantiya.ai>",license:"MIT",bugs:{email:"support@quantiya.ai"},homepage:"https://quantiya.ai/codevibe",engines:{node:">=22.0.0"},dependencies:{"@quantiya/codevibe-core":"^2.0.94","@quantiya/quorum-core":"^1.0.1",chokidar:"^4.0.0",dotenv:"^16.6.1",express:"^5.1.0",graphql:"^16.12.0","shell-quote":"1.9.0",uuid:"^13.0.0",ws:"^8.18.3"},bundledDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"],devDependencies:{"@types/express":"^5.0.5","@types/jest":"^30.0.0","@types/node":"^24.10.1","@types/uuid":"^10.0.0","@types/ws":"^8.18.1",esbuild:"^0.28.0",jest:"^30.3.0","ts-jest":"^29.4.9","ts-node":"^10.9.2",typescript:"^5.9.3"},bundleDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"]}});var wi={};oi(wi,{NATIVE_STARTUP_RESUME_TIMEOUT_MS:()=>qt,NativeLaunchCleanupError:()=>he,NativeObserverShutdownError:()=>Ee,consumeTmuxBootstrap:()=>Ht,findNativeCodex:()=>Ye,launchNativeCompanion:()=>Yt,launchNativeInsideTmux:()=>Ke,missingTmuxSession:()=>Gt,nativeChildEnvironment:()=>Qe,nativeExitReport:()=>zt,nativeExitStatus:()=>Xe,nativeStartupFailureMessage:()=>$e,nativeStartupStep:()=>Ge,nativeTmuxSocket:()=>Xt,stopNativeBackend:()=>Wt,waitExit:()=>U});module.exports=si(wi);var v=require("node:fs"),O=K(require("node:path")),Bt=K(require("node:os")),le=require("node:crypto"),$=require("node:child_process"),jt=require("node:util");var re=K(require("node:path")),be=class extends Error{constructor(t){super(`${t}: run plain codex for unsupported native launch forms.`);this.code=t;this.name="NativeLaunchError"}};function te(){throw new be("NATIVE_ARGUMENT_UNSUPPORTED")}function Be(i){return typeof i=="string"&&i.length>0&&!i.includes("\0")}function ai(i){let e=i.split("-");return e.length===5&&e.every((t,r)=>t.length===[8,4,4,4,12][r]&&[...t].every(n=>"0123456789abcdef".includes(n)))}var di=new Set(["agents","exec","e","review","login","logout","mcp","plugin","app-server","remote-control","app","completion","update","doctor","sandbox","debug","apply","a","queue","archive","delete","migrate-rollouts","migrate-nfs-db","unarchive","fork","cloud","exec-server","features","help"]);function dt(i,e,t){if(!re.isAbsolute(e)||!re.isAbsolute(t)||re.normalize(t)!==t||t.includes(":")||t.includes("\0")||Buffer.byteLength(t)>100)throw new be("NATIVE_LAUNCH_INVALID");let r={workingDirectory:re.resolve(e),cwdOverride:!1,resumeThreadId:null,model:null,policy:{},appServerArgs:[],tuiArgs:[]},n=null,o=!1,s=!1,d=new Set,a=c=>{d.has(c)&&te(),d.add(c)};for(let c=0;c<i.length;c++){let p=i[c];if(Be(p)||te(),!o&&p==="--"){o=!0;continue}if(!o&&p.startsWith("-")){let h=p.indexOf("="),m=h<0?p:p.slice(0,h);if(m==="--no-alt-screen"&&h<0){a("renderer"),r.tuiArgs.push(m);continue}let f=["--model","-m"].includes(m)?"model":["--cd","-C"].includes(m)?"cwd":["--sandbox","-s"].includes(m)?"sandbox":["--ask-for-approval","-a"].includes(m)?"approval":null;f||te(),a(f);let N=h<0?i[++c]:p.slice(h+1);(!Be(N)||N.startsWith("-"))&&te(),f==="model"&&(r.model=N),f==="cwd"&&(r.workingDirectory=re.resolve(e,N),r.cwdOverride=!0),f==="sandbox"&&(["read-only","workspace-write","danger-full-access"].includes(N)||te(),r.policy.sandbox=N),f==="approval"&&(["on-request","never"].includes(N)||te(),r.policy.approvalPolicy=N);continue}if(!o&&p==="resume"&&n===null&&!s){s=!0;let h=i[++c];(!Be(h)||!ai(h))&&te(),r.resumeThreadId=h;continue}!o&&!s&&di.has(p)&&te(),n!==null&&te(),n=p}let l=[];r.model!==null&&l.push("-c","model="+JSON.stringify(r.model)),r.policy.sandbox&&l.push("-c","sandbox_mode="+JSON.stringify(r.policy.sandbox)),r.policy.approvalPolicy&&l.push("-c","approval_policy="+JSON.stringify(r.policy.approvalPolicy)),r.appServerArgs=[...l,"app-server","--listen","unix://"+t];let u=r.tuiArgs;return r.tuiArgs=["--remote","unix://"+t,...u],r.model!==null&&r.tuiArgs.push("--model",r.model),s||(r.policy.sandbox&&r.tuiArgs.push("--sandbox",r.policy.sandbox),r.policy.approvalPolicy&&r.tuiArgs.push("--ask-for-approval",r.policy.approvalPolicy)),s&&r.tuiArgs.push("resume",r.resumeThreadId),n!==null&&r.tuiArgs.push("--",n),r}var fe=K(require("ws")),D=require("node:fs"),H=K(require("node:path")),lt=require("node:crypto");async function ut(i,e){if(!H.isAbsolute(i)||H.normalize(i)!==i||i.includes(":")||i.includes("\0"))throw new w("NATIVE_SOCKET_UNSAFE");let t=await D.promises.lstat(H.dirname(i)),r=await D.promises.lstat(i),n=typeof process.getuid=="function"?process.getuid():void 0;if(!t.isDirectory()||t.isSymbolicLink()||(t.mode&63)!==0||t.dev!==e.dev||t.ino!==e.ino||n!==void 0&&(t.uid!==n||r.uid!==n))throw new w("NATIVE_SOCKET_UNSAFE");let o=i,s;if(r.isSymbolicLink()){let u=await D.promises.readlink(i);o=await D.promises.realpath(i),s={path:i,dev:r.dev,ino:r.ino,target:u,rootDev:t.dev,rootIno:t.ino}}let d=await D.promises.lstat(o),a=await D.promises.lstat(H.dirname(o));if(!d.isSocket()||d.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink()||(a.mode&63)!==0||n!==void 0&&(d.uid!==n||a.uid!==n))throw new w("NATIVE_SOCKET_UNSAFE");let l=await D.promises.lstat(i);if(l.dev!==r.dev||l.ino!==r.ino||s&&(await D.promises.readlink(i)!==s.target||await D.promises.realpath(i)!==o))throw new w("NATIVE_SOCKET_UNSAFE");return{socketPath:o,socketIdentity:{dev:d.dev,ino:d.ino},...s?{alias:s}:{}}}var w=class extends Error{constructor(t,r,n,o){super(t);this.code=t;this.rpcCode=r;this.diagnostic=n;this.handlerFailure=o;this.name="NativeClientError"}};function ct(i,e){let t=i.length<=128&&[...i].every(a=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/_.-".includes(a))?i:"UNKNOWN_NATIVE_METHOD",r=e instanceof Error?e:null,n=["Error","TypeError","RangeError","NativeClientError","NativeRuntimeError","NativeControlError","SyncEventClientError","SyncJournalError","ZodError"],o=e?.code??r?.message,s=typeof o=="string"&&o.length<=96&&(o.startsWith("NATIVE_")||o.startsWith("SYNC_")||["ENOENT","EACCES","EPERM","EIO"].includes(o))&&[...o].every(a=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_".includes(a))?o:null,d=null;for(let a of(r?.stack??"").split(`
1
+ "use strict";var Zt=Object.create;var Ae=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ti=Object.getOwnPropertyNames;var ii=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var ni=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),oi=(i,e)=>{for(var t in e)Ae(i,t,{get:e[t],enumerable:!0})},at=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ti(e))!ri.call(i,n)&&n!==t&&Ae(i,n,{get:()=>e[n],enumerable:!(r=ei(e,n))||r.enumerable});return i};var K=(i,e,t)=>(t=i!=null?Zt(ii(i)):{},at(e||!i||!i.__esModule?Ae(t,"default",{value:i,enumerable:!0}):t,i)),si=i=>at(Ae({},"__esModule",{value:!0}),i);var Ut=ni((Wi,fi)=>{fi.exports={name:"@quantiya/codevibe-codex-plugin",version:"2.0.112",description:"Control OpenAI Codex CLI from your iPhone and Android \u2014 real-time sync, approve file edits, send prompts by voice. Part of CodeVibe.",main:"dist/server.js",codevibe:{companionLauncher:"./libexec/companion-launcher"},files:["dist/**/*.js","libexec","hooks","README.md",".env.example"],scripts:{typecheck:"tsc --noEmit",build:"rm -rf dist && npm run typecheck && esbuild src/server.ts src/native-launch.ts --bundle --platform=node --target=node18 --minify --packages=external --outdir=dist",prepack:"node scripts/prepare-publish.js && npm run build",postpack:"node scripts/restore-dev.js",dev:"ts-node src/server.ts",start:"node dist/server.js",test:"jest --config jest.config.js"},keywords:["codex","codex-cli","openai","plugin","extension","mobile","ios","android","codevibe","companion","remote-control","ai","developer-tools"],author:"Quantiya <support@quantiya.ai>",license:"MIT",bugs:{email:"support@quantiya.ai"},homepage:"https://quantiya.ai/codevibe",engines:{node:">=22.0.0"},dependencies:{"@quantiya/codevibe-core":"^2.0.96","@quantiya/quorum-core":"^1.0.1",chokidar:"^4.0.0",dotenv:"^16.6.1",express:"^5.1.0",graphql:"^16.12.0","shell-quote":"1.9.0",uuid:"^13.0.0",ws:"^8.18.3"},bundledDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"],devDependencies:{"@types/express":"^5.0.5","@types/jest":"^30.0.0","@types/node":"^24.10.1","@types/uuid":"^10.0.0","@types/ws":"^8.18.1",esbuild:"^0.28.0",jest:"^30.3.0","ts-jest":"^29.4.9","ts-node":"^10.9.2",typescript:"^5.9.3"},bundleDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"]}});var wi={};oi(wi,{NATIVE_STARTUP_RESUME_TIMEOUT_MS:()=>qt,NativeLaunchCleanupError:()=>he,NativeObserverShutdownError:()=>Ee,consumeTmuxBootstrap:()=>Ht,findNativeCodex:()=>Ye,launchNativeCompanion:()=>Yt,launchNativeInsideTmux:()=>Ke,missingTmuxSession:()=>Gt,nativeChildEnvironment:()=>Qe,nativeExitReport:()=>zt,nativeExitStatus:()=>Xe,nativeStartupFailureMessage:()=>$e,nativeStartupStep:()=>Ge,nativeTmuxSocket:()=>Xt,stopNativeBackend:()=>Wt,waitExit:()=>U});module.exports=si(wi);var v=require("node:fs"),O=K(require("node:path")),Bt=K(require("node:os")),le=require("node:crypto"),$=require("node:child_process"),jt=require("node:util");var re=K(require("node:path")),be=class extends Error{constructor(t){super(`${t}: run plain codex for unsupported native launch forms.`);this.code=t;this.name="NativeLaunchError"}};function te(){throw new be("NATIVE_ARGUMENT_UNSUPPORTED")}function Be(i){return typeof i=="string"&&i.length>0&&!i.includes("\0")}function ai(i){let e=i.split("-");return e.length===5&&e.every((t,r)=>t.length===[8,4,4,4,12][r]&&[...t].every(n=>"0123456789abcdef".includes(n)))}var di=new Set(["agents","exec","e","review","login","logout","mcp","plugin","app-server","remote-control","app","completion","update","doctor","sandbox","debug","apply","a","queue","archive","delete","migrate-rollouts","migrate-nfs-db","unarchive","fork","cloud","exec-server","features","help"]);function dt(i,e,t){if(!re.isAbsolute(e)||!re.isAbsolute(t)||re.normalize(t)!==t||t.includes(":")||t.includes("\0")||Buffer.byteLength(t)>100)throw new be("NATIVE_LAUNCH_INVALID");let r={workingDirectory:re.resolve(e),cwdOverride:!1,resumeThreadId:null,model:null,policy:{},appServerArgs:[],tuiArgs:[]},n=null,o=!1,s=!1,d=new Set,a=c=>{d.has(c)&&te(),d.add(c)};for(let c=0;c<i.length;c++){let p=i[c];if(Be(p)||te(),!o&&p==="--"){o=!0;continue}if(!o&&p.startsWith("-")){let h=p.indexOf("="),m=h<0?p:p.slice(0,h);if(m==="--no-alt-screen"&&h<0){a("renderer"),r.tuiArgs.push(m);continue}let f=["--model","-m"].includes(m)?"model":["--cd","-C"].includes(m)?"cwd":["--sandbox","-s"].includes(m)?"sandbox":["--ask-for-approval","-a"].includes(m)?"approval":null;f||te(),a(f);let N=h<0?i[++c]:p.slice(h+1);(!Be(N)||N.startsWith("-"))&&te(),f==="model"&&(r.model=N),f==="cwd"&&(r.workingDirectory=re.resolve(e,N),r.cwdOverride=!0),f==="sandbox"&&(["read-only","workspace-write","danger-full-access"].includes(N)||te(),r.policy.sandbox=N),f==="approval"&&(["on-request","never"].includes(N)||te(),r.policy.approvalPolicy=N);continue}if(!o&&p==="resume"&&n===null&&!s){s=!0;let h=i[++c];(!Be(h)||!ai(h))&&te(),r.resumeThreadId=h;continue}!o&&!s&&di.has(p)&&te(),n!==null&&te(),n=p}let l=[];r.model!==null&&l.push("-c","model="+JSON.stringify(r.model)),r.policy.sandbox&&l.push("-c","sandbox_mode="+JSON.stringify(r.policy.sandbox)),r.policy.approvalPolicy&&l.push("-c","approval_policy="+JSON.stringify(r.policy.approvalPolicy)),r.appServerArgs=[...l,"app-server","--listen","unix://"+t];let u=r.tuiArgs;return r.tuiArgs=["--remote","unix://"+t,...u],r.model!==null&&r.tuiArgs.push("--model",r.model),s||(r.policy.sandbox&&r.tuiArgs.push("--sandbox",r.policy.sandbox),r.policy.approvalPolicy&&r.tuiArgs.push("--ask-for-approval",r.policy.approvalPolicy)),s&&r.tuiArgs.push("resume",r.resumeThreadId),n!==null&&r.tuiArgs.push("--",n),r}var fe=K(require("ws")),D=require("node:fs"),H=K(require("node:path")),lt=require("node:crypto");async function ut(i,e){if(!H.isAbsolute(i)||H.normalize(i)!==i||i.includes(":")||i.includes("\0"))throw new w("NATIVE_SOCKET_UNSAFE");let t=await D.promises.lstat(H.dirname(i)),r=await D.promises.lstat(i),n=typeof process.getuid=="function"?process.getuid():void 0;if(!t.isDirectory()||t.isSymbolicLink()||(t.mode&63)!==0||t.dev!==e.dev||t.ino!==e.ino||n!==void 0&&(t.uid!==n||r.uid!==n))throw new w("NATIVE_SOCKET_UNSAFE");let o=i,s;if(r.isSymbolicLink()){let u=await D.promises.readlink(i);o=await D.promises.realpath(i),s={path:i,dev:r.dev,ino:r.ino,target:u,rootDev:t.dev,rootIno:t.ino}}let d=await D.promises.lstat(o),a=await D.promises.lstat(H.dirname(o));if(!d.isSocket()||d.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink()||(a.mode&63)!==0||n!==void 0&&(d.uid!==n||a.uid!==n))throw new w("NATIVE_SOCKET_UNSAFE");let l=await D.promises.lstat(i);if(l.dev!==r.dev||l.ino!==r.ino||s&&(await D.promises.readlink(i)!==s.target||await D.promises.realpath(i)!==o))throw new w("NATIVE_SOCKET_UNSAFE");return{socketPath:o,socketIdentity:{dev:d.dev,ino:d.ino},...s?{alias:s}:{}}}var w=class extends Error{constructor(t,r,n,o){super(t);this.code=t;this.rpcCode=r;this.diagnostic=n;this.handlerFailure=o;this.name="NativeClientError"}};function ct(i,e){let t=i.length<=128&&[...i].every(a=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/_.-".includes(a))?i:"UNKNOWN_NATIVE_METHOD",r=e instanceof Error?e:null,n=["Error","TypeError","RangeError","NativeClientError","NativeRuntimeError","NativeControlError","SyncEventClientError","SyncJournalError","ZodError"],o=e?.code??r?.message,s=typeof o=="string"&&o.length<=96&&(o.startsWith("NATIVE_")||o.startsWith("SYNC_")||["ENOENT","EACCES","EPERM","EIO"].includes(o))&&[...o].every(a=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_".includes(a))?o:null,d=null;for(let a of(r?.stack??"").split(`
2
2
  `).slice(1)){for(let[l,u]of[["server.js","server"],["index.js","core"],["native-launch.js","native-launch"]]){let c="/dist/"+l+":",p=a.lastIndexOf(c);if(p<0)continue;let h=a.slice(p+c.length).split(")")[0].trim().split(":");if(h.length===2&&h.every(m=>m.length>0&&[...m].every(f=>"0123456789".includes(f)))){let[m,f]=h.map(Number);m>0&&m<1e5&&f>0&&f<1e7&&(d={module:u,line:m,column:f})}if(d)break}if(d)break}return new w("NATIVE_HANDLER_FAILED",void 0,void 0,{method:t,errorName:r&&n.includes(r.name)?r.name:"Error",causeCode:s,site:d})}var ne=class{constructor(e){this.options=e;this.socket=null;this.pending=new Map;this.handlers=new Set;this.accepting=!1;this.intentionalClose=!1;this.initialized=!1;this.requestPrefix="codevibe-"+(0,lt.randomUUID)()+"-";this.sequence=0;if(e.maxPayloadBytes!==void 0&&(!Number.isSafeInteger(e.maxPayloadBytes)||e.maxPayloadBytes<1024||e.maxPayloadBytes>8*1024*1024))throw new w("NATIVE_PROTOCOL_INVALID");this.instanceId=e.instanceId,this.endpoint={socketPath:e.socketPath,socketIdentity:{...e.socketIdentity},...e.alias?{alias:{...e.alias}}:{}}}get isConnected(){return this.initialized&&this.accepting&&!this.intentionalClose&&this.socket?.readyState===fe.default.OPEN}async assertSocket(){this.options.assertOwner();let e=this.endpoint.socketPath;if(!H.isAbsolute(e)||H.normalize(e)!==e||e.includes(":")||e.includes("\0"))throw new w("NATIVE_SOCKET_UNSAFE");let t=await D.promises.lstat(H.dirname(e)),r=await D.promises.lstat(e),n=typeof process.getuid=="function"?process.getuid():void 0,o={rootDirectory:t.isDirectory(),rootNotSymlink:!t.isSymbolicLink(),rootPrivate:(t.mode&63)===0,ownerMatches:n===void 0||t.uid===n&&r.uid===n,socketType:r.isSocket(),socketNotSymlink:!r.isSymbolicLink(),socketIdentityMatches:r.dev===this.endpoint.socketIdentity.dev&&r.ino===this.endpoint.socketIdentity.ino};if(Object.values(o).some(d=>!d))throw new w("NATIVE_SOCKET_UNSAFE",void 0,o);let s=this.endpoint.alias;if(s){let d=await D.promises.lstat(H.dirname(s.path)),a=await D.promises.lstat(s.path);if(!d.isDirectory()||d.isSymbolicLink()||(d.mode&63)!==0||d.dev!==s.rootDev||d.ino!==s.rootIno||!a.isSymbolicLink()||a.dev!==s.dev||a.ino!==s.ino||n!==void 0&&(d.uid!==n||a.uid!==n)||await D.promises.readlink(s.path)!==s.target||await D.promises.realpath(s.path)!==e)throw new w("NATIVE_SOCKET_UNSAFE",void 0,{originalAliasMatches:!1})}this.options.assertOwner()}async connect(){try{await this.connectOnce()}catch(e){throw await this.close(),e}}async connectOnce(){if(this.socket||this.intentionalClose)throw new w("NATIVE_DISCONNECTED");await this.assertSocket();let e=new fe.default("ws+unix://"+this.endpoint.socketPath+":/",this.options.maxPayloadBytes===void 0?{}:{maxPayload:this.options.maxPayloadBytes});this.socket=e,this.accepting=!0,e.on("message",t=>this.receive(t.toString())),e.on("error",()=>this.fail(new w("NATIVE_DISCONNECTED"))),e.on("close",()=>{this.initialized=!1,this.accepting=!1,this.rejectPending(),this.intentionalClose||this.report(new w("NATIVE_DISCONNECTED"))}),await new Promise((t,r)=>{let n=setTimeout(()=>{d(new w("NATIVE_RPC_TIMEOUT",void 0,{webSocketOpenTimedOut:!0})),e.terminate()},2e3),o=()=>d(),s=()=>d(new w("NATIVE_DISCONNECTED")),d=a=>{clearTimeout(n),e.off("open",o),e.off("error",s),e.off("close",s),a?r(a):t()};e.once("open",o),e.once("error",s),e.once("close",s)}),await this.assertSocket(),await this.request("initialize",{clientInfo:{name:"codevibe-codex",version:this.options.pluginVersion},capabilities:{experimentalApi:!0,requestAttestation:!1}},2e3),await this.notify("initialized"),this.initialized=!0}report(e){try{Promise.resolve(this.options.onFailure(e)).catch(()=>{})}catch{}}rejectPending(){for(let e of this.pending.values())clearTimeout(e.timer),e.reject(new w("NATIVE_DISCONNECTED"));this.pending.clear()}fail(e){this.accepting=!1,this.initialized=!1,this.rejectPending(),this.intentionalClose||this.report(e),this.socket?.terminate()}receive(e){if(!this.accepting)return;let t;try{let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw Error();t=n}catch{this.fail(new w("NATIVE_PROTOCOL_INVALID"));return}if(typeof t.method=="string"){if(t.id!==void 0&&typeof t.id!="string"&&typeof t.id!="number"){this.fail(new w("NATIVE_PROTOCOL_INVALID"));return}let n;try{this.options.assertOwner()}catch{this.fail(new w("NATIVE_OWNER_CHANGED"));return}try{n=this.options.onMessage(t)}catch(s){this.report(ct(t.method,s));return}let o=Promise.resolve(n).catch(s=>this.report(ct(t.method,s)));this.handlers.add(o),o.then(()=>this.handlers.delete(o));return}if(typeof t.id!="string")return;let r=this.pending.get(t.id);if(r)if(this.pending.delete(t.id),clearTimeout(r.timer),t.error!==void 0){let n=t.error?.code;r.reject(new w("NATIVE_RPC_REJECTED",typeof n=="number"?n:void 0))}else Object.prototype.hasOwnProperty.call(t,"result")?r.resolve(t.result):r.reject(new w("NATIVE_PROTOCOL_INVALID"))}async write(e){this.options.assertOwner();let t=this.socket;if(!t||t.readyState!==fe.default.OPEN||!this.accepting)throw new w("NATIVE_DISCONNECTED");await new Promise((r,n)=>t.send(JSON.stringify(e),o=>o?n(new w("NATIVE_DISCONNECTED")):r())),this.options.assertOwner()}async request(e,t,r=1e4,n){if(!this.initialized&&e!=="initialize")throw new w("NATIVE_DISCONNECTED");if(!Number.isFinite(r)||r<=0||r>3e5)throw new w("NATIVE_PROTOCOL_INVALID");if(n?.aborted)throw new w("NATIVE_REQUEST_CANCELLED");let o=this.requestPrefix+ ++this.sequence,d=new Promise((l,u)=>{let c=()=>{this.pending.delete(o),m.reject(new w("NATIVE_REQUEST_CANCELLED"))},p=()=>{n?.removeEventListener("abort",c),clearTimeout(h)},h=setTimeout(()=>{this.pending.delete(o),u(new w("NATIVE_RPC_TIMEOUT",void 0,{initializeTimedOut:e==="initialize",threadResumeTimedOut:e==="thread/resume",otherRpcTimedOut:e!=="initialize"&&e!=="thread/resume"})),n?.removeEventListener("abort",c)},r),m={resolve:f=>{p(),l(f)},reject:f=>{p(),u(f)},timer:h};this.pending.set(o,m),n?.addEventListener("abort",c,{once:!0}),n?.aborted&&c()}).then(l=>({value:l}),l=>({error:l}));try{n?.aborted||await this.write({id:o,method:e,params:t})}catch(l){let u=this.pending.get(o);throw u&&(clearTimeout(u.timer),this.pending.delete(o),u.reject(new w("NATIVE_DISCONNECTED"))),await d,l}let a=await d;if("error"in a)throw a.error;return a.value}async notify(e,t){await this.write({method:e,...t===void 0?{}:{params:t}})}async respond(e,t){if(!this.initialized)throw new w("NATIVE_DISCONNECTED");await this.write({id:e,result:t})}async close(){this.intentionalClose=!0,this.accepting=!1,this.initialized=!1,this.rejectPending();let e=this.socket;e&&e.readyState!==fe.default.CLOSED&&await new Promise(t=>{let r=setTimeout(()=>{e.terminate(),t()},2e3);e.once("close",()=>{clearTimeout(r),t()}),e.close()}),await this.joinHandlers(),this.socket=null}async joinHandlers(){await Promise.allSettled([...this.handlers])}};var oe=require("node:fs"),W=K(require("node:path")),vt=K(require("node:os")),qe=require("node:util");var ci=256,pt=2*1024*1024;function x(){throw Error("NATIVE_QUESTION_RESUME_NOT_PROVEN")}function me(i){return!i||typeof i!="object"||Array.isArray(i)?x():i}async function ht(i,e,t,r,n){if(!r.length||r.length>64||r.some(d=>d.kind!=="async"||d.threadId!==t))return x();let o=()=>{i.assertCurrent(),n()},s=new ne({...i.record.endpoint,instanceId:i.record.instanceId,pluginVersion:e,maxPayloadBytes:4*1024*1024,assertOwner:o,onMessage:()=>{},onFailure:()=>{}});try{await s.connect();let d=Date.now()+2e3,a=async(S,_)=>{o();let j=d-Date.now();if(j<=0)return x();let A=me(await s.request(S,_,j));return o(),Buffer.byteLength(JSON.stringify(A))>pt?x():A},l=me((await a("thread/read",{threadId:t,includeTurns:!1})).thread);if(l.id!==t||l.sessionId!==t||l.ephemeral!==!1||l.parentThreadId!=null)return x();let u=new Set(r.map(S=>JSON.stringify([S.turnId,S.itemId]))),c=[],p=new Set,h=new Set,m;for(let S=0;S<8&&u.size;S++){let _=await a("thread/items/list",{threadId:t,limit:32,sortDirection:"desc",...m?{cursor:m}:{}});if(!Array.isArray(_.data)||!_.data.length||_.data.length>32)return x();for(let j of _.data){let A=me(j),q=me(A.item);if(typeof A.turnId!="string"||!A.turnId.length||typeof q.id!="string"||!q.id.length)return x();let V=JSON.stringify([A.turnId,q.id]);if(p.has(V))return x();if(p.add(V),c.push({turnId:A.turnId,item:q}),u.delete(V),!u.size)break}if(c.length>ci||Buffer.byteLength(JSON.stringify(c))>pt)return x();if(!u.size)break;if(typeof _.nextCursor!="string"||!_.nextCursor.length||h.has(_.nextCursor))return x();m=_.nextCursor,h.add(m)}if(u.size)return x();let f=new Set(r.map(S=>S.turnId)),N=[],y=new Set;m=void 0,h.clear();for(let S=0;S<8&&f.size;S++){let _=await a("thread/turns/list",{threadId:t,limit:32,sortDirection:"desc",itemsView:"notLoaded",...m?{cursor:m}:{}});if(!Array.isArray(_.data)||!_.data.length||_.data.length>32)return x();for(let j of _.data){let A=me(j);if(typeof A.id!="string"||typeof A.status!="string"||A.itemsView!=="notLoaded"||!Array.isArray(A.items)||A.items.length||y.has(A.id))return x();y.add(A.id),f.delete(A.id)&&N.push({id:A.id,status:A.status})}if(!f.size)break;if(typeof _.nextCursor!="string"||!_.nextCursor.length||h.has(_.nextCursor))return x();m=_.nextCursor,h.add(m)}if(f.size)return x();let g=await a("thread/items/list",{threadId:t,limit:1,sortDirection:"desc"});return!Array.isArray(g.data)||g.data.length!==1||g.data[0].turnId!==c[0].turnId||JSON.stringify(g.data[0].item)!==JSON.stringify(c[0].item)?x():{threadId:t,nativeInstanceId:i.record.instanceId,items:c,turns:N}}finally{await s.close()}}var R=class extends Error{constructor(t){super(t);this.code=t;this.name="NativeRuntimeError"}},ae=()=>{throw new R("NATIVE_LAUNCH_AUTHORITY_INVALID")};function Se(i){return!i||typeof i!="object"||Array.isArray(i)?ae():i}function li(i,e){return Object.keys(i).sort().join(",")===e.sort().join(",")}function ft(i){return typeof i=="number"&&Number.isSafeInteger(i)&&i>0}function mt(i){try{process.kill(i,0)}catch{ae()}}async function Et(i,e){if(!W.isAbsolute(i)||W.normalize(i)!==i||W.basename(i)!=="launch.json")return ae();let t=typeof process.getuid=="function"?process.getuid():void 0,r=await oe.promises.open(i,oe.constants.O_RDONLY|oe.constants.O_NOFOLLOW),n,o;try{let d=await r.stat();if(!d.isFile()||d.nlink!==1||(d.mode&63)!==0||d.size>2*1024*1024||t!==void 0&&d.uid!==t)return ae();let a=Se(JSON.parse(await r.readFile("utf8")));if(!li(a,["version","instanceId","root","launcher","server","endpoint","plan"])||a.version!==1||a.instanceId!==e||typeof e!="string"||!e.length||!ft(a.launcher?.pid)||a.launcher.host!==vt.hostname()||!ft(a.server?.pid)||a.root?.path!==W.dirname(i)||!Number.isSafeInteger(a.root.dev)||!Number.isSafeInteger(a.root.ino)||a.root.uid!==t||!W.isAbsolute(a.endpoint?.socketPath??"")||!Number.isSafeInteger(a.endpoint?.socketIdentity?.dev)||!Number.isSafeInteger(a.endpoint?.socketIdentity?.ino)||!W.isAbsolute(a.plan?.workingDirectory??"")||a.plan.resumeThreadId!==null&&typeof a.plan.resumeThreadId!="string")return ae();let l=await r.stat();if(d.dev!==l.dev||d.ino!==l.ino||d.size!==l.size||d.mtimeMs!==l.mtimeMs)return ae();n=a,o={dev:d.dev,ino:d.ino,size:d.size,mtimeMs:d.mtimeMs}}finally{await r.close()}let s=()=>{let d=(0,oe.lstatSync)(n.root.path),a=(0,oe.lstatSync)(i);if(!d.isDirectory()||d.isSymbolicLink()||(d.mode&63)!==0||d.dev!==n.root.dev||d.ino!==n.root.ino||d.uid!==n.root.uid||!a.isFile()||a.isSymbolicLink()||a.nlink!==1||(a.mode&63)!==0||a.dev!==o.dev||a.ino!==o.ino||a.size!==o.size||a.mtimeMs!==o.mtimeMs||a.uid!==n.root.uid)return ae();mt(n.launcher.pid),mt(n.server.pid)};return s(),{record:JSON.parse(JSON.stringify(n)),assertCurrent:s}}function je(i){let e=Se(i);if(typeof e.id!="string"||!e.id.length)throw new R("NATIVE_ROOT_INVALID_ID");if(e.sessionId!==e.id||e.parentThreadId!=null)throw new R("NATIVE_ROOT_INVALID_SESSION");if(e.ephemeral!==!1)throw new R("NATIVE_ROOT_INVALID_PERSISTENCE");if(typeof e.cwd!="string"||!W.isAbsolute(e.cwd))throw new R("NATIVE_ROOT_INVALID_CWD");if(!Number.isFinite(e.createdAt)||e.createdAt<0)throw new R("NATIVE_ROOT_INVALID_TIMESTAMP");if(e.path!==null&&(typeof e.path!="string"||!W.isAbsolute(e.path)))throw new R("NATIVE_ROOT_INVALID_PATH");if(typeof e.cliVersion!="string")throw new R("NATIVE_ROOT_INVALID_VERSION");if(typeof e.modelProvider!="string")throw new R("NATIVE_ROOT_INVALID_PROVIDER");return{id:e.id,sessionId:e.sessionId,cwd:e.cwd,createdAt:e.createdAt,path:e.path,cliVersion:e.cliVersion,modelProvider:e.modelProvider}}var Ce=class{constructor(e){this.options=e;this.root=null;this.ready=!1;this.generation=0;this.bindingDepth=0;this.binding=Promise.resolve();this.closed=!1;this.refreshPending=null;this.pendingControls=new Map;this.pendingFiles=new Map;this.client=new ne({...e.authority.record.endpoint,instanceId:e.authority.record.instanceId,pluginVersion:e.pluginVersion,assertOwner:e.authority.assertCurrent,onMessage:t=>this.observe(t),onFailure:t=>t.handlerFailure?e.onFailure(t.code,t.handlerFailure):e.onFailure(t.code)})}get thread(){return this.root?{...this.root}:null}controlFacts(){return JSON.parse(JSON.stringify([...this.pendingFiles.values(),...this.pendingControls.values()]))}isCurrentControl(e){let t=e.id===void 0?void 0:this.pendingControls.get(e.id);return!this.closed&&!!t&&t.method===e.method&&(0,qe.isDeepStrictEqual)(t.params,e.params)}hasPendingControl(){return this.pendingControls.size>0}readQuestionResumeWindow(e){let t=this.root?.id;return!t||this.closed?Promise.reject(new R("NATIVE_BINDING_FAILED")):ht(this.options.authority,this.options.pluginVersion,t,e,()=>{if(this.closed||this.root?.id!==t)throw new R("NATIVE_BINDING_FAILED")})}async start(){await this.client.connect();let e=this.options.recoveryThreadId??this.options.authority.record.plan.resumeThreadId;e&&await this.bind(await this.readMetadata(e))}bind(e){let t=this.options.recoveryThreadId??this.options.authority.record.plan.resumeThreadId;if(!this.root&&t&&e.id!==t)return Promise.reject(new R("NATIVE_ROOT_INVALID"));if(this.root&&e.id===this.root.id&&e.cwd!==this.root.cwd)return Promise.reject(new R("NATIVE_ROOT_INVALID"));if(this.root&&(0,qe.isDeepStrictEqual)(this.root,e)&&(this.ready||this.bindingDepth>0))return this.binding;(!this.root||this.root.id!==e.id)&&(this.generation++,this.ready=!1,this.pendingControls.clear(),this.pendingFiles.clear());let r=this.generation;this.root={...e},this.bindingDepth++;let n=this.binding.then(async()=>{if(this.closed)throw new R("NATIVE_BINDING_FAILED");await this.options.onRoot({...e}),r===this.generation&&!this.closed&&(this.ready=!0)});return this.binding=n.catch(()=>{}),n.then(()=>{this.bindingDepth--},()=>{this.bindingDepth--}),n}observe(e){if(this.closed)return;let t=e.params;if(e.method==="thread/started"){let n=t?.thread;return n?.ephemeral===!0||n?.parentThreadId!=null||n?.sessionId!==n?.id?void 0:this.bind(je(n))}if(!this.root||t?.threadId!==this.root.id)return;if(e.id!==void 0&&this.pendingControls.set(e.id,JSON.parse(JSON.stringify(e))),e.method==="serverRequest/resolved"&&this.pendingControls.delete(t.requestId),["item/started","item/completed"].includes(e.method)&&t.item?.type==="fileChange"&&this.pendingFiles.set(t.item.id,JSON.parse(JSON.stringify(e))),e.method==="item/completed"&&["commandExecution","fileChange"].includes(t.item?.type)){for(let[n,o]of this.pendingControls){let s=o.params;s.turnId===t.turnId&&s.itemId===t.item.id&&this.pendingControls.delete(n)}this.pendingFiles.delete(t.item.id)}if(!this.ready&&this.bindingDepth===0&&e.method==="turn/started"&&this.bind(this.root).catch(()=>{}),["item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta"].includes(e.method))return;if(this.ready)return this.options.onMessage(e);let r=this.generation;return this.binding.then(()=>{if(!this.ready||this.closed||r!==this.generation)throw new R("NATIVE_BINDING_FAILED");return this.options.onMessage(e)})}async readMetadata(e){let t=await this.client.request("thread/resume",{threadId:e,excludeTurns:!0},2e3),r=je(Se(t).thread);if(r.id!==e)throw new R("NATIVE_ROOT_INVALID");return r}refreshMetadata(){if(this.refreshPending)return this.refreshPending;if(!this.root||this.closed)return Promise.resolve(null);let e=this.root.id,t=(async()=>{let r=Date.now()+2e3;for(let n=0;n<10&&Date.now()<r;n++)try{let o=await this.client.request("thread/resume",{threadId:e,excludeTurns:!0},Math.max(1,r-Date.now())),s=je(Se(o).thread);if(s.id!==e||this.root?.id!==e||this.closed)throw new R("NATIVE_ROOT_INVALID");return await this.bind(s),s}catch(o){if(!(o instanceof w)||o.code!=="NATIVE_RPC_REJECTED"||![-32600,-32601].includes(o.rpcCode??0))throw o;n<9&&Date.now()<r&&await new Promise(s=>setTimeout(s,Math.min(100,r-Date.now())))}return null})();return this.refreshPending=t,t.then(()=>{this.refreshPending=null},()=>{this.refreshPending=null}),t}async close(){this.closed=!0,await this.client.close(),await this.binding,await this.refreshPending?.catch(()=>{})}};async function Oe(i,e,t){let r;try{let n=(()=>{try{return Promise.resolve(i())}catch(d){return Promise.reject(d)}})(),o=new Promise(d=>{r=setTimeout(()=>d("timeout"),e),r.unref&&r.unref()}),s=await Promise.race([n.then(()=>"settled",()=>"settled"),o]);if(s==="timeout"){n.catch(()=>{});try{t?.()}catch{}}return s}finally{r&&clearTimeout(r)}}var Re=class{constructor(e){this.options=e;this.startWork=null;this.stopped=!1;this.failed=new WeakSet}get isReady(){return!this.stopped&&!!this.reader?.client.isConnected&&!this.failed.has(this.reader)&&!this.options.window.isUnavailable&&this.options.window.readiness.matches(this.options.threadId())}start(e){if(this.startWork)return this.startWork;let t=this.startOnce(e);this.startWork=t;let r=()=>{this.startWork===t&&(this.startWork=null)};return t.then(r,r),t}async closeReader(e){let t=!1;return await Oe(async()=>{await e.close(),t=!0},3e3),t}fail(e){this.reader!==e||this.stopped||this.failed.has(e)||(this.failed.add(e),this.options.window.beginTransport(),this.options.relay.flush(),this.options.unavailable())}async startOnce(e){let t=this.options,r=t.window.beginTransport();t.relay.flush(),await t.assertCurrent();let n=!0,o=()=>!this.stopped&&(!n||!e?.aborted)&&t.current();if(!o())throw Error("NATIVE_RECEIPT_OWNER_ENDED");let s=this.reader;if(s&&!await this.closeReader(s))throw Error("NATIVE_RECEIPT_CLOSE_UNCONFIRMED");this.reader===s&&(this.reader=void 0);let d=await t.authority();if(!o()||d.record.instanceId!==t.window.instanceId)throw Error("NATIVE_RECEIPT_OWNER_ENDED");let a=null,l=null,u=()=>{let p=c.thread?.id,h=r;if(!p||!o()||this.reader!==c||this.failed.has(c))return Promise.resolve();if(l?.generation===h)return l.work;let m=(async()=>{let N=await c.refreshMetadata();if(await t.assertCurrent(),h!==r||this.reader!==c||!o()||!N)return;let y=t.window.readiness.matches(p);if(!o()||this.reader!==c||this.failed.has(c)||!c.client.isConnected||N.id!==p||c.thread?.id!==p||t.threadId()!==p||!t.window.confirmTransport(h,p))throw Error("NATIVE_RECEIPT_SUBSCRIPTION_CHANGED");t.relay.flush(),y||t.available()})();l={generation:h,work:m};let f=()=>{l?.work===m&&(l=null)};return m.then(f,()=>{f(),r===h&&this.fail(c)}),m},c=new Ce({authority:d,pluginVersion:"launcher-receipts",recoveryThreadId:t.threadId()??void 0,onRoot:async p=>{this.reader!==c||!o()||this.failed.has(c)||a!==p.id&&(a!==null&&(r=t.window.beginTransport()),a=p.id,t.bound(p.id),t.relay.flush(),queueMicrotask(()=>{u().catch(()=>{})}))},onMessage:async p=>{if(!(this.reader!==c||!o()||this.failed.has(c))){if(t.window.observe(p),t.relay.flush(),t.window.hasInvalidData){this.fail(c);return}p.method==="thread/status/changed"&&await u()}},onFailure:()=>this.fail(c)});this.reader=c;try{if(await c.start(),!o()||this.failed.has(c)||(c.thread&&await u(),!o()||this.failed.has(c)))throw Error("NATIVE_RECEIPT_OWNER_ENDED");n=!1}catch(p){throw this.fail(c),await this.closeReader(c)&&this.reader===c&&(this.reader=void 0),p}}async close(){if(this.stopped=!0,this.options.window.beginTransport(),await this.startWork?.catch(()=>{}),this.reader&&!await this.closeReader(this.reader))throw Error("NATIVE_RECEIPT_CLOSE_UNCONFIRMED");this.reader=void 0}};var wt=require("node:crypto"),De=require("node:util");var Pe=class{constructor(e){this.instanceId=e;this.proof={instanceId:e,generation:0,threadId:null,ready:!1}}snapshot(){return{...this.proof}}invalidate(){return this.proof={instanceId:this.instanceId,generation:this.proof.generation+1,threadId:null,ready:!1},this.proof.generation}confirm(e,t){return e!==this.proof.generation||e<1||!this.validThread(t)||this.proof.ready&&this.proof.threadId!==t?!1:(this.proof={instanceId:this.instanceId,generation:e,threadId:t,ready:!0},!0)}receive(e){let t=e;return!t||t.instanceId!==this.instanceId||!Number.isSafeInteger(t.generation)||t.generation<0||typeof t.ready!="boolean"||(t.ready?!this.validThread(t.threadId)||t.generation<1:t.threadId!==null)||t.generation<this.proof.generation||t.generation===this.proof.generation&&this.proof.ready&&(!t.ready||t.threadId!==this.proof.threadId)?!1:(this.proof={instanceId:this.instanceId,generation:t.generation,threadId:t.threadId,ready:t.ready},!0)}matches(e){return this.proof.ready&&!!e&&this.proof.threadId===e}validThread(e){return typeof e=="string"&&e.length>0&&e.length<=512}};var Nt=2*1024*1024,xe=i=>JSON.parse(JSON.stringify(i)),yt=i=>(0,wt.createHash)("sha256").update(JSON.stringify(i)).digest("hex");function C(i){if(!i||typeof i!="object"||Array.isArray(i))throw Error("NATIVE_RECEIPT_INVALID");return i}function de(i){return typeof i=="string"&&i.length>0&&i.length<=512}function It(i){return de(i)||typeof i=="number"&&Number.isSafeInteger(i)&&i>=0}function gt(i){return{nativeInstanceId:i.nativeInstanceId,request:i.request,resolved:i.resolved,completed:i.completed,turnCompleted:i.turnCompleted}}function ui(i,e){let t=C(i);if(Buffer.byteLength(JSON.stringify(t))>Nt||Object.keys(t).sort().join(",")!=="completed,digest,nativeInstanceId,request,resolved,turnCompleted"||t.nativeInstanceId!==e||!de(e))throw Error("NATIVE_RECEIPT_INVALID");let r=C(t.request),n=C(t.resolved),o=C(t.turnCompleted),s=C(r.params),d=C(n.params),a=C(o.params),l=C(a.turn),u=r.method==="item/commandExecution/requestApproval"?"commandExecution":r.method==="item/fileChange/requestApproval"?"fileChange":null;if(!u||!It(r.id)||![s.threadId,s.turnId,s.itemId].every(de)||n.method!=="serverRequest/resolved"||d.threadId!==s.threadId||d.requestId!==r.id||o.method!=="turn/completed"||a.threadId!==s.threadId||l.id!==s.turnId||!["completed","failed","interrupted"].includes(l.status))throw Error("NATIVE_RECEIPT_INVALID");if(t.completed===null){if(u!=="fileChange"||l.status!=="interrupted")throw Error("NATIVE_RECEIPT_INVALID")}else{let p=C(t.completed),h=C(p.params),m=C(h.item);if(p.method!=="item/completed"||h.threadId!==s.threadId||h.turnId!==s.turnId||m.id!==s.itemId||m.type!==u||!["completed","failed","declined"].includes(m.status))throw Error("NATIVE_RECEIPT_INVALID")}let c=gt(t);if(t.digest!==yt(c))throw Error("NATIVE_RECEIPT_INVALID");return{...xe(c),digest:t.digest}}var Ve=class{constructor(e){this.instanceId=e;this.rows=new Map;this.unavailable=!1;if(!de(e))throw Error("NATIVE_RECEIPT_INVALID");this.readiness=new Pe(e)}invalidate(){this.unavailable||this.readiness.invalidate(),this.unavailable=!0}get hasInvalidData(){return this.unavailable}get isUnavailable(){return this.unavailable||!this.readiness.snapshot().ready}beginTransport(){return this.readiness.invalidate()}confirmTransport(e,t){return!this.unavailable&&this.readiness.confirm(e,t)}key(e,t){return JSON.stringify([e,t])}observe(e){if(!this.unavailable)try{let t=xe(e),r=C(t.params);if(!de(r.threadId)||!["item/commandExecution/requestApproval","item/fileChange/requestApproval","serverRequest/resolved","turn/completed"].includes(t.method)&&!(t.method==="item/completed"&&["commandExecution","fileChange"].includes(r.item?.type)))return;let n=new Map(xe([...this.rows]));if(t.id!==void 0&&["item/commandExecution/requestApproval","item/fileChange/requestApproval"].includes(t.method)){if(!It(t.id)||!de(r.turnId)||!de(r.itemId))throw Error("NATIVE_RECEIPT_INVALID");let o=this.key(r.threadId,t.id),s=n.get(o);if(s){if(s.request.method!==t.method||!(0,De.isDeepStrictEqual)(s.request.params,t.params))throw Error("NATIVE_RECEIPT_COLLISION");return}n.set(o,{request:t,resolved:null,completed:null,turnCompleted:null})}else for(let o of n.values()){let s=C(o.request.params);if(s.threadId===r.threadId){if(t.method==="serverRequest/resolved"&&r.requestId===o.request.id&&!o.resolved&&(o.resolved=t),t.method==="item/completed"&&r.turnId===s.turnId&&r.item?.id===s.itemId&&r.item.type===(o.request.method==="item/commandExecution/requestApproval"?"commandExecution":"fileChange")){let d=xe(t);if(delete C(C(d.params).item).aggregatedOutput,o.completed&&!(0,De.isDeepStrictEqual)(C(o.completed.params).item,C(d.params).item))throw Error("NATIVE_RECEIPT_COLLISION");o.completed??=d}if(t.method==="turn/completed"&&r.turn?.id===s.turnId){let d={method:t.method,params:{threadId:r.threadId,turn:{id:r.turn.id,status:r.turn.status}}};if(o.turnCompleted&&!(0,De.isDeepStrictEqual)(o.turnCompleted,d))throw Error("NATIVE_RECEIPT_COLLISION");o.turnCompleted??=d}}}if(Buffer.byteLength(JSON.stringify([...n]))>Nt)throw Error("NATIVE_RECEIPT_WINDOW_FULL");this.rows=n}catch{this.invalidate()}}receipts(){if(this.unavailable)throw Error("NATIVE_RECEIPTS_UNAVAILABLE");return[...this.rows.values()].flatMap(e=>{if(!e.resolved||!e.turnCompleted)return[];if(!e.completed&&!(e.request.method==="item/fileChange/requestApproval"&&C(C(e.turnCompleted.params).turn).status==="interrupted"))return[];let t=gt({nativeInstanceId:this.instanceId,request:e.request,resolved:e.resolved,completed:e.completed,turnCompleted:e.turnCompleted});return[ui({...t,digest:yt(t)},this.instanceId)]})}acknowledge(e){let t=this.receipts().find(r=>r.digest===e);if(!t)throw Error("NATIVE_RECEIPT_ACK_INVALID");this.rows.delete(this.key(C(t.request.params).threadId,t.request.id))}},ke=class{constructor(e){this.window=e;this.current=null;this.sent=new Set;this.warned=!1;this.readinessSent="";this.ready=!1}attach(e){this.current=e,this.sent.clear(),this.warned=!1,this.readinessSent="",this.ready=!1}close(){this.current=null,this.sent.clear(),this.ready=!1}handle(e,t){let r=t;if(!r||!["CODEVIBE_NATIVE_RECEIPTS_POLL","CODEVIBE_NATIVE_RECEIPT_ACK"].includes(String(r.type)))return!1;if(e!==this.current||r.instanceId!==this.window.instanceId||e.connected!==!0)return!0;if(r.type==="CODEVIBE_NATIVE_RECEIPTS_POLL")this.ready=!0,this.flush();else if(typeof r.digest=="string"&&this.sent.has(r.digest)&&typeof r.consumed=="boolean"){if(r.consumed)try{this.window.acknowledge(r.digest)}catch{this.window.invalidate()}this.sent.delete(r.digest)}return!0}flush(){let e=this.current;if(!(!this.ready||!e||e.connected!==!0)){if(this.window.isUnavailable){let t=this.window.readiness.snapshot(),r=JSON.stringify(t);(this.readinessSent!==r||!this.warned)&&(this.warned=!0,this.readinessSent=r,this.send(e,{type:"CODEVIBE_NATIVE_RECEIPTS_UNAVAILABLE",instanceId:this.window.instanceId,readiness:{...t,ready:!1,threadId:null}}));return}try{this.warned=!1;for(let n of this.window.receipts())this.sent.has(n.digest)||(this.sent.add(n.digest),this.send(e,{type:"CODEVIBE_NATIVE_RECEIPT",instanceId:this.window.instanceId,receipt:n}));let t=this.window.readiness.snapshot(),r=JSON.stringify(t);this.readinessSent!==r&&!this.window.isUnavailable&&(this.readinessSent=r,this.send(e,{type:"CODEVIBE_NATIVE_RECEIPTS_READY",instanceId:this.window.instanceId,readiness:t}))}catch{this.window.invalidate(),this.flush()}}}send(e,t){try{e.send(t,r=>{r&&this.current===e&&this.window.invalidate()})}catch{this.current===e&&this.window.invalidate()}}};var Tt=require("node:timers/promises"),Le=class{constructor(e){this.options=e;this.phase="idle";this.operation=null;this.controller=null;this.followUp=!1}get isExhausted(){return this.phase==="exhausted"}request(){if(this.operation)return this.phase==="idle"&&(this.followUp=!0),this.operation;if(this.phase!=="idle")return Promise.resolve();this.phase="running";let e=new AbortController;this.controller=e;let t=()=>{try{return!e.signal.aborted&&this.options.current()}catch{return!1}},r=!1,n,o=new Promise(u=>{n=u}),s=()=>n();e.signal.addEventListener("abort",s,{once:!0});let d=setTimeout(()=>{r=!0,e.abort()},this.options.timeoutMs??6e4);d.unref();let a=(async()=>{for(let u of(this.options.delays??[1e3,5e3,15e3]).slice(0,3))try{if(await(this.options.wait?.(u,e.signal)??(0,Tt.setTimeout)(u,void 0,{signal:e.signal,ref:!1})),!t())return;if(await this.options.recover(e.signal)&&this.options.isRecovered?.()!==!1){t()&&(this.phase="idle");return}}catch{if(!t())return}if(t()){this.phase="exhausted";try{await this.options.exhausted()}catch{}}})(),l=Promise.race([a,o]).then(async()=>{if(r&&this.phase==="running"){this.phase="exhausted";try{this.options.current()&&await this.options.exhausted()}catch{}}}).finally(()=>{clearTimeout(d),e.signal.removeEventListener("abort",s),this.phase==="running"&&(this.phase="exhausted"),this.controller===e&&(this.controller=null),this.operation===l&&(this.operation=null),this.followUp&&this.phase==="idle"&&(this.followUp=!1,this.request().catch(()=>{}))});return this.operation=l,l}readinessChanged(){this.phase==="exhausted"&&(this.phase="idle")}stop(){this.phase="stopped",this.followUp=!1,this.controller?.abort()}};var pe=require("node:fs"),ve=K(require("node:path")),_t=require("node:child_process"),At=require("node:util"),bt=require("node:crypto"),F=class extends Error{constructor(t,r=[]){super(t==="NATIVE_UPDATE_REQUIRED"?"This Codex installation lacks native capabilities required by CodeVibe. Update Codex, then retry codevibe --agent codex.":"CodeVibe could not inspect this Codex installation. Check that Codex runs normally, then retry.");this.code=t;this.missing=r;this.name="NativeCapabilityError"}};function Je(i){return new Set((i.oneOf??[]).flatMap(e=>e.properties?.method?.enum??[]))}function He(i,e,t,r=0){return!i||r>8?!1:i.$ref?.startsWith("#/definitions/")?He(t?.[i.$ref.slice(14)],e,t,r+1):i.type===e||Array.isArray(i.type)&&i.type.includes(e)||e==="string"&&i.enum?.length&&i.enum.every(n=>typeof n=="string")?!0:[...i.anyOf??[],...i.oneOf??[]].some(n=>He(n,e,t,r+1))}function pi(i){let e=[],t=Je(i.client),r=Je(i.requests),n=Je(i.notifications);for(let o of["initialize","thread/start","thread/resume","thread/read","thread/loaded/list","thread/items/list","thread/turns/list","turn/start"])t.has(o)||e.push(o);for(let o of["item/commandExecution/requestApproval","item/fileChange/requestApproval"])r.has(o)||e.push(o);for(let o of["thread/started","thread/status/changed","turn/started","turn/completed","item/started","item/completed","serverRequest/resolved"])n.has(o)||e.push(o);for(let[o,s,d]of[[i.client,"ThreadResumeParams",[["threadId","string"],["excludeTurns","boolean"]]],[i.client,"ThreadItemsListParams",[["threadId","string"],["limit","integer"],["sortDirection","string"]]],[i.client,"ThreadTurnsListParams",[["threadId","string"],["limit","integer"],["sortDirection","string"],["itemsView","string"]]],[i.client,"TurnStartParams",[["threadId","string"],["clientUserMessageId","string"],["input","array"],["toolOutput","object"]]],[i.client,"TurnToolOutput",[["namespace","string"],["name","string"],["output","string"],["retain","boolean"]]],[i.requests,"CommandExecutionRequestApprovalParams",[["threadId","string"],["turnId","string"],["itemId","string"],["availableDecisions","array"]]]]){let a=o.definitions?.[s]?.properties;for(let[l,u]of d)He(a?.[l],u,o.definitions)||e.push(`${s}.${l}`)}return e}async function St(i,e,t,r){let n=(0,At.promisify)(_t.execFile);await pe.promises.mkdir(e,{mode:448});try{let c=n(i,["--remote","unix://"+ve.join(ve.dirname(e),"native.sock"),"--help"],{env:t,timeout:1e4,maxBuffer:262144});r?.(c.child),await c}catch(c){throw c?.code===2&&!c.killed&&!c.signal?new F("NATIVE_UPDATE_REQUIRED",["remote terminal attachment"]):new F("NATIVE_CAPABILITY_PROBE_FAILED")}try{let c=n(i,["app-server","generate-json-schema","--experimental","--out",e],{env:t,timeout:15e3,maxBuffer:262144});r?.(c.child),await c}catch(c){throw c?.code===2&&!c.killed&&!c.signal?new F("NATIVE_UPDATE_REQUIRED",["native protocol introspection"]):new F("NATIVE_CAPABILITY_PROBE_FAILED")}let o=(0,bt.createHash)("sha256"),s=[];for(let c of["ClientRequest.json","ServerRequest.json","ServerNotification.json"]){let p=await pe.promises.open(ve.join(e,c),pe.constants.O_RDONLY|pe.constants.O_NOFOLLOW);try{let h=await p.stat();if(!h.isFile()||h.size>8*1024*1024)throw new F("NATIVE_CAPABILITY_PROBE_FAILED");let m=await p.readFile();o.update(c).update(m),s.push(JSON.parse(m.toString()))}finally{await p.close()}}let[d,a,l]=s,u=pi({client:d,requests:a,notifications:l});if(u.length)throw new F("NATIVE_UPDATE_REQUIRED",u);return{schemaSha256:o.digest("hex")}}var J=require("node:fs"),ce=K(require("node:path")),T=i=>!i.pid||i.exitCode!==null||i.signalCode!==null;async function U(i,e){return T(i)?!0:new Promise(t=>{let r=setTimeout(()=>o(T(i)),e);r.unref();let n=()=>o(!0),o=s=>{clearTimeout(r),i.off("close",n),t(s)};i.once("close",n)})}var M=()=>{throw Error("NATIVE_STARTUP_SHUTDOWN_UNSAFE")},Ct=(i,e)=>i.isFile()&&i.nlink===1&&i.uid===e&&(i.mode&63)===0;async function ze(i,e){let t=await J.promises.open(i,J.constants.O_RDONLY|J.constants.O_NOFOLLOW);try{let r=await t.stat();if(!Ct(r,e)||r.size>4096)return M();let n=await t.readFile("utf8"),o=await t.stat(),s=await J.promises.lstat(i);return!Ct(s,e)||s.isSymbolicLink()||s.dev!==r.dev||s.ino!==r.ino||s.size!==r.size||s.mtimeMs!==r.mtimeMs||o.size!==r.size||o.mtimeMs!==r.mtimeMs?M():{bytes:n,pin:{dev:r.dev,ino:r.ino,size:r.size,mtimeMs:r.mtimeMs,uid:r.uid}}}finally{await t.close()}}async function Ot(i){try{return await J.promises.lstat(i)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Rt(i,e,t,r){let n={...i},o=JSON.parse(JSON.stringify(t)),s=e.pid;if(!s||s===process.pid||n.pid!==process.pid||n.uid!==process.getuid?.())return M();let d=await ze(n.root+"/OWNER.json",n.uid),a=await ze(n.root+"/backend-owner.json",n.uid),l={root:n.root,dev:n.dev,ino:n.ino,uid:n.uid,instanceId:n.instanceId,pid:n.pid};if(d.bytes!==JSON.stringify(l)||a.bytes!==JSON.stringify({instanceId:n.instanceId,launcherPid:n.pid,backendPid:s}))return M();let u=ce.dirname(o.socketPath),c=await J.promises.lstat(u);if(!ce.isAbsolute(o.socketPath)||ce.normalize(o.socketPath)!==o.socketPath||!c.isDirectory()||c.isSymbolicLink()||c.uid!==n.uid||(c.mode&63)!==0)return M();async function p(){let f=await J.promises.lstat(n.root);if(!f.isDirectory()||f.isSymbolicLink()||(f.mode&63)!==0||f.dev!==n.dev||f.ino!==n.ino||f.uid!==n.uid||e.pid!==s)return M();for(let[N,y]of[[n.root+"/OWNER.json",d],[n.root+"/backend-owner.json",a]]){let g=await ze(N,n.uid);if(g.bytes!==y.bytes||Object.keys(y.pin).some(S=>g.pin[S]!==y.pin[S]))return M()}}async function h(){let f=await Ot(o.socketPath),N=[];if(f){let g=await J.promises.lstat(u);if(!g.isDirectory()||g.isSymbolicLink()||g.uid!==n.uid||(g.mode&63)!==0||g.dev!==c.dev||g.ino!==c.ino||!f.isSocket()||f.isSymbolicLink()||f.uid!==n.uid||f.dev!==o.socketIdentity.dev||f.ino!==o.socketIdentity.ino)return M();N.push(o.socketPath)}let y=o.alias;if(y){if(ce.dirname(y.path)!==n.root||y.rootDev!==n.dev||y.rootIno!==n.ino)return M();let g=await Ot(y.path);if(g){if(!g.isSymbolicLink()||g.uid!==n.uid||g.dev!==y.dev||g.ino!==y.ino||await J.promises.readlink(y.path)!==y.target)return M();N.push(y.path)}}return N}await p(),await h();async function m(){if(!T(e)||!r())return M();await p();let f=await h();for(let N of f)await p(),(await h()).includes(N)&&await J.promises.unlink(N);if(await p(),(await h()).length)return M()}return{cleanupExited:m,forceStop:async()=>{if(T(e))return r()&&await m(),{ended:!0,forced:!1};if(!r())return{ended:!1,forced:!1};if(await p(),await h(),T(e))return r()&&await m(),{ended:!0,forced:!1};if(!r())return{ended:!1,forced:!1};let f=e.kill("SIGKILL");return await U(e,1e4)?(await m(),{ended:!0,forced:f}):{ended:!1,forced:f}}}}var B=require("node:fs"),k=K(require("node:path")),xt=require("node:module"),ie=class extends Error{};async function Pt(i){try{await B.promises.access(i,B.constants.X_OK);let e=await B.promises.open(i,"r");try{if(!(await e.stat()).isFile())return!1;let t=Buffer.alloc(4);return(await e.read(t,0,4,0)).bytesRead===4&&["7f454c46","cffaedfe","cefaedfe","feedface","feedfacf","cafebabe","bebafeca","cafebabf","bfbafeca"].includes(t.toString("hex"))}finally{await e.close()}}catch{return!1}}var Dt=(i,e)=>{let t=k.relative(i,e);return t!==""&&!t.startsWith(".."+k.sep)&&t!==".."&&!k.isAbsolute(t)};async function Vt(i){if(await Pt(i))return{file:i,direct:!0};try{let e=k.resolve(k.dirname(i),"..","package.json"),t=await B.promises.realpath(k.dirname(e)),r=JSON.parse(await B.promises.readFile(e,"utf8")),n=typeof r.bin=="string"?r.bin:r.bin?.codex;if(r.name!=="@openai/codex"||typeof n!="string"||await B.promises.realpath(k.resolve(t,n))!==i)throw new ie;let o=process.platform==="android"?"linux":process.platform,s="@openai/codex-"+o+"-"+process.arch,d=t;try{let p=(0,xt.createRequire)(e).resolve(s+"/package.json"),h=JSON.parse(await B.promises.readFile(p,"utf8"));if(Array.isArray(h.os)&&!h.os.includes(o)||Array.isArray(h.cpu)&&!h.cpu.includes(process.arch))throw new ie;d=await B.promises.realpath(k.dirname(p))}catch(p){if(p instanceof ie||p.code!=="MODULE_NOT_FOUND")throw p}let a=await B.promises.realpath(d+"/vendor");if(!Dt(d,a))throw new ie;let l=(await B.promises.readdir(a,{withFileTypes:!0})).filter(p=>p.isDirectory());if(l.length>16)throw new ie;let u=[],c={"linux:x64":"x86_64-unknown-linux-musl","linux:arm64":"aarch64-unknown-linux-musl","darwin:x64":"x86_64-apple-darwin","darwin:arm64":"aarch64-apple-darwin"}[o+":"+process.arch];for(let p of l){if(d===t&&p.name!==c)continue;let h=k.join(a,p.name,"bin","codex");if(await Pt(h)){let m=await B.promises.realpath(h);if(!Dt(a,m))throw new ie;u.push(m)}}if(u.length!==1)throw new ie;return{file:u[0],direct:!0}}catch{return{file:i,direct:!1}}}var hi={gracefulMs:29e3,terminateMs:29e3,killMs:1e4};function kt(i){return!i||i.signalCode===null&&i.exitCode===0?0:1}function Lt(i){let e=()=>{},t=()=>{T(i)||i.kill("SIGTERM")};return process.on("SIGINT",e),process.on("SIGTERM",t),process.on("SIGHUP",t),()=>{process.off("SIGINT",e),process.off("SIGTERM",t),process.off("SIGHUP",t)}}function Mt(i,e,t,r,n,o=hi){let s=i.pid;if(s===void 0){let p=Promise.resolve({ended:!0,phase:"already-ended"});return()=>p}if(!s||!Number.isSafeInteger(s)||s<=0)throw Error("NATIVE_OBSERVER_SHUTDOWN_UNSAFE");let d,a=(p,h={})=>{try{n(p,{pid:s,...h})}catch{}},l=()=>{if(i.pid!==s||!r())throw Error("NATIVE_OBSERVER_SHUTDOWN_UNSAFE")},u=async()=>{l(),await t(),l()},c=async()=>{if(T(i))return{ended:!0,phase:"already-ended"};if(await u(),T(i))return{ended:!0,phase:"already-ended"};if(i.connected&&i.send({type:"CODEVIBE_NATIVE_TERMINAL_END",instanceId:e},()=>{}),a("OBSERVER_STOP_GRACE"),await U(i,o.gracefulMs))return{ended:!0,phase:"graceful"};if(await u(),T(i))return{ended:!0,phase:"graceful"};if(a("OBSERVER_SIGTERM_INTENT"),i.kill("SIGTERM"),await U(i,o.terminateMs))return{ended:!0,phase:"sigterm"};if(await u(),T(i))return{ended:!0,phase:"sigterm"};a("OBSERVER_SIGKILL_INTENT");let p=i.kill("SIGKILL"),h=await U(i,o.killMs);return a("OBSERVER_SIGKILL_RESULT",{sent:p,ended:h}),{ended:h,phase:"sigkill"}};return()=>d??=c()}var mi=i=>new Promise(e=>setTimeout(e,i)),qt=12e4;async function Ge(i,e,t=r=>console.error("CodeVibe: native startup failed",r)){let r=Date.now();try{return await e()}catch(n){try{t({stage:i,elapsedMs:Date.now()-r,code:n instanceof w?n.code:"NATIVE_STARTUP_FAILED",...n instanceof w&&n.diagnostic?{diagnostic:n.diagnostic}:{}})}catch{}throw n}}async function Wt(i){return T(i)||(i.stdin?.end(),await U(i,2e3))||(i.kill("SIGINT"),await U(i,5e3))||T(i)?!0:(i.kill("SIGINT"),U(i,5e3))}async function Jt(i,e,t){for(let r of(e.PATH??"").split(O.delimiter).filter(Boolean)){let n=O.resolve(t,r,i);try{await v.promises.access(n,v.constants.X_OK);let o=await v.promises.realpath(n);if((await v.promises.stat(o)).isFile())return o}catch{}}throw Error(i==="codex"?"Codex executable not found;install Codex,then retry.":"tmux executable not found;install tmux,then retry.")}var Ye=(i,e)=>Jt("codex",i,e);async function Me(i){let e=(0,le.createHash)("sha256");for await(let t of(0,v.createReadStream)(i))e.update(t);return e.digest("hex")}function Qe(i){let e={...i};return delete e.CODEVIBE_CODEX_TMUX_SESSION,delete e.CODEVIBE_CODEX_PRIMARY_COMPANION,delete e.QUORUM_REVIEWER_SUBPROCESS,e}async function Ke(i,e=process.env){let t=e.TMUX?.split(",")[0];if(!t||!O.isAbsolute(t)||!process.stdin.isTTY||!process.stdout.isTTY)throw Error("Native Companion requires its terminal launcher.");let r=await v.promises.mkdtemp(O.join(await v.promises.realpath("/tmp"),"cvcd-")),n=await v.promises.lstat(r),o=(0,le.randomUUID)(),s={root:r,dev:n.dev,ino:n.ino,uid:n.uid,instanceId:o,pid:process.pid};await v.promises.writeFile(r+"/OWNER.json",JSON.stringify(s),{flag:"wx",mode:384});let d=await v.promises.open(r+"/lifecycle.jsonl","wx",384),a=(E,L={})=>d.appendFile(JSON.stringify({utc:new Date().toISOString(),kind:E,...L})+`
3
3
  `);await a("RESOURCE",s);let l,u,c,p,h,m,f=new Ve(o),N=new ke(f),y=null,g=!1,S=0,_=!1,j=null,A=!1,q=!1,V=!1,we=!1,Ne=!1,ye,Ze,z=[],Ie=new Map,ge=async()=>{let E=await v.promises.lstat(r);if(!E.isDirectory()||E.isSymbolicLink()||E.dev!==n.dev||E.ino!==n.ino||E.uid!==n.uid||JSON.parse(await v.promises.readFile(r+"/OWNER.json","utf8")).instanceId!==o)throw Error("NATIVE_LAUNCH_ROOT_CHANGED")};try{let E=await Ye(e,process.cwd()),L=Qe(e),G=await Vt(E);Ne=G.direct;let Z=(0,$.spawn)(E,["--version"],{env:L,stdio:["ignore","pipe","pipe"]});z.push(Z),Z.on("error",()=>{}),await a("VERSION_PROCESS",{pid:Z.pid,executable:E});let se="",ee="";if(Z.stdout.on("data",I=>{se=(se+I.toString()).slice(0,1025)}),Z.stderr.on("data",I=>{ee=(ee+I.toString()).slice(0,65537)}),!await U(Z,1e4)||Z.exitCode!==0||se.length>1024||ee.length>64*1024)throw Error("NATIVE_VERSION_UNAVAILABLE");let Qt=await St(G.file,r+"/protocol",L,I=>{z.push(I),a("CAPABILITY_PROCESS",{pid:I.pid}).catch(()=>{})});await a("CAPABILITIES",Qt);let b=dt(i,process.cwd(),r+"/native.sock");b.workingDirectory=await v.promises.realpath(b.workingDirectory),y=b.resumeThreadId;let Fe=await Me(E),et=G.file===E?Fe:await Me(G.file);await a("PLAN",{nativeVersion:se.trim(),cli:E,cliSha256:Fe,backendExecutable:G.file,backendSha256:et,directBackend:Ne,argvSha256:(0,le.createHash)("sha256").update(JSON.stringify(i)).digest("hex")}),await v.promises.mkdir(r+"/tmp",{mode:448});let tt={...L,TMPDIR:r+"/tmp"},it=(0,v.openSync)(r+"/native.log","wx",384);l=(0,$.spawn)(G.file,b.appServerArgs,{cwd:b.workingDirectory,env:tt,detached:!0,stdio:["pipe","ignore",it]}),l.on("error",()=>{}),(0,v.closeSync)(it),z.push(l),await a("NATIVE_SERVER",{pid:l.pid}),l.pid&&await v.promises.writeFile(r+"/backend-owner.json",JSON.stringify({instanceId:o,launcherPid:process.pid,backendPid:l.pid}),{flag:"wx",mode:384});let Kt=Date.now()+2e3,rt=!1;for(;Date.now()<Kt&&!T(l);){try{await v.promises.lstat(r+"/native.sock"),rt=!0;break}catch(I){if(I.code!=="ENOENT")throw I}await mi(20)}if(!rt||!l.pid)throw Error("NATIVE_LISTENER_UNAVAILABLE");let Te=await ut(r+"/native.sock",n);if(j=Te.socketPath,b.resumeThreadId&&Ne)try{ye=await Rt(s,l,Te,()=>A&&!u)}catch(I){throw q=!0,I}p=new ne({...Te,instanceId:o,pluginVersion:"launcher",assertOwner:()=>{if(!l||T(l))throw Error("NATIVE_OWNER_ENDED")},onMessage:()=>{},onFailure:()=>{}}),await Ge("connect",()=>p.connect());try{let I=await p.request("thread/loaded/list",{},5e3);if(!Array.isArray(I?.data)||I.data.some(X=>typeof X!="string"||!X.length))throw new w("NATIVE_PROTOCOL_INVALID")}catch(I){throw I instanceof w&&I.code==="NATIVE_RPC_REJECTED"&&I.rpcCode===-32601?new F("NATIVE_UPDATE_REQUIRED",["thread/loaded/list"]):I}if(b.resumeThreadId){let I=new AbortController,X=Date.now(),P=()=>I.abort(),_e=setInterval(()=>console.error(`CodeVibe: loading Codex session (${Math.floor((Date.now()-X)/1e3)}s); Ctrl+C cancels startup.`),5e3);process.on("SIGINT",P);let ue;try{ue=await Ge("resume",()=>p.request("thread/resume",{threadId:b.resumeThreadId,excludeTurns:!0,...b.policy,...b.model!==null?{model:b.model}:{},...b.cwdOverride?{cwd:b.workingDirectory}:{}},qt,I.signal))}catch(Y){throw A=Y instanceof w&&(Y.code==="NATIVE_REQUEST_CANCELLED"||Y.code==="NATIVE_RPC_TIMEOUT"),Y}finally{clearInterval(_e),process.off("SIGINT",P)}if(ue?.thread?.id!==b.resumeThreadId||b.policy.approvalPolicy&&ue.approvalPolicy!==b.policy.approvalPolicy||b.policy.sandbox&&ue.sandbox?.type!=={"read-only":"readOnly","workspace-write":"workspaceWrite","danger-full-access":"dangerFullAccess"}[b.policy.sandbox])throw Error("NATIVE_RESUME_POLICY_MISMATCH")}await p.close(),p=void 0;let $t={version:1,instanceId:o,root:{path:r,dev:n.dev,ino:n.ino,uid:n.uid},launcher:{pid:process.pid,host:Bt.hostname()},server:{pid:l.pid},endpoint:Te,plan:b};await v.promises.writeFile(r+"/launch.json",JSON.stringify($t),{flag:"wx",mode:384}),h=new Re({authority:()=>Et(r+"/launch.json",o),assertCurrent:ge,current:()=>!g&&!!l&&!T(l),threadId:()=>y,bound:I=>{y=I},window:f,relay:N,unavailable:()=>{m?.request().catch(()=>{})},available:()=>{m?.readinessChanged()}}),m=new Le({current:()=>!g&&!!l&&!T(l),recover:async I=>f.hasInvalidData?!1:(await h.start(I),h.isReady),isRecovered:()=>h.isReady,exhausted:async()=>{console.error("CodeVibe: native receipt recovery unavailable;desktop Codex remains independent.")}});try{await h.start()}catch{f.beginTransport(),N.flush(),console.error("CodeVibe: native receipt recovery unavailable;desktop Codex remains independent."),m.request().catch(()=>{})}let nt=I=>{let X=(0,v.openSync)(r+"/observer.log","a",384),P=(0,$.fork)(O.join(__dirname,"server.js"),[],{cwd:b.workingDirectory,detached:!0,stdio:["ignore",X,X,"ipc"],env:{...L,TMPDIR:r+"/tmp",CODEX_WORKING_DIRECTORY:b.workingDirectory,CODEVIBE_CODEX_TMUX_SESSION:"native-"+o,CODEVIBE_CODEX_NATIVE_DESCRIPTOR:r+"/launch.json",CODEVIBE_CODEX_NATIVE_INSTANCE:o,CODEVIBE_CODEX_DAEMON_RECOVERY:I?"1":"0",CODEVIBE_CODEX_NATIVE_THREAD:I?y??"":""}});P.on("error",()=>{}),(0,v.closeSync)(X),z.push(P),a("OBSERVER",{pid:P.pid,recovery:I}).catch(()=>{}),Ie.set(P,Mt(P,o,ge,()=>g&&(!u||T(u)),(Y,Q)=>{a(Y,Q).catch(()=>{})})),N.attach(P);let _e,ue=new Promise(Y=>{_e=Y});return P.on("message",Y=>{let Q=Y;Q?.instanceId===o&&(N.handle(P,Q)||P!==c||g||(Q.type==="CODEVIBE_NATIVE_READY"&&(_e(),N.handle(P,{type:"CODEVIBE_NATIVE_RECEIPTS_POLL",instanceId:o})),Q.type==="CODEVIBE_NATIVE_BOUND"&&typeof Q.threadId=="string"&&(y=Q.threadId),Q.type==="CODEVIBE_NATIVE_CONNECTION_FAILED"&&!T(P)&&P.kill("SIGTERM"),Q.type==="CODEVIBE_NATIVE_MOBILE_END"&&u&&!T(u)&&u.kill("SIGTERM")))}),P.on("exit",()=>{if(!g&&u&&!T(u))if(y&&S++===0)try{c=nt(!0).child}catch{console.error("CodeVibe: mobile observer restart failed;desktop remains available.")}else console.error("CodeVibe: mobile sync unavailable;desktop Codex remains available.")}),{child:P,initialized:ue}},ot=nt(!1);if(c=ot.child,await Promise.race([ot.initialized,U(c,1e4)]),T(c)&&console.error("CodeVibe: mobile sync unavailable;desktop Codex remains available."),await ge(),await Me(E)!==Fe||await Me(G.file)!==et)throw Error("NATIVE_EXECUTABLE_CHANGED");u=(0,$.spawn)(E,b.tuiArgs,{cwd:b.workingDirectory,env:tt,stdio:"inherit"}),z.push(u);let st=new Promise((I,X)=>{u.once("error",X),u.once("close",()=>I())});if(st.catch(()=>{}),Ze=Lt(u),await a("FRONTEND",{pid:u.pid}),await st,g=!0,await a("FRONTEND_ENDED",{code:u.exitCode,signal:u.signalCode}),c){let I=await Ie.get(c)();if(!I.ended||I.phase==="sigterm"||I.phase==="sigkill")throw new Ee}return(u.exitCode??1)||kt(c)}finally{try{if(g=!0,m?.stop(),N.close(),u&&!T(u))await a("RETAINED_FRONTEND",{pid:u.pid});else for(let E of Ie.values())try{(await E()).ended||(V=!0)}catch{V=!0,await a("OBSERVER_STOP_REFUSED")}for(let E of[p,h])if(E){let L=!1;await Oe(async()=>{await E.close(),L=!0},3e3),L||(we=!0,await a("NATIVE_READER_CLOSE_TIMEOUT"))}if(!u||T(u)){if(l){let E=T(l)||await Wt(l);if(A&&!u&&ye)try{if(E)await ye.cleanupExited(),await a("STARTUP_BACKEND_ENDPOINT_CLEANED",{pid:l.pid});else{await a("STARTUP_BACKEND_FORCE_STOP_INTENT",{pid:l.pid});let L=await ye.forceStop();await a("STARTUP_BACKEND_FORCE_STOP_RESULT",{pid:l.pid,...L})}}catch{q=!0,await a("STARTUP_BACKEND_FORCE_STOP_REFUSED",{pid:l.pid})}}for(let E of z)E!==l&&!Ie.has(E)&&!T(E)&&(E.kill("SIGTERM"),await U(E,2e3));if(_=z.every(T)&&!q&&!V&&!we,j)try{await v.promises.lstat(j),_=!1}catch(E){if(E.code!=="ENOENT")throw E}}if(await a("CLEANUP",{allCreatedChildrenEnded:_,children:z.map(E=>({pid:E.pid,code:E.exitCode,signal:E.signalCode}))}),await d.close(),_){await ge();let E=0,L=async G=>{for(let Z of await v.promises.readdir(G)){if(++E>4096)throw Error("NATIVE_ROOT_CLEANUP_INVENTORY_EXCEEDED");let se=O.join(G,Z),ee=await v.promises.lstat(se);if(ee.isDirectory()&&!ee.isSymbolicLink())await L(se);else if(!ee.isFile()&&!ee.isSocket()&&!ee.isSymbolicLink())throw Error("NATIVE_ROOT_CLEANUP_TYPE_CHANGED")}};await L(r),await v.promises.rm(r,{recursive:!0})}else{console.error("CodeVibe: teardown incomplete;owned recovery files retained at "+r);for(let E of z)T(E)||(E.unref(),E.stdin?.destroy(),E.stdout?.destroy(),E.stderr?.destroy(),E.connected&&E.disconnect());throw new he(r,z.filter(E=>!T(E)).map(E=>E.pid).filter(Boolean),A&&!Ne)}}finally{Ze?.()}}}function Ft(i){return i.isFile()&&!i.isSymbolicLink()&&i.nlink===1&&(i.mode&63)===0&&i.uid===process.getuid?.()}async function Ht(i,e,t){if(!O.isAbsolute(i)||O.normalize(i)!==i||O.basename(i)!=="bootstrap.json")throw Error("NATIVE_TMUX_BOOTSTRAP_INVALID");let r=O.dirname(i),n=await v.promises.open(i,v.constants.O_RDONLY|v.constants.O_NOFOLLOW),o;try{let s=await n.stat();if(!Ft(s)||s.size>2*1024*1024)throw Error("NATIVE_TMUX_BOOTSTRAP_INVALID");o=JSON.parse(await n.readFile("utf8"));let d=await n.stat();if(s.dev!==d.dev||s.ino!==d.ino||s.size!==d.size||s.mtimeMs!==d.mtimeMs||o.version!==1||o.nonce!==e||o.root?.path!==r||!Array.isArray(o.args)||!o.args.every(u=>typeof u=="string")||!o.environment||typeof o.environment!="object"||Array.isArray(o.environment)||!Object.values(o.environment).every(u=>typeof u=="string"))throw Error("NATIVE_TMUX_BOOTSTRAP_INVALID");let a=await v.promises.lstat(r);if(!a.isDirectory()||a.isSymbolicLink()||(a.mode&63)!==0||a.uid!==process.getuid?.()||a.dev!==o.root.dev||a.ino!==o.root.ino||a.uid!==o.root.uid)throw Error("NATIVE_TMUX_BOOTSTRAP_INVALID");let l=await v.promises.open(r+"/status",v.constants.O_WRONLY|v.constants.O_NOFOLLOW);try{let u=await l.stat(),c=(await v.promises.readdir(r)).sort();if(!Ft(u)||u.size!==0||u.dev!==o.status?.dev||u.ino!==o.status?.ino||c.join(",")!=="bootstrap.json,status")throw Error("NATIVE_TMUX_BOOTSTRAP_INVALID");let p=await v.promises.lstat(r),h=await v.promises.lstat(i),m=await v.promises.lstat(r+"/status");if(p.dev!==a.dev||p.ino!==a.ino||h.dev!==s.dev||h.ino!==s.ino||m.dev!==u.dev||m.ino!==u.ino)throw Error("NATIVE_TMUX_BOOTSTRAP_INVALID");await v.promises.unlink(i),await v.promises.unlink(r+"/status"),await v.promises.rmdir(r);let f={...o.environment};return delete f.TMUX,delete f.TMUX_PANE,t.TMUX&&(f.TMUX=t.TMUX),t.TMUX_PANE&&(f.TMUX_PANE=t.TMUX_PANE),{args:o.args,environment:f,status:l}}catch(u){throw await l.close(),u}}finally{await n.close()}}var vi=i=>"'"+i.split("'").join("'\\''")+"'";function Xe(i){let e=Number(i.slice(0,-1));return Number.isInteger(e)&&e>=0&&e<=255&&i===String(e)+`
4
4
  `?e:null}var Ue={NATIVE_UPDATE_REQUIRED:new F("NATIVE_UPDATE_REQUIRED").message,NATIVE_CAPABILITY_PROBE_FAILED:new F("NATIVE_CAPABILITY_PROBE_FAILED").message,NATIVE_RPC_TIMEOUT:"Codex did not finish its native startup request in time. Try resuming the session directly with Codex.",NATIVE_REQUEST_CANCELLED:"Codex session loading was cancelled.",NATIVE_DISCONNECTED:"The native Codex connection ended during startup. Try the session directly with Codex.",NATIVE_STARTUP_FAILED:"CodeVibe could not start native Codex. Check that Codex runs directly, then retry.",NATIVE_LAUNCH_CLEANUP_INCOMPLETE:"Codex startup cleanup could not be completed safely.",NATIVE_OBSERVER_SHUTDOWN_ESCALATED:"Codex ended, but its mobile observer did not finish graceful shutdown and required a targeted stop. Mobile session retirement is unconfirmed; resume this Codex session to reconnect."},he=class extends Error{constructor(t,r,n=!1){super("NATIVE_LAUNCH_CLEANUP_INCOMPLETE");this.root=t;this.pids=r;this.needsNativeExecutable=n;this.code="NATIVE_LAUNCH_CLEANUP_INCOMPLETE"}},Ee=class extends Error{constructor(){super(Ue.NATIVE_OBSERVER_SHUTDOWN_ESCALATED);this.code="NATIVE_OBSERVER_SHUTDOWN_ESCALATED"}};function zt(i){if(i.length>2048)return null;let e=Xe(i);if(e!==null)return{code:e,diagnostic:null};let t=i.split(`
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var As=Object.create;var tt=Object.defineProperty;var Os=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var ks=Object.getPrototypeOf,Ds=Object.prototype.hasOwnProperty;var Ms=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Fs=(a,e)=>{for(var t in e)tt(a,t,{get:e[t],enumerable:!0})},ti=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xs(e))!Ds.call(a,s)&&s!==t&&tt(a,s,{get:()=>e[s],enumerable:!(i=Os(e,s))||i.enumerable});return a};var D=(a,e,t)=>(t=a!=null?As(ks(a)):{},ti(e||!a||!a.__esModule?tt(t,"default",{value:a,enumerable:!0}):t,a)),Ls=a=>ti(tt({},"__esModule",{value:!0}),a);var hs=Ms((io,Bn)=>{Bn.exports={name:"@quantiya/codevibe-codex-plugin",version:"2.0.110",description:"Control OpenAI Codex CLI from your iPhone and Android \u2014 real-time sync, approve file edits, send prompts by voice. Part of CodeVibe.",main:"dist/server.js",codevibe:{companionLauncher:"./libexec/companion-launcher"},files:["dist/**/*.js","libexec","hooks","README.md",".env.example"],scripts:{typecheck:"tsc --noEmit",build:"rm -rf dist && npm run typecheck && esbuild src/server.ts src/native-launch.ts --bundle --platform=node --target=node18 --minify --packages=external --outdir=dist",prepack:"node scripts/prepare-publish.js && npm run build",postpack:"node scripts/restore-dev.js",dev:"ts-node src/server.ts",start:"node dist/server.js",test:"jest --config jest.config.js"},keywords:["codex","codex-cli","openai","plugin","extension","mobile","ios","android","codevibe","companion","remote-control","ai","developer-tools"],author:"Quantiya <support@quantiya.ai>",license:"MIT",bugs:{email:"support@quantiya.ai"},homepage:"https://quantiya.ai/codevibe",engines:{node:">=22.0.0"},dependencies:{"@quantiya/codevibe-core":"^2.0.94","@quantiya/quorum-core":"^1.0.1",chokidar:"^4.0.0",dotenv:"^16.6.1",express:"^5.1.0",graphql:"^16.12.0","shell-quote":"1.9.0",uuid:"^13.0.0",ws:"^8.18.3"},bundledDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"],devDependencies:{"@types/express":"^5.0.5","@types/jest":"^30.0.0","@types/node":"^24.10.1","@types/uuid":"^10.0.0","@types/ws":"^8.18.1",esbuild:"^0.28.0",jest:"^30.3.0","ts-jest":"^29.4.9","ts-node":"^10.9.2",typescript:"^5.9.3"},bundleDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"]}});var Xn={};Fs(Xn,{CodexCompanionServer:()=>At,TERMINAL_SHUTDOWN_SIGNALS:()=>Ss,TmuxPaneObserver:()=>Je,classifyTmuxHasSessionError:()=>Es,extractShellCommandFromPromptText:()=>bs,extractShellCommandPartsFromPromptText:()=>et,nativeStopFailureFields:()=>Zt,restoreCodexPersistOptionCommand:()=>Ts,shellCommandPartsMatchExpected:()=>Nt});module.exports=Ls(Xn);var Se=require("uuid"),Ee=D(require("crypto")),Pe=D(require("fs")),W=D(require("path")),Ze=D(require("os")),Yt=require("util"),Ot=require("child_process"),Xt=require("shell-quote");var ge=require("node:fs"),Z=D(require("node:path")),di=D(require("node:os")),kt=require("node:util");var Be=D(require("ws")),be=require("node:fs"),Re=D(require("node:path")),si=require("node:crypto");var M=class extends Error{constructor(t,i,s,n){super(t);this.code=t;this.rpcCode=i;this.diagnostic=s;this.handlerFailure=n;this.name="NativeClientError"}};function ii(a,e){let t=a.length<=128&&[...a].every(d=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/_.-".includes(d))?a:"UNKNOWN_NATIVE_METHOD",i=e instanceof Error?e:null,s=["Error","TypeError","RangeError","NativeClientError","NativeRuntimeError","NativeControlError","SyncEventClientError","SyncJournalError","ZodError"],n=e?.code??i?.message,r=typeof n=="string"&&n.length<=96&&(n.startsWith("NATIVE_")||n.startsWith("SYNC_")||["ENOENT","EACCES","EPERM","EIO"].includes(n))&&[...n].every(d=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_".includes(d))?n:null,o=null;for(let d of(i?.stack??"").split(`
1
+ "use strict";var As=Object.create;var tt=Object.defineProperty;var Os=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var ks=Object.getPrototypeOf,Ds=Object.prototype.hasOwnProperty;var Ms=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Fs=(a,e)=>{for(var t in e)tt(a,t,{get:e[t],enumerable:!0})},ti=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xs(e))!Ds.call(a,s)&&s!==t&&tt(a,s,{get:()=>e[s],enumerable:!(i=Os(e,s))||i.enumerable});return a};var D=(a,e,t)=>(t=a!=null?As(ks(a)):{},ti(e||!a||!a.__esModule?tt(t,"default",{value:a,enumerable:!0}):t,a)),Ls=a=>ti(tt({},"__esModule",{value:!0}),a);var hs=Ms((io,Bn)=>{Bn.exports={name:"@quantiya/codevibe-codex-plugin",version:"2.0.112",description:"Control OpenAI Codex CLI from your iPhone and Android \u2014 real-time sync, approve file edits, send prompts by voice. Part of CodeVibe.",main:"dist/server.js",codevibe:{companionLauncher:"./libexec/companion-launcher"},files:["dist/**/*.js","libexec","hooks","README.md",".env.example"],scripts:{typecheck:"tsc --noEmit",build:"rm -rf dist && npm run typecheck && esbuild src/server.ts src/native-launch.ts --bundle --platform=node --target=node18 --minify --packages=external --outdir=dist",prepack:"node scripts/prepare-publish.js && npm run build",postpack:"node scripts/restore-dev.js",dev:"ts-node src/server.ts",start:"node dist/server.js",test:"jest --config jest.config.js"},keywords:["codex","codex-cli","openai","plugin","extension","mobile","ios","android","codevibe","companion","remote-control","ai","developer-tools"],author:"Quantiya <support@quantiya.ai>",license:"MIT",bugs:{email:"support@quantiya.ai"},homepage:"https://quantiya.ai/codevibe",engines:{node:">=22.0.0"},dependencies:{"@quantiya/codevibe-core":"^2.0.96","@quantiya/quorum-core":"^1.0.1",chokidar:"^4.0.0",dotenv:"^16.6.1",express:"^5.1.0",graphql:"^16.12.0","shell-quote":"1.9.0",uuid:"^13.0.0",ws:"^8.18.3"},bundledDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"],devDependencies:{"@types/express":"^5.0.5","@types/jest":"^30.0.0","@types/node":"^24.10.1","@types/uuid":"^10.0.0","@types/ws":"^8.18.1",esbuild:"^0.28.0",jest:"^30.3.0","ts-jest":"^29.4.9","ts-node":"^10.9.2",typescript:"^5.9.3"},bundleDependencies:["@quantiya/codevibe-core","@quantiya/quorum-core","chokidar","dotenv","express","graphql","shell-quote","uuid","ws"]}});var Xn={};Fs(Xn,{CodexCompanionServer:()=>At,TERMINAL_SHUTDOWN_SIGNALS:()=>Ss,TmuxPaneObserver:()=>Je,classifyTmuxHasSessionError:()=>Es,extractShellCommandFromPromptText:()=>bs,extractShellCommandPartsFromPromptText:()=>et,nativeStopFailureFields:()=>Zt,restoreCodexPersistOptionCommand:()=>Ts,shellCommandPartsMatchExpected:()=>Nt});module.exports=Ls(Xn);var Se=require("uuid"),Ee=D(require("crypto")),Pe=D(require("fs")),W=D(require("path")),Ze=D(require("os")),Yt=require("util"),Ot=require("child_process"),Xt=require("shell-quote");var ge=require("node:fs"),Z=D(require("node:path")),di=D(require("node:os")),kt=require("node:util");var Be=D(require("ws")),be=require("node:fs"),Re=D(require("node:path")),si=require("node:crypto");var M=class extends Error{constructor(t,i,s,n){super(t);this.code=t;this.rpcCode=i;this.diagnostic=s;this.handlerFailure=n;this.name="NativeClientError"}};function ii(a,e){let t=a.length<=128&&[...a].every(d=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/_.-".includes(d))?a:"UNKNOWN_NATIVE_METHOD",i=e instanceof Error?e:null,s=["Error","TypeError","RangeError","NativeClientError","NativeRuntimeError","NativeControlError","SyncEventClientError","SyncJournalError","ZodError"],n=e?.code??i?.message,r=typeof n=="string"&&n.length<=96&&(n.startsWith("NATIVE_")||n.startsWith("SYNC_")||["ENOENT","EACCES","EPERM","EIO"].includes(n))&&[...n].every(d=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_".includes(d))?n:null,o=null;for(let d of(i?.stack??"").split(`
2
2
  `).slice(1)){for(let[l,u]of[["server.js","server"],["index.js","core"],["native-launch.js","native-launch"]]){let h="/dist/"+l+":",p=d.lastIndexOf(h);if(p<0)continue;let m=d.slice(p+h.length).split(")")[0].trim().split(":");if(m.length===2&&m.every(f=>f.length>0&&[...f].every(g=>"0123456789".includes(g)))){let[f,g]=m.map(Number);f>0&&f<1e5&&g>0&&g<1e7&&(o={module:u,line:f,column:g})}if(o)break}if(o)break}return new M("NATIVE_HANDLER_FAILED",void 0,void 0,{method:t,errorName:i&&s.includes(i.name)?i.name:"Error",causeCode:r,site:o})}var xe=class{constructor(e){this.options=e;this.socket=null;this.pending=new Map;this.handlers=new Set;this.accepting=!1;this.intentionalClose=!1;this.initialized=!1;this.requestPrefix="codevibe-"+(0,si.randomUUID)()+"-";this.sequence=0;if(e.maxPayloadBytes!==void 0&&(!Number.isSafeInteger(e.maxPayloadBytes)||e.maxPayloadBytes<1024||e.maxPayloadBytes>8*1024*1024))throw new M("NATIVE_PROTOCOL_INVALID");this.instanceId=e.instanceId,this.endpoint={socketPath:e.socketPath,socketIdentity:{...e.socketIdentity},...e.alias?{alias:{...e.alias}}:{}}}get isConnected(){return this.initialized&&this.accepting&&!this.intentionalClose&&this.socket?.readyState===Be.default.OPEN}async assertSocket(){this.options.assertOwner();let e=this.endpoint.socketPath;if(!Re.isAbsolute(e)||Re.normalize(e)!==e||e.includes(":")||e.includes("\0"))throw new M("NATIVE_SOCKET_UNSAFE");let t=await be.promises.lstat(Re.dirname(e)),i=await be.promises.lstat(e),s=typeof process.getuid=="function"?process.getuid():void 0,n={rootDirectory:t.isDirectory(),rootNotSymlink:!t.isSymbolicLink(),rootPrivate:(t.mode&63)===0,ownerMatches:s===void 0||t.uid===s&&i.uid===s,socketType:i.isSocket(),socketNotSymlink:!i.isSymbolicLink(),socketIdentityMatches:i.dev===this.endpoint.socketIdentity.dev&&i.ino===this.endpoint.socketIdentity.ino};if(Object.values(n).some(o=>!o))throw new M("NATIVE_SOCKET_UNSAFE",void 0,n);let r=this.endpoint.alias;if(r){let o=await be.promises.lstat(Re.dirname(r.path)),d=await be.promises.lstat(r.path);if(!o.isDirectory()||o.isSymbolicLink()||(o.mode&63)!==0||o.dev!==r.rootDev||o.ino!==r.rootIno||!d.isSymbolicLink()||d.dev!==r.dev||d.ino!==r.ino||s!==void 0&&(o.uid!==s||d.uid!==s)||await be.promises.readlink(r.path)!==r.target||await be.promises.realpath(r.path)!==e)throw new M("NATIVE_SOCKET_UNSAFE",void 0,{originalAliasMatches:!1})}this.options.assertOwner()}async connect(){try{await this.connectOnce()}catch(e){throw await this.close(),e}}async connectOnce(){if(this.socket||this.intentionalClose)throw new M("NATIVE_DISCONNECTED");await this.assertSocket();let e=new Be.default("ws+unix://"+this.endpoint.socketPath+":/",this.options.maxPayloadBytes===void 0?{}:{maxPayload:this.options.maxPayloadBytes});this.socket=e,this.accepting=!0,e.on("message",t=>this.receive(t.toString())),e.on("error",()=>this.fail(new M("NATIVE_DISCONNECTED"))),e.on("close",()=>{this.initialized=!1,this.accepting=!1,this.rejectPending(),this.intentionalClose||this.report(new M("NATIVE_DISCONNECTED"))}),await new Promise((t,i)=>{let s=setTimeout(()=>{o(new M("NATIVE_RPC_TIMEOUT",void 0,{webSocketOpenTimedOut:!0})),e.terminate()},2e3),n=()=>o(),r=()=>o(new M("NATIVE_DISCONNECTED")),o=d=>{clearTimeout(s),e.off("open",n),e.off("error",r),e.off("close",r),d?i(d):t()};e.once("open",n),e.once("error",r),e.once("close",r)}),await this.assertSocket(),await this.request("initialize",{clientInfo:{name:"codevibe-codex",version:this.options.pluginVersion},capabilities:{experimentalApi:!0,requestAttestation:!1}},2e3),await this.notify("initialized"),this.initialized=!0}report(e){try{Promise.resolve(this.options.onFailure(e)).catch(()=>{})}catch{}}rejectPending(){for(let e of this.pending.values())clearTimeout(e.timer),e.reject(new M("NATIVE_DISCONNECTED"));this.pending.clear()}fail(e){this.accepting=!1,this.initialized=!1,this.rejectPending(),this.intentionalClose||this.report(e),this.socket?.terminate()}receive(e){if(!this.accepting)return;let t;try{let s=JSON.parse(e);if(!s||typeof s!="object"||Array.isArray(s))throw Error();t=s}catch{this.fail(new M("NATIVE_PROTOCOL_INVALID"));return}if(typeof t.method=="string"){if(t.id!==void 0&&typeof t.id!="string"&&typeof t.id!="number"){this.fail(new M("NATIVE_PROTOCOL_INVALID"));return}let s;try{this.options.assertOwner()}catch{this.fail(new M("NATIVE_OWNER_CHANGED"));return}try{s=this.options.onMessage(t)}catch(r){this.report(ii(t.method,r));return}let n=Promise.resolve(s).catch(r=>this.report(ii(t.method,r)));this.handlers.add(n),n.then(()=>this.handlers.delete(n));return}if(typeof t.id!="string")return;let i=this.pending.get(t.id);if(i)if(this.pending.delete(t.id),clearTimeout(i.timer),t.error!==void 0){let s=t.error?.code;i.reject(new M("NATIVE_RPC_REJECTED",typeof s=="number"?s:void 0))}else Object.prototype.hasOwnProperty.call(t,"result")?i.resolve(t.result):i.reject(new M("NATIVE_PROTOCOL_INVALID"))}async write(e){this.options.assertOwner();let t=this.socket;if(!t||t.readyState!==Be.default.OPEN||!this.accepting)throw new M("NATIVE_DISCONNECTED");await new Promise((i,s)=>t.send(JSON.stringify(e),n=>n?s(new M("NATIVE_DISCONNECTED")):i())),this.options.assertOwner()}async request(e,t,i=1e4,s){if(!this.initialized&&e!=="initialize")throw new M("NATIVE_DISCONNECTED");if(!Number.isFinite(i)||i<=0||i>3e5)throw new M("NATIVE_PROTOCOL_INVALID");if(s?.aborted)throw new M("NATIVE_REQUEST_CANCELLED");let n=this.requestPrefix+ ++this.sequence,o=new Promise((l,u)=>{let h=()=>{this.pending.delete(n),f.reject(new M("NATIVE_REQUEST_CANCELLED"))},p=()=>{s?.removeEventListener("abort",h),clearTimeout(m)},m=setTimeout(()=>{this.pending.delete(n),u(new M("NATIVE_RPC_TIMEOUT",void 0,{initializeTimedOut:e==="initialize",threadResumeTimedOut:e==="thread/resume",otherRpcTimedOut:e!=="initialize"&&e!=="thread/resume"})),s?.removeEventListener("abort",h)},i),f={resolve:g=>{p(),l(g)},reject:g=>{p(),u(g)},timer:m};this.pending.set(n,f),s?.addEventListener("abort",h,{once:!0}),s?.aborted&&h()}).then(l=>({value:l}),l=>({error:l}));try{s?.aborted||await this.write({id:n,method:e,params:t})}catch(l){let u=this.pending.get(n);throw u&&(clearTimeout(u.timer),this.pending.delete(n),u.reject(new M("NATIVE_DISCONNECTED"))),await o,l}let d=await o;if("error"in d)throw d.error;return d.value}async notify(e,t){await this.write({method:e,...t===void 0?{}:{params:t}})}async respond(e,t){if(!this.initialized)throw new M("NATIVE_DISCONNECTED");await this.write({id:e,result:t})}async close(){this.intentionalClose=!0,this.accepting=!1,this.initialized=!1,this.rejectPending();let e=this.socket;e&&e.readyState!==Be.default.CLOSED&&await new Promise(t=>{let i=setTimeout(()=>{e.terminate(),t()},2e3);e.once("close",()=>{clearTimeout(i),t()}),e.close()}),await this.joinHandlers(),this.socket=null}async joinHandlers(){await Promise.allSettled([...this.handlers])}};var qs=256,ni=2*1024*1024;function $(){throw Error("NATIVE_QUESTION_RESUME_NOT_PROVEN")}function Ve(a){return!a||typeof a!="object"||Array.isArray(a)?$():a}async function ri(a,e,t,i,s){if(!i.length||i.length>64||i.some(o=>o.kind!=="async"||o.threadId!==t))return $();let n=()=>{a.assertCurrent(),s()},r=new xe({...a.record.endpoint,instanceId:a.record.instanceId,pluginVersion:e,maxPayloadBytes:4*1024*1024,assertOwner:n,onMessage:()=>{},onFailure:()=>{}});try{await r.connect();let o=Date.now()+2e3,d=async(w,E)=>{n();let R=o-Date.now();if(R<=0)return $();let b=Ve(await r.request(w,E,R));return n(),Buffer.byteLength(JSON.stringify(b))>ni?$():b},l=Ve((await d("thread/read",{threadId:t,includeTurns:!1})).thread);if(l.id!==t||l.sessionId!==t||l.ephemeral!==!1||l.parentThreadId!=null)return $();let u=new Set(i.map(w=>JSON.stringify([w.turnId,w.itemId]))),h=[],p=new Set,m=new Set,f;for(let w=0;w<8&&u.size;w++){let E=await d("thread/items/list",{threadId:t,limit:32,sortDirection:"desc",...f?{cursor:f}:{}});if(!Array.isArray(E.data)||!E.data.length||E.data.length>32)return $();for(let R of E.data){let b=Ve(R),_=Ve(b.item);if(typeof b.turnId!="string"||!b.turnId.length||typeof _.id!="string"||!_.id.length)return $();let x=JSON.stringify([b.turnId,_.id]);if(p.has(x))return $();if(p.add(x),h.push({turnId:b.turnId,item:_}),u.delete(x),!u.size)break}if(h.length>qs||Buffer.byteLength(JSON.stringify(h))>ni)return $();if(!u.size)break;if(typeof E.nextCursor!="string"||!E.nextCursor.length||m.has(E.nextCursor))return $();f=E.nextCursor,m.add(f)}if(u.size)return $();let g=new Set(i.map(w=>w.turnId)),y=[],S=new Set;f=void 0,m.clear();for(let w=0;w<8&&g.size;w++){let E=await d("thread/turns/list",{threadId:t,limit:32,sortDirection:"desc",itemsView:"notLoaded",...f?{cursor:f}:{}});if(!Array.isArray(E.data)||!E.data.length||E.data.length>32)return $();for(let R of E.data){let b=Ve(R);if(typeof b.id!="string"||typeof b.status!="string"||b.itemsView!=="notLoaded"||!Array.isArray(b.items)||b.items.length||S.has(b.id))return $();S.add(b.id),g.delete(b.id)&&y.push({id:b.id,status:b.status})}if(!g.size)break;if(typeof E.nextCursor!="string"||!E.nextCursor.length||m.has(E.nextCursor))return $();f=E.nextCursor,m.add(f)}if(g.size)return $();let I=await d("thread/items/list",{threadId:t,limit:1,sortDirection:"desc"});return!Array.isArray(I.data)||I.data.length!==1||I.data[0].turnId!==h[0].turnId||JSON.stringify(I.data[0].item)!==JSON.stringify(h[0].item)?$():{threadId:t,nativeInstanceId:a.record.instanceId,items:h,turns:y}}finally{await r.close()}}var H=class extends Error{constructor(t){super(t);this.code=t;this.name="NativeRuntimeError"}},Te=()=>{throw new H("NATIVE_LAUNCH_AUTHORITY_INVALID")};function it(a){return!a||typeof a!="object"||Array.isArray(a)?Te():a}function Bs(a,e){return Object.keys(a).sort().join(",")===e.sort().join(",")}function oi(a){return typeof a=="number"&&Number.isSafeInteger(a)&&a>0}function ai(a){try{process.kill(a,0)}catch{Te()}}async function li(a,e){if(!Z.isAbsolute(a)||Z.normalize(a)!==a||Z.basename(a)!=="launch.json")return Te();let t=typeof process.getuid=="function"?process.getuid():void 0,i=await ge.promises.open(a,ge.constants.O_RDONLY|ge.constants.O_NOFOLLOW),s,n;try{let o=await i.stat();if(!o.isFile()||o.nlink!==1||(o.mode&63)!==0||o.size>2*1024*1024||t!==void 0&&o.uid!==t)return Te();let d=it(JSON.parse(await i.readFile("utf8")));if(!Bs(d,["version","instanceId","root","launcher","server","endpoint","plan"])||d.version!==1||d.instanceId!==e||typeof e!="string"||!e.length||!oi(d.launcher?.pid)||d.launcher.host!==di.hostname()||!oi(d.server?.pid)||d.root?.path!==Z.dirname(a)||!Number.isSafeInteger(d.root.dev)||!Number.isSafeInteger(d.root.ino)||d.root.uid!==t||!Z.isAbsolute(d.endpoint?.socketPath??"")||!Number.isSafeInteger(d.endpoint?.socketIdentity?.dev)||!Number.isSafeInteger(d.endpoint?.socketIdentity?.ino)||!Z.isAbsolute(d.plan?.workingDirectory??"")||d.plan.resumeThreadId!==null&&typeof d.plan.resumeThreadId!="string")return Te();let l=await i.stat();if(o.dev!==l.dev||o.ino!==l.ino||o.size!==l.size||o.mtimeMs!==l.mtimeMs)return Te();s=d,n={dev:o.dev,ino:o.ino,size:o.size,mtimeMs:o.mtimeMs}}finally{await i.close()}let r=()=>{let o=(0,ge.lstatSync)(s.root.path),d=(0,ge.lstatSync)(a);if(!o.isDirectory()||o.isSymbolicLink()||(o.mode&63)!==0||o.dev!==s.root.dev||o.ino!==s.root.ino||o.uid!==s.root.uid||!d.isFile()||d.isSymbolicLink()||d.nlink!==1||(d.mode&63)!==0||d.dev!==n.dev||d.ino!==n.ino||d.size!==n.size||d.mtimeMs!==n.mtimeMs||d.uid!==s.root.uid)return Te();ai(s.launcher.pid),ai(s.server.pid)};return r(),{record:JSON.parse(JSON.stringify(s)),assertCurrent:r}}function xt(a){let e=it(a);if(typeof e.id!="string"||!e.id.length)throw new H("NATIVE_ROOT_INVALID_ID");if(e.sessionId!==e.id||e.parentThreadId!=null)throw new H("NATIVE_ROOT_INVALID_SESSION");if(e.ephemeral!==!1)throw new H("NATIVE_ROOT_INVALID_PERSISTENCE");if(typeof e.cwd!="string"||!Z.isAbsolute(e.cwd))throw new H("NATIVE_ROOT_INVALID_CWD");if(!Number.isFinite(e.createdAt)||e.createdAt<0)throw new H("NATIVE_ROOT_INVALID_TIMESTAMP");if(e.path!==null&&(typeof e.path!="string"||!Z.isAbsolute(e.path)))throw new H("NATIVE_ROOT_INVALID_PATH");if(typeof e.cliVersion!="string")throw new H("NATIVE_ROOT_INVALID_VERSION");if(typeof e.modelProvider!="string")throw new H("NATIVE_ROOT_INVALID_PROVIDER");return{id:e.id,sessionId:e.sessionId,cwd:e.cwd,createdAt:e.createdAt,path:e.path,cliVersion:e.cliVersion,modelProvider:e.modelProvider}}var st=class{constructor(e){this.options=e;this.root=null;this.ready=!1;this.generation=0;this.bindingDepth=0;this.binding=Promise.resolve();this.closed=!1;this.refreshPending=null;this.pendingControls=new Map;this.pendingFiles=new Map;this.client=new xe({...e.authority.record.endpoint,instanceId:e.authority.record.instanceId,pluginVersion:e.pluginVersion,assertOwner:e.authority.assertCurrent,onMessage:t=>this.observe(t),onFailure:t=>t.handlerFailure?e.onFailure(t.code,t.handlerFailure):e.onFailure(t.code)})}get thread(){return this.root?{...this.root}:null}controlFacts(){return JSON.parse(JSON.stringify([...this.pendingFiles.values(),...this.pendingControls.values()]))}isCurrentControl(e){let t=e.id===void 0?void 0:this.pendingControls.get(e.id);return!this.closed&&!!t&&t.method===e.method&&(0,kt.isDeepStrictEqual)(t.params,e.params)}hasPendingControl(){return this.pendingControls.size>0}readQuestionResumeWindow(e){let t=this.root?.id;return!t||this.closed?Promise.reject(new H("NATIVE_BINDING_FAILED")):ri(this.options.authority,this.options.pluginVersion,t,e,()=>{if(this.closed||this.root?.id!==t)throw new H("NATIVE_BINDING_FAILED")})}async start(){await this.client.connect();let e=this.options.recoveryThreadId??this.options.authority.record.plan.resumeThreadId;e&&await this.bind(await this.readMetadata(e))}bind(e){let t=this.options.recoveryThreadId??this.options.authority.record.plan.resumeThreadId;if(!this.root&&t&&e.id!==t)return Promise.reject(new H("NATIVE_ROOT_INVALID"));if(this.root&&e.id===this.root.id&&e.cwd!==this.root.cwd)return Promise.reject(new H("NATIVE_ROOT_INVALID"));if(this.root&&(0,kt.isDeepStrictEqual)(this.root,e)&&(this.ready||this.bindingDepth>0))return this.binding;(!this.root||this.root.id!==e.id)&&(this.generation++,this.ready=!1,this.pendingControls.clear(),this.pendingFiles.clear());let i=this.generation;this.root={...e},this.bindingDepth++;let s=this.binding.then(async()=>{if(this.closed)throw new H("NATIVE_BINDING_FAILED");await this.options.onRoot({...e}),i===this.generation&&!this.closed&&(this.ready=!0)});return this.binding=s.catch(()=>{}),s.then(()=>{this.bindingDepth--},()=>{this.bindingDepth--}),s}observe(e){if(this.closed)return;let t=e.params;if(e.method==="thread/started"){let s=t?.thread;return s?.ephemeral===!0||s?.parentThreadId!=null||s?.sessionId!==s?.id?void 0:this.bind(xt(s))}if(!this.root||t?.threadId!==this.root.id)return;if(e.id!==void 0&&this.pendingControls.set(e.id,JSON.parse(JSON.stringify(e))),e.method==="serverRequest/resolved"&&this.pendingControls.delete(t.requestId),["item/started","item/completed"].includes(e.method)&&t.item?.type==="fileChange"&&this.pendingFiles.set(t.item.id,JSON.parse(JSON.stringify(e))),e.method==="item/completed"&&["commandExecution","fileChange"].includes(t.item?.type)){for(let[s,n]of this.pendingControls){let r=n.params;r.turnId===t.turnId&&r.itemId===t.item.id&&this.pendingControls.delete(s)}this.pendingFiles.delete(t.item.id)}if(!this.ready&&this.bindingDepth===0&&e.method==="turn/started"&&this.bind(this.root).catch(()=>{}),["item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta"].includes(e.method))return;if(this.ready)return this.options.onMessage(e);let i=this.generation;return this.binding.then(()=>{if(!this.ready||this.closed||i!==this.generation)throw new H("NATIVE_BINDING_FAILED");return this.options.onMessage(e)})}async readMetadata(e){let t=await this.client.request("thread/resume",{threadId:e,excludeTurns:!0},2e3),i=xt(it(t).thread);if(i.id!==e)throw new H("NATIVE_ROOT_INVALID");return i}refreshMetadata(){if(this.refreshPending)return this.refreshPending;if(!this.root||this.closed)return Promise.resolve(null);let e=this.root.id,t=(async()=>{let i=Date.now()+2e3;for(let s=0;s<10&&Date.now()<i;s++)try{let n=await this.client.request("thread/resume",{threadId:e,excludeTurns:!0},Math.max(1,i-Date.now())),r=xt(it(n).thread);if(r.id!==e||this.root?.id!==e||this.closed)throw new H("NATIVE_ROOT_INVALID");return await this.bind(r),r}catch(n){if(!(n instanceof M)||n.code!=="NATIVE_RPC_REJECTED"||![-32600,-32601].includes(n.rpcCode??0))throw n;s<9&&Date.now()<i&&await new Promise(r=>setTimeout(r,Math.min(100,i-Date.now())))}return null})();return this.refreshPending=t,t.then(()=>{this.refreshPending=null},()=>{this.refreshPending=null}),t}async close(){this.closed=!0,await this.client.close(),await this.binding,await this.refreshPending?.catch(()=>{})}};var lt=require("node:crypto"),Y=require("node:util"),F=require("@quantiya/codevibe-core");var ci=require("node:crypto"),ui=D(require("node:path")),nt=require("@quantiya/codevibe-core"),T=class extends Error{constructor(t){super(t);this.code=t;this.name="NativeControlError"}},le=class extends T{constructor(){super("NATIVE_CONTROL_UNSUPPORTED")}};function ee(){throw new T("NATIVE_CONTROL_INVALID")}var he=a=>!a||typeof a!="object"||Array.isArray(a)?ee():a,V=a=>typeof a!="string"||!a.length?ee():a,pi=a=>(0,ci.createHash)("sha256").update(JSON.stringify(a)).digest("hex");function hi(a,e){let t=a.payload;if(a.type!=="event_msg"||t?.type!=="item_completed"||t.item?.type!=="AgentMessage"||t.item.delivery!=="async")return null;if(t.thread_id!==e||typeof t.turn_id!="string"||!t.turn_id.length)throw new T("NATIVE_QUESTION_MISMATCH");let i={type:"agentMessage",id:t.item.id,delivery:"async",questions:t.item.questions};return rt(e,t.turn_id,i),{method:"item/completed",params:{threadId:e,turnId:t.turn_id,item:i}}}function mi(a,e){let t=a.payload;if(a.type!=="event_msg"||t?.type!=="item_completed"||!["UserMessage","FunctionCallOutput"].includes(t.item?.type))return null;if(t.thread_id!==e||typeof t.turn_id!="string"||!t.turn_id.length)throw new T("NATIVE_QUESTION_MISMATCH");let i=he(t.item);V(i.id);let s;if(i.type==="UserMessage"){if(i.client_id!==null&&typeof i.client_id!="string"||!Array.isArray(i.content))return ee();let n=i.content.map(r=>{let o=he(r);if(o.type==="image"){if(typeof o.image_url=="string"==(typeof o.file_id=="string"))return ee();let{image_url:d,file_id:l,...u}=o;return{...u,...d!==void 0?{url:V(d)}:{fileId:V(l)}}}if(o.type==="local_image")return{type:"localImage",detail:null,path:V(o.path)};if(o.type==="local_audio")return{type:"localAudio",path:V(o.path)};if(o.type==="audio"&&typeof o.audio_url=="string"){let{audio_url:d,...l}=o;return{...l,url:d}}return r});s={type:"userMessage",id:i.id,clientId:i.client_id,content:n}}else{if(i.namespace!=="functions"||i.name!=="request_user_input_async")return null;s={type:"functionCallOutput",id:i.id,name:i.name,namespace:i.namespace,output:V(i.output)}}return{method:"item/completed",params:{threadId:e,turnId:t.turn_id,item:s}}}function rt(a,e,t){let i=he(t);if(i.type!=="agentMessage"||i.delivery!=="async"||i.questions===null)return[];let s=V(i.id);return V(a),V(e),Array.isArray(i.questions)?i.questions.map((n,r)=>{let o=he(n),d=V(o.title);if(o.options!==null&&(!Array.isArray(o.options)||!o.options.length||!o.options.every(u=>typeof u=="string"&&u.length>0)))return ee();let l=o.options===null?null:[...o.options];return{key:pi(["codex-native-question",a,s,r]),threadId:a,turnId:e,itemId:s,questionIndex:r,questionItemId:JSON.stringify(["request_user_input_async",s,r]),title:d,options:l}}):ee()}function fi(a,e,t){if(t!==null&&t!==a.questionItemId)throw new T("NATIVE_QUESTION_MISMATCH");let i=e.trim(),s=Number(i),n=Number.isSafeInteger(s)&&String(s)===i,r;if(a.options?.length){if(!n){if(t!==null)throw new T("NATIVE_OPTION_INVALID");return{kind:"ordinary"}}if(s<1||s>a.options.length)throw new T("NATIVE_OPTION_INVALID");r=a.options[s-1]}else{if(t===null)return{kind:"ordinary"};if(!i.length)throw new T("NATIVE_OPTION_INVALID");r=e}return{kind:"answer",answer:r,output:JSON.stringify([{answer:r,question:a.title,questionItemId:a.questionItemId}])}}function Dt(a,e,t,i,s=2){let n=t.method==="item/commandExecution/requestApproval"?"command":t.method==="item/fileChange/requestApproval"?"file":null;if(!n)return null;if(typeof t.id!="string"&&typeof t.id!="number"||typeof t.id=="string"&&!t.id.length||typeof t.id=="number"&&(!Number.isSafeInteger(t.id)||t.id<0))return ee();let r=he(t.params),o=V(r.threadId),d=V(r.turnId),l=V(r.itemId);if(o!==e)throw new T("NATIVE_CONTROL_UNSUPPORTED");let u,h=!1;if(n==="command"){let m=new Set(["kind","threadId","turnId","itemId","startedAtMs","approvalId","environmentId","reason","networkApprovalContext","additionalPermissions","command","cwd","commandActions","proposedExecpolicyAmendment","proposedNetworkPolicyAmendments","availableDecisions"]);if(Object.keys(r).some(f=>!m.has(f))||r.kind!=null&&r.kind!=="command"||r.approvalId!=null||r.additionalPermissions!=null||r.networkApprovalContext!=null||r.environmentId!=null&&r.environmentId!=="local"||r.proposedNetworkPolicyAmendments!=null&&(!Array.isArray(r.proposedNetworkPolicyAmendments)||r.proposedNetworkPolicyAmendments.length))throw new le;if(V(r.command),V(r.cwd),!Array.isArray(r.availableDecisions))return ee();if(u=r.availableDecisions,s===1){let f=u.length;u=u.filter(g=>g==="accept"||g==="cancel"),h=u.length!==f}}else{let m=new Set(["threadId","turnId","itemId","startedAtMs","reason","grantRoot"]);if(Object.keys(r).some(f=>!m.has(f))||r.grantRoot!=null)throw new le;if(u=s===1?["accept","decline"]:["accept","acceptForSession","cancel"],!i||i.nativeInstanceId!==a||i.threadId!==o||i.turnId!==d||i.item.type!=="fileChange"||i.item.id!==l||!Array.isArray(i.item.changes)||!i.item.changes.length)throw new le;for(let f of i.item.changes)if(V(f.path),he(f.kind),typeof f.diff!="string")return ee()}if(r.reason!=null&&typeof r.reason!="string")return ee();let p=u.map((m,f)=>{let g,y;if(m==="accept")g=m,y=s===1?"Approve once":"Yes, proceed";else if(m==="cancel"||n==="file"&&m==="decline")g=m,y=m==="decline"?"Reject edit":s===1?"Cancel":"No, and tell Codex what to do differently";else if(m==="acceptForSession")g=m,y=n==="file"?"Yes, and don't ask again for these files":"Approve for this session";else if(n==="command"&&m&&typeof m=="object"&&!Array.isArray(m)){let S=he(m),I=he(S.acceptWithExecpolicyAmendment),w=I.execpolicy_amendment;if(Object.keys(S).length!==1||Object.keys(I).length!==1||!Array.isArray(w)||!w.length||!w.every(R=>typeof R=="string"&&R.length>0&&!R.includes("\0"))||r.proposedExecpolicyAmendment!=null&&(0,nt.stableStringify)(w)!==(0,nt.stableStringify)(r.proposedExecpolicyAmendment))throw new le;g=JSON.parse(JSON.stringify(m)),y="Yes, and don't ask again for commands that start with `"+w.map(R=>/^[A-Za-z0-9_./:@%+=,-]+$/.test(R)?R:"'"+R.split("'").join("'\\''")+"'").join(" ")+"`"}else throw new le;return{number:String(f+1),label:y,decision:g}});if(!p.length||new Set(p.map(m=>(0,nt.stableStringify)(m.decision))).size!==p.length)throw new le;return{key:pi(["codex-native-approval",a,o,d,l,t.id]),nativeInstanceId:a,threadId:o,turnId:d,itemId:l,requestId:t.id,kind:n,request:JSON.parse(JSON.stringify(t)),observedFile:i?JSON.parse(JSON.stringify(i)):null,choices:p,otherChoicesOnDesktop:h}}function ke(a,e,t){let i=t.approvalPresentationVersion;if(i!==void 0&&i!==2)throw new T("NATIVE_CONTROL_UNSUPPORTED");return Dt(a,e,t.request,t.observedFile??void 0,i===2?2:1)}function vi(a,e){let t=a.choices.find(i=>i.number===e.trim());if(!t)throw new T("NATIVE_OPTION_INVALID");return{decision:JSON.parse(JSON.stringify(t.decision))}}function ot(a,e,t,i=[]){if(V(a),V(e),!t.length&&!i.length)return ee();for(let s of i)if(!ui.isAbsolute(s)||s.includes("\0"))return ee();return{threadId:a,clientUserMessageId:e,input:[...t.length?[{type:"text",text:t,text_elements:[]}]:[],...i.map(s=>({type:"localImage",detail:null,path:V(s)}))]}}function gi(a,e){return{threadId:V(a),input:[],toolOutput:{namespace:"functions",name:"request_user_input_async",output:V(e),retain:!0}}}function De(a){let e=(a.options??[]).map((i,s)=>({number:String(s+1),text:i})),t=e.length?"Reply with the number of your choice.":"Type your answer.";return{content:[a.title,...e.map(i=>`${i.number}. ${i.text}`),t].join(`
3
3
 
4
4
  `),metadata:{isApprovalHint:!1,isQueuedQuestion:!0,prompt_source:"native_app_server",tool_name:"request_user_input_async",tool_use_id:a.itemId,turn_id:a.turnId,options:e,questions:[{question:a.title,multiSelect:!1,options:e,instructions:t}],submitMap:Object.fromEntries(e.map(i=>[i.number,i.number])),instructions:t}}}function yi(a,e){e!==null&&V(e);let t=he(a.request.params),i=a.kind==="command"?"Approve command?":"Approve file changes?",s=a.kind==="command"?`${V(t.command)}
@@ -111,13 +111,14 @@ declare const row: z.ZodObject<{
111
111
  claimedEchoSha256: z.ZodNullable<z.ZodString>;
112
112
  }, "strict", z.ZodTypeAny, {
113
113
  expiresAt: number;
114
- token: string;
114
+ normalized: string;
115
115
  target: {
116
116
  eventId: string;
117
117
  type: "USER_PROMPT" | "PROMPT_RESPONSE";
118
118
  timestamp: string;
119
119
  lane: "primary" | "follow_up" | "free_form";
120
120
  };
121
+ token: string;
121
122
  claim: {
122
123
  sourceSha256: string;
123
124
  streamSha256: string;
@@ -125,7 +126,6 @@ declare const row: z.ZodObject<{
125
126
  startOffset: number;
126
127
  endOffset: number;
127
128
  } | null;
128
- normalized: string;
129
129
  armedAt: number;
130
130
  clockPrecisionMs: 1 | 1000;
131
131
  normalization: "trim" | "whitespace";
@@ -133,13 +133,14 @@ declare const row: z.ZodObject<{
133
133
  claimedEchoSha256: string | null;
134
134
  }, {
135
135
  expiresAt: number;
136
- token: string;
136
+ normalized: string;
137
137
  target: {
138
138
  eventId: string;
139
139
  type: "USER_PROMPT" | "PROMPT_RESPONSE";
140
140
  timestamp: string;
141
141
  lane: "primary" | "follow_up" | "free_form";
142
142
  };
143
+ token: string;
143
144
  claim: {
144
145
  sourceSha256: string;
145
146
  streamSha256: string;
@@ -147,7 +148,6 @@ declare const row: z.ZodObject<{
147
148
  startOffset: number;
148
149
  endOffset: number;
149
150
  } | null;
150
- normalized: string;
151
151
  armedAt: number;
152
152
  clockPrecisionMs: 1 | 1000;
153
153
  normalization: "trim" | "whitespace";
@@ -155,13 +155,14 @@ declare const row: z.ZodObject<{
155
155
  claimedEchoSha256: string | null;
156
156
  }>, {
157
157
  expiresAt: number;
158
- token: string;
158
+ normalized: string;
159
159
  target: {
160
160
  eventId: string;
161
161
  type: "USER_PROMPT" | "PROMPT_RESPONSE";
162
162
  timestamp: string;
163
163
  lane: "primary" | "follow_up" | "free_form";
164
164
  };
165
+ token: string;
165
166
  claim: {
166
167
  sourceSha256: string;
167
168
  streamSha256: string;
@@ -169,7 +170,6 @@ declare const row: z.ZodObject<{
169
170
  startOffset: number;
170
171
  endOffset: number;
171
172
  } | null;
172
- normalized: string;
173
173
  armedAt: number;
174
174
  clockPrecisionMs: 1 | 1000;
175
175
  normalization: "trim" | "whitespace";
@@ -177,13 +177,14 @@ declare const row: z.ZodObject<{
177
177
  claimedEchoSha256: string | null;
178
178
  }, {
179
179
  expiresAt: number;
180
- token: string;
180
+ normalized: string;
181
181
  target: {
182
182
  eventId: string;
183
183
  type: "USER_PROMPT" | "PROMPT_RESPONSE";
184
184
  timestamp: string;
185
185
  lane: "primary" | "follow_up" | "free_form";
186
186
  };
187
+ token: string;
187
188
  claim: {
188
189
  sourceSha256: string;
189
190
  streamSha256: string;
@@ -191,7 +192,6 @@ declare const row: z.ZodObject<{
191
192
  startOffset: number;
192
193
  endOffset: number;
193
194
  } | null;
194
- normalized: string;
195
195
  armedAt: number;
196
196
  clockPrecisionMs: 1 | 1000;
197
197
  normalization: "trim" | "whitespace";
@@ -202,13 +202,14 @@ declare const row: z.ZodObject<{
202
202
  kind: "MOBILE_ECHOES";
203
203
  entries: {
204
204
  expiresAt: number;
205
- token: string;
205
+ normalized: string;
206
206
  target: {
207
207
  eventId: string;
208
208
  type: "USER_PROMPT" | "PROMPT_RESPONSE";
209
209
  timestamp: string;
210
210
  lane: "primary" | "follow_up" | "free_form";
211
211
  };
212
+ token: string;
212
213
  claim: {
213
214
  sourceSha256: string;
214
215
  streamSha256: string;
@@ -216,7 +217,6 @@ declare const row: z.ZodObject<{
216
217
  startOffset: number;
217
218
  endOffset: number;
218
219
  } | null;
219
- normalized: string;
220
220
  armedAt: number;
221
221
  clockPrecisionMs: 1 | 1000;
222
222
  normalization: "trim" | "whitespace";
@@ -232,13 +232,14 @@ declare const row: z.ZodObject<{
232
232
  kind: "MOBILE_ECHOES";
233
233
  entries: {
234
234
  expiresAt: number;
235
- token: string;
235
+ normalized: string;
236
236
  target: {
237
237
  eventId: string;
238
238
  type: "USER_PROMPT" | "PROMPT_RESPONSE";
239
239
  timestamp: string;
240
240
  lane: "primary" | "follow_up" | "free_form";
241
241
  };
242
+ token: string;
242
243
  claim: {
243
244
  sourceSha256: string;
244
245
  streamSha256: string;
@@ -246,7 +247,6 @@ declare const row: z.ZodObject<{
246
247
  startOffset: number;
247
248
  endOffset: number;
248
249
  } | null;
249
- normalized: string;
250
250
  armedAt: number;
251
251
  clockPrecisionMs: 1 | 1000;
252
252
  normalization: "trim" | "whitespace";
@@ -6,13 +6,13 @@ declare const ticketSchema: z.ZodObject<{
6
6
  sequence: z.ZodNumber;
7
7
  operationId: z.ZodString;
8
8
  }, "strict", z.ZodTypeAny, {
9
- sequence: number;
10
9
  operationId: string;
11
10
  sourceId: string;
12
- }, {
13
11
  sequence: number;
12
+ }, {
14
13
  operationId: string;
15
14
  sourceId: string;
15
+ sequence: number;
16
16
  }>;
17
17
  declare const schema: z.ZodObject<{
18
18
  schemaVersion: z.ZodLiteral<1>;
@@ -29,13 +29,13 @@ declare const schema: z.ZodObject<{
29
29
  input: z.ZodUnknown;
30
30
  }, "strict", z.ZodTypeAny, {
31
31
  state: "STAGED";
32
- sequence: number;
33
32
  operationId: string;
33
+ sequence: number;
34
34
  input?: unknown;
35
35
  }, {
36
36
  state: "STAGED";
37
- sequence: number;
38
37
  operationId: string;
38
+ sequence: number;
39
39
  input?: unknown;
40
40
  }>, z.ZodObject<{
41
41
  sequence: z.ZodNumber;
@@ -44,13 +44,13 @@ declare const schema: z.ZodObject<{
44
44
  fingerprint: z.ZodString;
45
45
  }, "strict", z.ZodTypeAny, {
46
46
  state: "OMITTED";
47
- sequence: number;
48
47
  operationId: string;
48
+ sequence: number;
49
49
  fingerprint: string;
50
50
  }, {
51
51
  state: "OMITTED";
52
- sequence: number;
53
52
  operationId: string;
53
+ sequence: number;
54
54
  fingerprint: string;
55
55
  }>, z.ZodObject<{
56
56
  sequence: z.ZodNumber;
@@ -58,29 +58,29 @@ declare const schema: z.ZodObject<{
58
58
  state: z.ZodLiteral<"SETTLED">;
59
59
  }, "strict", z.ZodTypeAny, {
60
60
  state: "SETTLED";
61
- sequence: number;
62
61
  operationId: string;
62
+ sequence: number;
63
63
  }, {
64
64
  state: "SETTLED";
65
- sequence: number;
66
65
  operationId: string;
66
+ sequence: number;
67
67
  }>]>, "many">;
68
68
  }, "strict", z.ZodTypeAny, {
69
69
  kind: "SHELL_SOURCE";
70
70
  entries: ({
71
71
  state: "STAGED";
72
- sequence: number;
73
72
  operationId: string;
73
+ sequence: number;
74
74
  input?: unknown;
75
75
  } | {
76
76
  state: "OMITTED";
77
- sequence: number;
78
77
  operationId: string;
78
+ sequence: number;
79
79
  fingerprint: string;
80
80
  } | {
81
81
  state: "SETTLED";
82
- sequence: number;
83
82
  operationId: string;
83
+ sequence: number;
84
84
  })[];
85
85
  sessionId: string;
86
86
  sessionGenerationId: string;
@@ -92,18 +92,18 @@ declare const schema: z.ZodObject<{
92
92
  kind: "SHELL_SOURCE";
93
93
  entries: ({
94
94
  state: "STAGED";
95
- sequence: number;
96
95
  operationId: string;
96
+ sequence: number;
97
97
  input?: unknown;
98
98
  } | {
99
99
  state: "OMITTED";
100
- sequence: number;
101
100
  operationId: string;
101
+ sequence: number;
102
102
  fingerprint: string;
103
103
  } | {
104
104
  state: "SETTLED";
105
- sequence: number;
106
105
  operationId: string;
106
+ sequence: number;
107
107
  })[];
108
108
  sessionId: string;
109
109
  sessionGenerationId: string;
@@ -83,6 +83,7 @@ export { executeGitStatusSummary, probeWorkspaceTreeFingerprint, getBrainstormQu
83
83
  export { runCompanionMode } from './companion-mode';
84
84
  export { pickMode, shouldRenderPlain } from './orchestration-shell';
85
85
  export { emitShellEvent, createShellEventEmitter } from './orchestration-shell';
86
+ export { classifyPromptIntentWithGemma } from './orchestration-shell/gemma-intent-classifier';
86
87
  export { processMarkers, withRoleMarker } from './orchestration-shell';
87
88
  export { ToolActivityOutbox, type ToolActivityOutboxOptions, type ListPendingResult, } from './tool-activity';
88
89
  export { ToolActivityLedger, LedgerEntrySchema, LedgerFileSchema, LegacyOwnedFileSchema, type LedgerEntry, type LedgerFile, type LegacyOwnedFile, type OccurrenceRef, type ToolActivityLedgerOptions, } from './tool-activity';