@quantiya/codevibe-core 2.0.0 → 2.0.1

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 (170) hide show
  1. package/dist/__tests__/cp-5-baseline-invariants.test.d.ts +1 -0
  2. package/dist/adapter/__tests__/capabilities.test.d.ts +1 -0
  3. package/dist/adapter/__tests__/contract-conformance.test.d.ts +1 -0
  4. package/dist/adapter/__tests__/packets.test.d.ts +1 -0
  5. package/dist/adapter/__tests__/progress.test.d.ts +1 -0
  6. package/dist/adapter/__tests__/registry.test.d.ts +1 -0
  7. package/dist/adapter/__tests__/smoke/claude.smoke.test.d.ts +1 -0
  8. package/dist/adapter/__tests__/smoke/codex.smoke.test.d.ts +1 -0
  9. package/dist/adapter/__tests__/smoke/gemini.smoke.test.d.ts +1 -0
  10. package/dist/adapter/capabilities.d.ts +68 -0
  11. package/dist/adapter/index.d.ts +7 -0
  12. package/dist/adapter/packets.d.ts +129 -0
  13. package/dist/adapter/progress.d.ts +93 -0
  14. package/dist/adapter/registry.d.ts +24 -0
  15. package/dist/adapter/types.d.ts +22 -0
  16. package/dist/appsync/__tests__/appsync-client-apply-user-decision.test.d.ts +1 -0
  17. package/dist/appsync/__tests__/appsync-client-classb.test.d.ts +1 -0
  18. package/dist/appsync/__tests__/appsync-client-planner.test.d.ts +1 -0
  19. package/dist/appsync/__tests__/appsync-client.test.d.ts +1 -0
  20. package/dist/appsync/appsync-client.d.ts +412 -0
  21. package/dist/appsync/index.d.ts +1 -1
  22. package/dist/appsync/queries.d.ts +15 -0
  23. package/dist/auth/__tests__/auth-telemetry.test.d.ts +1 -0
  24. package/dist/auth/auth-telemetry.d.ts +98 -5
  25. package/dist/companion-mode/__tests__/persist-preference.test.d.ts +1 -0
  26. package/dist/companion-mode/__tests__/resolve-agent.test.d.ts +1 -0
  27. package/dist/companion-mode/agent-picker.d.ts +9 -0
  28. package/dist/companion-mode/index.d.ts +55 -0
  29. package/dist/companion-mode/persist-preference.d.ts +24 -0
  30. package/dist/companion-mode/resolve-agent.d.ts +41 -0
  31. package/dist/index.d.ts +11 -3
  32. package/dist/index.js +243 -42
  33. package/dist/keychain/keychain-manager.d.ts +16 -2
  34. package/dist/local-executor/__tests__/authority-symlink-fixture.d.ts +15 -0
  35. package/dist/local-executor/__tests__/authority.test.d.ts +1 -0
  36. package/dist/local-executor/__tests__/class-a-emit.test.d.ts +1 -0
  37. package/dist/local-executor/__tests__/class-b-consumer.integration.test.d.ts +1 -0
  38. package/dist/local-executor/__tests__/class-b-consumer.test.d.ts +1 -0
  39. package/dist/local-executor/__tests__/hook-bridge.test.d.ts +1 -0
  40. package/dist/local-executor/__tests__/local-executor.integration.test.d.ts +1 -0
  41. package/dist/local-executor/__tests__/spawn.test.d.ts +1 -0
  42. package/dist/local-executor/__tests__/verification-runner.test.d.ts +1 -0
  43. package/dist/local-executor/authority.d.ts +29 -0
  44. package/dist/local-executor/class-a-emit.d.ts +138 -0
  45. package/dist/local-executor/class-b-consumer.d.ts +121 -0
  46. package/dist/local-executor/hook-bridge.d.ts +36 -0
  47. package/dist/local-executor/index.d.ts +8 -0
  48. package/dist/local-executor/local-executor-impl.d.ts +83 -0
  49. package/dist/local-executor/spawn.d.ts +6 -0
  50. package/dist/local-executor/types.d.ts +183 -0
  51. package/dist/local-executor/verification-gates/build.d.ts +6 -0
  52. package/dist/local-executor/verification-gates/deploy-preflight.d.ts +6 -0
  53. package/dist/local-executor/verification-gates/diff-sanity.d.ts +6 -0
  54. package/dist/local-executor/verification-gates/hostile-grep.d.ts +6 -0
  55. package/dist/local-executor/verification-gates/lint.d.ts +6 -0
  56. package/dist/local-executor/verification-gates/shell-runner.d.ts +40 -0
  57. package/dist/local-executor/verification-gates/source-traceability.d.ts +6 -0
  58. package/dist/local-executor/verification-gates/tests.d.ts +6 -0
  59. package/dist/local-executor/verification-gates/typecheck.d.ts +6 -0
  60. package/dist/local-executor/verification-runner.d.ts +28 -0
  61. package/dist/orchestration/__tests__/setup-bootstrap.test.d.ts +1 -0
  62. package/dist/orchestration/__tests__/setup-failure-recourse.test.d.ts +1 -0
  63. package/dist/orchestration/__tests__/setup-save.test.d.ts +1 -0
  64. package/dist/orchestration/__tests__/setup-seat-picker.test.d.ts +1 -0
  65. package/dist/orchestration/__tests__/setup-telemetry.test.d.ts +1 -0
  66. package/dist/orchestration/__tests__/setup-test-agents.test.d.ts +1 -0
  67. package/dist/orchestration/__tests__/setup-types.test.d.ts +1 -0
  68. package/dist/orchestration/__tests__/setup-wizard.test.d.ts +1 -0
  69. package/dist/orchestration/__tests__/v1-options.test.d.ts +1 -0
  70. package/dist/orchestration/detect-agents.d.ts +2 -1
  71. package/dist/orchestration/index.d.ts +1 -0
  72. package/dist/orchestration/orchestration-cli.d.ts +4 -1
  73. package/dist/orchestration/setup-bootstrap.d.ts +146 -0
  74. package/dist/orchestration/setup-failure-recourse.d.ts +23 -0
  75. package/dist/orchestration/setup-save.d.ts +47 -0
  76. package/dist/orchestration/setup-seat-picker.d.ts +72 -0
  77. package/dist/orchestration/setup-telemetry.d.ts +54 -0
  78. package/dist/orchestration/setup-test-agents.d.ts +108 -0
  79. package/dist/orchestration/setup-types.d.ts +140 -0
  80. package/dist/orchestration/setup-wizard.d.ts +57 -0
  81. package/dist/orchestration/v1-options.d.ts +97 -0
  82. package/dist/orchestration-shell/__tests__/cli-authority-bridge.test.d.ts +1 -0
  83. package/dist/orchestration-shell/__tests__/cli-planner-stack.test.d.ts +1 -0
  84. package/dist/orchestration-shell/__tests__/cli-singleton-enforcement.test.d.ts +1 -0
  85. package/dist/orchestration-shell/__tests__/cli-stub-session-adapter.test.d.ts +1 -0
  86. package/dist/orchestration-shell/__tests__/components.test.d.ts +1 -0
  87. package/dist/orchestration-shell/__tests__/emit-shell-event.test.d.ts +1 -0
  88. package/dist/orchestration-shell/__tests__/gate-prompts.test.d.ts +1 -0
  89. package/dist/orchestration-shell/__tests__/hostile-grep.test.d.ts +1 -0
  90. package/dist/orchestration-shell/__tests__/mode-selection.test.d.ts +1 -0
  91. package/dist/orchestration-shell/__tests__/process-markers.test.d.ts +1 -0
  92. package/dist/orchestration-shell/__tests__/reducer.test.d.ts +1 -0
  93. package/dist/orchestration-shell/__tests__/runOrchestrationShell-classify-dispatch.test.d.ts +1 -0
  94. package/dist/orchestration-shell/__tests__/runOrchestrationShell-planner-wiring.test.d.ts +1 -0
  95. package/dist/orchestration-shell/__tests__/runOrchestrationShell-signal.test.d.ts +1 -0
  96. package/dist/orchestration-shell/__tests__/runOrchestrationShell.test.d.ts +1 -0
  97. package/dist/orchestration-shell/__tests__/slash-router.test.d.ts +1 -0
  98. package/dist/orchestration-shell/__tests__/sticky-preference.test.d.ts +1 -0
  99. package/dist/orchestration-shell/cli.d.ts +96 -0
  100. package/dist/orchestration-shell/cli.js +8309 -0
  101. package/dist/orchestration-shell/cohort-flag.d.ts +16 -0
  102. package/dist/orchestration-shell/components/CodeVibeLogo.d.ts +2 -0
  103. package/dist/orchestration-shell/components/ConversationPane.d.ts +7 -0
  104. package/dist/orchestration-shell/components/GatePromptEntry.d.ts +9 -0
  105. package/dist/orchestration-shell/components/InputBar.d.ts +41 -0
  106. package/dist/orchestration-shell/components/OrchestrationApp.d.ts +63 -0
  107. package/dist/orchestration-shell/components/StatusBar.d.ts +7 -0
  108. package/dist/orchestration-shell/components/nodes/AdvisoryEntry.d.ts +8 -0
  109. package/dist/orchestration-shell/components/nodes/GateStatusNode.d.ts +8 -0
  110. package/dist/orchestration-shell/components/nodes/PlannerDecisionEntry.d.ts +8 -0
  111. package/dist/orchestration-shell/components/nodes/ReviewerQuorumStatusNode.d.ts +8 -0
  112. package/dist/orchestration-shell/components/nodes/SlashOutputEntry.d.ts +8 -0
  113. package/dist/orchestration-shell/components/nodes/SubagentEventEntry.d.ts +8 -0
  114. package/dist/orchestration-shell/components/nodes/UserMessageEntry.d.ts +8 -0
  115. package/dist/orchestration-shell/emit-shell-event.d.ts +64 -0
  116. package/dist/orchestration-shell/gate-prompts.d.ts +123 -0
  117. package/dist/orchestration-shell/index.d.ts +100 -0
  118. package/dist/orchestration-shell/ink-runtime.d.ts +64 -0
  119. package/dist/orchestration-shell/mode-selection.d.ts +46 -0
  120. package/dist/orchestration-shell/non-tty-fallback.d.ts +46 -0
  121. package/dist/orchestration-shell/process-markers.d.ts +12 -0
  122. package/dist/orchestration-shell/reducer.d.ts +8 -0
  123. package/dist/orchestration-shell/slash-router.d.ts +45 -0
  124. package/dist/orchestration-shell/sticky-preference.d.ts +24 -0
  125. package/dist/orchestration-shell/store.d.ts +17 -0
  126. package/dist/orchestration-shell/types.d.ts +417 -0
  127. package/dist/planner/__tests__/cache-clarification-bypass.test.d.ts +1 -0
  128. package/dist/planner/__tests__/cache.test.d.ts +1 -0
  129. package/dist/planner/__tests__/client.test.d.ts +1 -0
  130. package/dist/planner/__tests__/health-machine-transitions.test.d.ts +1 -0
  131. package/dist/planner/__tests__/types-zod.test.d.ts +1 -0
  132. package/dist/planner/adapter.d.ts +16 -0
  133. package/dist/planner/cache.d.ts +35 -0
  134. package/dist/planner/client.d.ts +103 -0
  135. package/dist/planner/health-state.d.ts +24 -0
  136. package/dist/planner/index.d.ts +5 -0
  137. package/dist/planner/types.d.ts +113 -0
  138. package/dist/session/__tests__/session-resume-service-keys.test.d.ts +1 -0
  139. package/dist/session/session-rekey.d.ts +40 -0
  140. package/dist/session/session-resume.d.ts +25 -0
  141. package/dist/structural-summary/__tests__/__fixtures__/fixture-helpers.d.ts +11 -0
  142. package/dist/structural-summary/__tests__/assembler.test.d.ts +1 -0
  143. package/dist/structural-summary/__tests__/generator.test.d.ts +1 -0
  144. package/dist/structural-summary/__tests__/language-detect.test.d.ts +1 -0
  145. package/dist/structural-summary/__tests__/manifest-parsers/cargo.test.d.ts +1 -0
  146. package/dist/structural-summary/__tests__/manifest-parsers/gomod.test.d.ts +1 -0
  147. package/dist/structural-summary/__tests__/manifest-parsers/gradle.test.d.ts +1 -0
  148. package/dist/structural-summary/__tests__/manifest-parsers/index.test.d.ts +1 -0
  149. package/dist/structural-summary/__tests__/manifest-parsers/npm.test.d.ts +1 -0
  150. package/dist/structural-summary/__tests__/manifest-parsers/podfile.test.d.ts +1 -0
  151. package/dist/structural-summary/__tests__/manifest-parsers/pyproject.test.d.ts +1 -0
  152. package/dist/structural-summary/__tests__/opt-in-store.test.d.ts +1 -0
  153. package/dist/structural-summary/__tests__/privacy-filter.test.d.ts +1 -0
  154. package/dist/structural-summary/__tests__/safe-file-read.test.d.ts +1 -0
  155. package/dist/structural-summary/__tests__/user-ignore-matcher.test.d.ts +1 -0
  156. package/dist/structural-summary/__tests__/walker.test.d.ts +1 -0
  157. package/dist/structural-summary/generator.d.ts +8 -0
  158. package/dist/structural-summary/index.d.ts +7 -0
  159. package/dist/structural-summary/manifest-parsers/cargo.d.ts +3 -0
  160. package/dist/structural-summary/manifest-parsers/index.d.ts +7 -0
  161. package/dist/structural-summary/manifest-parsers/npm.d.ts +3 -0
  162. package/dist/structural-summary/manifest-parsers/other.d.ts +17 -0
  163. package/dist/structural-summary/opt-in-store.d.ts +24 -0
  164. package/dist/structural-summary/privacy-filter.d.ts +110 -0
  165. package/dist/structural-summary/safe-file-read.d.ts +11 -0
  166. package/dist/structural-summary/types.d.ts +215 -0
  167. package/dist/structural-summary/user-ignore-matcher.d.ts +9 -0
  168. package/dist/structural-summary/walker.d.ts +20 -0
  169. package/dist/types/events.d.ts +17 -2
  170. package/package.json +17 -3
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";var Ar=Object.create;var we=Object.defineProperty;var Rr=Object.getOwnPropertyDescriptor;var Ir=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,Cr=Object.prototype.hasOwnProperty;var b=(r,e)=>()=>(r&&(e=r(r=0)),e);var ce=(r,e)=>{for(var t in e)we(r,t,{get:e[t],enumerable:!0})},ht=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ir(e))!Cr.call(r,i)&&i!==t&&we(r,i,{get:()=>e[i],enumerable:!(n=Rr(e,i))||n.enumerable});return r};var S=(r,e,t)=>(t=r!=null?Ar(xr(r)):{},ht(e||!r||!r.__esModule?we(t,"default",{value:r,enumerable:!0}):t,r)),vt=r=>ht(we({},"__esModule",{value:!0}),r);function _r(r,e){if(e instanceof Error){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);for(let n of Object.keys(e))n in t||(t[n]=e[n]);return t}return e}function Ue(r){return new V(r)}var Y,Se,St,wt,V,c,bt=b(()=>{"use strict";Y=S(require("fs")),Se=S(require("path")),St=S(require("os")),wt={debug:0,info:1,warn:2,error:3};V=class{constructor(e){this.name=e.name,this.logFile=e.logFile,this.level=e.level||"info",this.enableConsole=e.console??!1,this.logFile&&this.ensureLogDir()}ensureLogDir(){if(this.logFile){let e=Se.dirname(this.logFile);Y.existsSync(e)||Y.mkdirSync(e,{recursive:!0})}}shouldLog(e){return wt[e]>=wt[this.level]}formatMessage(e,t,n){let i=new Date().toISOString(),o=e.toUpperCase().padEnd(5),s=`[${i}] [${o}] [${this.name}] ${t}`;return n!==void 0&&(n instanceof Error?(s+=` ${n.name}: ${n.message}`,n.stack&&(s+=`
2
- ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,_r)}`:s+=` ${n}`),s}log(e,t,n){if(!this.shouldLog(e))return;let i=this.formatMessage(e,t,n);if(this.logFile)try{Y.appendFileSync(this.logFile,i+`
3
- `)}catch{}if(this.enableConsole)switch(e){case"error":console.error(i);break;case"warn":console.warn(i);break;default:console.log(i)}}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}setLevel(e){this.level=e}};c=new V({name:"codevibe-core",logFile:Se.join(St.tmpdir(),"codevibe-core.log"),level:"info"})});var $=b(()=>{"use strict";bt()});function Tr(r){for(let e of r)try{process.stderr.write(e+`
4
- `)}catch{}}function Pr(){Le=Be.join(Et.homedir(),".codevibe");try{N.mkdirSync(Le,{recursive:!0,mode:448})}catch{}F="file"}function Dr(){if(F!==null||Me!==null)return;let optedIn=process.env.CODEVIBE_ALLOW_FILE_KEYCHAIN==="1";if(optedIn){Tr(["","\u26A0 CodeVibe: file-based credential storage selected (CODEVIBE_ALLOW_FILE_KEYCHAIN=1).","\u26A0 Location: ~/.codevibe/ (directory 0700, files 0600)","\u26A0 Trust level: equivalent to ~/.ssh/id_rsa \u2014 weaker than OS keyring.","\u26A0 To use the OS keyring instead, unset CODEVIBE_ALLOW_FILE_KEYCHAIN and","\u26A0 install libsecret-1-0 + a running keyring daemon (Linux) or use the","\u26A0 native Keychain (macOS) / Credential Manager (Windows).",""]),c.warn("[keychain-backend] Using file-based storage at ~/.codevibe (CODEVIBE_ALLOW_FILE_KEYCHAIN=1 explicit opt-in)"),Pr();return}let keytarLoadError=null;try{let nodeRequire=eval("require");D=nodeRequire("keytar")}catch(r){keytarLoadError=r instanceof Error?r.message:String(r),D=null}if(D){F="keytar",c.info("[keychain-backend] Using keytar (OS-native keyring)");return}Me=new be(["CodeVibe could not load the OS-native keyring (keytar).",`Reason: ${keytarLoadError??"unknown"}`,"","Options to fix this:"," 1. (Linux) Install libsecret and a keyring daemon:"," sudo apt install libsecret-1-0 gnome-keyring"," Then unlock the keyring for your user session.",""," 2. (Headless / CI / Docker) Opt in to file-based credential"," storage at ~/.codevibe/ (0600 files). This is equivalent"," in trust to ~/.ssh/id_rsa \u2014 not the OS keyring:"," export CODEVIBE_ALLOW_FILE_KEYCHAIN=1"].join(`
5
- `))}function Kr(r){return r.replace(/[^a-zA-Z0-9._-]/g,"_")}function kt(r){return Be.join(Le,`${Kr(r)}.json`)}function We(r){try{let e=N.readFileSync(kt(r),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function At(r,e){let t=kt(r);N.writeFileSync(t,JSON.stringify(e,null,2),{mode:384});try{N.chmodSync(t,384)}catch{}}function Ve(){if(Dr(),F===null)throw Me??new be("Keychain backend not initialized")}async function Fe(r,e){return Ve(),F==="keytar"&&D?D.getPassword(r,e):We(r)[e]??null}async function je(r,e,t){if(Ve(),F==="keytar"&&D){await D.setPassword(r,e,t);return}let n=We(r);n[e]=t,At(r,n)}async function qe(r,e){if(Ve(),F==="keytar"&&D)return D.deletePassword(r,e);let t=We(r);return e in t?(delete t[e],At(r,t),!0):!1}var Et,Be,N,be,F,D,Le,Me,Rt=b(()=>{"use strict";Et=S(require("os")),Be=S(require("path")),N=S(require("fs"));$();be=class extends Error{constructor(e){super(e),this.name="KeychainBackendUnavailableError"}},F=null,D=null,Le="",Me=null});var T,j,Ge,$r,X,I,It=b(()=>{"use strict";T=S(require("crypto")),j=class extends Error{constructor(e){super(e),this.name="CryptoError"}},Ge=1,$r="CodeVibe E2E v1",X=class r{constructor(){}static getInstance(){return r.instance||(r.instance=new r),r.instance}generateKeyPair(){let e=T.createECDH("prime256v1");e.generateKeys();let n=e.getPublicKey().subarray(1).toString("base64");return{privateKey:e.getPrivateKey().toString("base64"),publicKey:n}}generateSessionKey(){return T.randomBytes(32).toString("base64")}deriveSharedKey(e,t){try{let n=T.createECDH("prime256v1"),i=Buffer.from(e,"base64");n.setPrivateKey(i);let o=Buffer.concat([Buffer.from([4]),Buffer.from(t,"base64")]),s=n.computeSecret(o),a=T.hkdfSync("sha256",s,Buffer.alloc(0),Buffer.from($r,"utf8"),32);return Buffer.from(a)}catch(n){throw new j(`Failed to derive shared key: ${n}`)}}encryptSessionKey(e,t){let n=this.generateKeyPair(),i=this.deriveSharedKey(n.privateKey,t),o=Buffer.from(e,"base64");return{encryptedKey:this.encrypt(o,i).toString("base64"),ephemeralPublicKey:n.publicKey}}decryptSessionKey(e,t){let n=this.deriveSharedKey(t,e.ephemeralPublicKey),i=Buffer.from(e.encryptedKey,"base64");return this.decrypt(i,n).toString("base64")}encryptContent(e,t){let n=Buffer.from(t,"base64"),i=Buffer.from(e,"utf8");return this.encrypt(i,n).toString("base64")}decryptContent(e,t){let n=Buffer.from(t,"base64"),i=Buffer.from(e,"base64");return this.decrypt(i,n).toString("utf8")}encryptMetadata(e,t){let n=JSON.stringify(e);return this.encryptContent(n,t)}decryptMetadata(e,t){let n=this.decryptContent(e,t);return JSON.parse(n)}encryptData(e,t){let n=Buffer.from(t,"base64");return this.encrypt(e,n)}decryptData(e,t){let n=Buffer.from(t,"base64");return this.decrypt(e,n)}encrypt(e,t){let n=T.randomBytes(12),i=T.createCipheriv("aes-256-gcm",t,n),o=Buffer.concat([i.update(e),i.final()]),s=i.getAuthTag();return Buffer.concat([n,o,s])}decrypt(e,t){let n=e.subarray(0,12),i=e.subarray(e.length-16),o=e.subarray(12,e.length-16),s=T.createDecipheriv("aes-256-gcm",t,n);s.setAuthTag(i);try{return Buffer.concat([s.update(o),s.final()])}catch{throw new j("Decryption failed: Invalid ciphertext or authentication tag")}}serializePrivateKey(e){return e}deserializePrivateKey(e){return e}},I=X.getInstance()});var de=b(()=>{"use strict";It()});function x(){let r=process.env.ENVIRONMENT;return r==="development"||r==="production"?r:"production"}function ke(r){let e=r||x();return Ee={...q[e],aws:{...q[e].aws,region:process.env.AWS_REGION||q[e].aws.region,appsyncUrl:process.env.APPSYNC_URL||q[e].aws.appsyncUrl,cognitoUserPoolId:process.env.COGNITO_USER_POOL_ID||q[e].aws.cognitoUserPoolId,cognitoClientId:process.env.COGNITO_CLIENT_ID||q[e].aws.cognitoClientId,cognitoDomain:process.env.COGNITO_DOMAIN||q[e].aws.cognitoDomain}},xt=!0,Ee}function k(){return(!xt||!Ee)&&ke(),Ee}var le,ue,q,Ee,xt,Ct=b(()=>{"use strict";le=S(require("os")),ue=S(require("path")),q={development:{environment:"development",aws:{region:"us-east-1",appsyncUrl:"https://te6rjr37sbfpjc4fiunmb2tgy4.appsync-api.us-east-1.amazonaws.com/graphql",cognitoUserPoolId:"us-east-1_yVwWDPvvJ",cognitoClientId:"e9r5apv6v5uui3l928r2ris0r",cognitoDomain:"codevibe-development.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:ue.default.join(le.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:ue.default.join(le.default.homedir(),".gemini","tmp")}},production:{environment:"production",aws:{region:"us-east-1",appsyncUrl:"https://jwhyxq4sgrgcdosewp5k4ns5ca.appsync-api.us-east-1.amazonaws.com/graphql",cognitoUserPoolId:"us-east-1_mNRO0j5og",cognitoClientId:"5p04dbc9ojptc5r8n7605fg78f",cognitoDomain:"codevibe-production.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:ue.default.join(le.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:ue.default.join(le.default.homedir(),".gemini","tmp")}}},Ee=null,xt=!1});var Q=b(()=>{"use strict";Ct()});var Ae,_t,K,He,Nr,G,y,Tt=b(()=>{"use strict";Ae=S(require("os")),_t=require("uuid");Rt();de();Q();$();K=class extends Error{constructor(e){super(e),this.name="KeychainError"}},He="device-identity",Nr="tokens-",G=class r{constructor(){this.deviceIdentity=null;this.sessionKeyCache=new Map;this.isRegistered=!1;this._serviceName=null}get serviceName(){return this._serviceName||(this._serviceName=k().keychain.serviceName),this._serviceName}static getInstance(){return r.instance||(r.instance=new r),r.instance}async getDeviceIdentity(){if(this.deviceIdentity)return this.deviceIdentity;let e=await Fe(this.serviceName,He);return e?(this.deviceIdentity=JSON.parse(e),c.info(`[KeychainManager] Loaded device identity: ${this.deviceIdentity.deviceId}`),this.deviceIdentity):null}async setDeviceIdentity(e){try{await je(this.serviceName,He,JSON.stringify(e)),this.deviceIdentity=e,c.info(`[KeychainManager] Saved device identity: ${e.deviceId}`)}catch(t){throw c.error(`[KeychainManager] Failed to save device identity: ${t}`),new K(`Failed to save device identity: ${t}`)}}async getOrCreateDeviceIdentity(){let e=await this.getDeviceIdentity();if(e)return e;let t=I.generateKeyPair();return e={deviceId:(0,_t.v4)().toUpperCase(),privateKey:t.privateKey,publicKey:t.publicKey,createdAt:new Date().toISOString()},await this.setDeviceIdentity(e),c.info(`[KeychainManager] Generated new device identity: ${e.deviceId}`),e}async getDeviceId(){return(await this.getOrCreateDeviceIdentity()).deviceId}async getDevicePublicKey(){return(await this.getOrCreateDeviceIdentity()).publicKey}async getDevicePrivateKey(){return(await this.getOrCreateDeviceIdentity()).privateKey}async hasDeviceIdentity(){return await this.getDeviceIdentity()!==null}async deleteDeviceIdentity(){try{await qe(this.serviceName,He),this.deviceIdentity=null,this.sessionKeyCache.clear(),this.isRegistered=!1,c.info("[KeychainManager] Deleted device identity")}catch(e){throw c.error(`[KeychainManager] Failed to delete device identity: ${e}`),new K(`Failed to delete device identity: ${e}`)}}getTokenAccount(e){return`${Nr}${e}`}async getTokens(e="production"){let t=await Fe(this.serviceName,this.getTokenAccount(e));if(!t)return null;let n=JSON.parse(t);return c.debug(`[KeychainManager] Loaded tokens for ${e}`),n}async setTokens(e,t="production"){try{await je(this.serviceName,this.getTokenAccount(t),JSON.stringify(e)),c.info(`[KeychainManager] Saved tokens for ${t}`,{userId:e.userId,email:e.email})}catch(n){throw c.error(`[KeychainManager] Failed to save tokens: ${n}`),new K(`Failed to save tokens: ${n}`)}}async deleteTokens(e="production"){try{let t=await qe(this.serviceName,this.getTokenAccount(e));return t&&c.info(`[KeychainManager] Deleted tokens for ${e}`),t}catch(t){return c.error(`[KeychainManager] Failed to delete tokens: ${t}`),!1}}isTokenExpired(e){return Date.now()>=e.expiresAt-3e5}async getSessionKey(e,t){let n=this.sessionKeyCache.get(e);if(n)return n;if(!t||t.length===0)return null;let i=await this.getDeviceId(),o=t.find(d=>d.deviceId===i);if(!o)return c.warn(`[KeychainManager] Device ${i} not found in encryptedKeys`),null;let s=await this.getDevicePrivateKey(),a=I.decryptSessionKey(o,s);return this.sessionKeyCache.set(e,a),c.info(`[KeychainManager] Decrypted and cached session key for ${e}`),a}createSessionKey(e){let t=I.generateSessionKey(),n=e.map(i=>{let o=I.encryptSessionKey(t,i.publicKey);return{deviceId:i.deviceId,encryptedKey:o.encryptedKey,ephemeralPublicKey:o.ephemeralPublicKey}});return c.info(`[KeychainManager] Created session key for ${e.length} devices`),{sessionKey:t,encryptedKeys:n}}cacheSessionKey(e,t){this.sessionKeyCache.set(e,t)}getCachedSessionKey(e){return this.sessionKeyCache.get(e)??null}getCachedSessionIds(){return Array.from(this.sessionKeyCache.keys())}clearSessionKey(e){this.sessionKeyCache.delete(e)}clearAllSessionKeys(){this.sessionKeyCache.clear()}getIsRegistered(){return this.isRegistered}setIsRegistered(e){this.isRegistered=e}getDeviceName(){return Ae.hostname()||"CLI Client"}getDevicePlatform(){let e=Ae.platform();return e==="darwin"?"MACOS":e==="linux"?"LINUX":e==="win32"?"WINDOWS":"CLI"}async clearAllData(){await this.deleteDeviceIdentity(),await this.deleteTokens("development"),await this.deleteTokens("production"),this.sessionKeyCache.clear(),this.isRegistered=!1,c.info("[KeychainManager] Cleared all data")}},y=G.getInstance()});var Pt={};ce(Pt,{KeychainError:()=>K,KeychainManager:()=>G,keychainManager:()=>y});var U=b(()=>{"use strict";Tt()});function Ur(){if(process.platform!=="linux")return!1;try{let r=Kt.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(r)}catch{return!1}}async function Z(r,e,t){try{return await fetch(r,e)}catch(n){let i=n?.cause?.code,o=n?.cause?.message,s=i||o||n?.message||"unknown",a=Lr(i),d=t?`${t}: `:"",l=`Node ${process.version} on ${process.platform}`,m=[`${d}Cannot reach ${r}`,` Underlying error: ${s}`];a&&m.push(` Suggested fix: ${a}`),m.push(` Platform: ${l}`);let u=new Error(m.join(`
6
- `));throw u.cause=n,u}}function Lr(r){if(!r)return null;switch(r){case"ENOTFOUND":case"EAI_AGAIN":return'DNS resolution failed. On WSL Ubuntu, check /etc/resolv.conf, or try running with NODE_OPTIONS="--dns-result-order=ipv4first".';case"ETIMEDOUT":case"ECONNREFUSED":case"ECONNRESET":case"EHOSTUNREACH":case"ENETUNREACH":return`Network unreachable. On WSL Ubuntu, try NODE_OPTIONS="--dns-result-order=ipv4first" (WSL's IPv6 is often broken). If behind a corporate proxy, set HTTPS_PROXY.`;case"CERT_HAS_EXPIRED":case"CERT_NOT_YET_VALID":return"TLS certificate time error \u2014 likely system clock drift. On WSL, run `sudo hwclock -s`, or shut down WSL from PowerShell with `wsl --shutdown` and restart.";case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":case"SELF_SIGNED_CERT_IN_CHAIN":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"DEPTH_ZERO_SELF_SIGNED_CERT":return"Corporate HTTPS proxy detected \u2014 the TLS cert is not trusted by Node. Set NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem, or configure HTTPS_PROXY if a proxy is required.";default:return null}}var Dt,Kt,Je=b(()=>{"use strict";Dt=S(require("dns")),Kt=S(require("fs"));if(Ur())try{Dt.setDefaultResultOrder("ipv4first")}catch{}});var H,C,ee,ze=b(()=>{"use strict";H={getSession:`
1
+ "use strict";var Jo=Object.create;var zt=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Xo=Object.getOwnPropertyNames;var Qo=Object.getPrototypeOf,Zo=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(t&&(e=t(t=0)),e);var ue=(t,e)=>{for(var r in e)zt(t,r,{get:e[r],enumerable:!0})},ri=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xo(e))!Zo.call(t,i)&&i!==r&&zt(t,i,{get:()=>e[i],enumerable:!(n=Yo(e,i))||n.enumerable});return t};var h=(t,e,r)=>(r=t!=null?Jo(Qo(t)):{},ri(e||!t||!t.__esModule?zt(r,"default",{value:t,enumerable:!0}):r,t)),ni=t=>ri(zt({},"__esModule",{value:!0}),t);function ea(t,e){if(e instanceof Error){let r={name:e.name,message:e.message};e.stack&&(r.stack=e.stack);for(let n of Object.keys(e))n in r||(r[n]=e[n]);return r}return e}function Gr(t){return new Pe(t)}var ze,jt,si,ii,Pe,u,oi=R(()=>{"use strict";ze=h(require("fs")),jt=h(require("path")),si=h(require("os")),ii={debug:0,info:1,warn:2,error:3};Pe=class{constructor(e){this.name=e.name,this.logFile=e.logFile,this.level=e.level||"info",this.enableConsole=e.console??!1,this.logFile&&this.ensureLogDir()}ensureLogDir(){if(this.logFile){let e=jt.dirname(this.logFile);ze.existsSync(e)||ze.mkdirSync(e,{recursive:!0})}}shouldLog(e){return ii[e]>=ii[this.level]}formatMessage(e,r,n){let i=new Date().toISOString(),s=e.toUpperCase().padEnd(5),o=`[${i}] [${s}] [${this.name}] ${r}`;return n!==void 0&&(n instanceof Error?(o+=` ${n.name}: ${n.message}`,n.stack&&(o+=`
2
+ ${n.stack}`)):typeof n=="object"?o+=` ${JSON.stringify(n,ea)}`:o+=` ${n}`),o}log(e,r,n){if(!this.shouldLog(e))return;let i=this.formatMessage(e,r,n);if(this.logFile)try{ze.appendFileSync(this.logFile,i+`
3
+ `)}catch{}if(this.enableConsole)switch(e){case"error":console.error(i);break;case"warn":console.warn(i);break;default:console.log(i)}}debug(e,r){this.log("debug",e,r)}info(e,r){this.log("info",e,r)}warn(e,r){this.log("warn",e,r)}error(e,r){this.log("error",e,r)}setLevel(e){this.level=e}};u=new Pe({name:"codevibe-core",logFile:jt.join(si.tmpdir(),"codevibe-core.log"),level:"info"})});var N=R(()=>{"use strict";oi()});function ta(t){for(let e of t)try{process.stderr.write(e+`
4
+ `)}catch{}}function ra(){Vr=zr.join(ai.homedir(),".codevibe");try{ve.mkdirSync(Vr,{recursive:!0,mode:448})}catch{}Ce="file"}function na(){if(Ce!==null||Hr!==null)return;let optedIn=process.env.CODEVIBE_ALLOW_FILE_KEYCHAIN==="1";if(optedIn){ta(["","\u26A0 CodeVibe: file-based credential storage selected (CODEVIBE_ALLOW_FILE_KEYCHAIN=1).","\u26A0 Location: ~/.codevibe/ (directory 0700, files 0600)","\u26A0 Trust level: equivalent to ~/.ssh/id_rsa \u2014 weaker than OS keyring.","\u26A0 To use the OS keyring instead, unset CODEVIBE_ALLOW_FILE_KEYCHAIN and","\u26A0 install libsecret-1-0 + a running keyring daemon (Linux) or use the","\u26A0 native Keychain (macOS) / Credential Manager (Windows).",""]),u.warn("[keychain-backend] Using file-based storage at ~/.codevibe (CODEVIBE_ALLOW_FILE_KEYCHAIN=1 explicit opt-in)"),ra();return}let keytarLoadError=null;try{let nodeRequire=eval("require");de=nodeRequire("keytar")}catch(t){keytarLoadError=t instanceof Error?t.message:String(t),de=null}if(de){Ce="keytar",u.info("[keychain-backend] Using keytar (OS-native keyring)");return}Hr=new qt(["CodeVibe could not load the OS-native keyring (keytar).",`Reason: ${keytarLoadError??"unknown"}`,"","Options to fix this:"," 1. (Linux) Install libsecret and a keyring daemon:"," sudo apt install libsecret-1-0 gnome-keyring"," Then unlock the keyring for your user session.",""," 2. (Headless / CI / Docker) Opt in to file-based credential"," storage at ~/.codevibe/ (0600 files). This is equivalent"," in trust to ~/.ssh/id_rsa \u2014 not the OS keyring:"," export CODEVIBE_ALLOW_FILE_KEYCHAIN=1"].join(`
5
+ `))}function ia(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_")}function ci(t){return zr.join(Vr,`${ia(t)}.json`)}function jr(t){try{let e=ve.readFileSync(ci(t),"utf-8"),r=JSON.parse(e);return r&&typeof r=="object"?r:{}}catch{return{}}}function li(t,e){let r=ci(t);ve.writeFileSync(r,JSON.stringify(e,null,2),{mode:384});try{ve.chmodSync(r,384)}catch{}}function qr(){if(na(),Ce===null)throw Hr??new qt("Keychain backend not initialized")}async function Jr(t,e){return qr(),Ce==="keytar"&&de?de.getPassword(t,e):jr(t)[e]??null}async function Yr(t,e,r){if(qr(),Ce==="keytar"&&de){await de.setPassword(t,e,r);return}let n=jr(t);n[e]=r,li(t,n)}async function Xr(t,e){if(qr(),Ce==="keytar"&&de)return de.deletePassword(t,e);let r=jr(t);return e in r?(delete r[e],li(t,r),!0):!1}var ai,zr,ve,qt,Ce,de,Vr,Hr,ui=R(()=>{"use strict";ai=h(require("os")),zr=h(require("path")),ve=h(require("fs"));N();qt=class extends Error{constructor(e){super(e),this.name="KeychainBackendUnavailableError"}},Ce=null,de=null,Vr="",Hr=null});var Q,pe,vt,oa,je,$,di=R(()=>{"use strict";Q=h(require("crypto")),pe=class extends Error{constructor(e){super(e),this.name="CryptoError"}},vt=1,oa="CodeVibe E2E v1",je=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}generateKeyPair(){let e=Q.createECDH("prime256v1");e.generateKeys();let n=e.getPublicKey().subarray(1).toString("base64");return{privateKey:e.getPrivateKey().toString("base64"),publicKey:n}}generateSessionKey(){return Q.randomBytes(32).toString("base64")}deriveSharedKey(e,r){try{let n=Q.createECDH("prime256v1"),i=Buffer.from(e,"base64");n.setPrivateKey(i);let s=Buffer.from(r,"base64"),o=s.length===65&&s[0]===4?s:Buffer.concat([Buffer.from([4]),s]),a=n.computeSecret(o),c=Q.hkdfSync("sha256",a,Buffer.alloc(0),Buffer.from(oa,"utf8"),32);return Buffer.from(c)}catch(n){throw new pe(`Failed to derive shared key: ${n}`)}}encryptSessionKey(e,r){let n=this.generateKeyPair(),i=this.deriveSharedKey(n.privateKey,r),s=Buffer.from(e,"base64");return{encryptedKey:this.encrypt(s,i).toString("base64"),ephemeralPublicKey:n.publicKey}}decryptSessionKey(e,r){let n=this.deriveSharedKey(r,e.ephemeralPublicKey),i=Buffer.from(e.encryptedKey,"base64");return this.decrypt(i,n).toString("base64")}encryptContent(e,r){let n=Buffer.from(r,"base64"),i=Buffer.from(e,"utf8");return this.encrypt(i,n).toString("base64")}decryptContent(e,r){let n=Buffer.from(r,"base64"),i=Buffer.from(e,"base64");return this.decrypt(i,n).toString("utf8")}encryptMetadata(e,r){let n=JSON.stringify(e);return this.encryptContent(n,r)}decryptMetadata(e,r){let n=this.decryptContent(e,r);return JSON.parse(n)}encryptData(e,r){let n=Buffer.from(r,"base64");return this.encrypt(e,n)}decryptData(e,r){let n=Buffer.from(r,"base64");return this.decrypt(e,n)}encrypt(e,r){let n=Q.randomBytes(12),i=Q.createCipheriv("aes-256-gcm",r,n),s=Buffer.concat([i.update(e),i.final()]),o=i.getAuthTag();return Buffer.concat([n,s,o])}decrypt(e,r){let n=e.subarray(0,12),i=e.subarray(e.length-16),s=e.subarray(12,e.length-16),o=Q.createDecipheriv("aes-256-gcm",r,n);o.setAuthTag(i);try{return Buffer.concat([o.update(s),o.final()])}catch{throw new pe("Decryption failed: Invalid ciphertext or authentication tag")}}serializePrivateKey(e){return e}deserializePrivateKey(e){return e}},$=je.getInstance()});var Te=R(()=>{"use strict";di()});function J(){let t=process.env.ENVIRONMENT;return t==="development"||t==="production"?t:"production"}function Yt(t){let e=t||J();return Jt={...Oe[e],aws:{...Oe[e].aws,region:process.env.AWS_REGION||Oe[e].aws.region,appsyncUrl:process.env.APPSYNC_URL||Oe[e].aws.appsyncUrl,cognitoUserPoolId:process.env.COGNITO_USER_POOL_ID||Oe[e].aws.cognitoUserPoolId,cognitoClientId:process.env.COGNITO_CLIENT_ID||Oe[e].aws.cognitoClientId,cognitoDomain:process.env.COGNITO_DOMAIN||Oe[e].aws.cognitoDomain}},pi=!0,Jt}function M(){return(!pi||!Jt)&&Yt(),Jt}var wt,Et,Oe,Jt,pi,mi=R(()=>{"use strict";wt=h(require("os")),Et=h(require("path")),Oe={development:{environment:"development",aws:{region:"us-east-1",appsyncUrl:"https://api-dev.codevibe.quantiya.ai/graphql",cognitoUserPoolId:"us-east-1_yVwWDPvvJ",cognitoClientId:"e9r5apv6v5uui3l928r2ris0r",cognitoDomain:"codevibe-development.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:Et.default.join(wt.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:Et.default.join(wt.default.homedir(),".gemini","tmp")}},production:{environment:"production",aws:{region:"us-east-1",appsyncUrl:"https://api.codevibe.quantiya.ai/graphql",cognitoUserPoolId:"us-east-1_mNRO0j5og",cognitoClientId:"5p04dbc9ojptc5r8n7605fg78f",cognitoDomain:"codevibe-production.auth.us-east-1.amazoncognito.com"},keychain:{serviceName:"ai.quantiya.app.codevibe"},server:{port:3456,host:"127.0.0.1",dynamicPort:!0},claude:{command:"claude",defaultTimeout:6e4},codex:{command:"codex",defaultTimeout:6e4,sessionsDir:Et.default.join(wt.default.homedir(),".codex","sessions"),approvalTimeoutMs:5e3},gemini:{command:"gemini",defaultTimeout:6e4,transcriptDir:Et.default.join(wt.default.homedir(),".gemini","tmp")}}},Jt=null,pi=!1});var qe=R(()=>{"use strict";mi()});var Xt,fi,me,Qr,aa,De,k,gi=R(()=>{"use strict";Xt=h(require("os")),fi=require("uuid");ui();Te();qe();N();me=class extends Error{constructor(e){super(e),this.name="KeychainError"}},Qr="device-identity",aa="tokens-",De=class t{constructor(){this.deviceIdentity=null;this.sessionKeyCache=new Map;this.isRegistered=!1;this._serviceName=null}get serviceName(){return this._serviceName||(this._serviceName=M().keychain.serviceName),this._serviceName}static getInstance(){return t.instance||(t.instance=new t),t.instance}async getDeviceIdentity(){if(this.deviceIdentity)return this.deviceIdentity;let e=await Jr(this.serviceName,Qr);return e?(this.deviceIdentity=JSON.parse(e),u.info(`[KeychainManager] Loaded device identity: ${this.deviceIdentity.deviceId}`),this.deviceIdentity):null}async setDeviceIdentity(e){try{await Yr(this.serviceName,Qr,JSON.stringify(e)),this.deviceIdentity=e,u.info(`[KeychainManager] Saved device identity: ${e.deviceId}`)}catch(r){throw u.error(`[KeychainManager] Failed to save device identity: ${r}`),new me(`Failed to save device identity: ${r}`)}}async getOrCreateDeviceIdentity(){let e=await this.getDeviceIdentity();if(e)return e;let r=$.generateKeyPair();return e={deviceId:(0,fi.v4)().toUpperCase(),privateKey:r.privateKey,publicKey:r.publicKey,createdAt:new Date().toISOString()},await this.setDeviceIdentity(e),u.info(`[KeychainManager] Generated new device identity: ${e.deviceId}`),e}async getDeviceId(){return(await this.getOrCreateDeviceIdentity()).deviceId}async getDevicePublicKey(){return(await this.getOrCreateDeviceIdentity()).publicKey}async getDevicePrivateKey(){return(await this.getOrCreateDeviceIdentity()).privateKey}async hasDeviceIdentity(){return await this.getDeviceIdentity()!==null}async deleteDeviceIdentity(){try{await Xr(this.serviceName,Qr),this.deviceIdentity=null,this.sessionKeyCache.clear(),this.isRegistered=!1,u.info("[KeychainManager] Deleted device identity")}catch(e){throw u.error(`[KeychainManager] Failed to delete device identity: ${e}`),new me(`Failed to delete device identity: ${e}`)}}getTokenAccount(e){return`${aa}${e}`}async getTokens(e="production"){let r=await Jr(this.serviceName,this.getTokenAccount(e));if(!r)return null;let n=JSON.parse(r);return u.debug(`[KeychainManager] Loaded tokens for ${e}`),n}async setTokens(e,r="production"){try{await Yr(this.serviceName,this.getTokenAccount(r),JSON.stringify(e)),u.info(`[KeychainManager] Saved tokens for ${r}`,{userId:e.userId,email:e.email})}catch(n){throw u.error(`[KeychainManager] Failed to save tokens: ${n}`),new me(`Failed to save tokens: ${n}`)}}async deleteTokens(e="production"){try{let r=await Xr(this.serviceName,this.getTokenAccount(e));return r&&u.info(`[KeychainManager] Deleted tokens for ${e}`),r}catch(r){return u.error(`[KeychainManager] Failed to delete tokens: ${r}`),!1}}isTokenExpired(e){return Date.now()>=e.expiresAt-3e5}async getSessionKey(e,r){let n=this.sessionKeyCache.get(e);if(n)return n;if(!r||r.length===0)return null;let i=await this.getDeviceId(),s=r.find(c=>c.deviceId===i);if(!s)return u.warn(`[KeychainManager] Device ${i} not found in encryptedKeys`),null;let o=await this.getDevicePrivateKey(),a=$.decryptSessionKey(s,o);return this.sessionKeyCache.set(e,a),u.info(`[KeychainManager] Decrypted and cached session key for ${e}`),a}createSessionKey(e,r){let n=$.generateSessionKey(),i=[],s=[];for(let o of e)try{let a=$.encryptSessionKey(n,o.publicKey);i.push({deviceId:o.deviceId,encryptedKey:a.encryptedKey,ephemeralPublicKey:a.ephemeralPublicKey})}catch(a){u.warn("[KeychainManager] Skipping device with invalid public key",{deviceId:o.deviceId,error:a instanceof Error?a.message:String(a)}),s.push(o.deviceId);try{r?.onDeviceSkipped?.(s.length)}catch{}}if(i.length===0)throw new pe(`Failed to encrypt session key for any of ${e.length} devices`);return u.info("[KeychainManager] Created session key",{encryptedCount:i.length,skippedCount:s.length,totalCount:e.length}),{sessionKey:n,encryptedKeys:i,skippedDeviceIds:s}}cacheSessionKey(e,r){this.sessionKeyCache.set(e,r)}getCachedSessionKey(e){return this.sessionKeyCache.get(e)??null}getCachedSessionIds(){return Array.from(this.sessionKeyCache.keys())}clearSessionKey(e){this.sessionKeyCache.delete(e)}clearAllSessionKeys(){this.sessionKeyCache.clear()}getIsRegistered(){return this.isRegistered}setIsRegistered(e){this.isRegistered=e}getDeviceName(){return Xt.hostname()||"CLI Client"}getDevicePlatform(){let e=Xt.platform();return e==="darwin"?"MACOS":e==="linux"?"LINUX":e==="win32"?"WINDOWS":"CLI"}async clearAllData(){await this.deleteDeviceIdentity(),await this.deleteTokens("development"),await this.deleteTokens("production"),this.sessionKeyCache.clear(),this.isRegistered=!1,u.info("[KeychainManager] Cleared all data")}},k=De.getInstance()});var yi={};ue(yi,{KeychainError:()=>me,KeychainManager:()=>De,keychainManager:()=>k});var re=R(()=>{"use strict";gi()});function ca(){if(process.platform!=="linux")return!1;try{let t=Si.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(t)}catch{return!1}}async function Je(t,e,r){try{return await fetch(t,e)}catch(n){let i=n?.cause?.code,s=n?.cause?.message,o=i||s||n?.message||"unknown",a=la(i),c=r?`${r}: `:"",l=`Node ${process.version} on ${process.platform}`,d=[`${c}Cannot reach ${t}`,` Underlying error: ${o}`];a&&d.push(` Suggested fix: ${a}`),d.push(` Platform: ${l}`);let p=new Error(d.join(`
6
+ `));throw p.cause=n,p}}function la(t){if(!t)return null;switch(t){case"ENOTFOUND":case"EAI_AGAIN":return'DNS resolution failed. On WSL Ubuntu, check /etc/resolv.conf, or try running with NODE_OPTIONS="--dns-result-order=ipv4first".';case"ETIMEDOUT":case"ECONNREFUSED":case"ECONNRESET":case"EHOSTUNREACH":case"ENETUNREACH":return`Network unreachable. On WSL Ubuntu, try NODE_OPTIONS="--dns-result-order=ipv4first" (WSL's IPv6 is often broken). If behind a corporate proxy, set HTTPS_PROXY.`;case"CERT_HAS_EXPIRED":case"CERT_NOT_YET_VALID":return"TLS certificate time error \u2014 likely system clock drift. On WSL, run `sudo hwclock -s`, or shut down WSL from PowerShell with `wsl --shutdown` and restart.";case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":case"SELF_SIGNED_CERT_IN_CHAIN":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"DEPTH_ZERO_SELF_SIGNED_CERT":return"Corporate HTTPS proxy detected \u2014 the TLS cert is not trusted by Node. Set NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem, or configure HTTPS_PROXY if a proxy is required.";default:return null}}var hi,Si,Zr=R(()=>{"use strict";hi=h(require("dns")),Si=h(require("fs"));if(ca())try{hi.setDefaultResultOrder("ipv4first")}catch{}});var oe,U,Ne,en=R(()=>{"use strict";oe={getSession:`
7
7
  query GetSession($sessionId: ID!) {
8
8
  getSession(sessionId: $sessionId) {
9
9
  sessionId
@@ -66,7 +66,39 @@ ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,_r)}`:s+=` ${n}`),s}log
66
66
  lastUsedAt
67
67
  }
68
68
  }
69
- `},C={createSession:`
69
+ `,listServiceDeviceKeys:`
70
+ query ListServiceDeviceKeys {
71
+ listServiceDeviceKeys {
72
+ userId
73
+ deviceId
74
+ publicKey
75
+ platform
76
+ deviceName
77
+ createdAt
78
+ lastUsedAt
79
+ }
80
+ }
81
+ `,listSessions:`
82
+ query ListSessions($userId: ID!, $limit: Int, $nextToken: String) {
83
+ listSessions(userId: $userId, limit: $limit, nextToken: $nextToken) {
84
+ items {
85
+ sessionId
86
+ agentType
87
+ status
88
+ lastHeartbeatAt
89
+ }
90
+ nextToken
91
+ }
92
+ }
93
+ `,getSubscriptionStatus:`
94
+ query GetSubscriptionStatus {
95
+ getSubscriptionStatus {
96
+ tier
97
+ status
98
+ expiresAt
99
+ }
100
+ }
101
+ `},U={createSession:`
70
102
  mutation CreateSession($input: CreateSessionInput!) {
71
103
  createSession(input: $input) {
72
104
  sessionId
@@ -158,6 +190,21 @@ ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,_r)}`:s+=` ${n}`),s}log
158
190
  updatedAt
159
191
  }
160
192
  }
193
+ `,updateAdapterCapabilities:`
194
+ mutation UpdateAdapterCapabilities($capabilities: AWSJSON!) {
195
+ updateAdapterCapabilities(capabilities: $capabilities) {
196
+ userId
197
+ availableAgents
198
+ adapterCapabilities
199
+ reviewerSeats {
200
+ seatId
201
+ role
202
+ agent
203
+ modelHint
204
+ }
205
+ updatedAt
206
+ }
207
+ }
161
208
  `,updateReviewerPolicy:`
162
209
  mutation UpdateReviewerPolicy($input: UpdateReviewerPolicyInput!) {
163
210
  updateReviewerPolicy(input: $input) {
@@ -173,7 +220,34 @@ ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,_r)}`:s+=` ${n}`),s}log
173
220
  updatedAt
174
221
  }
175
222
  }
176
- `},ee={onEventCreated:`
223
+ `,classifyPlannerPrompt:`
224
+ mutation ClassifyPlannerPrompt($input: ClassifyPlannerPromptInput!) {
225
+ classifyPlannerPrompt(input: $input) {
226
+ decision
227
+ cacheHit
228
+ cacheKind
229
+ serverLatencyMs
230
+ providerUsed
231
+ }
232
+ }
233
+ `,pingPlanner:`
234
+ mutation PingPlanner($input: PingPlannerInput!) {
235
+ pingPlanner(input: $input) {
236
+ ok
237
+ ms
238
+ }
239
+ }
240
+ `,applyUserDecision:`
241
+ mutation ApplyUserDecision($input: ApplyUserDecisionInput!) {
242
+ applyUserDecision(input: $input) {
243
+ sessionId
244
+ taskId
245
+ gateId
246
+ decision
247
+ payload
248
+ }
249
+ }
250
+ `},Ne={onEventCreated:`
177
251
  subscription OnEventCreated($sessionId: ID!) {
178
252
  onEventCreated(sessionId: $sessionId) {
179
253
  eventId
@@ -212,11 +286,118 @@ ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,_r)}`:s+=` ${n}`),s}log
212
286
  lastUsedAt
213
287
  }
214
288
  }
215
- `}});var Ot,Ye,$t,Nt=b(()=>{"use strict";Ot=(a=>(a.USER_PROMPT="USER_PROMPT",a.ASSISTANT_RESPONSE="ASSISTANT_RESPONSE",a.TOOL_USE="TOOL_USE",a.NOTIFICATION="NOTIFICATION",a.INTERACTIVE_PROMPT="INTERACTIVE_PROMPT",a.PROMPT_RESPONSE="PROMPT_RESPONSE",a.REASONING="REASONING",a))(Ot||{}),Ye=(t=>(t.DESKTOP="DESKTOP",t.MOBILE="MOBILE",t))(Ye||{}),$t=(n=>(n.SENT="SENT",n.DELIVERED="DELIVERED",n.EXECUTED="EXECUTED",n))($t||{})});var Xe,Ut,Lt=b(()=>{"use strict";Xe=(n=>(n.ACTIVE="ACTIVE",n.INACTIVE="INACTIVE",n.PAUSED="PAUSED",n))(Xe||{}),Ut=(n=>(n.CLAUDE="CLAUDE",n.GEMINI="GEMINI",n.CODEX="CODEX",n))(Ut||{})});var Mt=b(()=>{"use strict"});var Bt=b(()=>{"use strict"});var Qe,Wt=b(()=>{"use strict";Qe=(l=>(l.ARCHITECTURE="ARCHITECTURE",l.CORRECTNESS="CORRECTNESS",l.SECURITY="SECURITY",l.ACCURACY="ACCURACY",l.CLARITY="CLARITY",l.COMPLETENESS="COMPLETENESS",l.ARCHITECTURE_AND_ACCURACY="ARCHITECTURE_AND_ACCURACY",l.CORRECTNESS_AND_CLARITY="CORRECTNESS_AND_CLARITY",l.SECURITY_AND_COMPLETENESS="SECURITY_AND_COMPLETENESS",l))(Qe||{})});var pe=b(()=>{"use strict";Nt();Lt();Mt();Bt();Wt()});var ge,me,P,J,Vt=b(()=>{"use strict";ge=S(require("ws")),me=require("uuid");Q();$();U();Je();ze();pe();P={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3},J=class{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.activeSubscriptions=new Map;this.deviceKeyWatcher=null;this.heartbeatTimers=new Map;this.environment=x(),c.info("[AppSyncClient] Initialized",{environment:this.environment})}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}async authenticateWithStoredTokens(){try{let e=await y.getTokens(this.environment);if(!e)return c.debug("[AppSyncClient] No stored tokens found"),!1;if(c.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:y.isTokenExpired(e)}),y.isTokenExpired(e)){if(c.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return c.warn("[AppSyncClient] Token refresh failed"),!1}else this.tokens=e;return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,c.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){return c.error("[AppSyncClient] Authentication failed:",e),!1}}async refreshTokens(e){try{let t=k(),n=`https://${t.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e.refreshToken}),o=await Z(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");if(!o.ok)return c.error("[AppSyncClient] Token refresh failed",{status:o.status}),!1;let s=await o.json(),a={...e,accessToken:s.access_token,idToken:s.id_token,expiresAt:Date.now()+s.expires_in*1e3};return await y.setTokens(a,this.environment),this.tokens=a,c.info("[AppSyncClient] Tokens refreshed",{expiresAt:new Date(a.expiresAt).toISOString()}),!0}catch(t){return c.error("[AppSyncClient] Token refresh error:",t),!1}}isAuthenticated(){return this.authenticated}signOut(){this.authenticated=!1,this.tokens=null,this.currentUserId=null,this.currentEmail=null,this.cleanupSubscriptions(),c.info("[AppSyncClient] Signed out")}async graphqlRequest(e,t,n=!1){let i=k();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let o={"Content-Type":"application/json",Authorization:this.tokens.idToken},s=await Z(i.aws.appsyncUrl,{method:"POST",headers:o,body:JSON.stringify({query:e,variables:t})},"AppSync GraphQL request"),a=await s.json();if(s.status===401&&!n&&this.tokens){if(c.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),await this.refreshTokens(this.tokens))return this.graphqlRequest(e,t,!0);throw new Error("Token expired and refresh failed")}if(!s.ok)throw new Error(`GraphQL request failed: ${s.status}`);if(a.errors?.length)throw new Error(`GraphQL error: ${a.errors[0].message}`);return a}async createSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(C.createSession,{input:t});return c.info("[AppSyncClient] Session created",{sessionId:n.data.createSession.sessionId}),n.data.createSession}async updateSession(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(C.updateSession,{input:t});return c.debug("[AppSyncClient] Session updated",{sessionId:n.data.updateSession.sessionId}),n.data.updateSession}async getSession(e){return(await this.graphqlRequest(H.getSession,{sessionId:e})).data.getSession}async createEvent(e){let t={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(C.createEvent,{input:t});return c.debug("[AppSyncClient] Event created",{eventId:n.data.createEvent.eventId,type:n.data.createEvent.type}),n.data.createEvent}async updateEventStatus(e){return(await this.graphqlRequest(C.updateEventStatus,{input:e})).data.updateEventStatus}async listEvents(e,t,n){return(await this.graphqlRequest(H.listEvents,{sessionId:e,source:t,limit:n})).data.listEvents.items}async listUserDeviceKeys(){return(await this.graphqlRequest(H.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async registerDeviceKey(e,t,n,i){let o={deviceId:e,publicKey:t,platform:n,deviceName:i};await this.graphqlRequest(C.registerDeviceKey,{input:o}),c.info("[AppSyncClient] Device key registered",{deviceId:e,platform:n})}async grantSessionKey(e){await this.graphqlRequest(C.grantSessionKey,{input:e}),c.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(C.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}async updateAvailableAgents(e){let t=await this.graphqlRequest(C.updateAvailableAgents,{agents:e});return c.info("[AppSyncClient] Updated available agents",{agents:e}),t.data.updateAvailableAgents}async updateReviewerPolicy(e){let t=await this.graphqlRequest(C.updateReviewerPolicy,{input:e});return c.info("[AppSyncClient] Updated reviewer policy",{orchestrationEnabledDefault:e.orchestrationEnabledDefault,reviewerSeatCount:e.reviewerSeats?.length}),t.data.updateReviewerPolicy}subscribeToEvents(e,t,n){c.info("[AppSyncClient] Subscribing to events",{sessionId:e});let i=this.activeSubscriptions.get(e);i&&(this.cleanupSubscriptionState(i),this.activeSubscriptions.delete(e));let o={ws:null,subscriptionId:(0,me.v4)(),sessionId:e,onEvent:t,onError:n,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,o),this.createSubscription(o),()=>{this.cleanupSubscriptionState(o),this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=k(),t=e.aws.appsyncUrl.replace("https://","wss://").replace("appsync-api","appsync-realtime-api"),n={host:new URL(e.aws.appsyncUrl).host};this.tokens?.idToken&&(n.Authorization=this.tokens.idToken);let i=Buffer.from(JSON.stringify(n)).toString("base64"),o=Buffer.from(JSON.stringify({})).toString("base64");return`${t}?header=${i}&payload=${o}`}createSubscription(e){let{sessionId:t,subscriptionId:n,onEvent:i,onError:o}=e;try{let s=this.buildRealtimeUrl(),a=new ge.default(s,["graphql-ws"]);a.on("open",()=>{c.info("[AppSyncClient] WebSocket connected",{sessionId:t}),a.send(JSON.stringify({type:"connection_init"}))}),a.on("message",d=>{try{let l=JSON.parse(d.toString());switch(l.type){case"connection_ack":this.sendSubscriptionStart(a,e);break;case"start_ack":c.info("[AppSyncClient] Subscription started",{sessionId:t}),e.isReconnecting=!1,e.reconnectAttempts=0,this.startHeartbeat(t);break;case"data":this.resetKeepAliveTimer(e);let m=l.payload?.data?.onEventCreated;m&&m.source==="MOBILE"&&i(m);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let u=l.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(u));break}}catch(l){c.error("[AppSyncClient] Failed to parse message",{error:l})}}),a.on("error",d=>{c.error("[AppSyncClient] WebSocket error",{sessionId:t,error:d.message}),this.handleSubscriptionError(e,d)}),a.on("close",(d,l)=>{c.info("[AppSyncClient] WebSocket closed",{sessionId:t,code:d}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(t)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${d}`))}),e.ws=a,this.resetKeepAliveTimer(e)}catch(s){this.handleSubscriptionError(e,s)}}sendSubscriptionStart(e,t){let n=k(),{sessionId:i,subscriptionId:o}=t,s={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(s.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:o,type:"start",payload:{data:JSON.stringify({query:ee.onEventCreated,variables:{sessionId:i}}),extensions:{authorization:s}}}))}resetKeepAliveTimer(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSubscriptionError(e,new Error("Keep-alive timeout"))},300*1e3)}handleSubscriptionError(e,t){let{sessionId:n,onError:i}=e;if(e.isReconnecting||!this.activeSubscriptions.has(n))return;e.isReconnecting=!0,e.reconnectAttempts++,this.stopHeartbeat(n);let o=e.reconnectAttempts<=P.urgentMaxAttempts,s;if(o?s=Math.min(P.baseDelayMs*Math.pow(P.backoffMultiplier,e.reconnectAttempts-1),P.maxDelayMs):(s=P.persistentDelayMs,e.reconnectAttempts===P.urgentMaxAttempts+1&&c.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:n})),c.info("[AppSyncClient] Scheduling reconnect",{sessionId:n,attempt:e.reconnectAttempts,phase:o?"urgent":"persistent",delayMs:s}),e.ws){try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(n)!==e){c.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:n});return}try{let a=await y.getTokens(this.environment);a&&(y.isTokenExpired(a)?await this.refreshTokens(a)&&c.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:n}):this.tokens=a)}catch{c.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:n})}if(e.destroyed||this.activeSubscriptions.get(n)!==e){c.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:n});return}e.subscriptionId=(0,me.v4)(),this.createSubscription(e)},s)}cleanupSubscriptionState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===ge.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}subscribeToDeviceKeyRegistered(e,t,n,i){c.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let o={userId:e,subscriptionId:(0,me.v4)(),ws:null,onNewDevice:t,onReconnect:n,onError:i,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.deviceKeyWatcher=o,this.createDeviceKeyWatcherConnection(o),()=>{this.stopDeviceKeyWatcherInternal()}}stopDeviceKeyWatcher(){this.stopDeviceKeyWatcherInternal()}stopDeviceKeyWatcherInternal(){let e=this.deviceKeyWatcher;if(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===ge.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}this.deviceKeyWatcher=null,c.info("[AppSyncClient] Device key watcher stopped")}}createDeviceKeyWatcherConnection(e){try{let t=this.buildRealtimeUrl(),n=new ge.default(t,["graphql-ws"]);n.on("open",()=>{c.info("[AppSyncClient] Device key watcher WebSocket connected",{userId:e.userId}),n.send(JSON.stringify({type:"connection_init"}))}),n.on("message",i=>{try{let o=JSON.parse(i.toString());switch(o.type){case"connection_ack":this.sendDeviceKeyWatcherStart(n,e);break;case"start_ack":c.info("[AppSyncClient] Device key watcher subscription started",{userId:e.userId});let s=e.isReconnecting;if(e.isReconnecting=!1,e.reconnectAttempts=0,s&&e.onReconnect)try{e.onReconnect()}catch(l){c.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:l})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let a=o.payload?.data?.onDeviceKeyRegistered;if(a){c.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:a.deviceId,platform:a.platform});try{e.onNewDevice(a)}catch(l){c.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:l})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let d=o.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(d));break}}catch(o){c.error("[AppSyncClient] Failed to parse device key watcher message",{error:o})}}),n.on("error",i=>{c.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleDeviceKeyWatcherError(e,i)}),n.on("close",i=>{c.info("[AppSyncClient] Device key watcher WebSocket closed",{userId:e.userId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.deviceKeyWatcher===e&&this.handleDeviceKeyWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=n,this.resetDeviceKeyWatcherKeepAlive(e)}catch(t){this.handleDeviceKeyWatcherError(e,t)}}sendDeviceKeyWatcherStart(e,t){let n=k(),{userId:i,subscriptionId:o}=t,s={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(s.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:o,type:"start",payload:{data:JSON.stringify({query:ee.onDeviceKeyRegistered,variables:{userId:i}}),extensions:{authorization:s}}}))}resetDeviceKeyWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleDeviceKeyWatcherError(e,new Error("Device key watcher keep-alive timeout"))},300*1e3)}handleDeviceKeyWatcherError(e,t){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(t)}catch{}if(e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=P.urgentMaxAttempts?Math.min(P.baseDelayMs*Math.pow(P.backoffMultiplier,e.reconnectAttempts-1),P.maxDelayMs):P.persistentDelayMs;c.warn("[AppSyncClient] Device key watcher reconnect scheduled",{userId:e.userId,attempts:e.reconnectAttempts,delayMs:i,error:t.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.deviceKeyWatcher!==e){c.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}try{let o=await y.getTokens(this.environment);o&&(y.isTokenExpired(o)?await this.refreshTokens(o)&&c.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId}):this.tokens=o)}catch{c.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,me.v4)(),this.createDeviceKeyWatcherConnection(e))},i)}startHeartbeat(e,t=120*1e3){this.stopHeartbeat(e),this.sendHeartbeat(e);let n=setInterval(()=>{this.sendHeartbeat(e)},t);this.heartbeatTimers.set(e,n),c.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:t})}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e),c.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async sendHeartbeat(e){try{await this.updateSession({sessionId:e,lastHeartbeatAt:new Date().toISOString()}),c.debug("[AppSyncClient] Heartbeat sent",{sessionId:e})}catch(t){c.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:t})}}cleanupSubscriptions(){this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear(),this.stopDeviceKeyWatcherInternal(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear()}}});var Re=b(()=>{"use strict";Vt();ze()});function L(){let r=[];for(let e of["CLAUDE","GEMINI","CODEX"])Gr(e)&&r.push(e);return c.debug("[detectInstalledAgents] Detected",{detected:r}),r}function Gr(r){try{return(0,Zt.execSync)(`command -v ${qr[r]}`,{stdio:"ignore",shell:"/bin/sh"}),!0}catch{return!1}}async function Ie(r,e){let t=L();if(t.length===0){e.warn("No AI coding agents detected on PATH \u2014 skipping updateAvailableAgents");return}await r.updateAvailableAgents(t),e.info("Pushed available agents to backend",{agents:t})}async function xe(r,e,t){let n=process.env.CODEVIBE_ORCHESTRATION_OVERRIDE;if(n!=="true"&&n!=="false")return;let i=n==="true";try{await r.updateSession({sessionId:e,orchestrationEnabled:i}),t.info("Applied per-session orchestration override",{sessionId:e,enabled:i})}catch(o){t.warn("Failed to apply per-session orchestration override",{sessionId:e,enabled:i,error:o?.message})}}var Zt,qr,nt=b(()=>{"use strict";Zt=require("child_process");$();qr={CLAUDE:"claude",GEMINI:"gemini",CODEX:"codex"}});async function Ce(r){let t=r.slice(3).filter(n=>!n.startsWith("--"))[0];switch(t){case"enable":await zr();break;case"disable":await Yr();break;case"status":await Xr();break;case"configure":await Qr();break;default:Jr(),process.exit(t?1:0)}}function Jr(){console.log(""),console.log(`${p.bold}codevibe orchestration${p.reset} \u2014 Quorum 2.0 reviewer policy`),console.log(""),console.log("Usage: codevibe orchestration <command>"),console.log(""),console.log("Commands:"),console.log(" enable Auto-enable orchestration for new sessions"),console.log(" disable Disable orchestration (sessions route to 1.0 flow)"),console.log(" status Show current reviewer policy + installed agents"),console.log(" configure Interactive wizard (toggle + customize panel)"),console.log("")}async function zr(){let e=await(await _e()).updateReviewerPolicy({orchestrationEnabledDefault:!0});ot(e),console.log(`
216
- ${p.green}\u2713${p.reset} Orchestration enabled. New sessions will use your reviewer panel.`)}async function Yr(){let e=await(await _e()).updateReviewerPolicy({orchestrationEnabledDefault:!1});ot(e),console.log(`
217
- ${p.yellow}\u2713${p.reset} Orchestration disabled. New sessions route to the 1.0 companion flow.`)}async function Xr(){let r=L();if(console.log(""),console.log(`${p.bold}Installed agents${p.reset}`),r.length===0)console.log(` ${p.dim}(none detected on PATH)${p.reset}`);else for(let n of r)console.log(` ${p.green}\u2713${p.reset} ${n.toLowerCase()}`);console.log("");let t=await(await _e()).updateAvailableAgents(r);ot(t)}async function Qr(){let r=L();r.length===0&&(console.log(""),console.log(`${p.yellow}No agents detected on PATH.${p.reset}`),console.log(`Install at least one of ${p.bold}claude${p.reset}, ${p.bold}gemini${p.reset}, or ${p.bold}codex${p.reset} before configuring orchestration.`),process.exit(1)),console.log(""),console.log(`${p.bold}Quorum 2.0 orchestration configuration${p.reset}`),console.log(`${p.dim}Detected agents: ${r.map(n=>n.toLowerCase()).join(", ")}${p.reset}`),console.log("");let e=await _e();await e.updateAvailableAgents(r);let t=rr.createInterface({input:process.stdin,output:process.stdout});try{if(!await er(t,"Enable orchestration for new sessions?",!1)){await e.updateReviewerPolicy({orchestrationEnabledDefault:!1}),console.log(`
218
- ${p.yellow}\u2713${p.reset} Orchestration disabled.`);return}if(!await er(t,"Customize reviewer panel (otherwise use tier defaults)?",!1)){await e.updateReviewerPolicy({orchestrationEnabledDefault:!0,reviewerSeats:[]}),console.log(`
219
- ${p.green}\u2713${p.reset} Orchestration enabled with tier-default reviewer panel.`);return}let o=await Zr(t),s=[],a=new Set;for(let d=0;d<o;d++){console.log(""),console.log(`${p.bold}Seat ${d}${p.reset}`);let l=Hr.filter(w=>!a.has(w)),m=await tr(t,"Role:",l),u=await tr(t,"Agent:",r);s.push({seatId:d,role:m,agent:u}),a.add(m)}await e.updateReviewerPolicy({orchestrationEnabledDefault:!0,reviewerSeats:s}),console.log(""),console.log(`${p.green}\u2713${p.reset} Orchestration enabled with custom panel:`);for(let d of s)console.log(` Seat ${d.seatId}: ${d.role.toLowerCase()} \u2192 ${d.agent.toLowerCase()}`)}finally{t.close()}}function it(r,e){return new Promise(t=>r.question(e,n=>t(n.trim())))}async function er(r,e,t){let i=(await it(r,e+(t?" [Y/n] ":" [y/N] "))).toLowerCase();return i?i.startsWith("y"):t}async function Zr(r){for(;;){let e=await it(r,"How many seats (2 for Pro, 3 for Max)? "),t=parseInt(e,10);if(t===2||t===3)return t;console.log(`${p.yellow}Enter 2 or 3.${p.reset}`)}}async function tr(r,e,t){for(;;){console.log(e),t.forEach((o,s)=>{console.log(` ${p.cyan}${s+1}${p.reset}. ${o.toLowerCase()}`)});let n=await it(r,"> "),i=parseInt(n,10)-1;if(i>=0&&i<t.length)return t[i];console.log(`${p.yellow}Enter a number between 1 and ${t.length}.${p.reset}`)}}async function _e(){let r=new J;return await r.authenticateWithStoredTokens()||(console.log(""),console.log(`${p.yellow}Not authenticated.${p.reset} Run ${p.bold}codevibe login${p.reset} first.`),process.exit(1)),r}function ot(r){console.log(""),console.log(`${p.bold}Current reviewer policy${p.reset}`),console.log(` Orchestration default: ${en(r.orchestrationEnabledDefault)}`),console.log(` Available agents: ${r.availableAgents?.length?r.availableAgents.map(e=>e.toLowerCase()).join(", "):`${p.dim}(not yet detected)${p.reset}`}`),console.log(` Reviewer panel: ${tn(r.reviewerSeats)}`)}function en(r){return r===!0?`${p.green}enabled${p.reset}`:r===!1?`${p.yellow}disabled${p.reset}`:`${p.dim}(unset \u2014 defaults to disabled)${p.reset}`}function tn(r){return!r||r.length===0?`${p.dim}tier defaults${p.reset}`:r.map(e=>`Seat ${e.seatId} ${e.role.toLowerCase()}\u2192${e.agent.toLowerCase()}`).join(", ")}var rr,p,Hr,nr=b(()=>{"use strict";rr=S(require("readline"));Re();pe();nt();p={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",purple:"\x1B[35m",cyan:"\x1B[36m"},Hr=["ARCHITECTURE","CORRECTNESS","SECURITY","ACCURACY","CLARITY","COMPLETENESS","ARCHITECTURE_AND_ACCURACY","CORRECTNESS_AND_CLARITY","SECURITY_AND_COMPLETENESS"]});var ir={};ce(ir,{applyPerSessionOrchestrationOverride:()=>xe,detectInstalledAgents:()=>L,pushDetectedAgents:()=>Ie,runOrchestrationCli:()=>Ce});var st=b(()=>{"use strict";nt();nr()});var Gn={};ce(Gn,{AgentType:()=>Ut,AppSyncClient:()=>J,AuditKeys:()=>yt,AuthService:()=>te,CryptoError:()=>j,CryptoService:()=>X,DeliveryStatus:()=>$t,ENCRYPTION_VERSION:()=>Ge,EventSource:()=>Ye,EventType:()=>Ot,KeychainError:()=>K,KeychainManager:()=>G,Logger:()=>V,Reviewer:()=>ft,ReviewerRole:()=>Qe,SessionStatus:()=>Xe,applyPerSessionOrchestrationOverride:()=>xe,authService:()=>O,createLogger:()=>Ue,cryptoService:()=>I,detectInstalledAgents:()=>L,errorWasBeaconed:()=>ye,fireAuthCompletedBeacon:()=>fe,fireAuthFailedBeacon:()=>R,getConfig:()=>k,getEnvironment:()=>x,getErrorReason:()=>et,keychainManager:()=>y,loadConfig:()=>ke,logger:()=>c,markErrorBeaconed:()=>_,mutations:()=>C,normalizeSnapshot:()=>dt,parseInteractivePrompt:()=>or,prepareSessionEncryption:()=>Pe,pushDetectedAgents:()=>Ie,queries:()=>H,registerDeviceEncryptionKey:()=>pt,rekeySessionForNewDevices:()=>z,resumeOrCreateSession:()=>lt,runAuthCli:()=>Te,runOrchestrationCli:()=>Ce,startDeviceKeyWatcher:()=>ut,subscriptions:()=>ee});module.exports=vt(Gn);U();de();Re();Re();var zt=S(require("crypto")),Yt=S(require("fs")),rt=S(require("http")),Xt=require("child_process");Q();U();$();Je();var Ft=S(require("crypto")),jt=S(require("https")),qt=S(require("os")),Mr="G-GS74YEQTB8",Br="lAfOF6OxRzSQ-NsLBRjhAg",Wr="www.google-analytics.com",Vr=`/mp/collect?measurement_id=${Mr}&api_secret=${Br}`,Fr={port_in_use:"server_start",server_listen_failed:"server_start",browser_open_failed:"browser_open",login_timeout:"awaiting_callback",cognito_rejected:"awaiting_callback",state_mismatch:"awaiting_callback",no_authorization_code:"awaiting_callback",token_exchange_failed:"exchanging_code",token_exchange_network_error:"exchanging_code",keychain_write_failed:"storing_tokens",user_aborted:"unknown",unknown:"unknown"};function jr(){let r=typeof process.getuid=="function"?process.getuid():0;return Ft.createHash("sha256").update(`${qt.hostname()}-${r}`).digest("hex").substring(0,36)}function Gt(){return{platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production"}}async function Ht(r,e){try{let t=JSON.stringify({client_id:jr(),events:[{name:r,params:e}]});await new Promise(n=>{let i=jt.request({hostname:Wr,path:Vr,method:"POST",headers:{"Content-Type":"application/json"}},()=>n());i.on("error",()=>n()),i.write(t),i.end(),setTimeout(n,2e3)})}catch{}}async function fe(r){await Ht("auth_completed",{...Gt(),user_id:r})}async function R(r,e){let t={...Gt(),reason:r,stage:e?.stage??Fr[r]};typeof e?.httpStatus=="number"&&(t.http_status=e.httpStatus),await Ht("auth_failed",t)}var Ze=Symbol.for("codevibe.auth.beaconed"),Jt=Symbol.for("codevibe.auth.failureReason");function _(r,e){try{Object.defineProperty(r,Ze,{value:!0,enumerable:!1,configurable:!0,writable:!1}),Object.defineProperty(r,Jt,{value:e,enumerable:!1,configurable:!0,writable:!1})}catch{}return r}function ye(r){return!!(r&&typeof r=="object"&&r[Ze])}function et(r){if(r&&typeof r=="object"&&r[Ze]){let e=r[Jt];if(typeof e=="string")return e}}var he=8080,Qt="/callback",tt=`http://localhost:${he}${Qt}`,te=class r{constructor(){}static getInstance(){return r.instance||(r.instance=new r),r.instance}openBrowser(e){console.error(""),console.error("Opening your browser for sign-in..."),this.isRunningInWSL()?console.error("If your browser does not open, paste this URL in your Windows browser:"):console.error("If your browser does not open automatically, visit this URL:"),console.error(` ${e}`),console.error("");let t=this.getBrowserCommands();this.tryBrowserCommand(t,e,0)}getBrowserCommands(){let e=process.platform;if(e==="darwin")return[{cmd:"open",fixedArgs:[]}];if(e==="win32")return[{cmd:"cmd",fixedArgs:["/c","start",""]}];let t=[];return this.isRunningInWSL()&&(t.push({cmd:"wslview",fixedArgs:[]}),t.push({cmd:"cmd.exe",fixedArgs:["/c","start",""]}),t.push({cmd:"powershell.exe",fixedArgs:["-NoProfile","-Command","Start-Process"]})),t.push({cmd:"xdg-open",fixedArgs:[]}),t}isRunningInWSL(){if(process.platform!=="linux")return!1;try{let e=Yt.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,t,n){if(n>=e.length){c.debug("[AuthService] No browser-opening command succeeded. User must open the sign-in URL manually (printed to stderr above)."),console.error(""),console.error("\u26A0\uFE0F Could not open browser automatically."),this.isRunningInWSL()?console.error(" WSL detected \u2014 paste this URL in your Windows browser:"):console.error(" Please copy and paste this URL into your browser:"),console.error(` ${t}`),console.error("");return}let i=e[n],o=[...i.fixedArgs,t],s=!1,a=u=>{s||(s=!0,c.debug(`[AuthService] Browser command '${i.cmd}' ${u}; trying next fallback`),this.tryBrowserCommand(e,t,n+1))},d=u=>{s||(s=!0,c.debug(`[AuthService] Browser command '${i.cmd}' ${u}`))},l;try{l=(0,Xt.spawn)(i.cmd,o,{detached:!0,stdio:"ignore"})}catch(u){a(`threw synchronously: ${u?.message||u}`);return}l.on("error",u=>{a(`failed to spawn: ${u?.message||u}`)}),l.on("exit",(u,w)=>{u===0?d("exited successfully"):a(w?`terminated by signal ${w}`:`exited with code ${u}`)}),setTimeout(()=>{d("still running after 3s, assuming success")},3e3).unref(),l.unref()}generateState(){return zt.randomBytes(32).toString("hex")}buildAuthUrl(e){let t=k(),n=new URLSearchParams({client_id:t.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:tt,state:e});return`https://${t.aws.cognitoDomain}/oauth2/authorize?${n.toString()}`}async exchangeCodeForTokens(e){let t=k(),n=`https://${t.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"authorization_code",client_id:t.aws.cognitoClientId,code:e,redirect_uri:tt}),o;try{o=await Z(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token exchange")}catch(a){throw await R("token_exchange_network_error"),_(a,"token_exchange_network_error"),a}if(!o.ok){let a=await o.text(),d=new Error(`Token exchange failed: ${o.status} ${a}`);throw await R("token_exchange_failed",{httpStatus:o.status}),_(d,"token_exchange_failed"),d}let s=await o.json();return{accessToken:s.access_token,idToken:s.id_token,refreshToken:s.refresh_token,expiresIn:s.expires_in}}decodeJwt(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT");return JSON.parse(Buffer.from(t[1],"base64").toString("utf-8"))}async refreshTokens(e){let t=k(),n=`https://${t.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:t.aws.cognitoClientId,refresh_token:e}),o=await Z(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");if(!o.ok)throw new Error(`Token refresh failed: ${o.status}`);let s=await o.json();return{accessToken:s.access_token,idToken:s.id_token,expiresIn:s.expires_in}}async login(){let e=await y.getTokens(x());if(e&&!y.isTokenExpired(e))return e;let t=this.generateState(),n=this.buildAuthUrl(t);return new Promise((i,o)=>{let s=rt.createServer(async(a,d)=>{if(!a.url?.startsWith(Qt)){d.writeHead(404),d.end("Not found");return}try{let l=new URL(a.url,`http://localhost:${he}`),m=l.searchParams.get("code"),u=l.searchParams.get("state"),w=l.searchParams.get("error");if(w){let f=new Error(`OAuth error: ${w}`);throw await R("cognito_rejected"),_(f,"cognito_rejected"),f}if(u!==t){let f=new Error("State mismatch");throw await R("state_mismatch"),_(f,"state_mismatch"),f}if(!m){let f=new Error("No authorization code");throw await R("no_authorization_code"),_(f,"no_authorization_code"),f}let v=await this.exchangeCodeForTokens(m),W=this.decodeJwt(v.idToken),E={accessToken:v.accessToken,idToken:v.idToken,refreshToken:v.refreshToken,expiresAt:Date.now()+v.expiresIn*1e3,userId:W.sub,email:W.email||"unknown"};try{await y.setTokens(E,x())}catch(f){throw await R("keychain_write_failed"),_(f,"keychain_write_failed"),f}d.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),d.end(`
289
+ `,onSessionUpdated:`
290
+ subscription OnSessionUpdated($sessionId: ID!) {
291
+ onSessionUpdated(sessionId: $sessionId) {
292
+ sessionId
293
+ status
294
+ updatedAt
295
+ }
296
+ }
297
+ `}});var tn,rn,vi,nn=R(()=>{"use strict";tn=(g=>(g.USER_PROMPT="USER_PROMPT",g.ASSISTANT_RESPONSE="ASSISTANT_RESPONSE",g.TOOL_USE="TOOL_USE",g.NOTIFICATION="NOTIFICATION",g.INTERACTIVE_PROMPT="INTERACTIVE_PROMPT",g.PROMPT_RESPONSE="PROMPT_RESPONSE",g.REASONING="REASONING",g.MODE_SELECTED="MODE_SELECTED",g.PLANNER_DECISION="PLANNER_DECISION",g.PLANNER_CACHE_HIT="PLANNER_CACHE_HIT",g.PLANNER_DEGRADED="PLANNER_DEGRADED",g.PLANNER_OUTAGE="PLANNER_OUTAGE",g.PLANNER_RECOVERED="PLANNER_RECOVERED",g.SLASH_COMMAND_INVOKED="SLASH_COMMAND_INVOKED",g.STRUCTURAL_SUMMARY_GENERATED="STRUCTURAL_SUMMARY_GENERATED",g.LOCAL_AUTHORITY_REFUSAL="LOCAL_AUTHORITY_REFUSAL",g))(tn||{}),rn=(r=>(r.DESKTOP="DESKTOP",r.MOBILE="MOBILE",r))(rn||{}),vi=(n=>(n.SENT="SENT",n.DELIVERED="DELIVERED",n.EXECUTED="EXECUTED",n))(vi||{})});var Qt,wi,Ei=R(()=>{"use strict";Qt=(n=>(n.ACTIVE="ACTIVE",n.INACTIVE="INACTIVE",n.PAUSED="PAUSED",n))(Qt||{}),wi=(n=>(n.CLAUDE="CLAUDE",n.GEMINI="GEMINI",n.CODEX="CODEX",n))(wi||{})});var ki=R(()=>{"use strict"});var bi=R(()=>{"use strict"});var Zt,sn=R(()=>{"use strict";Zt=(l=>(l.ARCHITECTURE="ARCHITECTURE",l.CORRECTNESS="CORRECTNESS",l.SECURITY="SECURITY",l.ACCURACY="ACCURACY",l.CLARITY="CLARITY",l.COMPLETENESS="COMPLETENESS",l.ARCHITECTURE_AND_ACCURACY="ARCHITECTURE_AND_ACCURACY",l.CORRECTNESS_AND_CLARITY="CORRECTNESS_AND_CLARITY",l.SECURITY_AND_COMPLETENESS="SECURITY_AND_COMPLETENESS",l))(Zt||{})});var kt=R(()=>{"use strict";nn();Ei();ki();bi();sn()});var $e,Me,Ye,B,fe,on=R(()=>{"use strict";$e=h(require("ws")),Me=require("uuid");qe();N();re();Te();Zr();en();kt();Ye=class extends Error{constructor(e){super(`GraphQL error: ${e.message}`),this.name="AppSyncGraphQLError",this.errorType=e.errorType,this.extensions=e.extensions,this.path=e.path}},B={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3},fe=class t{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.activeSubscriptions=new Map;this.lastAuthFailureKind=null;this.lastRefreshNetworkError=!1;this.pendingRefresh=null;this.lastRefreshFailureAt=null;this.deviceKeyWatcher=null;this.sessionUpdateWatchers=new Map;this.heartbeatTimers=new Map;this.classBPacketHandlers=new Map;this.environment=J(),u.info("[AppSyncClient] Initialized",{environment:this.environment})}static{this.REFRESH_BACKOFF_MS=3e4}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}getLastAuthFailureKind(){return this.lastAuthFailureKind}static isNetworkLikeMessage(e){return/ECONN|ENETUNREACH|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|getaddrinfo|\b5\d\d\b|service unavailable|gateway timeout/i.test(e)}async authenticateWithStoredTokens(){this.lastAuthFailureKind=null;try{let e=await k.getTokens(this.environment);if(!e)return u.debug("[AppSyncClient] No stored tokens found"),this.lastAuthFailureKind="no_tokens",!1;if(u.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:k.isTokenExpired(e)}),k.isTokenExpired(e)){if(u.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return u.warn("[AppSyncClient] Token refresh failed"),this.lastAuthFailureKind=this.lastRefreshNetworkError?"refresh_network":"refresh_auth_rejected",!1}else this.tokens=e;return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,u.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){u.error("[AppSyncClient] Authentication failed:",e);let r=e instanceof Error?e.message:String(e);return this.lastAuthFailureKind=t.isNetworkLikeMessage(r)?"refresh_network":"refresh_auth_rejected",!1}}async refreshTokens(e){if(this.pendingRefresh)return this.pendingRefresh;if(this.lastRefreshFailureAt!==null&&Date.now()-this.lastRefreshFailureAt<t.REFRESH_BACKOFF_MS)return!1;this.pendingRefresh=this.performRefresh(e);try{return await this.pendingRefresh}finally{this.pendingRefresh=null}}async performRefresh(e){this.lastRefreshNetworkError=!1;let r=await this.callCognitoRefresh(e.refreshToken);if(r!==null)return this.applyRefreshedTokens(e,r);let n=null;try{n=await k.getTokens(this.environment)}catch(i){u.warn("[AppSyncClient] Failed to re-read tokens from storage during refresh recovery",{error:i instanceof Error?i.message:String(i)})}if(n&&n.refreshToken&&n.refreshToken!==e.refreshToken){u.info("[AppSyncClient] In-memory refresh token rejected; retrying with storage-backed token (likely out-of-band re-auth)"),this.lastRefreshNetworkError=!1;let i=await this.callCognitoRefresh(n.refreshToken);if(i!==null)return this.applyRefreshedTokens(n,i)}return this.lastRefreshFailureAt=Date.now(),!1}async callCognitoRefresh(e){try{let r=M(),n=`https://${r.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:r.aws.cognitoClientId,refresh_token:e}),s=await Je(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");return s.ok?await s.json():(u.error("[AppSyncClient] Token refresh failed",{status:s.status}),(s.status>=500&&s.status<600||s.status===429)&&(this.lastRefreshNetworkError=!0),null)}catch(r){return u.error("[AppSyncClient] Token refresh error:",r),this.lastRefreshNetworkError=!0,null}}async applyRefreshedTokens(e,r){let n={...e,accessToken:r.access_token,idToken:r.id_token,expiresAt:Date.now()+r.expires_in*1e3};this.tokens=n,this.lastRefreshFailureAt=null;try{await k.setTokens(n,this.environment),u.info("[AppSyncClient] Tokens refreshed",{expiresAt:new Date(n.expiresAt).toISOString()})}catch(i){u.warn("[AppSyncClient] Tokens refreshed but persistence failed; daemon keeps using fresh tokens in memory. A restart while persistence is still broken would lose them.",{error:i instanceof Error?i.message:String(i),expiresAt:new Date(n.expiresAt).toISOString()})}return!0}isAuthenticated(){return this.authenticated}signOut(){this.authenticated=!1,this.tokens=null,this.currentUserId=null,this.currentEmail=null,this.cleanupSubscriptions(),u.info("[AppSyncClient] Signed out")}async graphqlRequest(e,r,n=!1){let i=M();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let s={"Content-Type":"application/json",Authorization:this.tokens.idToken},o=await Je(i.aws.appsyncUrl,{method:"POST",headers:s,body:JSON.stringify({query:e,variables:r})},"AppSync GraphQL request"),a=await o.json();if(o.status===401&&!n&&this.tokens){if(u.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),await this.refreshTokens(this.tokens))return this.graphqlRequest(e,r,!0);throw new Error("Token expired and refresh failed")}if(!o.ok)throw new Error(`GraphQL request failed: ${o.status}`);if(a.errors?.length){let c=a.errors[0];throw new Ye({message:c.message,errorType:c.errorType,extensions:c.extensions,path:c.path})}return a}async createSession(e){let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(U.createSession,{input:r});return u.info("[AppSyncClient] Session created",{sessionId:n.data.createSession.sessionId}),n.data.createSession}async updateSession(e){let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(U.updateSession,{input:r});return u.debug("[AppSyncClient] Session updated",{sessionId:n.data.updateSession.sessionId}),n.data.updateSession}async getSession(e){return(await this.graphqlRequest(oe.getSession,{sessionId:e})).data.getSession}async createEvent(e){let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(U.createEvent,{input:r});return u.debug("[AppSyncClient] Event created",{eventId:n.data.createEvent.eventId,type:n.data.createEvent.type}),n.data.createEvent}async updateEventStatus(e){return(await this.graphqlRequest(U.updateEventStatus,{input:e})).data.updateEventStatus}async listEvents(e,r,n){return(await this.graphqlRequest(oe.listEvents,{sessionId:e,source:r,limit:n})).data.listEvents.items}async listSessions(e=100){if(!this.currentUserId)throw new Error("Not authenticated");let r=[],n=null;do{let s=(await this.graphqlRequest(oe.listSessions,{userId:this.currentUserId,limit:e,nextToken:n})).data?.listSessions;s?.items&&r.push(...s.items),n=s?.nextToken??null}while(n);return r}async sweepOrphanSessions(e){let r=e.staleThresholdMs??9e5,n=new Set(e.excludeSessionIds??[]),i=Date.now(),s;try{s=await this.listSessions()}catch(a){return u.warn("[AppSyncClient] OrphanSweep: listSessions failed, skipping sweep",{agentType:e.agentType,error:a instanceof Error?a.message:String(a)}),0}let o=0;for(let a of s){if(a.agentType!==e.agentType||a.status!=="ACTIVE"||n.has(a.sessionId)||!a.lastHeartbeatAt)continue;let c=i-new Date(a.lastHeartbeatAt).getTime();if(!(c<r)){u.warn("[AppSyncClient] OrphanSweep: marking stale session INACTIVE",{sessionId:a.sessionId,agentType:a.agentType,lastHeartbeatAt:a.lastHeartbeatAt,heartbeatAgeMinutes:Math.round(c/6e4)});try{await this.updateSession({sessionId:a.sessionId,status:"INACTIVE"}),o++}catch(l){u.warn("[AppSyncClient] OrphanSweep: updateSession failed, leaving row as-is",{sessionId:a.sessionId,error:l instanceof Error?l.message:String(l)})}}}return o>0&&u.info("[AppSyncClient] OrphanSweep complete",{agentType:e.agentType,swept:o}),o}async listUserDeviceKeys(){return(await this.graphqlRequest(oe.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async listServiceDeviceKeys(){return(await this.graphqlRequest(oe.listServiceDeviceKeys,{})).data.listServiceDeviceKeys||[]}async registerDeviceKey(e,r,n,i){let s={deviceId:e,publicKey:r,platform:n,deviceName:i};await this.graphqlRequest(U.registerDeviceKey,{input:s}),u.info("[AppSyncClient] Device key registered",{deviceId:e,platform:n})}async grantSessionKey(e){await this.graphqlRequest(U.grantSessionKey,{input:e}),u.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(U.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}async updateAvailableAgents(e){let r=await this.graphqlRequest(U.updateAvailableAgents,{agents:e});return u.info("[AppSyncClient] Updated available agents",{agents:e}),r.data.updateAvailableAgents}async updateAdapterCapabilities(e){let r=await this.graphqlRequest(U.updateAdapterCapabilities,{capabilities:JSON.stringify(e)});return u.info("[AppSyncClient] Updated adapter capabilities",{recordCount:e.length}),r.data.updateAdapterCapabilities}async updateReviewerPolicy(e){let r=await this.graphqlRequest(U.updateReviewerPolicy,{input:e});return u.info("[AppSyncClient] Updated reviewer policy",{orchestrationEnabledDefault:e.orchestrationEnabledDefault,reviewerSeatCount:e.reviewerSeats?.length}),r.data.updateReviewerPolicy}async getSubscriptionStatus(){return(await this.graphqlRequest(oe.getSubscriptionStatus,{})).data.getSubscriptionStatus}async classifyPlannerPrompt(e){return(await this.graphqlRequest(U.classifyPlannerPrompt,{input:e})).data.classifyPlannerPrompt}async pingPlanner(e){return(await this.graphqlRequest(U.pingPlanner,{input:e})).data.pingPlanner}async applyUserDecision(e,r){let n=null;if(e.notes!==void 0){if(typeof r!="string"||r.length===0)throw new Error("applyUserDecision: sessionKeyBase64 is required when notes are supplied");n={ciphertextB64:$.encryptContent(e.notes,r),sessionId:e.sessionId,keyVersion:vt}}let i=e.decision.toUpperCase(),o=(await this.graphqlRequest(U.applyUserDecision,{input:{gateId:e.gateId,taskId:e.taskId,sessionId:e.sessionId,currentRound:e.currentRound,decision:i,notes:n}})).data?.applyUserDecision;if(!o||typeof o!="object")throw new Error("applyUserDecision: missing envelope on response");let a=o.payload;if(typeof a!="string")throw new Error(`applyUserDecision: expected AWSJSON string for payload, got ${typeof a}`);let c;try{c=JSON.parse(a)}catch(p){throw new Error(`applyUserDecision: failed to parse AWSJSON payload: ${p.message}`)}if(!c||typeof c!="object")throw new Error("applyUserDecision: parsed payload is not an object");let l=c;return{decision:typeof o.decision=="string"?o.decision.toLowerCase():e.decision,postAction:l}}subscribeToEvents(e,r,n){u.info("[AppSyncClient] Subscribing to events",{sessionId:e});let i=this.activeSubscriptions.get(e);i&&(this.cleanupSubscriptionState(i),this.activeSubscriptions.delete(e));let s={ws:null,subscriptionId:(0,Me.v4)(),sessionId:e,onEvent:r,onError:n,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,s),this.createSubscription(s),()=>{this.cleanupSubscriptionState(s),this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=M(),r=new URL(e.aws.appsyncUrl),i=/\.appsync-api\.[^.]+\.amazonaws\.com$/.test(r.host)?e.aws.appsyncUrl.replace("https://","wss://").replace("appsync-api","appsync-realtime-api"):`wss://${r.host}/graphql/realtime`,s={host:r.host};this.tokens?.idToken&&(s.Authorization=this.tokens.idToken);let o=Buffer.from(JSON.stringify(s)).toString("base64"),a=Buffer.from(JSON.stringify({})).toString("base64");return`${i}?header=${o}&payload=${a}`}createSubscription(e){let{sessionId:r,subscriptionId:n,onEvent:i,onError:s}=e;try{let o=this.buildRealtimeUrl(),a=new $e.default(o,["graphql-ws"]);a.on("open",()=>{u.info("[AppSyncClient] WebSocket connected",{sessionId:r}),a.send(JSON.stringify({type:"connection_init"}))}),a.on("message",c=>{try{let l=JSON.parse(c.toString());switch(l.type){case"connection_ack":this.sendSubscriptionStart(a,e);break;case"start_ack":u.info("[AppSyncClient] Subscription started",{sessionId:r}),e.isReconnecting=!1,e.reconnectAttempts=0,this.startHeartbeat(r);break;case"data":this.resetKeepAliveTimer(e);let d=l.payload?.data?.onEventCreated;d&&d.source==="MOBILE"&&i(d);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let p=l.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(p));break}}catch(l){u.error("[AppSyncClient] Failed to parse message",{error:l})}}),a.on("error",c=>{u.error("[AppSyncClient] WebSocket error",{sessionId:r,error:c.message}),this.handleSubscriptionError(e,c)}),a.on("close",(c,l)=>{u.info("[AppSyncClient] WebSocket closed",{sessionId:r,code:c}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(r)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${c}`))}),e.ws=a,this.resetKeepAliveTimer(e)}catch(o){this.handleSubscriptionError(e,o)}}sendSubscriptionStart(e,r){let n=M(),{sessionId:i,subscriptionId:s}=r,o={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:Ne.onEventCreated,variables:{sessionId:i}}),extensions:{authorization:o}}}))}resetKeepAliveTimer(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSubscriptionError(e,new Error("Keep-alive timeout"))},300*1e3)}handleSubscriptionError(e,r){let{sessionId:n,onError:i}=e;if(e.isReconnecting||!this.activeSubscriptions.has(n))return;e.isReconnecting=!0,e.reconnectAttempts++,this.stopHeartbeat(n);let s=e.reconnectAttempts<=B.urgentMaxAttempts,o;if(s?o=Math.min(B.baseDelayMs*Math.pow(B.backoffMultiplier,e.reconnectAttempts-1),B.maxDelayMs):(o=B.persistentDelayMs,e.reconnectAttempts===B.urgentMaxAttempts+1&&u.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:n})),u.info("[AppSyncClient] Scheduling reconnect",{sessionId:n,attempt:e.reconnectAttempts,phase:s?"urgent":"persistent",delayMs:o}),e.ws){try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(n)!==e){u.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:n});return}try{let a=await k.getTokens(this.environment);a&&(k.isTokenExpired(a)?await this.refreshTokens(a)&&u.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:n}):this.tokens=a)}catch{u.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:n})}if(e.destroyed||this.activeSubscriptions.get(n)!==e){u.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:n});return}e.subscriptionId=(0,Me.v4)(),this.createSubscription(e)},o)}cleanupSubscriptionState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===$e.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}subscribeToDeviceKeyRegistered(e,r,n,i){u.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let s={userId:e,subscriptionId:(0,Me.v4)(),ws:null,onNewDevice:r,onReconnect:n,onError:i,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.deviceKeyWatcher=s,this.createDeviceKeyWatcherConnection(s),()=>{this.stopDeviceKeyWatcherInternal()}}stopDeviceKeyWatcher(){this.stopDeviceKeyWatcherInternal()}stopDeviceKeyWatcherInternal(){let e=this.deviceKeyWatcher;if(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===$e.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}this.deviceKeyWatcher=null,u.info("[AppSyncClient] Device key watcher stopped")}}createDeviceKeyWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new $e.default(r,["graphql-ws"]);n.on("open",()=>{u.info("[AppSyncClient] Device key watcher WebSocket connected",{userId:e.userId}),n.send(JSON.stringify({type:"connection_init"}))}),n.on("message",i=>{try{let s=JSON.parse(i.toString());switch(s.type){case"connection_ack":this.sendDeviceKeyWatcherStart(n,e);break;case"start_ack":u.info("[AppSyncClient] Device key watcher subscription started",{userId:e.userId});let o=e.isReconnecting;if(e.isReconnecting=!1,e.reconnectAttempts=0,o&&e.onReconnect)try{e.onReconnect()}catch(l){u.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:l})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let a=s.payload?.data?.onDeviceKeyRegistered;if(a){u.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:a.deviceId,platform:a.platform});try{e.onNewDevice(a)}catch(l){u.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:l})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let c=s.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(c));break}}catch(s){u.error("[AppSyncClient] Failed to parse device key watcher message",{error:s})}}),n.on("error",i=>{u.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleDeviceKeyWatcherError(e,i)}),n.on("close",i=>{u.info("[AppSyncClient] Device key watcher WebSocket closed",{userId:e.userId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.deviceKeyWatcher===e&&this.handleDeviceKeyWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=n,this.resetDeviceKeyWatcherKeepAlive(e)}catch(r){this.handleDeviceKeyWatcherError(e,r)}}sendDeviceKeyWatcherStart(e,r){let n=M(),{userId:i,subscriptionId:s}=r,o={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:Ne.onDeviceKeyRegistered,variables:{userId:i}}),extensions:{authorization:o}}}))}resetDeviceKeyWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleDeviceKeyWatcherError(e,new Error("Device key watcher keep-alive timeout"))},300*1e3)}handleDeviceKeyWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(r)}catch{}if(e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=B.urgentMaxAttempts?Math.min(B.baseDelayMs*Math.pow(B.backoffMultiplier,e.reconnectAttempts-1),B.maxDelayMs):B.persistentDelayMs;u.warn("[AppSyncClient] Device key watcher reconnect scheduled",{userId:e.userId,attempts:e.reconnectAttempts,delayMs:i,error:r.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.deviceKeyWatcher!==e){u.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}try{let s=await k.getTokens(this.environment);s&&(k.isTokenExpired(s)?await this.refreshTokens(s)&&u.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId}):this.tokens=s)}catch{u.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,Me.v4)(),this.createDeviceKeyWatcherConnection(e))},i)}watchForMobileEnd(e,r){u.info("[AppSyncClient] Starting mobile-end watcher",{sessionId:e});let n=this.sessionUpdateWatchers.get(e);n&&(u.info("[AppSyncClient] Replacing existing mobile-end watcher",{sessionId:e}),this.cleanupSessionUpdateWatcherState(n),this.sessionUpdateWatchers.delete(e));let i={sessionId:e,subscriptionId:(0,Me.v4)(),ws:null,onMobileEndRequested:r,priorStatus:"ACTIVE",firedOnce:!1,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.sessionUpdateWatchers.set(e,i),this.createSessionUpdateWatcherConnection(i),{stop:()=>{this.sessionUpdateWatchers.get(e)===i&&(this.cleanupSessionUpdateWatcherState(i),this.sessionUpdateWatchers.delete(e),u.info("[AppSyncClient] Mobile-end watcher stopped",{sessionId:e}))}}}createSessionUpdateWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new $e.default(r,["graphql-ws"]);n.on("open",()=>{u.info("[AppSyncClient] Mobile-end watcher WebSocket connected",{sessionId:e.sessionId}),n.send(JSON.stringify({type:"connection_init"}))}),n.on("message",i=>{try{let s=JSON.parse(i.toString());switch(s.type){case"connection_ack":this.sendSessionUpdateWatcherStart(n,e);break;case"start_ack":u.info("[AppSyncClient] Mobile-end watcher subscription started",{sessionId:e.sessionId}),e.isReconnecting=!1,e.reconnectAttempts=0;break;case"data":this.resetSessionUpdateWatcherKeepAlive(e),this.handleSessionUpdatePayload(e,s.payload);break;case"ka":this.resetSessionUpdateWatcherKeepAlive(e);break;case"error":let o=s.payload?.errors?.[0]?.message||"Unknown error";this.handleSessionUpdateWatcherError(e,new Error(o));break}}catch(s){u.error("[AppSyncClient] Failed to parse mobile-end watcher message",{error:s})}}),n.on("error",i=>{u.error("[AppSyncClient] Mobile-end watcher WebSocket error",{sessionId:e.sessionId,error:i.message}),this.handleSessionUpdateWatcherError(e,i)}),n.on("close",i=>{u.info("[AppSyncClient] Mobile-end watcher WebSocket closed",{sessionId:e.sessionId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.sessionUpdateWatchers.get(e.sessionId)===e&&this.handleSessionUpdateWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=n,this.resetSessionUpdateWatcherKeepAlive(e)}catch(r){this.handleSessionUpdateWatcherError(e,r)}}handleSessionUpdatePayload(e,r){let n=r?.data?.onSessionUpdated;if(!n){u.warn("[AppSyncClient] Mobile-end watcher received malformed payload",{sessionId:e.sessionId});return}if(e.firedOnce)return;let i=n.status;if(i==null){u.debug("[AppSyncClient] Mobile-end watcher skipped non-status payload",{sessionId:e.sessionId});return}if(e.priorStatus==="ACTIVE"&&i==="INACTIVE"){e.firedOnce=!0,e.priorStatus="INACTIVE",u.info("[AppSyncClient] Mobile end requested for session",{sessionId:e.sessionId}),Promise.resolve().then(()=>e.onMobileEndRequested()).catch(s=>{u.warn("[AppSyncClient] Mobile-end callback threw",{sessionId:e.sessionId,error:s})});return}e.priorStatus=i}sendSessionUpdateWatcherStart(e,r){let n=M(),{sessionId:i,subscriptionId:s}=r,o={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:s,type:"start",payload:{data:JSON.stringify({query:Ne.onSessionUpdated,variables:{sessionId:i}}),extensions:{authorization:o}}}))}resetSessionUpdateWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleSessionUpdateWatcherError(e,new Error("Mobile-end watcher keep-alive timeout"))},300*1e3)}handleSessionUpdateWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.ws){try{e.ws.removeAllListeners()}catch{}try{e.ws.close(1e3)}catch{}e.ws=null}e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=B.urgentMaxAttempts?Math.min(B.baseDelayMs*Math.pow(B.backoffMultiplier,e.reconnectAttempts-1),B.maxDelayMs):B.persistentDelayMs;u.warn("[AppSyncClient] Mobile-end watcher reconnect scheduled",{sessionId:e.sessionId,attempts:e.reconnectAttempts,delayMs:i,error:r.message}),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,!(e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e)){try{let s=await k.getTokens(this.environment);s&&(k.isTokenExpired(s)?await this.refreshTokens(s):this.tokens=s)}catch{u.warn("[AppSyncClient] Token refresh failed before mobile-end watcher reconnect",{sessionId:e.sessionId})}e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Me.v4)(),this.createSessionUpdateWatcherConnection(e))}},i)}cleanupSessionUpdateWatcherState(e){if(e.destroyed=!0,e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws){try{e.ws.readyState===$e.default.OPEN&&e.ws.send(JSON.stringify({id:e.subscriptionId,type:"stop"}))}catch{}try{e.ws.close(1e3)}catch{}try{e.ws.removeAllListeners()}catch{}e.ws=null}}startHeartbeat(e,r=120*1e3){this.stopHeartbeat(e),this.sendHeartbeat(e);let n=setInterval(()=>{this.sendHeartbeat(e)},r);this.heartbeatTimers.set(e,n),u.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:r})}stopHeartbeat(e){let r=this.heartbeatTimers.get(e);r&&(clearInterval(r),this.heartbeatTimers.delete(e),u.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async sendHeartbeat(e){try{await this.updateSession({sessionId:e,lastHeartbeatAt:new Date().toISOString()}),u.debug("[AppSyncClient] Heartbeat sent",{sessionId:e})}catch(r){u.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:r})}}cleanupSubscriptions(){this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear(),this.stopDeviceKeyWatcherInternal(),this.sessionUpdateWatchers.forEach(e=>{this.cleanupSessionUpdateWatcherState(e)}),this.sessionUpdateWatchers.clear(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear()}parseClassBPacketPayload(e){let r=JSON.parse(e);if(typeof r!="object"||r===null)throw new Error("parseClassBPacketPayload: packetJson is not an object");let n=r;if(typeof n.kind!="string")throw new Error("parseClassBPacketPayload: missing or invalid kind discriminator");if(typeof n.signedEnvelope!="object"||n.signedEnvelope===null)throw new Error("parseClassBPacketPayload: missing signedEnvelope");return r}subscribeToClassBPackets(e,r){if(typeof e!="string"||e.length===0)throw new Error("subscribeToClassBPackets: userId required");u.info("[AppSyncClient] Registering Class B packet subscription handler",{userId:e});let n={userId:e,onPacket:r.onPacket,onError:r.onError,destroyed:!1};return this.classBPacketHandlers.set(e,n),{unsubscribe:async()=>{n.destroyed=!0,this.classBPacketHandlers.delete(e),u.info("[AppSyncClient] Unregistered Class B packet subscription",{userId:e})}}}async _deliverClassBPacketForTests(e,r){let n=this.classBPacketHandlers.get(e);if(!(!n||n.destroyed))try{let i=this.parseClassBPacketPayload(r);await n.onPacket(i)}catch(i){n.onError?.(i instanceof Error?i:new Error(String(i)))}}}});var er=R(()=>{"use strict";on();en()});function Z(){let t=[];for(let e of["CLAUDE","GEMINI","CODEX"])va(e)&&t.push(e);return u.debug("[detectInstalledAgents] Detected",{detected:t}),t}function va(t){try{return(0,Ui.execSync)(`command -v ${Sa[t]}`,{stdio:"ignore",shell:"/bin/sh"}),!0}catch{return!1}}async function nr(t,e,r,n=Z){let i=n();if(i.length===0){e.warn("No AI coding agents detected on PATH \u2014 skipping updateAvailableAgents");return}if(await t.updateAvailableAgents(i),e.info("Pushed available agents to backend",{agents:i}),!r){e.info("Capability registry not wired \u2014 skipping updateAdapterCapabilities",{agents:i});return}try{let s=[];for(let o of i){let a=await r.refreshCapabilities(o);s.push(a)}await t.updateAdapterCapabilities(s),e.info("Pushed adapter capabilities to backend",{recordCount:s.length})}catch(s){e.warn("Failed to push adapter capabilities (non-fatal \u2014 legacy availableAgents still written)",{error:s?.message})}}async function ir(t,e,r){let n=process.env.CODEVIBE_ORCHESTRATION_OVERRIDE;if(n!=="true"&&n!=="false")return;let i=n==="true";try{await t.updateSession({sessionId:e,orchestrationEnabled:i}),r.info("Applied per-session orchestration override",{sessionId:e,enabled:i})}catch(s){r.warn("Failed to apply per-session orchestration override",{sessionId:e,enabled:i,error:s?.message})}}var Ui,Sa,_t=R(()=>{"use strict";Ui=require("child_process");N();Sa={CLAUDE:"claude",GEMINI:"gemini",CODEX:"codex"}});function ee(t){return t<2?"<2":t<5?"2-5":t<10?"5-10":t<30?"10-30":"30+"}function Ze(t){return t<=1?"1":t===2?"2":"3"}function Ki(t){switch(t){case"architecture":return"ARCHITECTURE";case"correctness":return"CORRECTNESS";case"security":return"SECURITY"}}function Bi(t){return t.toUpperCase()}var pn,ke,Li,sr,et=R(()=>{"use strict";sn();pn={FREE:null,PRO:2,MAX:3},ke=["architecture","correctness","security"],Li=["architecture","correctness","security"],sr=["claude","gemini","codex"]});function Ra(){let t=typeof process.getuid=="function"?process.getuid():0;return Ue.createHash("sha256").update(`${Gi.hostname()}-${t}`).digest("hex").substring(0,36)}function tt(){return{platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production"}}async function Aa(t,e){try{let r=JSON.stringify({client_id:Ra(),events:[{name:t,params:e}]});await new Promise(n=>{let i=Wi.request({hostname:ka,path:ba,method:"POST",headers:{"Content-Type":"application/json"}},()=>n());i.on("error",()=>n()),i.write(r),i.end(),setTimeout(n,2e3)})}catch{}}function Vi(){if(typeof Ue.randomUUID=="function")return Ue.randomUUID();let t=Ue.randomBytes(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=t.toString("hex");return e.substring(0,8)+"-"+e.substring(8,12)+"-"+e.substring(12,16)+"-"+e.substring(16,20)+"-"+e.substring(20,32)}async function Hi(t){await it("wizard_started",{...tt(),wizard_run_id:t.wizardRunId,tier:t.tier.toLowerCase(),entry:t.entry,installed_agents_bucket:t.installedAgentsBucket})}async function be(t){await it("wizard_step_started",{...tt(),wizard_run_id:t.wizardRunId,step:t.step})}async function Re(t){await it("wizard_step_completed",{...tt(),wizard_run_id:t.wizardRunId,step:t.step,latency_bucket_s:t.latencyBucket})}async function rt(t){await it("wizard_step_failed",{...tt(),wizard_run_id:t.wizardRunId,step:t.step,reason:t.reason,latency_bucket_s:t.latencyBucket})}async function zi(t){await it("wizard_completed",{...tt(),wizard_run_id:t.wizardRunId,outcome:t.outcome,tier:t.tier.toLowerCase(),seats_bucket:t.seatsBucket,agents_distinct_bucket:t.agentsDistinctBucket,roles_distinct_bucket:t.rolesDistinctBucket,total_latency_bucket_s:t.totalLatencyBucket})}async function nt(t){await it("wizard_aborted",{...tt(),wizard_run_id:t.wizardRunId,reason:t.reason,last_step:t.lastStep})}async function it(t,e){if(Fi!==null){Fi({name:t,params:e});return}await Aa(t,e)}var Ue,Wi,Gi,wa,Ea,ka,ba,Fi,st=R(()=>{"use strict";Ue=h(require("crypto")),Wi=h(require("https")),Gi=h(require("os")),wa="G-GS74YEQTB8",Ea="lAfOF6OxRzSQ-NsLBRjhAg",ka="www.google-analytics.com",ba=`/mp/collect?measurement_id=${wa}&api_secret=${Ea}`;Fi=null});async function ji(){let t=new fe;if(await t.authenticateWithStoredTokens())return t;if(t.getLastAuthFailureKind()==="refresh_network")throw new or("refresh-token POST failed");return null}async function qi(t){let e=Date.now();await be({wizardRunId:t.wizardRunId,step:"bootstrap"});let r;try{let d=await t.clientFactory();if(!d)return await Le(t,e,{kind:"not_signed_in"});r=d}catch(d){if(d instanceof or)return await Le(t,e,{kind:"subscription_status_network",cause:d.message});let p=d instanceof Error?d.message:String(d);return _a(p)?await Le(t,e,{kind:"subscription_status_network",cause:p}):await Le(t,e,{kind:"not_signed_in"})}let n;try{n=(await r.getSubscriptionStatus()).tier}catch(d){return await Le(t,e,{kind:"subscription_status_network",cause:d instanceof Error?d.message:"unknown"})}let i=t.agentDetector(),s=i.map(d=>d.toLowerCase()),o=Ze(s.length);if(await Hi({wizardRunId:t.wizardRunId,tier:n,entry:t.entry,installedAgentsBucket:o}),pn[n]===null)return await Le(t,e,{kind:"tier_gate_free",tier:"FREE"});if(i.length===0)return await Le(t,e,{kind:"no_clis_installed"});let a=pn[n],c=r.getCurrentUserEmail(),l=null;try{l=await r.updateAvailableAgents(s.map(d=>d.toUpperCase()))}catch(d){console.warn("[setup-bootstrap] updateAvailableAgents failed; proceeding without saved-policy defaults",d instanceof Error?d.message:String(d)),l=null}return await Re({wizardRunId:t.wizardRunId,step:"bootstrap",latencyBucket:ee((Date.now()-e)/1e3)}),{ok:!0,result:{tier:n,seatBudget:a,installedAgents:s,installedAgentsBucket:o,client:r,userEmail:c,savedPolicy:l}}}function _a(t){return/ECONN|ENETUNREACH|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|getaddrinfo|\b5\d\d\b|service unavailable|gateway timeout/i.test(t)}async function Le(t,e,r){let n=ee((Date.now()-e)/1e3),i=r.kind;await rt({wizardRunId:t.wizardRunId,step:"bootstrap",reason:i,latencyBucket:n});let s=r.kind==="tier_gate_free"?"tier_gate_free":r.kind==="no_clis_installed"?"no_clis":r.kind==="not_signed_in"?"auth_expired":"bootstrap_failure";return await nt({wizardRunId:t.wizardRunId,reason:s,lastStep:"bootstrap"}),{ok:!1,failure:r}}var or,Ji=R(()=>{"use strict";on();et();st();or=class extends Error{constructor(e){super(`auth refresh network failure: ${e}`),this.name="AuthRefreshNetworkError"}}});async function Yi(t){let e=Date.now();await be({wizardRunId:t.wizardRunId,step:"seat_assignment"});let r=[],n=new Set;t.io.write(""),t.io.write(`${P.bold}Step 1 of 3 \u2014 Reviewer seat assignment${P.reset}
298
+ `),t.io.write(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
299
+ You have ${t.seatBudget} reviewer seats.
300
+ For each seat, pick an agent + a role.
301
+
302
+ `);for(let i=0;i<t.seatBudget;i++){t.io.write(`${P.bold}Seat ${i+1}${P.reset}
303
+ `);let s=t.savedSeats?.find(d=>d.seatId===i),o=await xa(t.io,t.installedAgents,s?.agent),a=ke.filter(d=>!n.has(d)),c=Pa(i,a,s?.role),l=await Ia(t.io,a,c);r.push({seatId:i,agent:o,role:l}),n.add(l),t.io.write(`
304
+ `)}return await Re({wizardRunId:t.wizardRunId,step:"seat_assignment",latencyBucket:ee((Date.now()-e)/1e3)}),r}async function xa(t,e,r){if(e.length===1)return t.write(` Agent: ${P.bold}${e[0]}${P.reset} ${P.dim}(only installed agent)${P.reset}
305
+ `),e[0];let n=sr.find(s=>e.includes(s))??e[0],i=r&&e.includes(r)?r:n;for(t.write(` Agent ${P.dim}(default: ${i})${P.reset}:
306
+ `),e.forEach((s,o)=>{let a=s===i?`${P.cyan}*${P.reset}`:" ";t.write(` ${a} ${o+1}. ${s}
307
+ `)});;){let s=await t.ask(" > ");if(s==="")return i;let o=parseInt(s,10)-1;if(o>=0&&o<e.length)return e[o];t.write(` ${P.yellow}Enter a number 1-${e.length} or press Enter for the default.${P.reset}
308
+ `)}}async function Ia(t,e,r){if(e.length===1)return t.write(` Role: ${P.bold}${e[0]}${P.reset} ${P.dim}(only remaining role; press Enter to accept)${P.reset}
309
+ `),await t.ask(" > "),e[0];for(t.write(` Role ${P.dim}(default: ${r})${P.reset}:
310
+ `),e.forEach((n,i)=>{let s=n===r?`${P.cyan}*${P.reset}`:" ";t.write(` ${s} ${i+1}. ${n}
311
+ `)});;){let n=await t.ask(" > ");if(n==="")return r;let i=parseInt(n,10)-1;if(i>=0&&i<e.length)return e[i];t.write(` ${P.yellow}Enter a number 1-${e.length} or press Enter for the default.${P.reset}
312
+ `)}}function Pa(t,e,r){if(r&&ke.includes(r)&&e.includes(r))return r;let n=Li[t]??ke[0];if(e.includes(n))return n;for(let i of ke)if(e.includes(i))return i;return e[0]}function Xi(t){return{write:e=>process.stdout.write(e),ask:e=>new Promise(r=>t.question(e,n=>r(n.trim())))}}var P,Qi=R(()=>{"use strict";et();st();P={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m"}});function Ca(t){switch(t.kind){case"timeout":return`${t.agent} reviewer timed out after ${t.elapsed_ms}ms`;case"spawn_failed":return`${t.agent} reviewer spawn failed: ${t.reason}`;case"parse_failure":return`${t.agent} reviewer output was unparseable`;case"cancelled":return"reviewer cancelled before completion";case"internal_join_failure":return`reviewer task internal join failure: ${t.reason}`}}var _,Ke=R(()=>{"use strict";_=class t extends Error{constructor(e){super(Ca(e)),this.name="ReviewerError",this.detail=e,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,t)}}});function Ta(t){switch(t.kind){case"empty_output":return"reviewer returned an empty reply";case"invalid_verdict":return`first non-blank line ${JSON.stringify(t.found)} is not a valid verdict (expected APPROVE | REJECT | REVISE | ESCALATE)`;case"reasoning_missing":return"reviewer returned a bare verdict with no reasoning";case"revise_missing_changes":return"REVISE verdict requires at least one suggested change in a bulleted list";case"suggested_changes_require_revise":return`suggested changes are reserved for REVISE verdicts; ${JSON.stringify(t.found)} verdict must not carry a bulleted list`}}function Ae(t){let r=t.replace(/\r\n/g,`
313
+ `).split(`
314
+ `),n=0;for(;n<r.length&&r[n].trim()==="";)n+=1;if(n>=r.length)return{ok:!1,error:{kind:"empty_output"}};let i=r[n];n+=1;let s=Oa(i.trim());if(!s.ok)return s;let o=s.kind,a=[],c=[],l=!1;for(;n<r.length;n+=1){let p=r[n];if(Da(p)){l=!0;let m=Na(p).trimEnd();m.length>0&&c.push(m);continue}let f=$a(p);if(l){if(f==="")continue;let m=c[c.length-1];if(m!==void 0&&(p.startsWith(" ")||p.startsWith(" "))){c[c.length-1]=m+" "+f.trimStart();continue}return{ok:!1,error:{kind:"invalid_verdict",found:f}}}a.push(f)}for(;a.length>0&&a[0]==="";)a.shift();for(;a.length>0&&a[a.length-1]==="";)a.pop();let d=a.join(`
315
+ `);if(d.trim()==="")return{ok:!1,error:{kind:"reasoning_missing"}};if(o==="REVISE"){if(c.length===0)return{ok:!1,error:{kind:"revise_missing_changes"}}}else if(c.length>0)return{ok:!1,error:{kind:"suggested_changes_require_revise",found:o}};return{ok:!0,verdict:{kind:o,reasoning:d,suggested_changes:c}}}function Oa(t){let e=t;switch((e.endsWith(":")||e.endsWith("."))&&(e=e.slice(0,-1)),e.toUpperCase()){case"APPROVE":return{ok:!0,kind:"APPROVE"};case"REJECT":return{ok:!0,kind:"REJECT"};case"REVISE":return{ok:!0,kind:"REVISE"};case"ESCALATE":return{ok:!0,kind:"ESCALATE"};default:return{ok:!1,error:{kind:"invalid_verdict",found:t}}}}function Da(t){return t.startsWith("- ")||t.startsWith("* ")}function Na(t){return t.slice(2).trimStart()}function $a(t){return t.trimEnd()}var ar,xt=R(()=>{"use strict";ar=class t extends Error{constructor(e){super(Ta(e)),this.name="VerdictParseError",this.detail=e,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,t)}}});function Ma(t){switch(t.kind){case"spawn_failed":return`failed to spawn subprocess: ${t.reason}`;case"timeout":return`subprocess timed out after ${t.elapsed_ms}ms`;case"io":return`subprocess IO error: ${t.reason}`;case"cancelled":return"subprocess cancelled before completion"}}function _e(t){return new Promise((e,r)=>{let n=Date.now(),i;try{i=(0,Zi.spawn)(t.command,[...t.args],{env:t.env,cwd:t.cwd,stdio:["pipe","pipe","pipe"],windowsHide:!0})}catch(g){r(new F({kind:"spawn_failed",reason:g instanceof Error?g.message:String(g)}));return}let s=!1,o=[],a=[],c=()=>{try{i.stdin&&!i.stdin.destroyed&&i.stdin.destroy()}catch{}try{i.stdout&&!i.stdout.destroyed&&i.stdout.destroy()}catch{}try{i.stderr&&!i.stderr.destroyed&&i.stderr.destroy()}catch{}},l=()=>{try{i.kill("SIGKILL")}catch{}},d=()=>{},p=()=>{},f=g=>{s||(s=!0,d(),p(),e(g))},m=g=>{s||(s=!0,d(),p(),c(),l(),r(g))};i.stdout.on("data",g=>{o.push(g)}),i.stderr.on("data",g=>{a.push(g)}),i.on("error",g=>{g.code==="ENOENT"||g.code==="EACCES"||g.code==="EPERM"?m(new F({kind:"spawn_failed",reason:g.message})):m(new F({kind:"io",reason:g.message}))}),i.on("close",(g,A)=>{if(s)return;let b=Date.now()-n,T=Buffer.concat(o).toString("utf8"),O=Buffer.concat(a).toString("utf8");f({stdout:T,stderr:O,elapsed_ms:b,exit_success:g===0&&A===null})}),i.stdin.on("error",g=>{});try{i.stdin.write(t.prompt,"utf8",()=>{try{i.stdin.end()}catch{}})}catch(g){m(new F({kind:"io",reason:g instanceof Error?g.message:String(g)}));return}let S=setTimeout(()=>{m(new F({kind:"timeout",elapsed_ms:t.timeout_ms}))},t.timeout_ms);p=()=>{clearTimeout(S)};let y=()=>{m(new F({kind:"cancelled"}))};if(t.signal){if(d=()=>{t.signal.removeEventListener("abort",y)},t.signal.aborted){y();return}t.signal.addEventListener("abort",y,{once:!0})}})}var Zi,F,It=R(()=>{"use strict";Zi=require("child_process"),F=class t extends Error{constructor(e){super(Ma(e)),this.name="SubprocessError",this.detail=e,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,t)}}});function ot(t,e){switch(e.kind){case"spawn_failed":return{kind:"spawn_failed",agent:t,reason:e.reason};case"timeout":return{kind:"timeout",agent:t,elapsed_ms:e.elapsed_ms};case"io":return{kind:"spawn_failed",agent:t,reason:`io error: ${e.reason}`};case"cancelled":return{kind:"cancelled"}}}var cr=R(()=>{"use strict"});function Ua(t,e){let r=[];r.push("--print"),r.push("--allowed-tools",e.tool_allowlist.join(",")),e.model_hint!==null&&r.push("--model",e.model_hint);let n={...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"};return{command:t,args:r,env:n}}function La(t,e,r){if(!r.exit_success)throw new _({kind:"spawn_failed",agent:t.agent,reason:`claude exited with non-zero status; stderr: ${r.stderr.trim()}`});let n=Ae(r.stdout);if(!n.ok)throw new _({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{verdict_id:(0,es.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,verdict:n.verdict.kind,reasoning:n.verdict.reasoning,suggested_changes:n.verdict.suggested_changes,model_used:t.model_hint,tokens_used:null,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString()}}var es,at,mn=R(()=>{"use strict";es=require("uuid");xt();Ke();It();cr();at=class{constructor(e={}){this.executable=e.executable??"claude"}async evaluate(e,r){if(e.agent!=="claude")throw new Error(`ClaudeReviewerProvider called with non-Claude spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let n=Ua(this.executable,e),i;try{i=await _e({command:n.command,args:n.args,env:n.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms})}catch(s){throw s instanceof F?new _(ot(e.agent,s.detail)):s}return La(e,r,i)}}});function Ka(t,e){let r=[];r.push("-p",""),r.push("--approval-mode","plan"),r.push("--output-format","json"),e.model_hint!==null&&r.push("--model",e.model_hint);let n={...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"};return{command:t,args:r,env:n}}function Ba(t,e,r){if(!r.exit_success)throw new _({kind:"spawn_failed",agent:t.agent,reason:`gemini exited with non-zero status; stderr: ${r.stderr.trim()}`});let n=Wa(r.stdout);if(n===null)throw new _({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});let i=Ae(n.response);if(!i.ok)throw new _({kind:"parse_failure",agent:t.agent,raw_output:n.response});let s=Fa(n);return{verdict_id:(0,ts.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,verdict:i.verdict.kind,reasoning:i.verdict.reasoning,suggested_changes:i.verdict.suggested_changes,model_used:t.model_hint,tokens_used:s,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString()}}function Fa(t){let e=t.stats?.models;if(!e)return null;let r=[];for(let n of Object.values(e)){let i=n.tokens?.total;typeof i=="number"&&r.push(i)}return r.length===0?null:r.reduce((n,i)=>n+i,0)}function Wa(t){let e=t.indexOf("{");if(e<0)return null;let r=0,n=!1,i=!1;for(let s=e;s<t.length;s+=1){let o=t[s];if(i){i=!1;continue}if(n){o==="\\"?i=!0:o==='"'&&(n=!1);continue}if(o==='"'){n=!0;continue}if(o==="{")r+=1;else if(o==="}"&&(r-=1,r===0)){let a=t.slice(e,s+1),c;try{c=JSON.parse(a)}catch{return null}return Ga(c)}}return null}function Ga(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;return typeof e.response!="string"?null:e}var ts,ct,fn=R(()=>{"use strict";ts=require("uuid");xt();Ke();It();cr();ct=class{constructor(e={}){this.executable=e.executable??"gemini"}async evaluate(e,r){if(e.agent!=="gemini")throw new Error(`GeminiReviewerProvider called with non-Gemini spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let n=Ka(this.executable,e),i;try{i=await _e({command:n.command,args:n.args,env:n.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms})}catch(s){throw s instanceof F?new _(ot(e.agent,s.detail)):s}return Ba(e,r,i)}}});function Va(t,e,r){let n=[];n.push("exec"),n.push("--sandbox","read-only"),n.push("--skip-git-repo-check"),n.push("--color","never"),n.push("--json"),n.push("--ephemeral"),n.push("--output-last-message",r),e.model_hint!==null&&n.push("--model",e.model_hint),n.push("-");let i={...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"};return{command:t,args:n,env:i}}function Ha(t,e,r,n){if(!r.exit_success)throw new _({kind:"spawn_failed",agent:t.agent,reason:`codex exited with non-zero status; stderr: ${r.stderr.trim()}`});let i=Ae(n);if(!i.ok)throw new _({kind:"parse_failure",agent:t.agent,raw_output:n});let s=za(r.stdout);return{verdict_id:(0,gn.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,verdict:i.verdict.kind,reasoning:i.verdict.reasoning,suggested_changes:i.verdict.suggested_changes,model_used:t.model_hint,tokens_used:s,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString()}}function za(t){let e=[];for(let r of t.split(`
316
+ `)){let n=r.trim();if(n==="")continue;let i;try{i=JSON.parse(n)}catch{continue}if(i.type==="turn.completed"&&i.usage){let s=i.usage.input_tokens??0,o=i.usage.output_tokens??0;e.push(s+o)}}return e.length===0?null:e.reduce((r,n)=>r+n,0)}function ja(){return ns.join(rs.tmpdir(),`quorum-codex-last-${process.pid}-${(0,gn.v4)()}.txt`)}function lr(t){try{ur.unlinkSync(t)}catch{}}var ur,rs,ns,gn,lt,yn=R(()=>{"use strict";ur=h(require("fs")),rs=h(require("os")),ns=h(require("path")),gn=require("uuid");xt();Ke();It();cr();lt=class{constructor(e={}){this.executable=e.executable??"codex"}async evaluate(e,r){if(e.agent!=="codex")throw new Error(`CodexReviewerProvider called with non-Codex spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let n=ja(),i=Va(this.executable,e,n),s;try{s=await _e({command:i.command,args:i.args,env:i.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms})}catch(a){throw lr(n),a instanceof F?new _(ot(e.agent,a.detail)):a}if(!s.exit_success)throw lr(n),new _({kind:"spawn_failed",agent:e.agent,reason:`codex exited with non-zero status; stderr: ${s.stderr.trim()}`});let o;try{o=ur.readFileSync(n,"utf8")}catch(a){lr(n);let c=a instanceof Error?a.message:String(a);throw new _({kind:"parse_failure",agent:e.agent,raw_output:`codex exited 0 but --output-last-message file unreadable (${c}): stdout follows
317
+ ${s.stdout}`})}return lr(n),Ha(e,r,s,o)}}});function dr(){return new Pt().with("claude",new at).with("gemini",new ct).with("codex",new lt)}var Pt,is=R(()=>{"use strict";Ke();mn();yn();fn();Pt=class{constructor(){this.providers=new Map}with(e,r){return this.providers.set(e,r),this}register(e,r){this.providers.set(e,r)}providerFor(e){return this.providers.get(e)}registeredAgents(){return Array.from(this.providers.keys())}async evaluate(e,r){let n=this.providers.get(e.agent);if(n===void 0)throw new _({kind:"spawn_failed",agent:e.agent,reason:`no provider registered for ${e.agent} \u2014 registry was built without a ${e.agent} entry but the policy snapshot includes a ${e.agent} reviewer`});return n.evaluate(e,r)}}});function ss(){return{type:"verdict",kind:"APPROVE",reasoning:"static mock: approve",suggested_changes:[]}}function os(){return{type:"verdict",kind:"REJECT",reasoning:"static mock: reject",suggested_changes:[]}}function as(t){return{type:"verdict",kind:"REVISE",reasoning:"static mock: revise",suggested_changes:t.length===0?["static mock: placeholder revision"]:t}}function cs(){return{type:"verdict",kind:"ESCALATE",reasoning:"static mock: escalate",suggested_changes:[]}}var hn,pr,mr,ls=R(()=>{"use strict";hn=require("uuid");Ke();pr=class t{constructor(){this.scripts=new Map}static key(e,r){return`${e}|${r}`}scriptVerdict(e,r,n,i){this.scriptVerdictWithChanges(e,r,n,i,[])}scriptVerdictWithChanges(e,r,n,i,s){let o=t.key(e,r),a=this.scripts.get(o)??[];a.push({type:"verdict",kind:n,reasoning:i,suggested_changes:s}),this.scripts.set(o,a)}scriptError(e,r,n){let i=t.key(e,r),s=this.scripts.get(i)??[];s.push({type:"error",error:n}),this.scripts.set(i,s)}remaining(e,r){let n=t.key(e,r);return this.scripts.get(n)?.length??0}async evaluate(e,r){let n=t.key(e.agent,r),i=this.scripts.get(n),s=i&&i.length>0?i.shift():null;if(s===null)throw new _({kind:"spawn_failed",agent:e.agent,reason:`no scripted response for (${e.agent}, gate=${r}); test forgot to wire a reviewer`});if(s.type==="error")throw new _(s.error);return{verdict_id:(0,hn.v4)(),gate_id:r,seat_id:e.seat_id,role:e.role,reviewer_agent:e.agent,verdict:s.kind,reasoning:s.reasoning,suggested_changes:s.suggested_changes,model_used:`mock-${e.agent}`,tokens_used:0,latency_ms:0,submitted_at:new Date().toISOString()}}};mr=class t{constructor(){this.defaultResponse=null;this.perAgent=new Map}static new(){return new t}static allApprove(){let e=new t;return e.defaultResponse=ss(),e}static allReject(){let e=new t;return e.defaultResponse=os(),e}static allRevise(e){let r=new t;return r.defaultResponse=as(e),r}static allEscalate(){let e=new t;return e.defaultResponse=cs(),e}static allError(e){let r=new t;return r.defaultResponse={type:"error",error:e},r}withAgentVerdict(e,r){let n;switch(r){case"APPROVE":n=ss();break;case"REJECT":n=os();break;case"REVISE":n=as([]);break;case"ESCALATE":n=cs();break}return this.perAgent.set(e,n),this}withAgentError(e,r){return this.perAgent.set(e,{type:"error",error:r}),this}async evaluate(e,r){let n=this.perAgent.get(e.agent)??this.defaultResponse;if(n===null)throw new _({kind:"spawn_failed",agent:e.agent,reason:`StaticReviewerMock has no response configured for ${e.agent} (set a default via allApprove() / allReject() / etc., or an override via withAgentVerdict() / withAgentError())`});if(n.type==="error")throw new _(n.error);return{verdict_id:(0,hn.v4)(),gate_id:r,seat_id:e.seat_id,role:e.role,reviewer_agent:e.agent,verdict:n.kind,reasoning:n.reasoning,suggested_changes:n.suggested_changes,model_used:`static-mock-${e.agent}`,tokens_used:0,latency_ms:0,submitted_at:new Date().toISOString()}}}});var Sn={};ue(Sn,{ClaudeReviewerProvider:()=>at,CodexReviewerProvider:()=>lt,GeminiReviewerProvider:()=>ct,MockReviewerSpawner:()=>pr,ReviewerErrorClass:()=>_,ReviewerRegistry:()=>Pt,StaticReviewerMock:()=>mr,SubprocessErrorClass:()=>F,VerdictParseErrorClass:()=>ar,createSubprocessReviewerRegistry:()=>dr,parseVerdictOutput:()=>Ae,runReviewer:()=>_e});var vn=R(()=>{"use strict";Ke();xt();It();mn();fn();yn();is();ls()});async function us(t){let e=Date.now();await be({wizardRunId:t.wizardRunId,step:"test_my_agents"});let r=t.write??(p=>process.stdout.write(p)),n=t.registryFactory?t.registryFactory():dr(),i=t.gateId??(await import("crypto")).randomUUID();for(let p of t.seats)r(`Spawning seat ${p.seatId} (${p.agent} / ${p.role})\u2026
318
+ `);let s=t.seats.map(p=>Ya(p)),o=new Map;for(let p of t.seats)o.set(p.seatId,Date.now());let a=await Promise.allSettled(s.map(p=>n.evaluate(p,i))),c=[];for(let p=0;p<t.seats.length;p++){let f=t.seats[p],m=a[p],S=Date.now()-(o.get(f.seatId)??e),y=S/1e3,g={seatId:f.seatId,agent:f.agent,role:f.role,elapsedSeconds:y,result:Xa(m,S)};c.push(g),r(Qa(g))}let l=Za(c),d=ee((Date.now()-e)/1e3);return l===null?(r(`${I.green}\u2713${I.reset} All reviewers responded with parseable verdicts (parallel run, total wall: ${((Date.now()-e)/1e3).toFixed(1)}s)
319
+ `),await Re({wizardRunId:t.wizardRunId,step:"test_my_agents",latencyBucket:d}),{ok:!0,seatOutcomes:c}):(await rt({wizardRunId:t.wizardRunId,step:"test_my_agents",reason:l,latencyBucket:d}),{ok:!1,reason:l,canSaveAnyway:ec(l),seatOutcomes:c})}function Ya(t){return{seat_id:t.seatId,role:t.role,agent:t.agent,tool_allowlist:["Read","Grep","Glob"],prompt_template:qa,timeout_ms:Ja,model_hint:null}}function Xa(t,e){if(t.status==="fulfilled"){let n=t.value.verdict;return n==="APPROVE"?{kind:"approve"}:n==="REVISE"?{kind:"revise"}:n==="REJECT"?{kind:"reject"}:n==="ESCALATE"?{kind:"escalate"}:{kind:"parse_failure"}}let r=t.reason;if(r instanceof _){let n=r.detail;return n.kind==="timeout"?{kind:"timeout",elapsedMs:n.elapsed_ms}:n.kind==="spawn_failed"?{kind:"spawn_failure",reason:n.reason}:n.kind==="parse_failure"?{kind:"parse_failure"}:{kind:"unknown_error",message:`unexpected reviewer error: ${n.kind}`}}return{kind:"unknown_error",message:r instanceof Error?r.message:String(r)}}function Qa(t){let e=` [${t.elapsedSeconds.toFixed(1)}s] seat ${t.seatId}:`,r=` ${I.dim}(${t.agent} / ${t.role})${I.reset}
320
+ `;switch(t.result.kind){case"approve":return`${e} ${I.green}APPROVE${I.reset}${r}`;case"revise":return`${e} ${I.yellow}REVISE${I.reset}${r}`;case"reject":return`${e} ${I.red}REJECT${I.reset}${r}`;case"escalate":return`${e} ${I.yellow}ESCALATE${I.reset}${r}`;case"parse_failure":return`${e} ${I.red}parse failure${I.reset}${r}`;case"spawn_failure":return`${e} ${I.red}spawn failure${I.reset} ${I.dim}\u2014 ${t.result.reason}${I.reset}${r}`;case"timeout":return`${e} ${I.red}timeout${I.reset} ${I.dim}(${(t.result.elapsedMs/1e3).toFixed(0)}s)${I.reset}${r}`;case"unknown_error":return`${e} ${I.red}error${I.reset} ${I.dim}\u2014 ${t.result.message}${I.reset}${r}`}}function Za(t){for(let e of t)if(e.result.kind==="spawn_failure")return"test_spawn_failure";for(let e of t)if(e.result.kind==="timeout")return"test_timeout";for(let e of t)if(e.result.kind==="parse_failure")return"test_parse_failure";for(let e of t)if(e.result.kind==="reject")return"test_reject";for(let e of t)if(e.result.kind==="escalate")return"test_escalate";for(let e of t)if(e.result.kind==="revise")return"test_revise";for(let e of t)if(e.result.kind==="unknown_error")return"test_parse_failure";return null}function ec(t){return!(t==="test_spawn_failure"||t==="test_timeout")}function ds(t){let e=[];for(let r of t)switch(r.result.kind){case"approve":continue;case"spawn_failure":e.push(`Couldn't spawn the ${r.agent} CLI for seat ${r.seatId} \u2014 install or fix it before retrying (cause: ${r.result.reason}).`);break;case"timeout":e.push(`Seat ${r.seatId}'s ${r.agent} reviewer didn't respond within ${(r.result.elapsedMs/1e3).toFixed(0)}s \u2014 your CLI may be hanging.`);break;case"parse_failure":e.push(`Seat ${r.seatId}'s ${r.agent} reviewer returned output the parser couldn't understand. Try a different agent or re-run.`);break;case"reject":e.push(`Seat ${r.seatId} (${r.agent} / ${r.role}) REJECTED the test proposal. Either save anyway, or try a different role/agent.`);break;case"escalate":e.push(`Seat ${r.seatId} (${r.agent} / ${r.role}) ESCALATED \u2014 the reviewer wants human input. Save anyway or retry.`);break;case"revise":e.push(`Seat ${r.seatId} (${r.agent} / ${r.role}) requested REVISIONS. Safe to save anyway; the canned proposal is intentionally trivial.`);break;case"unknown_error":e.push(`Seat ${r.seatId} (${r.agent} / ${r.role}) hit an unexpected error: ${r.result.message}.`);break}return e}var I,qa,Ja,ps=R(()=>{"use strict";et();st();vn();I={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},qa=`## Problem
321
+ Add a one-line Python "Hello, World" script to a new file.
322
+
323
+ ## Proposal
324
+ Create a single Python file at /tmp/quorum_test_hello.py containing the
325
+ single line: print("hello world")
326
+
327
+ ## Implementation Plan
328
+ 1. Create the file at /tmp/quorum_test_hello.py
329
+ 2. Write print("hello world") on line 1 followed by a trailing newline
330
+ 3. Make no other changes
331
+
332
+ ## Expected Outputs
333
+ - /tmp/quorum_test_hello.py \u2014 exists, contains the single-line script
334
+ `,Ja=6e4});async function ms(t){let e=Date.now();await be({wizardRunId:t.wizardRunId,step:"save"});let r=t.seats.map(n=>({seatId:n.seatId,role:Ki(n.role),agent:Bi(n.agent)}));try{return await t.client.updateReviewerPolicy({orchestrationEnabledDefault:!0,reviewerSeats:r}),await Re({wizardRunId:t.wizardRunId,step:"save",latencyBucket:ee((Date.now()-e)/1e3)}),{ok:!0}}catch(n){let i=tc(n),s=i!=="auth_token_expired";return await rt({wizardRunId:t.wizardRunId,step:"save",reason:i,latencyBucket:ee((Date.now()-e)/1e3)}),{ok:!1,reason:i,recoverable:s}}}function tc(t){let e=t instanceof Error?t.message:String(t);return/401|Unauthorized|NotAuthorizedException|(?:token|session|access[_-]?token|refresh[_-]?token|sign[ -]?in)\b[^.]{0,40}\bexpired/i.test(e)?"auth_token_expired":/429|throttl|RateExceeded|TooManyRequests/i.test(e)?"update_policy_throttle":/\b5\d\d\b|InternalServerError|InternalFailure|ServiceUnavailable/i.test(e)?"update_policy_5xx":"update_policy_network"}var fs=R(()=>{"use strict";et();st()});async function gs(t,e){for(t.write(`
335
+ `),t.write(`${W.bold}What now?${W.reset}
336
+ `),t.write(` [r] retry the test
337
+ `),e&&t.write(` [s] save the policy anyway (use with caution \u2014 your reviewers may not work as expected)
338
+ `),t.write(` [x] exit without saving
339
+ `);;){let r=(await t.ask("> ")).toLowerCase();if(r==="r"||r==="retry")return"retry";if(e&&(r==="s"||r==="save"))return"save_anyway";if(r==="x"||r==="exit"||r==="q"||r==="quit")return"exit";let n=e?"[r]/[s]/[x]":"[r]/[x]";t.write(`${W.yellow}Enter ${n}.${W.reset}
340
+ `)}}async function ys(t,e=!0){if(t.write(`
341
+ `),!e)for(t.write(`${W.bold}Your sign-in expired between bootstrap and save.${W.reset}
342
+ `),t.write(`Re-run ${W.bold}codevibe login${W.reset} and then ${W.bold}codevibe orchestration setup${W.reset} to try again.
343
+ `),t.write(` [x] exit (your picks are lost)
344
+ `);;){let r=(await t.ask("> ")).toLowerCase();if(r==="x"||r==="exit"||r==="q"||r==="quit")return"exit";t.write(`${W.yellow}Enter [x].${W.reset}
345
+ `)}for(t.write(`${W.bold}What now?${W.reset}
346
+ `),t.write(` [r] retry the save
347
+ `),t.write(` [x] exit (your picks are lost)
348
+ `);;){let r=(await t.ask("> ")).toLowerCase();if(r==="r"||r==="retry")return"retry";if(r==="x"||r==="exit"||r==="q"||r==="quit")return"exit";t.write(`${W.yellow}Enter [r]/[x].${W.reset}
349
+ `)}}var W,hs=R(()=>{"use strict";W={reset:"\x1B[0m",bold:"\x1B[1m",yellow:"\x1B[33m"}});function rc(t){for(let e of t)if(e.startsWith("--entry=")){let r=e.slice(8);if(r==="meta_cli"||r==="claude_alias"||r==="gemini_alias"||r==="codex_alias")return r}return"meta_cli"}async function vs(t){let e=await nc(t,{clientFactory:ji,agentDetector:Z,write:r=>process.stdout.write(r),createPickerIO:()=>{let r=Ss.createInterface({input:process.stdin,output:process.stdout});return{io:Xi(r),close:()=>r.close()}}});process.exit(e.exitCode)}async function nc(t,e){let r=Vi(),n=rc(t),i=Date.now(),s="bootstrap",o=!1,a=async()=>{o&&process.exit(130),o=!0;try{await nt({wizardRunId:r,reason:"ctrl_c",lastStep:s})}catch{}e.write(`
350
+ ^C \u2014 wizard aborted, nothing saved.
351
+ `),process.exit(130)};process.on("SIGINT",a);try{ic(e.write),s="bootstrap";let c=await qi({wizardRunId:r,clientFactory:e.clientFactory,agentDetector:e.agentDetector,entry:n});if(!c.ok)return ac(e.write,c.failure),{exitCode:1};let l=c.result;sc(e.write,l);let d=l.client;s="seat_assignment";let p=e.createPickerIO(),f;try{let b=l.savedPolicy?.reviewerSeats?.filter(T=>ke.includes(T.role.toLowerCase())).map(T=>({seatId:T.seatId,agent:T.agent.toLowerCase(),role:T.role.toLowerCase()}));f=await Yi({wizardRunId:r,installedAgents:l.installedAgents,seatBudget:l.seatBudget,io:p.io,savedSeats:b??void 0})}finally{p.close()}s="test_my_agents";let m=!1,S=!1;for(;;){e.write(`
352
+ ${w.bold}Step 2 of 3 \u2014 Test My Agents${w.reset}
353
+ `),e.write(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
354
+ `);let b=await us({wizardRunId:r,seats:f,registryFactory:e.registryFactory,write:e.write});if(b.ok){S=!0,m=!1;break}for(let le of ds(b.seatOutcomes))e.write(`${w.yellow}${le}${w.reset}
355
+ `);let T=e.createPickerIO(),O;try{O=await gs(T.io,b.canSaveAnyway)}finally{T.close()}if(O!=="retry"){if(O==="save_anyway"){S=!0,m=!0;break}return await nt({wizardRunId:r,reason:"step_user_exit",lastStep:"test_my_agents"}),e.write(`
356
+ Exited without saving.
357
+ `),{exitCode:0}}}if(!S)return{exitCode:1};for(s="save";;){e.write(`
358
+ ${w.bold}Step 3 of 3 \u2014 Save${w.reset}
359
+ `),e.write(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
360
+ `),e.write(`Saving reviewer policy to your account\u2026
361
+ `);let b=await ms({wizardRunId:r,client:d,seats:f,savedAfterTestWarning:m});if(b.ok)break;e.write(`
362
+ ${w.red}Save failed:${w.reset} ${lc(b.reason)}
363
+ `);let T=e.createPickerIO(),O;try{O=await ys(T.io,b.recoverable)}finally{T.close()}if(O!=="retry")return await nt({wizardRunId:r,reason:"step_save_failed_exit",lastStep:"save"}),e.write(`
364
+ Exited; your picks are lost.
365
+ `),{exitCode:1}}e.write(`
366
+ ${w.green}\u2713${w.reset} Policy saved
367
+
368
+ `),cc(e.write,f,l.installedAgents);let y=ee((Date.now()-i)/1e3),g=new Set(f.map(b=>b.agent)).size,A=new Set(f.map(b=>b.role)).size;return await zi({wizardRunId:r,outcome:m?"saved_after_test_warning":"ok",tier:l.tier,seatsBucket:Ze(f.length),agentsDistinctBucket:Ze(g),rolesDistinctBucket:Ze(A),totalLatencyBucket:y}),{exitCode:0}}finally{process.removeListener("SIGINT",a)}}function ic(t){t(`
369
+ `),t(`${w.bold}Quorum 2.0 setup wizard${w.reset}
370
+ `),t(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
371
+
372
+ `),t(`Checking your account\u2026
373
+ `)}function sc(t,e){e.userEmail&&t(` ${w.green}\u2713${w.reset} Signed in as ${w.bold}${e.userEmail}${w.reset}
374
+ `),t(` ${w.green}\u2713${w.reset} Tier: ${w.bold}${oc(e.tier)}${w.reset}
375
+ `),t(` ${w.green}\u2713${w.reset} Reviewer-seat budget: ${e.seatBudget} seat${e.seatBudget===1?"":"s"}
376
+ `),t(`
377
+ Detecting installed agents\u2026
378
+ `);for(let r of e.installedAgents)t(` ${w.green}\u2713${w.reset} ${r}
379
+ `)}function oc(t){return t.charAt(0)+t.slice(1).toLowerCase()}function ac(t,e){switch(t(`
380
+ `),e.kind){case"tier_gate_free":t(`${w.yellow}Quorum review is a Pro/Max feature.${w.reset}
381
+ `),t(`Upgrade in the CodeVibe app or visit ${w.bold}https://quantiya.ai/codevibe${w.reset}.
382
+ `);break;case"not_signed_in":t(`${w.yellow}Not signed in.${w.reset} Run ${w.bold}codevibe login${w.reset} first.
383
+ `);break;case"subscription_status_network":t(`${w.red}Couldn't fetch your account info.${w.reset} Check your connection and try again.
384
+ `);break;case"no_clis_installed":t(`${w.red}No supported agent CLI detected.${w.reset} Install at least one of: ${w.bold}claude${w.reset}, ${w.bold}gemini${w.reset}, or ${w.bold}codex${w.reset}.
385
+ `);break}}function cc(t,e,r){t(`${w.bold}Your reviewer panel:${w.reset}
386
+ `);for(let n of e)t(` Seat ${n.seatId}: ${w.bold}${n.role}${w.reset} \u2192 ${w.bold}${n.agent}${w.reset}
387
+ `);t(`
388
+ Notifications: mobile push + desktop status pane (both on by default).
389
+ `),t(`
390
+ You're set. Next steps:
391
+ `),t(` Start an orchestrated session with any installed agent:
392
+ `);for(let n of sr)r.includes(n)&&t(` - ${w.bold}codevibe-${n} --orchestration${w.reset}
393
+ `);t(`
394
+ Re-run this wizard: ${w.bold}codevibe orchestration setup${w.reset}
395
+ `),t(`
396
+ `)}function lc(t){switch(t){case"update_policy_network":return"network failure \u2014 check your connection";case"update_policy_5xx":return"the orchestration service couldn't be reached \u2014 try again in a moment";case"update_policy_throttle":return"rate-limited \u2014 wait a moment and retry";case"auth_token_expired":return"your session expired \u2014 re-run `codevibe login` and try again";default:return`unexpected error (${t})`}}var Ss,w,ws=R(()=>{"use strict";Ss=h(require("readline"));_t();et();st();Ji();Qi();ps();fs();hs();w={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"}});async function fr(t){let r=t.slice(3).filter(n=>!n.startsWith("--"))[0];switch(r){case"enable":await pc();break;case"disable":await mc();break;case"status":await fc();break;case"configure":await gc();break;case"setup":await vs(t);break;default:dc(),process.exit(r?1:0)}}function dc(){console.log(""),console.log(`${v.bold}codevibe orchestration${v.reset} \u2014 Quorum 2.0 reviewer policy`),console.log(""),console.log("Usage: codevibe orchestration <command>"),console.log(""),console.log("Commands:"),console.log(" setup Run the locked 3-step setup wizard (recommended for first-time)"),console.log(" enable Auto-enable orchestration for new sessions"),console.log(" disable Disable orchestration (sessions route to 1.0 flow)"),console.log(" status Show current reviewer policy + installed agents"),console.log(" configure Advanced wizard (all 9 roles, manual seat-count)"),console.log("")}async function pc(){let e=await(await gr()).updateReviewerPolicy({orchestrationEnabledDefault:!0});En(e),console.log(`
397
+ ${v.green}\u2713${v.reset} Orchestration enabled. New sessions will use your reviewer panel.`)}async function mc(){let e=await(await gr()).updateReviewerPolicy({orchestrationEnabledDefault:!1});En(e),console.log(`
398
+ ${v.yellow}\u2713${v.reset} Orchestration disabled. New sessions route to the 1.0 companion flow.`)}async function fc(){let t=Z();if(console.log(""),console.log(`${v.bold}Installed agents${v.reset}`),t.length===0)console.log(` ${v.dim}(none detected on PATH)${v.reset}`);else for(let n of t)console.log(` ${v.green}\u2713${v.reset} ${n.toLowerCase()}`);console.log("");let r=await(await gr()).updateAvailableAgents(t);En(r)}async function gc(){let t=Z();t.length===0&&(console.log(""),console.log(`${v.yellow}No agents detected on PATH.${v.reset}`),console.log(`Install at least one of ${v.bold}claude${v.reset}, ${v.bold}gemini${v.reset}, or ${v.bold}codex${v.reset} before configuring orchestration.`),process.exit(1)),console.log(""),console.log(`${v.bold}Quorum 2.0 orchestration configuration${v.reset}`),console.log(`${v.dim}Detected agents: ${t.map(n=>n.toLowerCase()).join(", ")}${v.reset}`),console.log("");let e=await gr();await e.updateAvailableAgents(t);let r=bs.createInterface({input:process.stdin,output:process.stdout});try{if(!await Es(r,"Enable orchestration for new sessions?",!1)){await e.updateReviewerPolicy({orchestrationEnabledDefault:!1}),console.log(`
399
+ ${v.yellow}\u2713${v.reset} Orchestration disabled.`);return}if(!await Es(r,"Customize reviewer panel (otherwise use tier defaults)?",!1)){await e.updateReviewerPolicy({orchestrationEnabledDefault:!0,reviewerSeats:[]}),console.log(`
400
+ ${v.green}\u2713${v.reset} Orchestration enabled with tier-default reviewer panel.`);return}let s=await yc(r),o=[],a=new Set;for(let c=0;c<s;c++){console.log(""),console.log(`${v.bold}Seat ${c}${v.reset}`);let l=uc.filter(f=>!a.has(f)),d=await ks(r,"Role:",l),p=await ks(r,"Agent:",t);o.push({seatId:c,role:d,agent:p}),a.add(d)}await e.updateReviewerPolicy({orchestrationEnabledDefault:!0,reviewerSeats:o}),console.log(""),console.log(`${v.green}\u2713${v.reset} Orchestration enabled with custom panel:`);for(let c of o)console.log(` Seat ${c.seatId}: ${c.role.toLowerCase()} \u2192 ${c.agent.toLowerCase()}`)}finally{r.close()}}function wn(t,e){return new Promise(r=>t.question(e,n=>r(n.trim())))}async function Es(t,e,r){let i=(await wn(t,e+(r?" [Y/n] ":" [y/N] "))).toLowerCase();return i?i.startsWith("y"):r}async function yc(t){for(;;){let e=await wn(t,"How many seats (2 for Pro, 3 for Max)? "),r=parseInt(e,10);if(r===2||r===3)return r;console.log(`${v.yellow}Enter 2 or 3.${v.reset}`)}}async function ks(t,e,r){for(;;){console.log(e),r.forEach((s,o)=>{console.log(` ${v.cyan}${o+1}${v.reset}. ${s.toLowerCase()}`)});let n=await wn(t,"> "),i=parseInt(n,10)-1;if(i>=0&&i<r.length)return r[i];console.log(`${v.yellow}Enter a number between 1 and ${r.length}.${v.reset}`)}}async function gr(){let t=new fe;return await t.authenticateWithStoredTokens()||(console.log(""),console.log(`${v.yellow}Not authenticated.${v.reset} Run ${v.bold}codevibe login${v.reset} first.`),process.exit(1)),t}function En(t){console.log(""),console.log(`${v.bold}Current reviewer policy${v.reset}`),console.log(` Orchestration default: ${hc(t.orchestrationEnabledDefault)}`),console.log(` Available agents: ${t.availableAgents?.length?t.availableAgents.map(e=>e.toLowerCase()).join(", "):`${v.dim}(not yet detected)${v.reset}`}`),console.log(` Reviewer panel: ${Sc(t.reviewerSeats)}`)}function hc(t){return t===!0?`${v.green}enabled${v.reset}`:t===!1?`${v.yellow}disabled${v.reset}`:`${v.dim}(unset \u2014 defaults to disabled)${v.reset}`}function Sc(t){return!t||t.length===0?`${v.dim}tier defaults${v.reset}`:t.map(e=>`Seat ${e.seatId} ${e.role.toLowerCase()}\u2192${e.agent.toLowerCase()}`).join(", ")}var bs,v,uc,Rs=R(()=>{"use strict";bs=h(require("readline"));er();kt();_t();ws();v={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",purple:"\x1B[35m",cyan:"\x1B[36m"},uc=["ARCHITECTURE","CORRECTNESS","SECURITY","ACCURACY","CLARITY","COMPLETENESS","ARCHITECTURE_AND_ACCURACY","CORRECTNESS_AND_CLARITY","SECURITY_AND_COMPLETENESS"]});function Ct(t){return!Number.isInteger(t)||t<1||t>ut.length?null:ut[t-1].kind}var yr,ut,hr,As=R(()=>{"use strict";yr="orchestration_escalated_gate",ut=[{number:"1",label:"Accept",kind:"accept"},{number:"2",label:"Reject (restart proposal)",kind:"reject_restart"},{number:"3",label:"Abort task",kind:"abort_task"}];hr=Ct});var _s={};ue(_s,{V1_ORCHESTRATION_OPTIONS:()=>ut,V1_ORCHESTRATION_PROMPT_KIND:()=>yr,applyPerSessionOrchestrationOverride:()=>ir,detectInstalledAgents:()=>Z,mapOptionNumberToUserDecisionKind:()=>Ct,mapOptionToUserDecisionKind:()=>hr,pushDetectedAgents:()=>nr,runOrchestrationCli:()=>fr});var kn=R(()=>{"use strict";_t();Rs();As()});var Su={};ue(Su,{AgentType:()=>wi,AppSyncClient:()=>fe,AppSyncGraphQLError:()=>Ye,AuditKeys:()=>In,AuthService:()=>Qe,CryptoError:()=>pe,CryptoService:()=>je,DeliveryStatus:()=>vi,ENCRYPTION_VERSION:()=>vt,EventSource:()=>rn,EventType:()=>tn,KeychainError:()=>me,KeychainManager:()=>De,Logger:()=>Pe,Planner:()=>On,Reviewer:()=>Sn,ReviewerRole:()=>Zt,SessionStatus:()=>Qt,StructuralSummary:()=>Bn,TierError:()=>St,V1_ORCHESTRATION_OPTIONS:()=>ut,V1_ORCHESTRATION_PROMPT_KIND:()=>yr,applyPerSessionOrchestrationOverride:()=>ir,authService:()=>ge,createLogger:()=>Gr,createShellEventEmitter:()=>Gt,cryptoService:()=>$,detectInstalledAgents:()=>Z,emitShellEvent:()=>Kr,errorWasBeaconed:()=>Rt,fireAuthCompletedBeacon:()=>bt,fireAuthFailedBeacon:()=>V,getConfig:()=>M,getEnvironment:()=>J,getErrorReason:()=>ln,keychainManager:()=>k,loadConfig:()=>Yt,logger:()=>u,mapOptionNumberToUserDecisionKind:()=>Ct,mapOptionToUserDecisionKind:()=>hr,markErrorBeaconed:()=>Y,mutations:()=>U,normalizeSnapshot:()=>An,parseInteractivePrompt:()=>xs,pickMode:()=>ei,prepareSessionEncryption:()=>wr,processMarkers:()=>Ge,pushDetectedAgents:()=>nr,queries:()=>oe,registerDeviceEncryptionKey:()=>Tt,rekeySessionForNewDevices:()=>Be,resumeOrCreateSession:()=>_n,runAuthCli:()=>Sr,runCompanionMode:()=>jo,runOrchestrationCli:()=>fr,runOrchestrationShell:()=>Do,startDeviceKeyWatcher:()=>xn,subscriptions:()=>Ne,withRoleMarker:()=>Yn});module.exports=ni(Su);re();Te();er();er();var Di=h(require("crypto")),Ni=h(require("fs")),dn=h(require("http")),$i=require("child_process");qe();re();N();Zr();var an=h(require("crypto")),Ri=h(require("https")),tr=h(require("os")),ua="G-GS74YEQTB8",da="lAfOF6OxRzSQ-NsLBRjhAg",pa="www.google-analytics.com",ma=`/mp/collect?measurement_id=${ua}&api_secret=${da}`,fa={port_in_use:"server_start",server_listen_failed:"server_start",browser_open_failed:"browser_open",login_timeout:"awaiting_callback",cognito_rejected:"awaiting_callback",state_mismatch:"awaiting_callback",no_authorization_code:"awaiting_callback",token_exchange_failed:"exchanging_code",token_exchange_network_error:"exchanging_code",keychain_write_failed:"storing_tokens",user_aborted:"unknown",unknown:"unknown"};function ga(){let t=typeof process.getuid=="function"?process.getuid():0;return an.createHash("sha256").update(`${tr.hostname()}-${t}`).digest("hex").substring(0,36)}function we(){return{platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production"}}async function Ee(t,e){try{let r=JSON.stringify({client_id:ga(),events:[{name:t,params:e}]});await new Promise(n=>{let i=Ri.request({hostname:pa,path:ma,method:"POST",headers:{"Content-Type":"application/json"}},()=>n());i.on("error",()=>n()),i.write(r),i.end(),setTimeout(n,2e3)})}catch{}}async function bt(t){await Ee("auth_completed",{...we(),user_id:t})}function Ai(t){if(!t)return"";let e=t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"").replace(/\\/g,"/").replace(/[\n\r\t"]/g," ").replace(/[^\x20-\x7E]/g,"").trim(),r=[process.env.HOME,process.env.USERPROFILE,(()=>{try{return tr.homedir()}catch{return}})()].filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/\\/g,"/"));for(let n of r){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(i,"g"),"~")}return e.replace(/\/Users\/[^/ ]+/g,"/Users/<user>").replace(/\/home\/[^/ ]+/g,"/home/<user>").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"<email>")}function ya(t){return Ai(t).substring(0,100)}function ha(t){return Ai(t).substring(100,200)}async function V(t,e){let r={...we(),reason:t,stage:e?.stage??fa[t]};if(typeof e?.httpStatus=="number"&&(r.http_status=e.httpStatus),e?.errorFragment){let n=ya(e.errorFragment),i=ha(e.errorFragment);n&&(r.error_fragment=n),i&&(r.error_fragment_2=i)}await Ee("auth_failed",r)}var cn=Symbol.for("codevibe.auth.beaconed"),_i=Symbol.for("codevibe.auth.failureReason");function Y(t,e){try{Object.defineProperty(t,cn,{value:!0,enumerable:!1,configurable:!0,writable:!1}),Object.defineProperty(t,_i,{value:e,enumerable:!1,configurable:!0,writable:!1})}catch{}return t}function Rt(t){return!!(t&&typeof t=="object"&&t[cn])}function ln(t){if(t&&typeof t=="object"&&t[cn]){let e=t[_i];if(typeof e=="string")return e}}function Xe(t){return t<=0?"0":t===1?"1":t<=5?"2-5":"6+"}function rr(t){return an.createHash("sha256").update(t).digest("hex").slice(0,8)}async function xi(t){return Ee("session_encryption_device_skipped",{...we(),...t})}async function Ii(t){return Ee("session_encryption_partial_success",{...we(),...t})}async function Pi(t){return Ee("session_encryption_catch_up_grant",{...we(),...t})}async function Ci(t){return Ee("session_encryption_self_rekey_request",{...we(),...t})}async function Ti(t){return Ee("session_encryption_self_rekey_success",{...we(),...t})}async function Oi(t){return Ee("session_encryption_self_rekey_timeout",{...we(),...t})}var At=8080,Mi="/callback",un=`http://localhost:${At}${Mi}`,Qe=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}openBrowser(e){console.error(""),console.error("Opening your browser for sign-in..."),this.isRunningInWSL()?console.error("If your browser does not open, paste this URL in your Windows browser:"):console.error("If your browser does not open automatically, visit this URL:"),console.error(` ${e}`),console.error("");let r=this.getBrowserCommands();this.tryBrowserCommand(r,e,0)}getBrowserCommands(){let e=process.platform;if(e==="darwin")return[{cmd:"open",fixedArgs:[]}];if(e==="win32")return[{cmd:"cmd",fixedArgs:["/c","start",""]}];let r=[];return this.isRunningInWSL()&&(r.push({cmd:"wslview",fixedArgs:[]}),r.push({cmd:"cmd.exe",fixedArgs:["/c","start",""]}),r.push({cmd:"powershell.exe",fixedArgs:["-NoProfile","-Command","Start-Process"]})),r.push({cmd:"xdg-open",fixedArgs:[]}),r}isRunningInWSL(){if(process.platform!=="linux")return!1;try{let e=Ni.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,r,n){if(n>=e.length){u.debug("[AuthService] No browser-opening command succeeded. User must open the sign-in URL manually (printed to stderr above)."),console.error(""),console.error("\u26A0\uFE0F Could not open browser automatically."),this.isRunningInWSL()?console.error(" WSL detected \u2014 paste this URL in your Windows browser:"):console.error(" Please copy and paste this URL into your browser:"),console.error(` ${r}`),console.error("");return}let i=e[n],s=[...i.fixedArgs,r],o=!1,a=p=>{o||(o=!0,u.debug(`[AuthService] Browser command '${i.cmd}' ${p}; trying next fallback`),this.tryBrowserCommand(e,r,n+1))},c=p=>{o||(o=!0,u.debug(`[AuthService] Browser command '${i.cmd}' ${p}`))},l;try{l=(0,$i.spawn)(i.cmd,s,{detached:!0,stdio:"ignore"})}catch(p){a(`threw synchronously: ${p?.message||p}`);return}l.on("error",p=>{a(`failed to spawn: ${p?.message||p}`)}),l.on("exit",(p,f)=>{p===0?c("exited successfully"):a(f?`terminated by signal ${f}`:`exited with code ${p}`)}),setTimeout(()=>{c("still running after 3s, assuming success")},3e3).unref(),l.unref()}generateState(){return Di.randomBytes(32).toString("hex")}buildAuthUrl(e){let r=M(),n=new URLSearchParams({client_id:r.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:un,state:e});return`https://${r.aws.cognitoDomain}/oauth2/authorize?${n.toString()}`}async exchangeCodeForTokens(e){let r=M(),n=`https://${r.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"authorization_code",client_id:r.aws.cognitoClientId,code:e,redirect_uri:un}),s;try{s=await Je(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token exchange")}catch(a){throw await V("token_exchange_network_error"),Y(a,"token_exchange_network_error"),a}if(!s.ok){let a=await s.text(),c=new Error(`Token exchange failed: ${s.status} ${a}`);throw await V("token_exchange_failed",{httpStatus:s.status}),Y(c,"token_exchange_failed"),c}let o=await s.json();return{accessToken:o.access_token,idToken:o.id_token,refreshToken:o.refresh_token,expiresIn:o.expires_in}}decodeJwt(e){let r=e.split(".");if(r.length!==3)throw new Error("Invalid JWT");return JSON.parse(Buffer.from(r[1],"base64").toString("utf-8"))}async refreshTokens(e){let r=M(),n=`https://${r.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:r.aws.cognitoClientId,refresh_token:e}),s=await Je(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()},"Token refresh");if(!s.ok)throw new Error(`Token refresh failed: ${s.status}`);let o=await s.json();return{accessToken:o.access_token,idToken:o.id_token,expiresIn:o.expires_in}}async login(){let e=await k.getTokens(J());if(e&&!k.isTokenExpired(e))return e;let r=this.generateState(),n=this.buildAuthUrl(r);return new Promise((i,s)=>{let o=dn.createServer(async(a,c)=>{if(!a.url?.startsWith(Mi)){c.writeHead(404),c.end("Not found");return}try{let l=new URL(a.url,`http://localhost:${At}`),d=l.searchParams.get("code"),p=l.searchParams.get("state"),f=l.searchParams.get("error");if(f){let g=new Error(`OAuth error: ${f}`);throw await V("cognito_rejected"),Y(g,"cognito_rejected"),g}if(p!==r){let g=new Error("State mismatch");throw await V("state_mismatch"),Y(g,"state_mismatch"),g}if(!d){let g=new Error("No authorization code");throw await V("no_authorization_code"),Y(g,"no_authorization_code"),g}let m=await this.exchangeCodeForTokens(d),S=this.decodeJwt(m.idToken),y={accessToken:m.accessToken,idToken:m.idToken,refreshToken:m.refreshToken,expiresAt:Date.now()+m.expiresIn*1e3,userId:S.sub,email:S.email||"unknown"};try{await k.setTokens(y,J())}catch(g){throw await V("keychain_write_failed"),Y(g,"keychain_write_failed"),g}c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(`
220
401
  <!DOCTYPE html>
221
402
  <html>
222
403
  <head><title>Success</title></head>
@@ -225,17 +406,17 @@ ${p.green}\u2713${p.reset} Orchestration enabled with tier-default reviewer pane
225
406
  <p>You can close this window.</p>
226
407
  </body>
227
408
  </html>
228
- `),setTimeout(()=>{s.close(()=>i(E))},500)}catch(l){let m=String(l?.message||l).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");d.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),d.end(`
409
+ `),setTimeout(()=>{o.close(()=>i(y))},500)}catch(l){let d=String(l?.message||l).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end(`
229
410
  <!DOCTYPE html>
230
411
  <html>
231
412
  <head><title>Error</title></head>
232
413
  <body style="font-family: system-ui; max-width: 720px; margin: 50px auto; padding: 0 16px;">
233
414
  <h1 style="color: #ef4444; text-align: center;">&#10007; Authentication Failed</h1>
234
- <pre style="background: #f4f4f5; padding: 16px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.5;">${m}</pre>
415
+ <pre style="background: #f4f4f5; padding: 16px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.5;">${d}</pre>
235
416
  <p style="text-align: center; color: #71717a; margin-top: 24px;">You can close this window and try again in your terminal.</p>
236
417
  </body>
237
418
  </html>
238
- `),setTimeout(()=>{s.close(()=>o(l))},500)}});s.on("error",async a=>{if(a.code==="EADDRINUSE"){let d=new Error(`Port ${he} is in use`);await R("port_in_use"),_(d,"port_in_use"),o(d)}else await R("server_listen_failed"),_(a,"server_listen_failed"),o(a)}),s.listen(he,"localhost",()=>{c.info("[AuthService] Callback server started"),this.openBrowser(n)}),setTimeout(async()=>{let a=new Error("Login timeout");await R("login_timeout"),_(a,"login_timeout"),s.close(()=>o(a))},120*1e3)})}async logout(){let e=k(),t=await y.deleteTokens(x());return t&&new Promise(n=>{let i=rt.createServer((o,s)=>{o.url?.startsWith("/signout")?(s.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),s.end(`
419
+ `),setTimeout(()=>{o.close(()=>s(l))},500)}});o.on("error",async a=>{if(a.code==="EADDRINUSE"){let c=new Error(`Port ${At} is in use`);await V("port_in_use"),Y(c,"port_in_use"),s(c)}else await V("server_listen_failed"),Y(a,"server_listen_failed"),s(a)}),o.listen(At,"localhost",()=>{u.info("[AuthService] Callback server started"),this.openBrowser(n)}),setTimeout(async()=>{let a=new Error("Login timeout");await V("login_timeout"),Y(a,"login_timeout"),o.close(()=>s(a))},120*1e3)})}async logout(){let e=M(),r=await k.deleteTokens(J());return r&&new Promise(n=>{let i=dn.createServer((s,o)=>{s.url?.startsWith("/signout")?(o.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),o.end(`
239
420
  <!DOCTYPE html>
240
421
  <html>
241
422
  <head><title>Signed Out</title></head>
@@ -244,32 +425,52 @@ ${p.green}\u2713${p.reset} Orchestration enabled with tier-default reviewer pane
244
425
  <p>You can close this window.</p>
245
426
  </body>
246
427
  </html>
247
- `),setTimeout(()=>{i.close(()=>n(!0))},500)):(s.writeHead(404),s.end("Not found"))});i.on("error",()=>{n(!0)}),i.listen(he,"localhost",()=>{let o=`https://${e.aws.cognitoDomain}/logout?client_id=${e.aws.cognitoClientId}&logout_uri=${encodeURIComponent(tt.replace("/callback","/signout"))}`;this.openBrowser(o)}),setTimeout(()=>{i.close(()=>n(!0))},30*1e3)})}async getStatus(){let e=await y.getTokens(x());return e?{authenticated:!y.isTokenExpired(e),tokens:e}:{authenticated:!1}}},O=te.getInstance();Q();var g={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function rn(){console.log(`${g.cyan}CodeVibe Login${g.reset}
248
- `);try{let r=await O.getStatus();if(r.authenticated&&r.tokens){console.log(`${g.yellow}Already logged in as: ${r.tokens.email}${g.reset}`),console.log(`Token expires: ${new Date(r.tokens.expiresAt).toLocaleString()}`),console.log(`
249
- Run '${g.dim}codevibe logout${g.reset}' to sign out first.`),process.exit(0);return}console.log("Opening browser for authentication..."),console.log(`${g.dim}Waiting for callback...${g.reset}
250
- `);let e=await O.login();e&&(console.log(`
251
- ${g.green}\u2713 Authentication successful!${g.reset}`),console.log(` User: ${e.email}`),console.log(` User ID: ${e.userId}`),console.log(` Expires: ${new Date(e.expiresAt).toLocaleString()}`),await fe(e.userId)),process.exit(0)}catch(r){console.error(`
252
- ${g.red}\u2717 Authentication failed${g.reset}`),console.error(` Error: ${r.message}`),ye(r)||await R("unknown"),process.exit(1)}}async function nn(){console.log(`${g.cyan}CodeVibe Logout${g.reset}
253
- `);try{let r=await O.getStatus();if(!r.authenticated){console.log(`${g.yellow}Not logged in.${g.reset}`),process.exit(0);return}let e=r.tokens?.email;await O.logout()?(console.log(`${g.green}\u2713 Logged out successfully.${g.reset}`),console.log(` Previous user: ${e}`),console.log(`
254
- ${g.dim}Clearing browser session...${g.reset}`)):console.log(`${g.red}\u2717 Failed to log out.${g.reset}`),process.exit(0)}catch(r){console.error(`${g.red}\u2717 Logout failed: ${r.message}${g.reset}`),process.exit(1)}}async function on(){console.log(`${g.cyan}CodeVibe Auth Status${g.reset}
255
- `);try{let r=await O.getStatus();if(!r.tokens){console.log(`${g.yellow}Not authenticated.${g.reset}`),console.log(`
256
- Run '${g.dim}codevibe login${g.reset}' to sign in.`),process.exit(0);return}let e=!r.authenticated;console.log(e?`${g.yellow}\u26A0 Token expired${g.reset}`:`${g.green}\u2713 Authenticated${g.reset}`),console.log(` User: ${r.tokens.email}`),console.log(` User ID: ${r.tokens.userId}`),console.log(` Expires: ${new Date(r.tokens.expiresAt).toLocaleString()}`),e&&console.log(`
257
- ${g.dim}Token will be refreshed automatically.${g.reset}`),process.exit(0)}catch(r){console.error(`${g.red}\u2717 Status check failed: ${r.message}${g.reset}`),process.exit(1)}}async function sn(){console.log(`${g.cyan}CodeVibe Reset Device${g.reset}
258
- `),console.log(`${g.red}\u26A0 WARNING: This will delete your device identity.${g.reset}`),console.log(`${g.red} Old encrypted sessions will become inaccessible.${g.reset}
259
- `);let{keychainManager:r}=await Promise.resolve().then(()=>(U(),Pt));try{await r.clearAllData(),console.log(`${g.green}\u2713 Device reset complete.${g.reset}`),console.log(` Run '${g.dim}codevibe login${g.reset}' to set up again.`),process.exit(0)}catch(e){console.error(`${g.red}\u2717 Reset failed: ${e.message}${g.reset}`),process.exit(1)}}function an(){console.log(`CodeVibe Authentication
428
+ `),setTimeout(()=>{i.close(()=>n(!0))},500)):(o.writeHead(404),o.end("Not found"))});i.on("error",()=>{n(!0)}),i.listen(At,"localhost",()=>{let s=`https://${e.aws.cognitoDomain}/logout?client_id=${e.aws.cognitoClientId}&logout_uri=${encodeURIComponent(un.replace("/callback","/signout"))}`;this.openBrowser(s)}),setTimeout(()=>{i.close(()=>n(!0))},30*1e3)})}async getStatus(){let e=await k.getTokens(J());return e?{authenticated:!k.isTokenExpired(e),tokens:e}:{authenticated:!1}}},ge=Qe.getInstance();qe();var E={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function vc(){console.log(`${E.cyan}CodeVibe Login${E.reset}
429
+ `);try{let t=await ge.getStatus();if(t.authenticated&&t.tokens){console.log(`${E.yellow}Already logged in as: ${t.tokens.email}${E.reset}`),console.log(`Token expires: ${new Date(t.tokens.expiresAt).toLocaleString()}`),console.log(`
430
+ Run '${E.dim}codevibe logout${E.reset}' to sign out first.`),process.exit(0);return}console.log("Opening browser for authentication..."),console.log(`${E.dim}Waiting for callback...${E.reset}
431
+ `);let e=await ge.login();e&&(console.log(`
432
+ ${E.green}\u2713 Authentication successful!${E.reset}`),console.log(` User: ${e.email}`),console.log(` User ID: ${e.userId}`),console.log(` Expires: ${new Date(e.expiresAt).toLocaleString()}`),await bt(e.userId)),process.exit(0)}catch(t){let e=(()=>{let r=t?.message;return typeof r=="string"&&r.length>0?r:t==null?"(null/undefined error)":`[no_message ctor=${t?.constructor?.name??typeof t}] ${String(t).substring(0,80)}`})();console.error(`
433
+ ${E.red}\u2717 Authentication failed${E.reset}`),console.error(` Error: ${e}`),Rt(t)||await V("unknown",{errorFragment:e}),process.exit(1)}}async function wc(){console.log(`${E.cyan}CodeVibe Logout${E.reset}
434
+ `);try{let t=await ge.getStatus();if(!t.authenticated){console.log(`${E.yellow}Not logged in.${E.reset}`),process.exit(0);return}let e=t.tokens?.email;await ge.logout()?(console.log(`${E.green}\u2713 Logged out successfully.${E.reset}`),console.log(` Previous user: ${e}`),console.log(`
435
+ ${E.dim}Clearing browser session...${E.reset}`)):console.log(`${E.red}\u2717 Failed to log out.${E.reset}`),process.exit(0)}catch(t){console.error(`${E.red}\u2717 Logout failed: ${t.message}${E.reset}`),process.exit(1)}}async function Ec(){console.log(`${E.cyan}CodeVibe Auth Status${E.reset}
436
+ `);try{let t=await ge.getStatus();if(!t.tokens){console.log(`${E.yellow}Not authenticated.${E.reset}`),console.log(`
437
+ Run '${E.dim}codevibe login${E.reset}' to sign in.`),process.exit(0);return}let e=!t.authenticated;console.log(e?`${E.yellow}\u26A0 Token expired${E.reset}`:`${E.green}\u2713 Authenticated${E.reset}`),console.log(` User: ${t.tokens.email}`),console.log(` User ID: ${t.tokens.userId}`),console.log(` Expires: ${new Date(t.tokens.expiresAt).toLocaleString()}`),e&&console.log(`
438
+ ${E.dim}Token will be refreshed automatically.${E.reset}`),process.exit(0)}catch(t){console.error(`${E.red}\u2717 Status check failed: ${t.message}${E.reset}`),process.exit(1)}}async function kc(){console.log(`${E.cyan}CodeVibe Reset Device${E.reset}
439
+ `),console.log(`${E.red}\u26A0 WARNING: This will delete your device identity.${E.reset}`),console.log(`${E.red} Old encrypted sessions will become inaccessible.${E.reset}
440
+ `);let{keychainManager:t}=await Promise.resolve().then(()=>(re(),yi));try{await t.clearAllData(),console.log(`${E.green}\u2713 Device reset complete.${E.reset}`),console.log(` Run '${E.dim}codevibe login${E.reset}' to set up again.`),process.exit(0)}catch(e){console.error(`${E.red}\u2717 Reset failed: ${e.message}${E.reset}`),process.exit(1)}}function bc(){console.log(`CodeVibe Authentication
260
441
  `),console.log("Usage:"),console.log(" codevibe login - Sign in via browser"),console.log(" codevibe logout - Sign out"),console.log(" codevibe status - Show auth status"),console.log(" codevibe reset-device - Reset device identity (destructive)"),console.log(`
261
- Environment:`),console.log(' Set ENVIRONMENT env var to "development" or "production" (default)'),console.log(" Example: ENVIRONMENT=development codevibe login")}async function Te(r){let e=x();console.log(`${g.dim}Environment: ${e}${g.reset}
262
- `);let n=r.slice(2).filter(i=>!i.startsWith("--"))[0];switch(n){case"login":await rn();break;case"logout":await nn();break;case"status":await on();break;case"reset-device":await sn();break;case"orchestration":{let{runOrchestrationCli:i}=(st(),vt(ir));await i(r);break}default:an(),process.exit(n?1:0)}}require.main===module&&Te(process.argv).catch(r=>{console.error("Error:",r),process.exit(1)});Q();$();var cn=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function or(r){let e=dt(r);if(!e)return null;let t=dn(e);if(t)return t;let n=ln(e);return n||null}function dt(r){return r.replace(/\r/g,`
263
- `).replace(cn,"").replace(/[│┌┐└┘─├┤┬┴┼╌╎╭╮╯╰║═╔╗╚╝╠╣╦╩╬]/g," ").replace(/[ \t]+\n/g,`
442
+ Environment:`),console.log(' Set ENVIRONMENT env var to "development" or "production" (default)'),console.log(" Example: ENVIRONMENT=development codevibe login")}async function Sr(t){let e=J();console.log(`${E.dim}Environment: ${e}${E.reset}
443
+ `);let n=t.slice(2).filter(i=>!i.startsWith("--"))[0];switch(n){case"login":await vc();break;case"logout":await wc();break;case"status":await Ec();break;case"reset-device":await kc();break;case"orchestration":{let{runOrchestrationCli:i}=(kn(),ni(_s));await i(t);break}default:bc(),process.exit(n?1:0)}}require.main===module&&Sr(process.argv).catch(t=>{console.error("Error:",t),process.exit(1)});qe();N();var Rc=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;function xs(t){let e=An(t);if(!e)return null;let r=Ac(e);if(r)return r;let n=_c(e);return n||null}function An(t){return t.replace(/\r/g,`
444
+ `).replace(Rc,"").replace(/[│┌┐└┘─├┤┬┴┼╌╎╭╮╯╰║═╔╗╚╝╠╣╦╩╬]/g," ").replace(/[ \t]+\n/g,`
264
445
  `).replace(/\n{3,}/g,`
265
446
 
266
- `).trim()}function dn(r){let e=r.split(`
267
- `).map(m=>m.trim()),t=un(e,m=>/\[(?:y\/n|Y\/n|y\/N)\]/.test(m)),n=t>=0?e[t]:null;if(!n)return null;let i=ar(e,t),o=i.length>0?i.join(`
268
- `):n,s=o.toLowerCase(),a=s.includes("what to change")||s.includes("what should")||s.includes("provide")||s.includes("instructions");return{kind:"yes_no",promptText:o,options:a?[{number:"1",text:"Yes"},{number:"2",text:"No, provide instructions"}]:[{number:"1",text:"Yes"},{number:"2",text:"No"}],submitMap:{1:"y",2:"n"},requiresFollowUpText:a}}function ln(r){let e=r.split(`
269
- `).map(d=>d.trim()),t=pn(e);if(t.length<2)return null;let n=t.map(({line:d})=>sr(d)).filter(d=>!!d),i={};for(let d of n)i[d.number]=d.number;let o=t[0]?.index??-1,s=ar(e,o-1);return{kind:"numbered",promptText:s.length>0?s.join(`
270
- `):"Select an option",options:n,submitMap:i}}function un(r,e){for(let t=r.length-1;t>=0;t-=1)if(e(r[t]))return t;return-1}function sr(r){let e=r.match(/^(?:[>›❯▸▶➜➤*●]\s*)?(\d+)\.\s+(.*)$/);return e?{number:e[1],text:e[2]}:null}function pn(r){let e=r.map((n,i)=>({index:i,line:n,parsed:sr(n)})).filter(n=>!!n.parsed);if(e.length===0)return[];let t=[e[e.length-1]];for(let n=e.length-2;n>=0;n-=1){let i=e[n],o=t[0];if(i.index!==o.index-1)break;t.unshift(i)}return t.map(({index:n,line:i})=>({index:n,line:i}))}function ar(r,e){if(e<0)return[];let t=at(r,e);if(t<0)return[];let{start:n,end:i}=ct(r,t),o=r.slice(n,i+1).filter(Boolean);if(mn(o)){let u=gn(r,n-1);return u.length>0?u:o}if(n<=1)return o;let s=n-1;if(s=at(r,s),s<0||s===n-1)return o;let{start:a,end:d}=ct(r,s),l=r.slice(a,d+1).filter(Boolean);return l.some(cr)?[...l,...o]:o}function cr(r){return/^(?:would you like to|do you want to|the model would like to|action required|confirm)\b/i.test(r)}function at(r,e){let t=e;for(;t>=0&&!r[t];)t-=1;return t}function ct(r,e){let t=e;for(;t>=0&&r[t];)t-=1;return{start:t+1,end:e}}function gn(r,e){let t=[],n=e;for(;n>=0&&t.length<2&&(n=at(r,n),!(n<0));){let{start:o,end:s}=ct(r,n),a=r.slice(o,s+1).filter(Boolean);a.length>0&&t.unshift(a),n=o-1}if(t.length===0)return[];let i=t.findIndex(o=>o.some(cr));return i>=0?t.slice(i).flat():t[t.length-1]}function mn(r){return r.length===0?!1:r.filter(fn).length>=Math.max(2,Math.ceil(r.length/2))}function fn(r){return/^\d+\s/.test(r)}de();U();pe();de();$();async function z(r,e,t,n={}){let i;try{i=await t.getSession(r)}catch(u){return c.warn("[SessionRekey] Failed to fetch session state for re-key",{sessionId:r,error:u instanceof Error?u.message:String(u)}),0}if(!i)return c.warn("[SessionRekey] Session not found, skipping re-key",{sessionId:r}),0;if(!i.isEncrypted)return 0;let o=i.encryptedKeys||[],s=new Set(o.map(u=>u.deviceId)),a=n.forceDeviceIds??new Set,d;try{d=await t.listUserDeviceKeys()}catch(u){return c.warn("[SessionRekey] Failed to fetch user device keys",{sessionId:r,error:u instanceof Error?u.message:String(u)}),0}let l=d.filter(u=>!s.has(u.deviceId)||a.has(u.deviceId));if(l.length===0)return 0;c.info("[SessionRekey] Granting session key to devices",{sessionId:r,existingDeviceCount:o.length,grantCount:l.length,grantDeviceIds:l.map(u=>u.deviceId),forceCount:a.size});let m=0;for(let u of l)try{let w=I.encryptSessionKey(e,u.publicKey);await t.grantSessionKey({sessionId:r,deviceId:u.deviceId,encryptedKey:w.encryptedKey,ephemeralPublicKey:w.ephemeralPublicKey}),m++,c.info("[SessionRekey] Granted session key to device",{sessionId:r,deviceId:u.deviceId,platform:u.platform})}catch(w){c.warn("[SessionRekey] Failed to grant session key to device",{sessionId:r,deviceId:u.deviceId,error:w instanceof Error?w.message:String(w)})}return m>0&&c.info("[SessionRekey] Re-key complete",{sessionId:r,grantedCount:m,requestedCount:l.length}),m}async function Pe(r,e,t){try{let n=await e.listUserDeviceKeys();if(n.length===0)return t.info("No device keys found, session will not be encrypted"),null;t.info("Preparing session encryption",{sessionId:r,deviceCount:n.length});let{sessionKey:i,encryptedKeys:o}=y.createSessionKey(n);return t.info("Session encryption prepared",{sessionId:r,deviceCount:o.length}),{sessionKey:i,encryptedKeys:o}}catch(n){return t.warn("Failed to prepare session encryption:",n),null}}async function lt(r,e,t){let{sessionId:n,userId:i,agentType:o,projectPath:s,metadata:a}=r,d=null;try{d=await e.getSession(n)}catch(v){t.warn("Failed to get session (will attempt to create new)",{sessionId:n,error:v})}if(d){t.info("Session exists in backend - reactivating",{sessionId:n,previousStatus:d.status});try{await e.updateSession({sessionId:n,status:"ACTIVE"})}catch(E){t.warn("Failed to reactivate existing session, will continue",{sessionId:n,error:E})}let v=null,W=d.encryptedKeys;if(d.isEncrypted&&W?.length)try{let E=await y.getSessionKey(n,W);E?(v=E,y.cacheSessionKey(n,E),t.info("Session key retrieved for resumed session",{sessionId:n})):t.warn("No encrypted key for this device; proceeding without decryption",{sessionId:n})}catch(E){t.warn("Failed to retrieve session key for resumed session",{sessionId:n,error:E})}if(v)try{let E=await z(n,v,e);E>0&&t.info("Session re-keyed for newly registered devices on resume",{sessionId:n,newDeviceCount:E})}catch(E){t.warn("Session re-key on resume failed (non-fatal)",{sessionId:n,error:E instanceof Error?E.message:String(E)})}return{resumed:!0,sessionKey:v}}let l=await Pe(n,e,t),m=s,u=a;l&&(m=I.encryptContent(s,l.sessionKey),u&&Object.keys(u).length>0&&(u={encrypted:I.encryptMetadata(u,l.sessionKey)}),t.info("Session data encrypted",{sessionId:n})),t.info("Creating new session in backend",{sessionId:n,userId:i,agentType:o,isEncrypted:!!l}),await e.createSession({sessionId:n,userId:i,agentType:o,projectPath:m,status:"ACTIVE",metadata:u,isEncrypted:l?!0:void 0,creatorDeviceId:l?await y.getDeviceId():void 0,encryptionVersion:l?1:void 0,encryptedKeys:l?.encryptedKeys});let w=l?.sessionKey||null;return l&&y.cacheSessionKey(n,l.sessionKey),t.info("Session created",{sessionId:n,userId:i,isEncrypted:!!l}),{resumed:!1,sessionKey:w}}U();function ut(r,e){let t=r.getCurrentUserId(),n=async(o,s)=>{let a=y.getCachedSessionIds();if(a.length===0){e.info("[DeviceKeyWatcher] No active sessions to re-key",{reason:o});return}e.info("[DeviceKeyWatcher] Running re-key pass",{reason:o,activeSessionCount:a.length,forceDeviceCount:s?.size??0});for(let d of a){let l=y.getCachedSessionKey(d);if(l)try{let m=await z(d,l,r,s?{forceDeviceIds:s}:void 0);m>0&&e.info("[DeviceKeyWatcher] Session re-keyed",{sessionId:d,newDeviceCount:m,reason:o})}catch(m){e.warn("[DeviceKeyWatcher] Re-key failed for session (non-fatal)",{sessionId:d,reason:o,error:m instanceof Error?m.message:String(m)})}}},i=r.subscribeToDeviceKeyRegistered(t,o=>{e.info("[DeviceKeyWatcher] New device observed, triggering re-key",{userId:t,newDeviceId:o.deviceId,platform:o.platform,deviceName:o.deviceName}),n(`new-device:${o.deviceId}`,new Set([o.deviceId]))},()=>{n("watcher-reconnect")},o=>{e.warn("[DeviceKeyWatcher] Subscription error (will retry)",{error:o instanceof Error?o.message:String(o)})});return e.info("[DeviceKeyWatcher] Started",{userId:t}),i}U();async function pt(r,e){try{let t=await y.getDeviceId(),n=await y.getDevicePublicKey(),i=y.getDevicePlatform(),o=y.getDeviceName();e.info("Registering device encryption key",{deviceId:t,platform:i,deviceName:o}),await r.registerDeviceKey(t,n,i,o),y.setIsRegistered(!0),e.info("Device encryption key registered successfully",{deviceId:t})}catch(t){e.warn("Failed to register device encryption key (E2E encryption may not work):",t)}}st();var ft={};ce(ft,{ClaudeReviewerProvider:()=>ne,CodexReviewerProvider:()=>oe,GeminiReviewerProvider:()=>ie,MockReviewerSpawner:()=>$e,ReviewerErrorClass:()=>h,ReviewerRegistry:()=>ve,StaticReviewerMock:()=>Ne,SubprocessErrorClass:()=>A,VerdictParseErrorClass:()=>De,createSubprocessReviewerRegistry:()=>mr,parseVerdictOutput:()=>M,runReviewer:()=>B});var h=class r extends Error{constructor(e){super(yn(e)),this.name="ReviewerError",this.detail=e,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};function yn(r){switch(r.kind){case"timeout":return`${r.agent} reviewer timed out after ${r.elapsed_ms}ms`;case"spawn_failed":return`${r.agent} reviewer spawn failed: ${r.reason}`;case"parse_failure":return`${r.agent} reviewer output was unparseable`;case"cancelled":return"reviewer cancelled before completion";case"internal_join_failure":return`reviewer task internal join failure: ${r.reason}`}}var De=class r extends Error{constructor(e){super(hn(e)),this.name="VerdictParseError",this.detail=e,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};function hn(r){switch(r.kind){case"empty_output":return"reviewer returned an empty reply";case"invalid_verdict":return`first non-blank line ${JSON.stringify(r.found)} is not a valid verdict (expected APPROVE | REJECT | REVISE | ESCALATE)`;case"reasoning_missing":return"reviewer returned a bare verdict with no reasoning";case"revise_missing_changes":return"REVISE verdict requires at least one suggested change in a bulleted list";case"suggested_changes_require_revise":return`suggested changes are reserved for REVISE verdicts; ${JSON.stringify(r.found)} verdict must not carry a bulleted list`}}function M(r){let t=r.replace(/\r\n/g,`
271
- `).split(`
272
- `),n=0;for(;n<t.length&&t[n].trim()==="";)n+=1;if(n>=t.length)return{ok:!1,error:{kind:"empty_output"}};let i=t[n];n+=1;let o=vn(i.trim());if(!o.ok)return o;let s=o.kind,a=[],d=[],l=!1;for(;n<t.length;n+=1){let u=t[n];if(wn(u)){l=!0;let v=Sn(u).trimEnd();v.length>0&&d.push(v);continue}let w=bn(u);if(l){if(w==="")continue;let v=d[d.length-1];if(v!==void 0&&(u.startsWith(" ")||u.startsWith(" "))){d[d.length-1]=v+" "+w.trimStart();continue}return{ok:!1,error:{kind:"invalid_verdict",found:w}}}a.push(w)}for(;a.length>0&&a[0]==="";)a.shift();for(;a.length>0&&a[a.length-1]==="";)a.pop();let m=a.join(`
273
- `);if(m.trim()==="")return{ok:!1,error:{kind:"reasoning_missing"}};if(s==="REVISE"){if(d.length===0)return{ok:!1,error:{kind:"revise_missing_changes"}}}else if(d.length>0)return{ok:!1,error:{kind:"suggested_changes_require_revise",found:s}};return{ok:!0,verdict:{kind:s,reasoning:m,suggested_changes:d}}}function vn(r){let e=r;switch((e.endsWith(":")||e.endsWith("."))&&(e=e.slice(0,-1)),e.toUpperCase()){case"APPROVE":return{ok:!0,kind:"APPROVE"};case"REJECT":return{ok:!0,kind:"REJECT"};case"REVISE":return{ok:!0,kind:"REVISE"};case"ESCALATE":return{ok:!0,kind:"ESCALATE"};default:return{ok:!1,error:{kind:"invalid_verdict",found:r}}}}function wn(r){return r.startsWith("- ")||r.startsWith("* ")}function Sn(r){return r.slice(2).trimStart()}function bn(r){return r.trimEnd()}var dr=require("child_process"),A=class r extends Error{constructor(e){super(En(e)),this.name="SubprocessError",this.detail=e,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};function En(r){switch(r.kind){case"spawn_failed":return`failed to spawn subprocess: ${r.reason}`;case"timeout":return`subprocess timed out after ${r.elapsed_ms}ms`;case"io":return`subprocess IO error: ${r.reason}`;case"cancelled":return"subprocess cancelled before completion"}}function B(r){return new Promise((e,t)=>{let n=Date.now(),i;try{i=(0,dr.spawn)(r.command,[...r.args],{env:r.env,cwd:r.cwd,stdio:["pipe","pipe","pipe"],windowsHide:!0})}catch(f){t(new A({kind:"spawn_failed",reason:f instanceof Error?f.message:String(f)}));return}let o=!1,s=[],a=[],d=()=>{try{i.stdin&&!i.stdin.destroyed&&i.stdin.destroy()}catch{}try{i.stdout&&!i.stdout.destroyed&&i.stdout.destroy()}catch{}try{i.stderr&&!i.stderr.destroyed&&i.stderr.destroy()}catch{}},l=()=>{try{i.kill("SIGKILL")}catch{}},m=()=>{},u=()=>{},w=f=>{o||(o=!0,m(),u(),e(f))},v=f=>{o||(o=!0,m(),u(),d(),l(),t(f))};i.stdout.on("data",f=>{s.push(f)}),i.stderr.on("data",f=>{a.push(f)}),i.on("error",f=>{f.code==="ENOENT"||f.code==="EACCES"||f.code==="EPERM"?v(new A({kind:"spawn_failed",reason:f.message})):v(new A({kind:"io",reason:f.message}))}),i.on("close",(f,Sr)=>{if(o)return;let br=Date.now()-n,Er=Buffer.concat(s).toString("utf8"),kr=Buffer.concat(a).toString("utf8");w({stdout:Er,stderr:kr,elapsed_ms:br,exit_success:f===0&&Sr===null})}),i.stdin.on("error",f=>{});try{i.stdin.write(r.prompt,"utf8",()=>{try{i.stdin.end()}catch{}})}catch(f){v(new A({kind:"io",reason:f instanceof Error?f.message:String(f)}));return}let W=setTimeout(()=>{v(new A({kind:"timeout",elapsed_ms:r.timeout_ms}))},r.timeout_ms);u=()=>{clearTimeout(W)};let E=()=>{v(new A({kind:"cancelled"}))};if(r.signal){if(m=()=>{r.signal.removeEventListener("abort",E)},r.signal.aborted){E();return}r.signal.addEventListener("abort",E,{once:!0})}})}var lr=require("uuid");function re(r,e){switch(e.kind){case"spawn_failed":return{kind:"spawn_failed",agent:r,reason:e.reason};case"timeout":return{kind:"timeout",agent:r,elapsed_ms:e.elapsed_ms};case"io":return{kind:"spawn_failed",agent:r,reason:`io error: ${e.reason}`};case"cancelled":return{kind:"cancelled"}}}var ne=class{constructor(e={}){this.executable=e.executable??"claude"}async evaluate(e,t){if(e.agent!=="claude")throw new Error(`ClaudeReviewerProvider called with non-Claude spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let n=kn(this.executable,e),i;try{i=await B({command:n.command,args:n.args,env:n.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms})}catch(o){throw o instanceof A?new h(re(e.agent,o.detail)):o}return An(e,t,i)}};function kn(r,e){let t=[];t.push("--print"),t.push("--allowed-tools",e.tool_allowlist.join(",")),e.model_hint!==null&&t.push("--model",e.model_hint);let n={...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"};return{command:r,args:t,env:n}}function An(r,e,t){if(!t.exit_success)throw new h({kind:"spawn_failed",agent:r.agent,reason:`claude exited with non-zero status; stderr: ${t.stderr.trim()}`});let n=M(t.stdout);if(!n.ok)throw new h({kind:"parse_failure",agent:r.agent,raw_output:t.stdout});return{verdict_id:(0,lr.v4)(),gate_id:e,seat_id:r.seat_id,role:r.role,reviewer_agent:r.agent,verdict:n.verdict.kind,reasoning:n.verdict.reasoning,suggested_changes:n.verdict.suggested_changes,model_used:r.model_hint,tokens_used:null,latency_ms:t.elapsed_ms,submitted_at:new Date().toISOString()}}var ur=require("uuid");var ie=class{constructor(e={}){this.executable=e.executable??"gemini"}async evaluate(e,t){if(e.agent!=="gemini")throw new Error(`GeminiReviewerProvider called with non-Gemini spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let n=Rn(this.executable,e),i;try{i=await B({command:n.command,args:n.args,env:n.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms})}catch(o){throw o instanceof A?new h(re(e.agent,o.detail)):o}return In(e,t,i)}};function Rn(r,e){let t=[];t.push("-p",""),t.push("--approval-mode","plan"),t.push("--output-format","json"),e.model_hint!==null&&t.push("--model",e.model_hint);let n={...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"};return{command:r,args:t,env:n}}function In(r,e,t){if(!t.exit_success)throw new h({kind:"spawn_failed",agent:r.agent,reason:`gemini exited with non-zero status; stderr: ${t.stderr.trim()}`});let n=Cn(t.stdout);if(n===null)throw new h({kind:"parse_failure",agent:r.agent,raw_output:t.stdout});let i=M(n.response);if(!i.ok)throw new h({kind:"parse_failure",agent:r.agent,raw_output:n.response});let o=xn(n);return{verdict_id:(0,ur.v4)(),gate_id:e,seat_id:r.seat_id,role:r.role,reviewer_agent:r.agent,verdict:i.verdict.kind,reasoning:i.verdict.reasoning,suggested_changes:i.verdict.suggested_changes,model_used:r.model_hint,tokens_used:o,latency_ms:t.elapsed_ms,submitted_at:new Date().toISOString()}}function xn(r){let e=r.stats?.models;if(!e)return null;let t=[];for(let n of Object.values(e)){let i=n.tokens?.total;typeof i=="number"&&t.push(i)}return t.length===0?null:t.reduce((n,i)=>n+i,0)}function Cn(r){let e=r.indexOf("{");if(e<0)return null;let t=0,n=!1,i=!1;for(let o=e;o<r.length;o+=1){let s=r[o];if(i){i=!1;continue}if(n){s==="\\"?i=!0:s==='"'&&(n=!1);continue}if(s==='"'){n=!0;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t===0)){let a=r.slice(e,o+1),d;try{d=JSON.parse(a)}catch{return null}return _n(d)}}return null}function _n(r){if(typeof r!="object"||r===null||Array.isArray(r))return null;let e=r;return typeof e.response!="string"?null:e}var Oe=S(require("fs")),pr=S(require("os")),gr=S(require("path")),gt=require("uuid");var oe=class{constructor(e={}){this.executable=e.executable??"codex"}async evaluate(e,t){if(e.agent!=="codex")throw new Error(`CodexReviewerProvider called with non-Codex spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let n=Kn(),i=Tn(this.executable,e,n),o;try{o=await B({command:i.command,args:i.args,env:i.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms})}catch(a){throw Ke(n),a instanceof A?new h(re(e.agent,a.detail)):a}if(!o.exit_success)throw Ke(n),new h({kind:"spawn_failed",agent:e.agent,reason:`codex exited with non-zero status; stderr: ${o.stderr.trim()}`});let s;try{s=Oe.readFileSync(n,"utf8")}catch(a){Ke(n);let d=a instanceof Error?a.message:String(a);throw new h({kind:"parse_failure",agent:e.agent,raw_output:`codex exited 0 but --output-last-message file unreadable (${d}): stdout follows
274
- ${o.stdout}`})}return Ke(n),Pn(e,t,o,s)}};function Tn(r,e,t){let n=[];n.push("exec"),n.push("--sandbox","read-only"),n.push("--skip-git-repo-check"),n.push("--color","never"),n.push("--json"),n.push("--ephemeral"),n.push("--output-last-message",t),e.model_hint!==null&&n.push("--model",e.model_hint),n.push("-");let i={...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"};return{command:r,args:n,env:i}}function Pn(r,e,t,n){if(!t.exit_success)throw new h({kind:"spawn_failed",agent:r.agent,reason:`codex exited with non-zero status; stderr: ${t.stderr.trim()}`});let i=M(n);if(!i.ok)throw new h({kind:"parse_failure",agent:r.agent,raw_output:n});let o=Dn(t.stdout);return{verdict_id:(0,gt.v4)(),gate_id:e,seat_id:r.seat_id,role:r.role,reviewer_agent:r.agent,verdict:i.verdict.kind,reasoning:i.verdict.reasoning,suggested_changes:i.verdict.suggested_changes,model_used:r.model_hint,tokens_used:o,latency_ms:t.elapsed_ms,submitted_at:new Date().toISOString()}}function Dn(r){let e=[];for(let t of r.split(`
275
- `)){let n=t.trim();if(n==="")continue;let i;try{i=JSON.parse(n)}catch{continue}if(i.type==="turn.completed"&&i.usage){let o=i.usage.input_tokens??0,s=i.usage.output_tokens??0;e.push(o+s)}}return e.length===0?null:e.reduce((t,n)=>t+n,0)}function Kn(){return gr.join(pr.tmpdir(),`quorum-codex-last-${process.pid}-${(0,gt.v4)()}.txt`)}function Ke(r){try{Oe.unlinkSync(r)}catch{}}var ve=class{constructor(){this.providers=new Map}with(e,t){return this.providers.set(e,t),this}register(e,t){this.providers.set(e,t)}providerFor(e){return this.providers.get(e)}registeredAgents(){return Array.from(this.providers.keys())}async evaluate(e,t){let n=this.providers.get(e.agent);if(n===void 0)throw new h({kind:"spawn_failed",agent:e.agent,reason:`no provider registered for ${e.agent} \u2014 registry was built without a ${e.agent} entry but the policy snapshot includes a ${e.agent} reviewer`});return n.evaluate(e,t)}};function mr(){return new ve().with("claude",new ne).with("gemini",new ie).with("codex",new oe)}var mt=require("uuid");var $e=class r{constructor(){this.scripts=new Map}static key(e,t){return`${e}|${t}`}scriptVerdict(e,t,n,i){this.scriptVerdictWithChanges(e,t,n,i,[])}scriptVerdictWithChanges(e,t,n,i,o){let s=r.key(e,t),a=this.scripts.get(s)??[];a.push({type:"verdict",kind:n,reasoning:i,suggested_changes:o}),this.scripts.set(s,a)}scriptError(e,t,n){let i=r.key(e,t),o=this.scripts.get(i)??[];o.push({type:"error",error:n}),this.scripts.set(i,o)}remaining(e,t){let n=r.key(e,t);return this.scripts.get(n)?.length??0}async evaluate(e,t){let n=r.key(e.agent,t),i=this.scripts.get(n),o=i&&i.length>0?i.shift():null;if(o===null)throw new h({kind:"spawn_failed",agent:e.agent,reason:`no scripted response for (${e.agent}, gate=${t}); test forgot to wire a reviewer`});if(o.type==="error")throw new h(o.error);return{verdict_id:(0,mt.v4)(),gate_id:t,seat_id:e.seat_id,role:e.role,reviewer_agent:e.agent,verdict:o.kind,reasoning:o.reasoning,suggested_changes:o.suggested_changes,model_used:`mock-${e.agent}`,tokens_used:0,latency_ms:0,submitted_at:new Date().toISOString()}}};function fr(){return{type:"verdict",kind:"APPROVE",reasoning:"static mock: approve",suggested_changes:[]}}function yr(){return{type:"verdict",kind:"REJECT",reasoning:"static mock: reject",suggested_changes:[]}}function hr(r){return{type:"verdict",kind:"REVISE",reasoning:"static mock: revise",suggested_changes:r.length===0?["static mock: placeholder revision"]:r}}function vr(){return{type:"verdict",kind:"ESCALATE",reasoning:"static mock: escalate",suggested_changes:[]}}var Ne=class r{constructor(){this.defaultResponse=null;this.perAgent=new Map}static new(){return new r}static allApprove(){let e=new r;return e.defaultResponse=fr(),e}static allReject(){let e=new r;return e.defaultResponse=yr(),e}static allRevise(e){let t=new r;return t.defaultResponse=hr(e),t}static allEscalate(){let e=new r;return e.defaultResponse=vr(),e}static allError(e){let t=new r;return t.defaultResponse={type:"error",error:e},t}withAgentVerdict(e,t){let n;switch(t){case"APPROVE":n=fr();break;case"REJECT":n=yr();break;case"REVISE":n=hr([]);break;case"ESCALATE":n=vr();break}return this.perAgent.set(e,n),this}withAgentError(e,t){return this.perAgent.set(e,{type:"error",error:t}),this}async evaluate(e,t){let n=this.perAgent.get(e.agent)??this.defaultResponse;if(n===null)throw new h({kind:"spawn_failed",agent:e.agent,reason:`StaticReviewerMock has no response configured for ${e.agent} (set a default via allApprove() / allReject() / etc., or an override via withAgentVerdict() / withAgentError())`});if(n.type==="error")throw new h(n.error);return{verdict_id:(0,mt.v4)(),gate_id:t,seat_id:e.seat_id,role:e.role,reviewer_agent:e.agent,verdict:n.kind,reasoning:n.reasoning,suggested_changes:n.suggested_changes,model_used:`static-mock-${e.agent}`,tokens_used:0,latency_ms:0,submitted_at:new Date().toISOString()}}};var yt={};ce(yt,{dedupKeyForDestructiveActionEscalated:()=>jn,dedupKeyForFlagBadApproval:()=>qn,dedupKeyForProgressEvent:()=>Vn,dedupKeyForTaskCreated:()=>Bn,dedupKeyForTaskTerminated:()=>Wn,dedupKeyForToolUse:()=>Fn});var wr=require("node:crypto"),On="task_created",$n="task_terminated",Nn="progress",Un="tool_use",Ln="destructive_escalated",Mn="flag_bad_approval";function se(r){if(r.length!==36)throw new Error(`UUID must be 36 chars (got ${r.length}): ${r}`);if(r[8]!=="-"||r[13]!=="-"||r[18]!=="-"||r[23]!=="-")throw new Error(`UUID dashes misplaced: ${r}`);let e=r.replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error(`UUID contains non-hex characters: ${r}`);return Buffer.from(e,"hex")}function ae(r){let e=(0,wr.createHash)("sha256");for(let t of r)typeof t=="string"?e.update(t,"utf8"):e.update(t);return e.digest("hex")}function Bn(r){return ae([se(r),On])}function Wn(r){return ae([se(r),$n])}function Vn(r,e){return ae([se(r),Nn,e])}function Fn(r,e){return ae([se(r),Un,e])}function jn(r,e){return ae([se(r),Ln,e])}function qn(r){return ae([se(r),Mn])}pe();0&&(module.exports={AgentType,AppSyncClient,AuditKeys,AuthService,CryptoError,CryptoService,DeliveryStatus,ENCRYPTION_VERSION,EventSource,EventType,KeychainError,KeychainManager,Logger,Reviewer,ReviewerRole,SessionStatus,applyPerSessionOrchestrationOverride,authService,createLogger,cryptoService,detectInstalledAgents,errorWasBeaconed,fireAuthCompletedBeacon,fireAuthFailedBeacon,getConfig,getEnvironment,getErrorReason,keychainManager,loadConfig,logger,markErrorBeaconed,mutations,normalizeSnapshot,parseInteractivePrompt,prepareSessionEncryption,pushDetectedAgents,queries,registerDeviceEncryptionKey,rekeySessionForNewDevices,resumeOrCreateSession,runAuthCli,runOrchestrationCli,startDeviceKeyWatcher,subscriptions});
447
+ `).trim()}function Ac(t){let e=t.split(`
448
+ `).map(d=>d.trim()),r=xc(e,d=>/\[(?:y\/n|Y\/n|y\/N)\]/.test(d)),n=r>=0?e[r]:null;if(!n)return null;let i=Ps(e,r),s=i.length>0?i.join(`
449
+ `):n,o=s.toLowerCase(),a=o.includes("what to change")||o.includes("what should")||o.includes("provide")||o.includes("instructions");return{kind:"yes_no",promptText:s,options:a?[{number:"1",text:"Yes"},{number:"2",text:"No, provide instructions"}]:[{number:"1",text:"Yes"},{number:"2",text:"No"}],submitMap:{1:"y",2:"n"},requiresFollowUpText:a}}function _c(t){let e=t.split(`
450
+ `).map(c=>c.trim()),r=Ic(e);if(r.length<2)return null;let n=r.map(({line:c})=>Is(c)).filter(c=>!!c),i={};for(let c of n)i[c.number]=c.number;let s=r[0]?.index??-1,o=Ps(e,s-1);return{kind:"numbered",promptText:o.length>0?o.join(`
451
+ `):"Select an option",options:n,submitMap:i}}function xc(t,e){for(let r=t.length-1;r>=0;r-=1)if(e(t[r]))return r;return-1}function Is(t){let e=t.match(/^(?:[>›❯▸▶➜➤*●]\s*)?(\d+)\.\s+(.*)$/);return e?{number:e[1],text:e[2]}:null}function Ic(t){let e=t.map((n,i)=>({index:i,line:n,parsed:Is(n)})).filter(n=>!!n.parsed);if(e.length===0)return[];let r=[e[e.length-1]];for(let n=e.length-2;n>=0;n-=1){let i=e[n],s=r[0];if(i.index!==s.index-1)break;r.unshift(i)}return r.map(({index:n,line:i})=>({index:n,line:i}))}function Ps(t,e){if(e<0)return[];let r=bn(t,e);if(r<0)return[];let{start:n,end:i}=Rn(t,r),s=t.slice(n,i+1).filter(Boolean);if(Cc(s)){let p=Pc(t,n-1);return p.length>0?p:s}if(n<=1)return s;let o=n-1;if(o=bn(t,o),o<0||o===n-1)return s;let{start:a,end:c}=Rn(t,o),l=t.slice(a,c+1).filter(Boolean);return l.some(Cs)?[...l,...s]:s}function Cs(t){return/^(?:would you like to|do you want to|the model would like to|action required|confirm)\b/i.test(t)}function bn(t,e){let r=e;for(;r>=0&&!t[r];)r-=1;return r}function Rn(t,e){let r=e;for(;r>=0&&t[r];)r-=1;return{start:r+1,end:e}}function Pc(t,e){let r=[],n=e;for(;n>=0&&r.length<2&&(n=bn(t,n),!(n<0));){let{start:s,end:o}=Rn(t,n),a=t.slice(s,o+1).filter(Boolean);a.length>0&&r.unshift(a),n=s-1}if(r.length===0)return[];let i=r.findIndex(s=>s.some(Cs));return i>=0?r.slice(i).flat():r[r.length-1]}function Cc(t){return t.length===0?!1:t.filter(Tc).length>=Math.max(2,Math.ceil(t.length/2))}function Tc(t){return/^\d+\s/.test(t)}Te();re();kt();Te();re();N();async function Be(t,e,r,n={}){let i;try{i=await r.getSession(t)}catch(m){return u.warn("[SessionRekey] Failed to fetch session state for re-key",{sessionId:t,error:m instanceof Error?m.message:String(m)}),0}if(!i)return u.warn("[SessionRekey] Session not found, skipping re-key",{sessionId:t}),0;if(!i.isEncrypted)return 0;let s=i.encryptedKeys||[],o=new Set(s.map(m=>m.deviceId)),a=n.forceDeviceIds??new Set,c;try{c=await r.listUserDeviceKeys()}catch(m){return u.warn("[SessionRekey] Failed to fetch user device keys",{sessionId:t,error:m instanceof Error?m.message:String(m)}),0}let l=!1,d=!1;try{let m=await r.listServiceDeviceKeys(),S=new Set(c.map(g=>g.deviceId)),y=m.filter(g=>!S.has(g.deviceId));y.length>0?(c=[...c,...y],l=!0):(d=!0,u.warn("[SessionRekey] listServiceDeviceKeys returned empty; catch-up rekey will need to retry on next session resume",{sessionId:t}))}catch(m){d=!0,u.warn("[SessionRekey] Failed to fetch service device keys (continuing with user-only; next rekey pass will retry)",{sessionId:t,error:m instanceof Error?m.message:String(m)})}let p=c.filter(m=>!o.has(m.deviceId)||a.has(m.deviceId));if(p.length===0)return 0;u.info("[SessionRekey] Granting session key to devices",{sessionId:t,existingDeviceCount:s.length,grantCount:p.length,grantDeviceIds:p.map(m=>m.deviceId),forceCount:a.size});let f=0;for(let m of p)try{let S=$.encryptSessionKey(e,m.publicKey);await r.grantSessionKey({sessionId:t,deviceId:m.deviceId,encryptedKey:S.encryptedKey,ephemeralPublicKey:S.ephemeralPublicKey}),f++,u.info("[SessionRekey] Granted session key to device",{sessionId:t,deviceId:m.deviceId,platform:m.platform})}catch(S){u.warn("[SessionRekey] Failed to grant session key to device",{sessionId:t,deviceId:m.deviceId,error:S instanceof Error?S.message:String(S)})}return f>0&&u.info("[SessionRekey] Re-key complete",{sessionId:t,grantedCount:f,requestedCount:p.length,serviceKeysIncluded:l,serviceKeysRetryNeeded:d}),d&&u.warn("[SessionRekey] Catch-up rekey completed WITHOUT service device key \u2014 Lambda decrypt will fail on this session until next rekey pass succeeds",{sessionId:t,grantedCount:f}),f}async function Ts(t,e){let r=e.pollIntervalMs??5e3,n=e.maxAttempts??6,i,s;try{i=await k.getDeviceId(),s=await k.getDevicePrivateKey()}catch(o){u.warn("[SessionRekey] A1 pre-loop keychain read failed",{sessionId:t,error:o instanceof Error?o.message:String(o)});try{e.onTimeout?.(0)}catch{}return null}for(let o=1;o<=n;o++){o>1&&await new Promise(f=>setTimeout(f,r));let a;try{a=await e.appSyncClient.getSession(t)}catch(f){u.warn("[SessionRekey] A1 getSession failed during poll, will retry",{sessionId:t,attempt:o,error:f instanceof Error?f.message:String(f)});continue}let c=a?.encryptedKeys??[],l=c.filter(f=>f.deviceId===i);if(l.length===0){u.info("[SessionRekey] A1 our deviceId still not in encryptedKeys",{sessionId:t,attempt:o,freshDeviceCount:c.length});continue}let d=null,p=[];for(let f=l.length-1;f>=0;f--)try{d=$.decryptSessionKey(l[f],s);break}catch(m){p.push(m instanceof Error?m.message:String(m))}if(d){k.cacheSessionKey(t,d);try{e.onSuccess?.(o)}catch{}return u.info("[SessionRekey] A1 self-rekey successful",{sessionId:t,attempt:o,entriesTriedToDecrypt:l.length}),d}u.warn("[SessionRekey] A1 found entries but all decrypt-failed, will retry",{sessionId:t,attempt:o,entriesTried:l.length,errors:p})}try{e.onTimeout?.(n)}catch{}return u.warn("[SessionRekey] A1 self-rekey exhausted maxAttempts",{sessionId:t,maxAttempts:n}),null}re();async function Tt(t,e){try{let r=await k.getDeviceId(),n=await k.getDevicePublicKey(),i=k.getDevicePlatform(),s=k.getDeviceName();e.info("Registering device encryption key",{deviceId:r,platform:i,deviceName:s}),await t.registerDeviceKey(r,n,i,s),k.setIsRegistered(!0),e.info("Device encryption key registered successfully",{deviceId:r})}catch(r){e.warn("Failed to register device encryption key (E2E encryption may not work):",r)}}var vr=class extends Error{constructor(e){super(e),this.name="PlannerProxyServiceKeyMissingError"}};async function wr(t,e,r){try{let n=await e.listUserDeviceKeys();if(n.length===0)return r.info("No user device keys found, session will not be encrypted (skipping service-key fetch)",{sessionId:t}),null;let i=[1e3,2e3,4e3],s=i.length+1,o=[],a=null;for(let y=0;y<s;y++){try{o=await e.listServiceDeviceKeys()}catch(g){a=g instanceof Error?g:new Error(String(g)),o=[],r.warn("Service device keys fetch failed",{sessionId:t,attempt:y+1,totalAttempts:s,error:a.message})}if(o.length>0){a=null;break}if(y<i.length){let g=i[y];r.info("Service device keys empty, retrying after backoff",{sessionId:t,attempt:y+1,delayMs:g}),await new Promise(A=>setTimeout(A,g))}}if(o.length===0)throw r.error("PlannerProxyServiceKeyMissing: listServiceDeviceKeys returned empty after 4 attempts",{sessionId:t,totalAttempts:s,lastError:a?.message}),new vr(`PlannerProxyServiceKeyMissing: listServiceDeviceKeys returned empty after ${s} attempts (sessionId=${t}). The planner-proxy Lambda may not have completed its bootstrap; retry session creation in ~30s, or contact support.`);let c=new Set(n.map(y=>y.deviceId)),l=o.filter(y=>!c.has(y.deviceId)),d=[...n,...l];if(d.length===0)return r.info("No device keys found, session will not be encrypted"),null;r.info("Preparing session encryption",{sessionId:t,userDeviceCount:n.length,serviceDeviceCount:l.length,totalDeviceCount:d.length});let p=rr(t),{sessionKey:f,encryptedKeys:m,skippedDeviceIds:S}=k.createSessionKey(d,{onDeviceSkipped:y=>{xi({skipped_count_bucket:Xe(y),session_hash:p}).catch(()=>{})}});return S.length>0&&Ii({session_hash:p,encrypted_count_bucket:Xe(m.length),skipped_count_bucket:Xe(S.length)}).catch(()=>{}),r.info("Session encryption prepared",{sessionId:t,deviceCount:m.length,skippedCount:S.length}),{sessionKey:f,encryptedKeys:m,skippedDeviceIds:S}}catch(n){if(n instanceof vr)throw n;return r.warn("Failed to prepare session encryption:",n),null}}async function _n(t,e,r){let{sessionId:n,userId:i,agentType:s,projectPath:o,metadata:a}=t,c=null;try{c=await e.getSession(n)}catch(m){r.warn("Failed to get session (will attempt to create new)",{sessionId:n,error:m})}if(c){r.info("Session exists in backend - reactivating",{sessionId:n,previousStatus:c.status});try{await e.updateSession({sessionId:n,status:"ACTIVE"})}catch(y){r.warn("Failed to reactivate existing session, will continue",{sessionId:n,error:y})}let m=null,S=c.encryptedKeys??[];if(c.isEncrypted){if(S.length>0){try{let y=await k.getSessionKey(n,S);y&&(m=y,k.cacheSessionKey(n,y),r.info("Session key retrieved for resumed session",{sessionId:n}))}catch(y){r.warn("Failed to retrieve session key for resumed session",{sessionId:n,error:y})}if(!m){let y=rr(n);r.info("Self-rekey: re-registering device key + awaiting grant",{sessionId:n,otherDeviceCount:S.length}),Ci({session_hash:y,other_device_count_bucket:Xe(S.length)}).catch(()=>{});try{await Tt(e,r),m=await Ts(n,{appSyncClient:e,onSuccess:g=>{Ti({session_hash:y,attempt_count:g}).catch(()=>{})},onTimeout:g=>{Oi({session_hash:y,attempt_count:g}).catch(()=>{})}})}catch(g){r.warn("Self-rekey path failed",{sessionId:n,error:g instanceof Error?g.message:String(g)})}}}else r.warn("Encrypted session has empty encryptedKeys; cannot self-rekey",{sessionId:n});if(!m){let y=new Error(`Cannot resume encrypted session ${n}: `+(S.length===0?"session is marked encrypted but session.encryptedKeys is empty (corrupt state). Cannot self-rekey without a peer device. Start a new session.":"this device's key is not in session.encryptedKeys and self-rekey did not complete within 30s. This typically means the device key was rotated and mobile has not yet granted access to this device. Open the mobile app to refresh device keys, then retry."));throw y.code="ENCRYPTED_SESSION_NO_KEY",y}}if(m)try{let y=await Be(n,m,e);y>0&&(r.info("Session re-keyed for newly registered devices on resume",{sessionId:n,newDeviceCount:y}),Pi({session_hash:rr(n),granted_count_bucket:Xe(y)}).catch(()=>{}))}catch(y){r.warn("Session re-key on resume failed (non-fatal)",{sessionId:n,error:y instanceof Error?y.message:String(y)})}return{resumed:!0,sessionKey:m}}let l=await wr(n,e,r),d=o,p=a;l&&(d=$.encryptContent(o,l.sessionKey),p&&Object.keys(p).length>0&&(p={encrypted:$.encryptMetadata(p,l.sessionKey)}),r.info("Session data encrypted",{sessionId:n})),r.info("Creating new session in backend",{sessionId:n,userId:i,agentType:s,isEncrypted:!!l}),await e.createSession({sessionId:n,userId:i,agentType:s,projectPath:d,status:"ACTIVE",metadata:p,isEncrypted:l?!0:void 0,creatorDeviceId:l?await k.getDeviceId():void 0,encryptionVersion:l?1:void 0,encryptedKeys:l?.encryptedKeys});let f=l?.sessionKey||null;return l&&k.cacheSessionKey(n,l.sessionKey),r.info("Session created",{sessionId:n,userId:i,isEncrypted:!!l}),{resumed:!1,sessionKey:f}}re();function xn(t,e){let r=t.getCurrentUserId(),n=async(s,o)=>{let a=k.getCachedSessionIds();if(a.length===0){e.info("[DeviceKeyWatcher] No active sessions to re-key",{reason:s});return}e.info("[DeviceKeyWatcher] Running re-key pass",{reason:s,activeSessionCount:a.length,forceDeviceCount:o?.size??0});for(let c of a){let l=k.getCachedSessionKey(c);if(l)try{let d=await Be(c,l,t,o?{forceDeviceIds:o}:void 0);d>0&&e.info("[DeviceKeyWatcher] Session re-keyed",{sessionId:c,newDeviceCount:d,reason:s})}catch(d){e.warn("[DeviceKeyWatcher] Re-key failed for session (non-fatal)",{sessionId:c,reason:s,error:d instanceof Error?d.message:String(d)})}}},i=t.subscribeToDeviceKeyRegistered(r,s=>{e.info("[DeviceKeyWatcher] New device observed, triggering re-key",{userId:r,newDeviceId:s.deviceId,platform:s.platform,deviceName:s.deviceName}),n(`new-device:${s.deviceId}`,new Set([s.deviceId]))},()=>{n("watcher-reconnect")},s=>{e.warn("[DeviceKeyWatcher] Subscription error (will retry)",{error:s instanceof Error?s.message:String(s)})});return e.info("[DeviceKeyWatcher] Started",{userId:r}),i}kn();vn();var In={};ue(In,{dedupKeyForDestructiveActionEscalated:()=>Wc,dedupKeyForFlagBadApproval:()=>Gc,dedupKeyForProgressEvent:()=>Bc,dedupKeyForTaskCreated:()=>Lc,dedupKeyForTaskTerminated:()=>Kc,dedupKeyForToolUse:()=>Fc});var Os=require("node:crypto"),Oc="task_created",Dc="task_terminated",Nc="progress",$c="tool_use",Mc="destructive_escalated",Uc="flag_bad_approval";function dt(t){if(t.length!==36)throw new Error(`UUID must be 36 chars (got ${t.length}): ${t}`);if(t[8]!=="-"||t[13]!=="-"||t[18]!=="-"||t[23]!=="-")throw new Error(`UUID dashes misplaced: ${t}`);let e=t.replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error(`UUID contains non-hex characters: ${t}`);return Buffer.from(e,"hex")}function pt(t){let e=(0,Os.createHash)("sha256");for(let r of t)typeof r=="string"?e.update(r,"utf8"):e.update(r);return e.digest("hex")}function Lc(t){return pt([dt(t),Oc])}function Kc(t){return pt([dt(t),Dc])}function Bc(t,e){return pt([dt(t),Nc,e])}function Fc(t,e){return pt([dt(t),$c,e])}function Wc(t,e){return pt([dt(t),Mc,e])}function Gc(t){return pt([dt(t),Uc])}kt();var On={};ue(On,{BackendPlannerClient:()=>Rr,BudgetHintSchema:()=>Hc,ClarificationSchema:()=>zc,PlannerBudgetExceededError:()=>Ot,PlannerCacheLayer:()=>kr,PlannerDecisionSchema:()=>Pn,PlannerHealthMachine:()=>br,PlannerTierGateRejectedError:()=>Dt,SessionContextSchema:()=>Vc});var D=require("zod"),Vc=D.z.object({sessionId:D.z.string(),userId:D.z.string(),tier:D.z.enum(["FREE","PRO","MAX"]),currentTaskState:D.z.enum(["none","in_progress","awaiting_user","awaiting_review","merge_gate_pending"]),structuralSummaryDigest:D.z.string(),recentEventCount:D.z.number().int().nonnegative()}),Hc=D.z.object({wallClockMsRemaining:D.z.number(),reviseAttempts:D.z.number().int().nonnegative()}),zc=D.z.object({question:D.z.string(),answer:D.z.string()}),Pn=D.z.object({action:D.z.enum(["start_task","summarize_current_status","advisory_response","ask_user","refuse"]),rationale:D.z.string(),clarifying_question:D.z.string().optional(),advisory_summary:D.z.string().optional(),gateRequest:D.z.record(D.z.unknown()).optional()});var j=require("node:fs"),Fe=h(require("node:path")),$s=h(require("node:os")),Cn=h(require("node:crypto")),Er=1,jc=1440*60*1e3,qc=300*1e3,Jc=1e3,Ds=384,Ns=448,Yc=new Set(["workflow_status_query","workflow_audit_query","workflow_review_query","workflow_continuation_query","advisory_response_safe","ask_user_clarification"]),Tn=class{constructor(){this.chain=Promise.resolve()}async run(e){let r=this.chain,n;this.chain=new Promise(i=>n=i);try{return await r,await e()}finally{n()}}},kr=class{constructor(e){this.workflowCache=new Map;this.signatureCache=new Map;this.hydrated=new Set;this.mutex=new Tn;this.cacheRoot=e??Fe.join($s.homedir(),".codevibe","cache")}async getWorkflowClassification(e,r){await this.hydrateWorkflowIfNeeded(e);let n=this.workflowCache.get(e);if(!n)return null;let i=this.canonicalize(r),s=n.get(i);return s?Date.now()-s.insertedAt>jc?(n.delete(i),await this.mutex.run(()=>this.persistWorkflow(e)),null):(s.lastAccessedAt=Date.now(),s.classification):null}async setWorkflowClassification(e,r,n){this.assertNoActionJson(n),await this.hydrateWorkflowIfNeeded(e);let i=this.workflowCache.get(e);i||(i=new Map,this.workflowCache.set(e,i));let s=!1;i.size>=Jc&&(this.evictLru(i),s=!0);let o=Date.now();i.set(this.canonicalize(r),{schemaVersion:Er,classification:n,insertedAt:o,lastAccessedAt:o}),s&&await this.mutex.run(()=>this.persistWorkflow(e))}async flush(){await this.mutex.run(async()=>{for(let e of this.workflowCache.keys())await this.persistWorkflow(e)})}getSignatureClassification(e,r){let n=this.signatureCache.get(e);if(!n)return null;let i=n.get(r);return i?Date.now()-i.insertedAt>qc?(n.delete(r),null):(i.lastAccessedAt=Date.now(),i.classification):null}setSignatureClassification(e,r,n){this.assertNoActionJson(n);let i=this.signatureCache.get(e);i||(i=new Map,this.signatureCache.set(e,i));let s=Date.now();i.set(r,{schemaVersion:Er,classification:n,insertedAt:s,lastAccessedAt:s})}async flushForTier(e){await this.mutex.run(async()=>{this.workflowCache.delete(e),this.signatureCache.delete(e),this.hydrated.delete(e);let r=this.cacheDir(e);await this.rmRecursiveSafe(r)})}async flushAll(){await this.mutex.run(async()=>{this.workflowCache.clear(),this.signatureCache.clear(),this.hydrated.clear();try{let e=await j.promises.readdir(this.cacheRoot,{withFileTypes:!0});for(let r of e)r.isDirectory()&&await this.rmRecursiveSafe(Fe.join(this.cacheRoot,r.name))}catch{}})}async purgeOnUserSwitch(e){await this.mutex.run(async()=>{let r=this.userIdPrefix(e),n=Fe.join(this.cacheRoot,".last-user"),i=null;try{let o=(await j.promises.readFile(n,"utf-8")).trim();/^[0-9a-f]{16}$/.test(o)?i=o:i="__corrupt__"}catch(o){o?.code!=="ENOENT"&&(i="__error__")}if(i&&i!==r){this.workflowCache.clear(),this.signatureCache.clear(),this.hydrated.clear();try{let o=await j.promises.readdir(this.cacheRoot,{withFileTypes:!0});for(let a of o)a.isDirectory()&&await this.rmRecursiveSafe(Fe.join(this.cacheRoot,a.name))}catch{}}await this.ensureCacheRoot();let s=n+".tmp";try{await j.promises.writeFile(s,r+`
452
+ `,{mode:Ds}),await j.promises.rename(s,n)}catch{}})}async hydrateWorkflowIfNeeded(e){if(this.hydrated.has(e))return;this.hydrated.add(e);let r=this.workflowFilePath(e);try{if(((await j.promises.stat(r)).mode&63)!==0){await this.rotateCorrupt(r);return}let i=await j.promises.readFile(r,"utf-8"),s=JSON.parse(i);if(s.schemaVersion!==Er){await this.rotateCorrupt(r);return}let o=new Map(s.entries);this.workflowCache.set(e,o)}catch(n){n?.code!=="ENOENT"&&await this.rotateCorrupt(r)}}async rotateCorrupt(e){try{await j.promises.rename(e,e+".bak")}catch{}}async persistWorkflow(e){let r=this.cacheDir(e);await this.ensureDir(r);let n=this.workflowFilePath(e),i=n+".tmp",s=this.workflowCache.get(e)??new Map,o={schemaVersion:Er,entries:Array.from(s.entries())};await j.promises.writeFile(i,JSON.stringify(o),{mode:Ds}),await j.promises.rename(i,n)}cacheDir(e){return Fe.join(this.cacheRoot,this.userIdPrefix(e))}userIdPrefix(e){return Cn.createHash("sha256").update(e).digest("hex").slice(0,16)}workflowFilePath(e){return Fe.join(this.cacheDir(e),"workflow-query-classifications.json")}canonicalize(e){return Cn.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}assertNoActionJson(e){if(!e||typeof e.kind!="string"||!Yc.has(e.kind))throw new Error(`cache invariant violated: invalid kind ${e?.kind}`);let r=e;if(typeof r.action=="string")throw new Error("cache invariant violated: action-JSON in classification");if(r.gateRequest!==void 0)throw new Error("cache invariant violated: gateRequest in classification")}evictLru(e){let r=null,n=1/0;for(let[i,s]of e)s.lastAccessedAt<n&&(n=s.lastAccessedAt,r=i);r!==null&&e.delete(r)}async ensureCacheRoot(){await j.promises.mkdir(this.cacheRoot,{recursive:!0,mode:Ns})}async ensureDir(e){await j.promises.mkdir(e,{recursive:!0,mode:Ns})}async rmRecursiveSafe(e){try{await j.promises.rm(e,{recursive:!0,force:!0})}catch{}}};var br=class{constructor(e){this.emitFn=e;this.state="Available";this.consecutiveFailures=0;this.consecutiveSuccesses=0;this.recentLatenciesMs=[];this.URGENT_FAILURE_FOR_DEGRADE=3;this.P95_DEGRADE_THRESHOLD_MS=6e3;this.P95_RECOVER_THRESHOLD_MS=3e3;this.DEGRADED_TO_OUTAGE_FAILURES=10;this.RECOVER_SUCCESSES_NEEDED=5;this.RING_BUFFER_SIZE=20;this.DEGRADED_PROBE_INTERVAL_MS=3e4;this.OUTAGE_PROBE_INTERVAL_MS=5*6e4;this.lastProbeAt=0}recordCall(e,r){this.recentLatenciesMs.push(e),this.recentLatenciesMs.length>this.RING_BUFFER_SIZE&&this.recentLatenciesMs.shift(),r?(this.consecutiveSuccesses+=1,this.consecutiveFailures=0):(this.consecutiveFailures+=1,this.consecutiveSuccesses=0);let n=this.state;return this.state=this.deriveNextState(n),this.state!==n&&this.emitFn({newState:this.state,fromState:n,reason:r?"consecutive successes met threshold":"consecutive failures met threshold",consecutiveFailures:this.consecutiveFailures,consecutiveSuccesses:this.consecutiveSuccesses,p95Ms:this.p95Of(this.recentLatenciesMs)}),this.state}shouldProbe(){let e=Date.now();if(this.state==="Available")return!1;let r=this.state==="Degraded"?this.DEGRADED_PROBE_INTERVAL_MS:this.OUTAGE_PROBE_INTERVAL_MS;return e-this.lastProbeAt>=r}markProbeFired(){this.lastProbeAt=Date.now()}deriveNextState(e){let r=this.p95Of(this.recentLatenciesMs);return e==="Available"?this.consecutiveFailures>=this.URGENT_FAILURE_FOR_DEGRADE||r>this.P95_DEGRADE_THRESHOLD_MS&&this.recentLatenciesMs.length>=this.RING_BUFFER_SIZE?"Degraded":"Available":e==="Degraded"?this.consecutiveFailures>=this.DEGRADED_TO_OUTAGE_FAILURES?"Outage":this.consecutiveSuccesses>=this.RECOVER_SUCCESSES_NEEDED&&r<this.P95_RECOVER_THRESHOLD_MS?"Available":"Degraded":this.consecutiveSuccesses>=this.RECOVER_SUCCESSES_NEEDED?"Available":"Outage"}p95Of(e){if(e.length===0)return 0;let r=[...e].sort((i,s)=>i-s),n=Math.min(r.length-1,Math.floor(.95*r.length));return r[n]}};var Xc=1500,Ot=class extends Error{constructor(e){super(e),this.name="PlannerBudgetExceededError"}},Dt=class extends Error{constructor(e){super(e),this.name="PlannerTierGateRejectedError"}};function Qc(t){let e=t,r=(e?.errorType??e?.name??e?.message??"").toString();return/BudgetExceeded/i.test(r)?"budget_exceeded":/TierGateRejected/i.test(r)?"tier_gate_rejected":"provider"}function Zc(t){let e=`cache hit (${t.kind})`;switch(t.kind){case"workflow_status_query":case"workflow_audit_query":case"workflow_review_query":case"workflow_continuation_query":return{action:"summarize_current_status",rationale:e};case"advisory_response_safe":return{action:"advisory_response",rationale:e,advisory_summary:t.advisorySummary??""};case"ask_user_clarification":return{action:"ask_user",rationale:e,clarifying_question:t.clarifyingQuestion??""}}}function el(t){return t.gateRequest!==void 0||t.action==="start_task"||t.action==="refuse"?null:t.action==="ask_user"?t.clarifying_question?{kind:"ask_user_clarification",clarifyingQuestion:t.clarifying_question}:null:t.action==="advisory_response"?t.advisory_summary?{kind:"advisory_response_safe",advisorySummary:t.advisory_summary}:null:t.action==="summarize_current_status"?{kind:"workflow_status_query"}:null}var Rr=class{constructor(e,r,n,i,s,o){this.transport=e;this.cache=r;this.health=n;this.crypto=i;this.sessionKeyResolver=s;this.emitShellEvent=o;this.lastClassifyTier=null;this.activeSessionId=null}setActiveSession(e){this.activeSessionId=e}async classify(e){let r=e.clarifications.length>0;if(this.lastClassifyTier!==null&&this.lastClassifyTier!==e.sessionContext.tier&&await this.cache.flushForTier(e.sessionContext.userId),this.lastClassifyTier=e.sessionContext.tier,!r){let m=await this.cache.getWorkflowClassification(e.sessionContext.userId,e.prompt);if(m){let S=Zc(m);return await this.emitShellEvent({sessionId:e.sessionContext.sessionId,type:"PLANNER_CACHE_HIT",metadata:{cacheKind:"workflow_classification",decision:S}}),S}}if(e.budgetHint.wallClockMsRemaining<=Xc)return{action:"ask_user",rationale:"wall-clock deadline reached",clarifying_question:"Planner deadline reached \u2014 please clarify or try again."};if(this.health.state!=="Available")return{action:"ask_user",rationale:`planner state is ${this.health.state.toLowerCase()}`,clarifying_question:"Planner is temporarily limited \u2014 please use a slash command or try again shortly."};let n=await this.sessionKeyResolver.getSessionKey(e.sessionContext.sessionId);if(!n)throw new Error("session key unresolved on planner classify");let i=this.crypto.encryptString(e.prompt,n),s=this.crypto.encryptJson({clarifications:e.clarifications},n),o=this.crypto.encryptJson(e.sessionContext,n),a=this.crypto.encryptJson(e.budgetHint,n),c=Date.now(),l,d=!1;try{l=await this.transport.classifyPlannerPrompt({sessionId:e.sessionContext.sessionId,prompt:i,clarifications:JSON.stringify({encrypted:s}),sessionContext:JSON.stringify({encrypted:o}),budgetHint:JSON.stringify({encrypted:a})}),d=!0}catch(m){let S=Date.now()-c,y=Qc(m);throw y==="budget_exceeded"?(await this.emitShellEvent({sessionId:e.sessionContext.sessionId,type:"PLANNER_DEGRADED",metadata:{notification:"planner_budget_exceeded",elapsedMs:S}}),new Ot(m.message)):y==="tier_gate_rejected"?(await this.emitShellEvent({sessionId:e.sessionContext.sessionId,type:"PLANNER_DEGRADED",metadata:{notification:"planner_tier_gate_rejected",elapsedMs:S}}),new Dt(m.message)):(this.health.recordCall(S,!1),m)}let p=this.crypto.decryptString(l.decision,n),f;try{let m=JSON.parse(p);f=Pn.parse(m)}catch(m){throw this.health.recordCall(Date.now()-c,!1),new Error(`MalformedRequest: planner decision Zod validation failed: ${m.message}`)}if(this.health.recordCall(l.serverLatencyMs,d),!r){let m=el(f);m&&await this.cache.setWorkflowClassification(e.sessionContext.userId,e.prompt,m)}return await this.emitShellEvent({sessionId:e.sessionContext.sessionId,type:"PLANNER_DECISION",metadata:{decision:f}}),f}async probe(){let e=this.activeSessionId;if(!e)throw new Error("probe() called with no active session \u2014 call setActiveSession(sessionId) before invoking");let r=Date.now();try{let n=await this.transport.pingPlanner({sessionId:e});return this.health.recordCall(n.ms,n.ok),this.health.markProbeFired(),{ok:n.ok,latencyMs:n.ms,errorClass:n.ok?void 0:"unreachable"}}catch{let i=Date.now()-r;return this.health.recordCall(i,!1),this.health.markProbeFired(),{ok:!1,latencyMs:i,errorClass:"unreachable"}}}};var Bn={};ue(Bn,{SECRET_DENY_LIST:()=>mt,StructuralSummaryError:()=>C,addBodyPath:()=>Dr,compileUserIgnore:()=>_r,createStructuralSummaryGenerator:()=>Or,emptyUserIgnoreMatcher:()=>xr,isPathAccountedFor:()=>ft,isPathAdmissible:()=>xe,isPathInIgnoredPrefixes:()=>Nt,matchesSecretDenyList:()=>Dn,optInFilePath:()=>Ut,readOptIn:()=>Lt,readReadmePreview:()=>Kn,removeBodyPath:()=>to,walkRepoTree:()=>Ir});var Xs=h(require("crypto")),Tr=h(require("path"));N();var q=h(require("path"));function Ar(t){return!!(t===".."||t.startsWith(".."+q.sep)||q.sep!=="/"&&t.startsWith("../"))}var mt=[".env",".env.local",".env.development",".env.production",".env.test",".env.staging","credentials","id_rsa","id_dsa","id_ecdsa","id_ed25519"],tl=[".pem",".key",".crt",".pfx",".p12",".keystore"];function Dn(t){let e=q.basename(t);for(let r of mt)if(e===r){if(r==="credentials"){let n=q.dirname(t);if(q.basename(n)===".aws")return!0;continue}return!0}for(let r of mt)if(r.startsWith("id_")&&e.startsWith(r))return!0;if(e.startsWith(".env."))return!0;for(let r of tl)if(e.endsWith(r)&&e.length>r.length)return!0;return!1}function Nt(t,e,r){if(e.has(t))return!0;let n=t;for(let i=0;i<4096;i++){if(r.has(n))return!0;let s=q.dirname(n);if(s===n)return!1;n=s}return!1}function ft(t,e,r){if(e.has(t))return!0;let n=t;for(let i=0;i<4096;i++){if(r.has(n))return!0;let s=q.dirname(n);if(s===n)return!1;n=s}return!1}function xe(t,e,r=!1){if(Dn(t))return{admissible:!1,reason:"secret"};if(!e.notInGitRepo&&e.untrackedSet.has(t))return{admissible:!1,reason:"untracked"};if(!e.notInGitRepo&&Nt(t,e.ignoredExactPaths,e.ignoredDirPrefixes))return{admissible:!1,reason:"gitignore"};let n=q.relative(e.realRootPath,t);return n.length>0&&!Ar(n)&&!q.isAbsolute(n)&&e.userIgnoreMatcher.ignores(n,r)?{admissible:!1,reason:"userIgnore"}:{admissible:!0}}var C=class extends Error{constructor(e,r){super(e),this.name="StructuralSummaryError",this.kind=r}};var ne=h(require("fs/promises")),L=h(require("path")),Ls=require("child_process"),Ks=require("util");N();function rl(t){let e=t,r=e.startsWith("/");r&&(e=e.slice(1)),e=nl(e);let n=e.includes("/"),i="",s=0;for(;s<e.length;){let a=e[s];if(a==="*"&&e[s+1]==="*"){let c=s===0,l=s+2===e.length,d=s>0&&e[s-1]==="/",p=e[s+2]==="/";if(d&&p){i=i.slice(0,-1)+"(?:/.+)?/",s+=3;continue}if(c&&p){i+="(?:.+/)?",s+=3;continue}if(d&&l){i=i.slice(0,-1)+"/.+",s+=2;continue}i+=".*",s+=2;continue}a==="*"?i+="[^/]*":a==="?"?i+="[^/]":/[.+^${}()|\\[\]]/.test(a)?i+="\\"+a:i+=a,s++}let o;return r||n?o=`^${i}(/.*)?$`:o=`^(.*/)?${i}(/.*)?$`,new RegExp(o)}function nl(t){if(!t.includes("**"))return t;let e=t.split("/"),r=[];for(let n of e)n==="**"&&r.length>0&&r[r.length-1]==="**"||r.push(n);return r.join("/")}function il(t){let e=[];for(let r of t.split(`
453
+ `)){let n=r.replace(/[\r]+$/,"").replace(/\s+$/u,"");if(n.length===0||n.startsWith("#"))continue;let i=!1;n.startsWith("!")&&(i=!0,n=n.slice(1));let s=n.endsWith("/");s&&(n=n.slice(0,-1)),n.length!==0&&e.push({pattern:rl(n),negated:i,directoryOnly:s})}return e}var Nn=class{constructor(e){this.rules=il(e)}ignores(e,r=!1){let n=e.split(/[/\\]/).filter(s=>s.length>0).join("/");if(n.length===0)return!1;let i=!1;for(let s of this.rules)s.directoryOnly&&!r||s.pattern.test(n)&&(i=!s.negated);return i}},Ms={ignores:()=>!1};function _r(t){return!t||t.trim().length===0?Ms:new Nn(t)}function xr(){return Ms}var $n=(0,Ks.promisify)(Ls.execFile),Us=512*1024,sl=new Set(["node_modules","target","build","dist",".git",".next",".nuxt","Pods",".gradle",".dart_tool","vendor"]);async function Ir(t){let e;try{e=await ne.realpath(t.rootPath)}catch{e=t.rootPath}let r=await al(t.rootPath,e,t.ignoreFile);if(!r.notInGitRepo&&Nt(e,r.ignoredExactPaths,r.ignoredDirPrefixes))return{directoryTree:{path:t.rootPath,fileCount:0,bytes:0,children:[]},fileExtensions:new Map,excludedByGitignore:1,excludedByIgnoreFile:0,excludedAsUntracked:0,truncated:!1,bodyBudgetExceeded:!1,notInGitRepo:r.notInGitRepo,exclusionState:r,countedExactPaths:new Set,countedPrunedPrefixes:new Set([e])};let n={state:r,opts:t,counts:{excludedByGitignore:0,excludedByIgnoreFile:0,excludedAsUntracked:0},truncated:!1,bodyBudgetExceeded:!1,countedExactPaths:new Set,countedPrunedPrefixes:new Set,fileExtensions:new Map};return{directoryTree:await Bs(e,t.rootPath,0,n,!0),fileExtensions:n.fileExtensions,excludedByGitignore:n.counts.excludedByGitignore,excludedByIgnoreFile:n.counts.excludedByIgnoreFile,excludedAsUntracked:n.counts.excludedAsUntracked,truncated:n.truncated,bodyBudgetExceeded:n.bodyBudgetExceeded,notInGitRepo:r.notInGitRepo,exclusionState:r,countedExactPaths:n.countedExactPaths,countedPrunedPrefixes:n.countedPrunedPrefixes}}async function Bs(t,e,r,n,i){let s={path:e,fileCount:0,bytes:0,children:[]};if(r>=n.opts.maxDepth)return s.truncatedByDepth=!0,s;let o;try{o=await ne.readdir(t,{withFileTypes:!0})}catch(a){if(i)throw new C(`Launch root readdir failed: ${a.message}`,"fs_unreadable");return u.info(`[structural-summary] readdir failed for ${t}`,{error:a.message}),s}o.sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(let a of o){if(n.truncated)break;if(n.opts.fileCountBudget.remaining<=0){n.truncated=!0;break}let c=L.join(t,a.name),l=L.join(e,a.name);if(a.isDirectory()&&sl.has(a.name)){n.counts.excludedByGitignore++,n.countedPrunedPrefixes.add(c);continue}let d=xe(c,n.state,a.isDirectory());if(!d.admissible){switch(d.reason){case"secret":break;case"untracked":n.counts.excludedAsUntracked++,n.countedExactPaths.add(c);break;case"gitignore":n.counts.excludedByGitignore++,a.isDirectory()?n.countedPrunedPrefixes.add(c):n.countedExactPaths.add(c);break;case"userIgnore":n.counts.excludedByIgnoreFile++,a.isDirectory()?n.countedPrunedPrefixes.add(c):n.countedExactPaths.add(c);break}continue}if(a.isSymbolicLink()){let p={path:l,fileCount:0,bytes:0,children:[]};s.children.push(p);continue}if(a.isDirectory()){let p=await Bs(c,l,r+1,n,!1);s.children.push(p),s.fileCount+=p.fileCount,s.bytes+=p.bytes,p.truncatedByDepth&&(s.truncatedByDepth=!0);continue}if(a.isFile()){let p=0;try{p=(await ne.stat(c)).size}catch{continue}n.opts.fileCountBudget.remaining--,s.fileCount++,s.bytes+=p;let f=L.extname(a.name).toLowerCase();if(f&&n.fileExtensions.set(f,(n.fileExtensions.get(f)??0)+1),ol(c,n.opts.includeBodies,n.state.realRootPath))if(n.opts.bodyBudget.remaining<=0){n.bodyBudgetExceeded=!0;let m={path:l,fileCount:0,bytes:0,children:[],bodyTruncated:!0};s.children.push(m)}else{let m={path:l,fileCount:0,bytes:0,children:[]},S=Math.min(p,Us);if(p>Us)try{let y=await ne.open(c,"r");try{let g=Buffer.alloc(S);await y.read(g,0,S,0),m.body=g.toString("utf8")}finally{await y.close()}m.bodyTruncated=!0}catch{m.bodyTruncated=!0}else try{m.body=await ne.readFile(c,"utf8")}catch{m.bodyTruncated=!0}n.opts.bodyBudget.remaining-=S,n.opts.bodyBudget.remaining<=0&&(n.bodyBudgetExceeded=!0),s.children.push(m)}}}return s}function ol(t,e,r){if(!e||e.length===0)return!1;for(let n of e){if(!L.isAbsolute(n))continue;if(t===n)return!0;let i=n.endsWith(L.sep)?n:n+L.sep;if(t.startsWith(i))return!0}return!1}async function al(t,e,r){let n="",i=!1;try{let{stdout:l}=await $n("git",["rev-parse","--show-toplevel"],{cwd:e});if(n=l.trim(),!n)i=!0;else{let d=L.relative(n,e);d.length>0&&(Ar(d)||L.isAbsolute(d))&&(i=!0,u.info("[structural-summary] realRootPath outside repoTopLevel \u2014 non-git fallback",{realRootPath:e,repoTopLevel:n}))}}catch(l){i=!0,u.info("[structural-summary] git rev-parse failed \u2014 non-git fallback",{rootPath:t,error:l.message})}let s=new Set;if(!i)try{let{stdout:l}=await $n("git",["status","--porcelain","-z","--untracked-files=all"],{cwd:n,maxBuffer:67108864}),d=l.split("\0").filter(p=>p.length>0);for(let p of d)if(p.startsWith("?? ")){let f=p.slice(3),m=L.join(n,f),S=L.relative(e,m);S.length>0&&!Ar(S)&&!L.isAbsolute(S)&&s.add(m)}}catch(l){u.info("[structural-summary] git status failed \u2014 empty untracked set",{error:l.message})}let o=new Set,a=new Set;if(!i)try{let{stdout:l}=await $n("git",["ls-files","-z","--ignored","--exclude-standard","--others","--directory"],{cwd:n,maxBuffer:67108864}),d=l.split("\0").filter(p=>p.length>0);for(let p of d){let f=p.endsWith("/"),m=f?p.slice(0,-1):p,S=L.join(n,m);f?a.add(S):o.add(S)}}catch(l){u.info("[structural-summary] git ls-files failed \u2014 empty ignored set",{error:l.message})}let c=xr();if(r)try{let l=await ne.readFile(r,"utf8");c=_r(l)}catch(l){let d=l.code;d&&d!=="ENOENT"&&u.warn("[structural-summary] failed to read user-ignore file",{ignoreFile:r,error:l.message})}return{rootPath:t,realRootPath:e,notInGitRepo:i,repoTopLevel:n,untrackedSet:s,ignoredExactPaths:o,ignoredDirPrefixes:a,userIgnoreMatcher:c,secretDenyList:mt}}var Cr=h(require("path"));N();var Un={};ue(Un,{findManifest:()=>cl,parse:()=>ll});var Fs=h(require("fs/promises")),Ws=h(require("path"));var Pr=h(require("fs/promises")),Mn=h(require("fs"));async function ie(t){let e;try{e=await Pr.lstat(t,{bigint:!0})}catch{return null}if(e.isSymbolicLink()||!e.isFile())return null;let r=Mn.constants.O_NOFOLLOW,n=Mn.constants.O_RDONLY|(r??0),i;try{i=await Pr.open(t,n)}catch{return null}try{let s=await i.stat({bigint:!0});return!s.isFile()||s.dev!==e.dev||s.ino!==e.ino?null:await i.readFile("utf8")}catch{return null}finally{try{await i.close()}catch{}}}async function cl(t){let e=Ws.join(t,"package.json");try{let r=await Fs.lstat(e);if(r.isSymbolicLink())return null;if(r.isFile())return e}catch{return null}return null}async function ll(t){let e=await ie(t);if(e===null)throw new C(`npm manifest read refused (symlink / non-regular / dev-ino-mismatch): ${t}`,"fs_unreadable");let r=JSON.parse(e),n=typeof r.name=="string"?r.name:void 0,i=new Set;for(let s of["dependencies","peerDependencies","optionalDependencies"]){let o=r[s];if(o&&typeof o=="object"&&!Array.isArray(o))for(let a of Object.keys(o))i.add(a)}return{type:"npm",packageName:n,dependencies:Array.from(i).sort()}}var Ln={};ue(Ln,{findManifest:()=>ul,parse:()=>dl});var Gs=h(require("fs/promises")),Vs=h(require("path")),Hs=h(require("@iarna/toml"));async function ul(t){let e=Vs.join(t,"Cargo.toml");try{let r=await Gs.lstat(e);if(r.isSymbolicLink())return null;if(r.isFile())return e}catch{return null}return null}async function dl(t){let e=await ie(t);if(e===null)throw new C(`cargo manifest read refused (symlink / non-regular / dev-ino-mismatch): ${t}`,"fs_unreadable");let r=Hs.parse(e),n,i=r.package;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=i.name;typeof c=="string"&&(n=c)}let s=new Set,o=r.dependencies;if(o&&typeof o=="object"&&!Array.isArray(o))for(let c of Object.keys(o))s.add(c);let a=r.workspace;if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.dependencies;if(c&&typeof c=="object"&&!Array.isArray(c))for(let l of Object.keys(c))s.add(l)}return{type:"cargo",packageName:n,dependencies:Array.from(s).sort()}}var $t=h(require("fs/promises")),Mt=h(require("path"));N();var zs={async findManifest(t){let e=Mt.join(t,"pyproject.toml");try{let r=await $t.lstat(e);if(r.isSymbolicLink())return null;if(r.isFile())return e}catch{return null}return null},async parse(t){let e=await ie(t);if(e===null)throw new C(`pyproject manifest read refused (symlink / non-regular / dev-ino-mismatch): ${t}`,"fs_unreadable");let r=e.indexOf("[project]");if(r===-1)return{type:"pyproject",dependencies:[]};let n=e.slice(r+9),i=n.match(/\n\[[^\]]+\]/),s=i?n.slice(0,i.index??n.length):n,o,a=s.match(/\bname\s*=\s*["']([^"']+)["']/);a&&(o=a[1]);let c=[],l=s.match(/\bdependencies\s*=\s*\[([\s\S]*?)\]/);if(l){let d=l[1],p=/["']([^"']+)["']/g,f;for(;(f=p.exec(d))!==null;){let S=f[1].trim().split(/[\s<>=!~;]/)[0]?.trim();S&&S.length>0&&c.push(S)}}return{type:"pyproject",packageName:o,dependencies:Array.from(new Set(c)).sort()}}},js={async findManifest(t){let e=Mt.join(t,"go.mod");try{let r=await $t.lstat(e);if(r.isSymbolicLink())return null;if(r.isFile())return e}catch{return null}return null},async parse(t){let e=await ie(t);if(e===null)throw new C(`go.mod manifest read refused (symlink / non-regular / dev-ino-mismatch): ${t}`,"fs_unreadable");let r,n=e.match(/^\s*module\s+(\S+)/m);n&&(r=n[1]);let i=[],s=e.match(/require\s*\(([\s\S]*?)\)/);if(s){let c=s[1];for(let l of c.split(`
454
+ `)){let d=l.trim();if(!d||d.startsWith("//"))continue;let p=d.match(/^(\S+)/);p&&i.push(p[1])}}let o=/^require\s+([^\s(]+)\s+\S+/gm,a;for(;(a=o.exec(e))!==null;)i.push(a[1]);return{type:"go",packageName:r,dependencies:Array.from(new Set(i)).sort()}}},qs={async findManifest(t){let e=Mt.join(t,"Podfile");try{let r=await $t.lstat(e);if(r.isSymbolicLink())return null;if(r.isFile())return e}catch{return null}return null},async parse(t){let e=await ie(t);if(e===null)throw new C(`Podfile manifest read refused (symlink / non-regular / dev-ino-mismatch): ${t}`,"fs_unreadable");let r,n=e.match(/\btarget\s+['"]([^'"]+)['"]\s+do/);n&&(r=n[1]);let i=[],s=/^\s*pod\s+['"]([^'"]+)['"]/gm,o;for(;(o=s.exec(e))!==null;)i.push(o[1]);return i.length===0&&u.warn("[structural-summary] Podfile parsed with 0 pod entries \u2014 likely conditional/non-standard syntax",{file:t}),{type:"podfile",packageName:r,dependencies:Array.from(new Set(i)).sort()}}},Js={async findManifest(t){for(let e of["build.gradle","build.gradle.kts"]){let r=Mt.join(t,e);try{let n=await $t.lstat(r);if(n.isSymbolicLink())continue;if(n.isFile())return r}catch{continue}}return null},async parse(t){let e=await ie(t);if(e===null)throw new C(`gradle manifest read refused (symlink / non-regular / dev-ino-mismatch): ${t}`,"fs_unreadable");let r,n=e.match(/\bapplicationId\s*=?\s*["']([^"']+)["']/)||e.match(/\bnamespace\s*=?\s*["']([^"']+)["']/);n&&(r=n[1]);let i=[],s=/\b(?:implementation|api|compileOnly|runtimeOnly|testImplementation|androidTestImplementation)\s*\(?\s*["']([^"']+)["']/g,o;for(;(o=s.exec(e))!==null;)i.push(o[1]);return{type:"gradle",packageName:r,dependencies:Array.from(new Set(i)).sort()}}};var pl=[Un,Ln,zs,js,qs,Js];async function Ys(t,e,r,n,i){for(let s of pl){let o=await s.findManifest(t);if(!o)continue;let a=Cr.join(e.realRootPath,Cr.basename(o)),c=xe(a,e);if(!c.admissible){let l=ft(a,r,n);if(!l)switch(c.reason){case"untracked":i.excludedAsUntracked++;break;case"gitignore":i.excludedByGitignore++;break;case"userIgnore":i.excludedByIgnoreFile++;break;case"secret":break}u.info(`[structural-summary] Manifest at ${a} is inadmissible (${c.reason}); skipping (walkerAccountedFor=${l})`);continue}try{return await s.parse(a)}catch(l){u.warn(`[structural-summary] Failed to parse ${a}; continuing to next parser`,{err:l.message});continue}}return{type:"none",dependencies:[]}}function Or(){return{generate:yl}}var fl=5e4,gl=64*1024*1024;async function yl(t){if(t.includeBodies&&t.includeBodies.length>0&&t.tier!=="MAX")throw new C("includeBodies opt-in is Max-tier only. Upgrade at quantiya.ai/codevibe/pricing.","tier_gate");if(t.includeBodies){for(let A of t.includeBodies)if(!Tr.isAbsolute(A))throw new C(`includeBodies entry must be absolute (got: ${A}).`,"invalid_path")}let e={remaining:t._test_caps?.fileCountCap??fl},r={remaining:t._test_caps?.bodyByteCap??gl},n=[],i=0,s=0,o=0,a=!1,c=!1,l;for(let A of t.rootPaths){if(e.remaining<=0){c=!0,l=l??"fileCount";break}let b=await Ir({rootPath:A,ignoreFile:t.ignoreFile,includeBodies:t.includeBodies??[],maxDepth:12,fileCountBudget:e,bodyBudget:r});i+=b.excludedByGitignore,s+=b.excludedByIgnoreFile,o+=b.excludedAsUntracked,a=a||b.notInGitRepo,b.truncated&&!l&&(l="fileCount"),b.bodyBudgetExceeded&&!l&&(l="bodyBytes"),c=c||b.truncated||b.bodyBudgetExceeded;let T=b.exclusionState,O=b.countedExactPaths,le=b.countedPrunedPrefixes,Se={excludedAsUntracked:0,excludedByGitignore:0,excludedByIgnoreFile:0},He=await Ys(A,T,O,le,Se);o+=Se.excludedAsUntracked,i+=Se.excludedByGitignore,s+=Se.excludedByIgnoreFile;let Vt=El(b.fileExtensions),Ht={excludedAsUntracked:0,excludedByGitignore:0,excludedByIgnoreFile:0},qo=await Kn(A,T,O,le,Ht);o+=Ht.excludedAsUntracked,i+=Ht.excludedByGitignore,s+=Ht.excludedByIgnoreFile,n.push({rootPath:A,manifestType:He.type,packageName:He.packageName,dependencies:He.dependencies,inferredLanguages:Vt,readmePreview:qo,directoryTree:b.directoryTree})}let d={bodyInclusionPaths:t.includeBodies??[],excludedByGitignore:i,excludedByIgnoreFile:s,excludedAsUntracked:o,budgetExceeded:c,budgetReason:l,notInGitRepo:a},p=n.reduce((A,b)=>A+Sl(b.directoryTree),0),f=n.reduce((A,b)=>A+vl(b.directoryTree),0),m={generatedAt:new Date().toISOString(),rootPaths:t.rootPaths,repos:n,totalFileCount:p,totalBytes:f,privacyEnvelope:d},{generatedAt:S,...y}=m,g=Xs.createHash("sha256").update(JSON.stringify(y,hl)).digest("hex");return{...m,sha256:g}}function hl(t,e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let r=e,n={};for(let i of Object.keys(r).sort())n[i]=r[i];return n}return e}function Sl(t){return t.fileCount}function vl(t){return t.bytes}var wl=["README.md","README.rst","README.txt","README"];async function Kn(t,e,r,n,i){for(let s of wl){let o=Tr.join(e.realRootPath,s);try{let a=xe(o,e);if(!a.admissible){let d=ft(o,r,n);if(!d)switch(a.reason){case"untracked":i.excludedAsUntracked++;break;case"gitignore":i.excludedByGitignore++;break;case"userIgnore":i.excludedByIgnoreFile++;break;case"secret":break}u.info(`[structural-summary] README candidate ${o} is inadmissible (${a.reason}); skipping (walkerAccountedFor=${d})`);continue}let c=await ie(o);if(c===null){u.info(`[structural-summary] README candidate ${o} refused by safeReadTextFile (symlink / non-regular / dev-ino-mismatch); skipping`);continue}return c.split(`
455
+ `).slice(0,50).join(`
456
+ `)}catch(a){if(a.code==="ENOENT")continue;u.warn(`[structural-summary] Failed to read ${o}`,{error:a.message})}}return""}function El(t){let e={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".py":"python",".rs":"rust",".go":"go",".swift":"swift",".kt":"kotlin",".java":"java",".rb":"ruby",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".m":"objc",".mm":"objc",".sh":"shell",".toml":"toml",".json":"json",".md":"markdown",".yaml":"yaml",".yml":"yaml"},r=new Map;for(let[n,i]of t){let s=e[n];s&&r.set(s,(r.get(s)??0)+i)}return Array.from(r.entries()).sort((n,i)=>i[1]!==n[1]?i[1]-n[1]:n[0]<i[0]?-1:n[0]>i[0]?1:0).map(([n])=>n)}var X=h(require("fs/promises")),ye=h(require("path")),Qs=h(require("os"));N();function kl(){return(process.env.VITEST==="true"||process.env.NODE_ENV==="test")&&process.env.CODEVIBE_HOME_OVERRIDE?process.env.CODEVIBE_HOME_OVERRIDE:Qs.homedir()}function Ut(){return ye.join(kl(),".codevibe","structural-summary.opt-in.json")}function Zs(t){if(!t||typeof t!="object")return!1;let e=t;if(e.schemaVersion!==1||!Array.isArray(e.bodyInclusionPaths))return!1;for(let r of e.bodyInclusionPaths)if(typeof r!="string")return!1;return!(typeof e.lastUpdatedAt!="string"||e.tierAtOptIn!=="MAX")}function bl(t){let e=[],r=[];for(let n of t.bodyInclusionPaths)ye.isAbsolute(n)?r.push(n):e.push(n);return e.length===0?t:(process.stderr.write(`structural-summary.opt-in.json: dropping ${e.length} non-absolute legacy entr${e.length===1?"y":"ies"} on read (privacy fix). Re-opt-in with absolute paths via /structural-summary --include-bodies <absolute-path>.
457
+ `),u.warn("[structural-summary] opt-in legacy migration \u2014 dropped non-absolute entries on read",{dropped:e}),{...t,bodyInclusionPaths:r})}async function Lt(t){let e=Ut(),r;try{r=await X.stat(e)}catch(s){return s?.code!=="ENOENT"&&u.debug("[structural-summary] opt-in stat error \u2014 treating as missing",{filePath:e,error:s.message}),null}if((r.mode&63)!==0)return process.stderr.write(`structural-summary.opt-in.json has loose permissions; ignoring
458
+ `),null;let n;try{n=await X.readFile(e,"utf8")}catch(s){return u.debug("[structural-summary] opt-in read error \u2014 treating as missing",{filePath:e,error:s.message}),null}let i;try{i=JSON.parse(n)}catch(s){return u.debug("[structural-summary] opt-in malformed JSON \u2014 treating as missing",{filePath:e,error:s.message}),null}return Zs(i)?i.tierAtOptIn!==t?(u.debug("[structural-summary] opt-in tier downgrade \u2014 treating as missing",{filePath:e,tierAtOptIn:i.tierAtOptIn,currentTier:t}),null):bl(i):(u.debug("[structural-summary] opt-in schema mismatch \u2014 treating as missing",{filePath:e}),null)}async function eo(t){let e=Ut(),r=ye.dirname(e);await X.mkdir(r,{recursive:!0}),await X.writeFile(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384});try{await X.chmod(e,384)}catch{}}async function Dr(t,e){if(e!=="MAX")throw new C("Body inclusion opt-in is Max-tier only. Upgrade at quantiya.ai/codevibe/pricing.","tier_gate");if(!ye.isAbsolute(t))throw new C(`Body inclusion opt-in path must be absolute (got: ${t}).`,"invalid_path");let r=ye.resolve(t),n;try{n=await X.realpath(r)}catch(o){let a=o?.code;throw new C(`Body inclusion opt-in path cannot be resolved (${a??"unknown"}): ${r}.`,"invalid_path")}let i=await Lt(e),s={schemaVersion:1,bodyInclusionPaths:Array.from(new Set([...i?.bodyInclusionPaths??[],n])).sort(),lastUpdatedAt:new Date().toISOString(),tierAtOptIn:"MAX"};return await eo(s),s}async function to(t){let e=Ut(),r=null;try{r=await X.readFile(e,"utf8")}catch(o){if(o.code!=="ENOENT")throw o}let n=null;if(r)try{let o=JSON.parse(r);Zs(o)&&(n=o)}catch{}let s={schemaVersion:1,bodyInclusionPaths:(n?.bodyInclusionPaths??[]).filter(o=>o!==t),lastUpdatedAt:new Date().toISOString(),tierAtOptIn:"MAX"};return await eo(s),s}var Co=h(require("react")),To=h(require("path")),Oo=h(require("os"));re();N();var gt=null,Nr=null;async function Rl(t){return await new Function("m","return import(m)")(t)}var Al=Rl;async function Kt(t){return Al(t)}async function ro(){return gt||Nr||(Nr=(async()=>{let[t,e,r,n,i]=await Promise.all([Kt("ink"),Kt("ink-text-input"),Kt("ink-spinner"),Kt("ink-select-input"),Kt("gradient-string")]);return gt={ink:t,inkTextInput:e,inkSpinner:r,inkSelectInput:n,gradientString:i},gt})(),Nr)}function x(){if(!gt)throw new Error("ink-runtime not initialized \u2014 call `await initInkRuntime()` from the entrypoint before mounting any TUI component");return gt}var Ie=require("ulid"),no=500;function Wn(t,e){switch(e.type){case"USER_INPUT":return Fn(t,e.text);case"PLANNER_DECISION":return _l(t,e.decision,e.taskId);case"EVENT_RECEIVED":return xl(t,e.event,e.role??"implementor");case"REVIEWER_STATE_CHANGED":return Il(t,e.nodeId,e.seatId,e.newState);case"GATE_STATE_CHANGED":return Cl(t,e.nodeId,e.gate);case"PLANNER_HEALTH_CHANGED":return{...t,plannerHealth:e.newState};case"SLASH_OUTPUT":return Tl(t,e.command,e.output);case"CLARIFICATION_ANSWERED":return Ol(t,e.answer);case"TASK_QUEUED":return{...t,queuedTasks:[...t.queuedTasks,e.queuedTask]};case"TASK_DEQUEUED":return{...t,queuedTasks:t.queuedTasks.filter(r=>r.queuedTaskId!==e.queuedTaskId)};case"TASK_LIFECYCLE":return Dl(t,e.task);case"CLEAR_PENDING_CLARIFICATION":return{...t,pendingClarification:null};case"STRUCTURAL_SUMMARY_GENERATED":return{...t,structuralSummary:e.summary,structuralSummaryError:null};case"STRUCTURAL_SUMMARY_FAILED":return{...t,structuralSummary:null,structuralSummaryError:e.error};case"GATE_PROMPT_RECEIVED":return $l(t,e.envelope);case"GATE_PROMPT_NOTES_REQUESTED":return Ml(t,e.promptEntryId,e.decisionDraft);case"GATE_PROMPT_SUBMIT_STARTED":return Ul(t,e.promptEntryId);case"GATE_PROMPT_RESOLVED":return Ll(t,e.promptEntryId,e.postAction);case"GATE_PROMPT_SUBMIT_FAILED":return Kl(t,e.promptEntryId);case"GATE_PROMPT_NOTES_CANCELLED":return Bl(t,e.promptEntryId);case"SHELL_ADVISORY":return We(t,{kind:"advisory",id:(0,Ie.ulid)(),timestamp:new Date().toISOString(),final:!0,source:e.source,text:e.text});case"EXIT":return t;default:{let r=e;return t}}}function We(t,e){let r=[...t.conversation,e],n=r.length>no?r.slice(r.length-no):r;return{...t,conversation:n}}function Fn(t,e){let r={kind:"user-message",id:(0,Ie.ulid)(),timestamp:new Date().toISOString(),final:!0,text:e},n=We(t,r),i={...n,inputHistory:[...n.inputHistory,e]};if(t.pendingClarification===null)return i;let s=t.pendingClarification.rounds,o=s.length-1;if(o<0||s[o].answer!==void 0)return i;let a=s.map((c,l)=>l===o?{question:c.question,answer:e}:c);return{...i,pendingClarification:{...t.pendingClarification,rounds:a}}}function _l(t,e,r){let n={kind:"planner-decision",id:(0,Ie.ulid)(),timestamp:new Date().toISOString(),final:!0,action:e.action,rationale:e.rationale,taskId:r},i=We(t,n);if(e.action==="ask_user"&&e.clarifying_question){let s={kind:"advisory",id:(0,Ie.ulid)(),timestamp:new Date().toISOString(),final:!0,source:"planner",text:e.clarifying_question},o=We(i,s),a=t.pendingClarification;if(a===null){let l=[...o.conversation].reverse().find(d=>d.kind==="user-message")?.text??"";return{...o,pendingClarification:{originalPrompt:l,rounds:[{question:e.clarifying_question}],conversationEntryId:s.id}}}else return{...o,pendingClarification:{originalPrompt:a.originalPrompt,rounds:[...a.rounds,{question:e.clarifying_question}],conversationEntryId:s.id}}}return t.pendingClarification!==null?{...i,pendingClarification:null}:i}function xl(t,e,r){let n=e.parentTaskId??"",i={kind:"subagent-event",id:(0,Ie.ulid)(),timestamp:e.timestamp||new Date().toISOString(),final:!0,parentTaskId:n,role:r,event:e};return We(t,i)}function Il(t,e,r,n){let i=t.conversation.findIndex(f=>f.kind==="reviewer-status-node"&&f.id===e);if(i===-1){let f=new Map(t.activeReviewerSeats);return f.set(r,n),{...t,activeReviewerSeats:f}}let s=t.conversation[i];if(s.kind!=="reviewer-status-node"||s.final)return t;let o=s.seats.map(f=>f.seatId===r?n:f),a=Pl(o),l={...s,seats:o,quorumStatus:a,final:a==="PASS"||a==="REVISE"||a==="BLOCK"},d=[...t.conversation.slice(0,i),l,...t.conversation.slice(i+1)],p=new Map(t.activeReviewerSeats);return p.set(r,n),{...t,conversation:d,activeReviewerSeats:p}}function Pl(t){return t.length===0?"queued":t.some(e=>e.status==="BLOCK")?"BLOCK":t.some(e=>e.status==="queued")?"queued":t.some(e=>e.status==="running")?"running":t.some(e=>e.status==="REVISE")?"REVISE":"PASS"}function Cl(t,e,r){let n=t.conversation.findIndex(c=>c.kind==="gate-status-node"&&c.id===e);if(n===-1)return{...t,currentGate:r};let i=t.conversation[n];if(i.kind!=="gate-status-node"||i.final)return t;let s=r.status==="PASS"||r.status==="REVISE"||r.status==="BLOCK"||r.status==="merge_gate_pending",o={...i,gate:r,final:s},a=[...t.conversation.slice(0,n),o,...t.conversation.slice(n+1)];return{...t,conversation:a,currentGate:r}}function Tl(t,e,r){let n={kind:"slash-output",id:(0,Ie.ulid)(),timestamp:new Date().toISOString(),final:!0,command:e,output:r};return We(t,n)}function Ol(t,e){if(t.pendingClarification===null)return Fn(t,e);let r=t.pendingClarification.rounds.map((i,s,o)=>s===o.length-1&&i.answer===void 0?{question:i.question,answer:e}:i);return{...Fn(t,e),pendingClarification:{...t.pendingClarification,rounds:r}}}function Dl(t,e){let r=new Map(t.runningTasks);return e.status==="completed"||e.status==="cancelled"||e.status==="failed"?r.delete(e.taskId):r.set(e.taskId,e),{...t,runningTasks:r}}function Nl(t,e){for(let r=0;r<t.conversation.length;r++){let n=t.conversation[r];if(n.kind==="gate-prompt"&&n.envelope.taskId===e&&n.final===!1)return r}return-1}function $l(t,e){let r=Nl(t,e.taskId);if(r!==-1){let i=t.conversation[r];if(i.kind!=="gate-prompt")return t;let s={...i,queue:[...i.queue,e]},o=[...t.conversation.slice(0,r),s,...t.conversation.slice(r+1)];return{...t,conversation:o}}let n={kind:"gate-prompt",id:(0,Ie.ulid)(),timestamp:e.receivedAt||new Date().toISOString(),final:!1,envelope:e,queue:[],uiState:{phase:"awaiting-number"}};return We(t,n)}function Ml(t,e,r){let n=t.conversation.findIndex(a=>a.kind==="gate-prompt"&&a.id===e);if(n===-1)return t;let i=t.conversation[n];if(i.kind!=="gate-prompt"||i.uiState.phase!=="awaiting-number")return t;let s={...i,uiState:{phase:"awaiting-notes",decisionDraft:r}},o=[...t.conversation.slice(0,n),s,...t.conversation.slice(n+1)];return{...t,conversation:o}}function Ul(t,e){let r=t.conversation.findIndex(o=>o.kind==="gate-prompt"&&o.id===e);if(r===-1)return t;let n=t.conversation[r];if(n.kind!=="gate-prompt"||n.uiState.phase!=="awaiting-number"&&n.uiState.phase!=="awaiting-notes")return t;let i={...n,uiState:{phase:"submitting"}},s=[...t.conversation.slice(0,r),i,...t.conversation.slice(r+1)];return{...t,conversation:s}}function Ll(t,e,r){let n=t.conversation.findIndex(a=>a.kind==="gate-prompt"&&a.id===e);if(n===-1)return t;let i=t.conversation[n];if(i.kind!=="gate-prompt")return t;if(i.queue.length>0){let[a,...c]=i.queue,l={...i,envelope:a,queue:c,uiState:{phase:"awaiting-number"},final:!1},d=[...t.conversation.slice(0,n),l,...t.conversation.slice(n+1)];return{...t,conversation:d}}let s={...i,uiState:{phase:"resolved",postAction:r,resolvedBy:"self"},final:!0},o=[...t.conversation.slice(0,n),s,...t.conversation.slice(n+1)];return{...t,conversation:o}}function Kl(t,e){let r=t.conversation.findIndex(o=>o.kind==="gate-prompt"&&o.id===e);if(r===-1)return t;let n=t.conversation[r];if(n.kind!=="gate-prompt"||n.uiState.phase!=="submitting")return t;let i={...n,uiState:{phase:"awaiting-number"}},s=[...t.conversation.slice(0,r),i,...t.conversation.slice(r+1)];return{...t,conversation:s}}function Bl(t,e){let r=t.conversation.findIndex(o=>o.kind==="gate-prompt"&&o.id===e);if(r===-1)return t;let n=t.conversation[r];if(n.kind!=="gate-prompt"||n.uiState.phase!=="awaiting-notes")return t;let i={...n,uiState:{phase:"awaiting-number"}},s=[...t.conversation.slice(0,r),i,...t.conversation.slice(r+1)];return{...t,conversation:s}}function Fl(t){return{...{session:t.session,plannerHealth:"Available",conversation:[],runningTasks:new Map,queuedTasks:[],activeReviewerSeats:new Map,currentGate:null,pendingClarification:null,inputHistory:[],structuralSummary:null,structuralSummaryError:null},...t.initial??{}}}function Gn(t){let e=Fl(t),r=new Set;function n(){return e}function i(o){e=Wn(e,o);for(let a of r)a(e)}function s(o){return r.add(o),()=>{r.delete(o)}}return{getState:n,dispatch:i,subscribe:s}}var H=h(require("react"));nn();var Bt="orchestration_escalated_gate",Vn="orchestration_final_approval";function io(t){if(t.type!=="INTERACTIVE_PROMPT")return null;let e=t.metadata,r=null;if(e&&typeof e=="object")r=e;else if(typeof e=="string")try{let O=JSON.parse(e);O&&typeof O=="object"&&!Array.isArray(O)&&(r=O)}catch{return null}if(!r)return null;let n=r.prompt_kind;if(n!==Bt&&n!==Vn)return null;let i=n,s=r.payload;if(!s||typeof s!="object"||Array.isArray(s))return null;let o=s,a=o.outcome;if(!a||typeof a!="object"||Array.isArray(a))return null;let c=a,l=c.taskId,d=c.gateId,p=c.round;if(typeof l!="string"||l.length===0||typeof d!="string"||d.length===0||typeof p!="number"||!Number.isFinite(p))return null;let f=i===Bt?5:2,m=o.options;if(!Array.isArray(m)||m.length!==f)return null;let S=[];for(let O of m){if(!O||typeof O!="object"||Array.isArray(O))return null;let le=O,Se=le.id,He=le.label,Vt=le.description;if(typeof Se!="string"||Se.length===0||typeof He!="string"||typeof Vt!="string")return null;S.push({id:Se,label:He,description:Vt})}let y=c.reason,g=typeof y=="string"?y:void 0,A=r.summary,b=typeof A=="string"?A:void 0,T=typeof t.timestamp=="string"?t.timestamp:"";return{promptKind:i,taskId:l,gateId:d,currentRound:p,options:S,reason:g,summary:b,receivedAt:T}}function so(t,e){if(typeof e!="number"||!Number.isInteger(e)||e<1||e>t.options.length)return null;let r=t.options[e-1];if(!r||typeof r.id!="string"||r.id.length===0)return null;let n=r.id.toLowerCase(),i=n.endsWith("_with_notes");return{kind:n,needsNotes:i}}var Ft=h(require("react"));var Wl=["#7C3AED","#A855F7","#D946EF","#F59E0B","#F97316"],Gl=[" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E "," \u2502 C o d e V i b e \u2502 "," \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F "];function Vl(){return process.env.NO_COLOR==="1"||process.env.TERM==="dumb"||process.env.CODEVIBE_NO_TUI==="1"}function oo(){let{ink:t,gradientString:e}=x(),{Box:r,Text:n}=t;if(Vl())return Ft.createElement(r,{flexDirection:"column"},Ft.createElement(n,null,"CodeVibe"));let i=e.default(Wl);return Ft.createElement(r,{flexDirection:"column"},...Gl.map((s,o)=>Ft.createElement(n,{key:o},i(s))))}var se=h(require("react"));var $r=h(require("react"));function ao(t){let{ink:e}=x(),{Box:r,Text:n}=e;return $r.createElement(r,{flexDirection:"row"},$r.createElement(n,{color:"cyan"},"> "),$r.createElement(n,null,t.entry.text))}var yt=h(require("react"));function co(t){let{ink:e}=x(),{Box:r,Text:n}=e;return yt.createElement(r,{flexDirection:"column"},yt.createElement(n,null,yt.createElement(n,{color:"magenta"},"\u25CF "),`Planner classified: ${t.entry.action}`),yt.createElement(r,{marginLeft:2},yt.createElement(n,{dimColor:!0},`rationale: ${JSON.stringify(t.entry.rationale)}`)))}var Mr=h(require("react"));function Hl(t){switch(t.kind){case"EXECUTOR_REFUSAL":return`refusal ${t.payload.refusalCategory}: ${t.payload.refusalDetail}`;case"TASK_BYPASS":return`bypass: ${t.payload.bypassReason}`;case"USER_PROMPT":case"ASSISTANT_RESPONSE":case"INTERACTIVE_PROMPT":case"NOTIFICATION":return t.kind.toLowerCase();case"PROCESS_SPAWNED":return"process spawned";case"FILE_CHANGE":return"file change";case"TOOL_USE":return"tool use";case"VERIFICATION_RUN":return"verification run";case"PROCESS_EXITED":return"process exited";default:{let e=t;return"event"}}}function lo(t){let{ink:e}=x(),{Box:r,Text:n}=e,i=Hl(t.entry.event);return Mr.createElement(r,{marginLeft:2},Mr.createElement(n,{dimColor:!0},"\u23BF "),Mr.createElement(n,null,i))}var he=h(require("react"));var zl={queued:"\u25CC",running:"\u25D0",PASS:"\u2713",REVISE:"\u270E",BLOCK:"\u2717"},jl={queued:"gray",running:"yellow",PASS:"green",REVISE:"yellow",BLOCK:"red"};function uo(t){let{ink:e}=x(),{Box:r,Text:n}=e,i=t.entry.seats.length,s=t.entry.seats.filter(o=>o.status==="PASS"||o.status==="REVISE"||o.status==="BLOCK").length;return he.createElement(r,{flexDirection:"column"},he.createElement(n,null,he.createElement(n,{color:"magenta"},"\u25CF "),`Reviewer quorum (${s}/${i} done): ${t.entry.quorumStatus}`),...t.entry.seats.map(o=>he.createElement(r,{key:o.seatId,marginLeft:2},he.createElement(n,{dimColor:!0},"\u23BF "),he.createElement(n,null,`${o.seatId} ${o.reviewerKind.padEnd(7)} `),he.createElement(n,{color:jl[o.status]},zl[o.status]),he.createElement(n,null,` ${o.status}`))))}var Ur=h(require("react"));function po(t){let{ink:e}=x(),{Box:r,Text:n}=e,i=t.entry.gate;return Ur.createElement(r,{flexDirection:"row"},Ur.createElement(n,{color:"magenta"},"\u25CF "),Ur.createElement(n,null,`Gate: ${i.gateKind} Status: ${i.status} Auto-revise: ${i.autoReviseRound}/${i.autoReviseCap}`))}var Wt=h(require("react"));function mo(t){let{ink:e}=x(),{Box:r,Text:n}=e;return Wt.createElement(r,{flexDirection:"column"},Wt.createElement(n,{color:"cyan"},t.entry.command),Wt.createElement(r,{marginLeft:2},Wt.createElement(n,null,t.entry.output)))}var Lr=h(require("react"));function fo(t){let{ink:e}=x(),{Box:r,Text:n}=e,i=t.entry.source==="planner"?"magenta":"yellow";return Lr.createElement(r,{flexDirection:"row"},Lr.createElement(n,{color:i},"\u25CF "),Lr.createElement(n,{italic:!0},t.entry.text))}var G=h(require("react"));function ql(t){if(!t)return null;switch(t){case"blocked_by_review":return"Blocked by review";case"auto_revise_cap_exhausted":return"Auto-revise cap exhausted";case"insufficient_quorum":return"Insufficient reviewer quorum";case"policy_resolution_failed":return"Policy resolution failed";case"cohort_disabled":return"Orchestration cohort disabled";default:return t}}function Jl(t){return t===Bt?"Escalated review":t===Vn?"Final approval":t}function Yl(t){switch(t.phase){case"awaiting-number":return{text:"awaiting your response",color:"cyan"};case"awaiting-notes":return{text:"Notes mode: type your notes + Enter",color:"cyan"};case"submitting":return{text:"submitting\u2026",color:"yellow"};case"resolved":return{text:`Resolved \u2014 ${t.postAction.kind}`,color:"green"};default:{let e=t;return{text:"",color:"white"}}}}function go(t){let{ink:e}=x(),{Box:r,Text:n}=e,{entry:i}=t,{envelope:s,uiState:o,queue:a}=i,l=s.promptKind===Bt?ql(s.reason):null,d=Jl(s.promptKind),p=Yl(o),f=[G.createElement(n,{key:"badge",color:"magenta",bold:!0},"[GATE] "),G.createElement(n,{key:"kind"},d)];l&&f.push(G.createElement(n,{key:"reason",color:"red"},` \u2014 ${l}`));let m=[G.createElement(r,{key:"header",flexDirection:"row"},...f)];return s.summary&&m.push(G.createElement(r,{key:"summary",marginLeft:2},G.createElement(n,{dimColor:!0,italic:!0},s.summary))),s.options.forEach((S,y)=>{let g=y+1;m.push(G.createElement(r,{key:`opt-${y}`,marginLeft:2,flexDirection:"row"},G.createElement(n,{color:"cyan",bold:!0},`${g}. `),G.createElement(n,{bold:!0},S.label),G.createElement(n,{dimColor:!0},` \u2014 ${S.description}`)))}),m.push(G.createElement(r,{key:"status",marginLeft:2,marginTop:0},G.createElement(n,{color:p.color},p.text))),a.length>0&&m.push(G.createElement(r,{key:"queue",marginLeft:2},G.createElement(n,{dimColor:!0},`(+${a.length} more queued)`))),G.createElement(r,{flexDirection:"column"},...m)}function Hn(t){switch(t.kind){case"user-message":return se.createElement(ao,{entry:t});case"planner-decision":return se.createElement(co,{entry:t});case"subagent-event":return se.createElement(lo,{entry:t});case"reviewer-status-node":return se.createElement(uo,{entry:t});case"gate-status-node":return se.createElement(po,{entry:t});case"slash-output":return se.createElement(mo,{entry:t});case"advisory":return se.createElement(fo,{entry:t});case"gate-prompt":return se.createElement(go,{entry:t});default:{let e=t;throw new Error("Unknown conversation entry kind")}}}function yo(t){let{ink:e}=x(),{Box:r}=e;return se.createElement(r,{flexDirection:"column"},...t.entries.map(n=>se.createElement(r,{key:n.id,flexDirection:"column",marginBottom:0},Hn(n))))}var ht=h(require("react"));var Xl={Available:"green",Degraded:"yellow",Outage:"red"},Ql={Available:"Available",Degraded:"Degraded",Outage:"Outage"};function ho(t){let{ink:e}=x(),{Box:r,Text:n}=e;return ht.createElement(r,{flexDirection:"row",justifyContent:"space-between"},ht.createElement(r,{flexDirection:"row"},ht.createElement(n,{color:Xl[t.plannerHealth]},"\u25CF "),ht.createElement(n,null,Ql[t.plannerHealth])),ht.createElement(n,{dimColor:!0},`${t.tier}`))}var K=h(require("react"));var zn="__GATE_PROMPT_NOTES_CANCEL__";function So(t){let{ink:e,inkTextInput:r}=x(),{Box:n,Text:i}=e,s=r.default,[o,a]=K.useState(t.initialValue??""),[c,l]=K.useState(null),d=t.gatePromptMode??null;K.useEffect(()=>{l(null),a("")},[d?.kind]);let p=K.useCallback(y=>{if(d?.kind!=="submitting"){if(d?.kind==="awaiting-number"){let g=y.trim();if(!/^[0-9]$/.test(g)){l(`Please type a number 1..${d.maxOption}`),a("");return}let b=parseInt(g,10);if(b<1||b>d.maxOption){l(`Out of range \u2014 type 1..${d.maxOption}`),a("");return}l(null),a(""),t.onSubmit(g);return}if(d?.kind==="awaiting-notes"){if(y==="/cancel"){l(null),a(""),t.onSubmit(zn);return}if(y.length===0){l("Notes cannot be empty");return}l(null),a(""),t.onSubmit(y);return}a(""),t.onSubmit(y)}},[d,t]);if(d?.kind==="submitting")return K.createElement(n,{flexDirection:"row"},K.createElement(i,{dimColor:!0},"> "),K.createElement(i,{dimColor:!0,italic:!0},"submitting\u2026"));let f=t.placeholder??"";d?.kind==="awaiting-number"?f=`Type a number 1..${d.maxOption}`:d?.kind==="awaiting-notes"&&(f="Type your notes + Enter");let m=[K.createElement(i,{key:"prompt"},"> "),K.createElement(s,{key:"input",value:o,onChange:a,onSubmit:p,placeholder:f})],S=[K.createElement(n,{key:"row",flexDirection:"row"},...m)];return c&&S.push(K.createElement(n,{key:"hint",marginLeft:2},K.createElement(i,{color:"red"},c))),K.createElement(n,{flexDirection:"column"},...S)}N();function Zl(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.kind==="gate-prompt"&&r.final===!1)return r}return null}function eu(t){if(!t)return null;switch(t.uiState.phase){case"awaiting-number":return{kind:"awaiting-number",maxOption:t.envelope.options.length};case"awaiting-notes":return{kind:"awaiting-notes",decisionDraft:t.uiState.decisionDraft};case"submitting":return{kind:"submitting"};case"resolved":return null;default:return null}}function wo(t){let{ink:e}=x(),{Box:r,Static:n}=e,[i,s]=H.useState(()=>t.store.getState());H.useEffect(()=>t.store.subscribe(s),[t.store]);let o=[{key:"__logo__",element:H.createElement(oo)},...i.conversation.filter(f=>f.final).map(f=>({key:f.id,element:Hn(f)}))],a=i.conversation.filter(f=>!f.final),c=Zl(i.conversation),l=eu(c),d=H.useCallback(f=>{if(!c){t.onUserInput(f);return}let m=c,S=m.uiState.phase;if(S==="awaiting-number"){let y=parseInt(f,10),g=so(m.envelope,y);if(!g){u.warn("[OrchestrationApp] mapTypedNumberToDecisionKind returned null",{typed:f});return}if(g.needsNotes){t.store.dispatch({type:"GATE_PROMPT_NOTES_REQUESTED",promptEntryId:m.id,decisionDraft:g.kind});return}p(m.id,{gateId:m.envelope.gateId,taskId:m.envelope.taskId,sessionId:vo(t.store),currentRound:m.envelope.currentRound,decision:g.kind});return}if(S==="awaiting-notes"){if(f===zn){t.store.dispatch({type:"GATE_PROMPT_NOTES_CANCELLED",promptEntryId:m.id});return}let y=m.uiState.decisionDraft;p(m.id,{gateId:m.envelope.gateId,taskId:m.envelope.taskId,sessionId:vo(t.store),currentRound:m.envelope.currentRound,decision:y,notes:f});return}},[c,t.onUserInput,t.store,t.appsyncClient,t.getSessionKey]),p=H.useCallback(async(f,m)=>{let S=t.appsyncClient;if(!S){u.error("[OrchestrationApp] gate-prompt submit attempted with no AppSync client",{promptEntryId:f}),t.store.dispatch({type:"GATE_PROMPT_SUBMIT_FAILED",promptEntryId:f,error:"AppSync client not configured"});return}t.store.dispatch({type:"GATE_PROMPT_SUBMIT_STARTED",promptEntryId:f});try{let y=null;if(m.notes!==void 0&&(y=await t.getSessionKey(m.sessionId),y===null)){let A="Session key unavailable \u2014 cannot encrypt notes for orchestration submission";u.warn("[OrchestrationApp] applyUserDecision aborted \u2014 no session key",{promptEntryId:f,sessionId:m.sessionId}),t.store.dispatch({type:"GATE_PROMPT_SUBMIT_FAILED",promptEntryId:f,error:A});return}let g=await S.applyUserDecision(m,y??void 0);t.store.dispatch({type:"GATE_PROMPT_RESOLVED",promptEntryId:f,postAction:g.postAction})}catch(y){let g=y?.message??String(y);u.warn("[OrchestrationApp] applyUserDecision failed",{promptEntryId:f,error:g}),t.store.dispatch({type:"GATE_PROMPT_SUBMIT_FAILED",promptEntryId:f,error:g})}},[t.appsyncClient,t.getSessionKey,t.store]);return H.createElement(r,{flexDirection:"column"},H.createElement(n,{items:o,children:f=>H.createElement(r,{key:f.key,flexDirection:"column",marginBottom:0},f.element)}),H.createElement(yo,{entries:a}),H.createElement(ho,{plannerHealth:i.plannerHealth,tier:t.tier}),H.createElement(So,{onSubmit:d,placeholder:"Type a message or /help",gatePromptMode:l}))}function vo(t){return t.getState().session.sessionId}var Eo=h(require("readline"));function tu(t){switch(t.kind){case"user-message":return`> ${t.text}`;case"planner-decision":return`[planner] ${t.action}: ${t.rationale}`;case"subagent-event":return` \u23BF [${t.role}] ${t.event.kind}`;case"reviewer-status-node":{let e=t.seats.map(r=>`${r.seatId} ${r.reviewerKind} ${r.status}`).join(", ");return`[quorum ${t.quorumStatus}] ${e}`}case"gate-status-node":return`[gate ${t.gate.gateKind}] ${t.gate.status} (rev ${t.gate.autoReviseRound}/${t.gate.autoReviseCap})`;case"slash-output":return`${t.command}
459
+ ${t.output.replace(/\n/g,`
460
+ `)}`;case"advisory":return`[${t.source}] ${t.text}`;case"gate-prompt":{let e=[],r=t.envelope.reason?` (${t.envelope.reason})`:"";e.push(`[gate-prompt ${t.envelope.promptKind}${r}] ${t.envelope.summary??""}`);for(let n=0;n<t.envelope.options.length;n++){let i=t.envelope.options[n];e.push(` ${n+1}. ${i.label} \u2014 ${i.description}`)}switch(t.uiState.phase){case"awaiting-number":e.push(` (type 1-${t.envelope.options.length} to choose)`);break;case"awaiting-notes":e.push(` (enter notes for "${t.uiState.decisionDraft}")`);break;case"submitting":e.push(" (submitting\u2026)");break;case"resolved":e.push(` (resolved: ${t.uiState.postAction.kind})`);break}return e.join(`
461
+ `)}default:{let e=t;return""}}}async function ko(t){let e=t.output??process.stdout,r=t.input??process.stdin,n=0,i=t.store.subscribe(a=>{let c=a.conversation.slice(n);n=a.conversation.length;for(let l of c)e.write(tu(l)+`
462
+ `)}),s=Eo.createInterface({input:r,output:e,terminal:!1}),o=null;t.signal&&(t.signal.aborted?s.close():(o=()=>{try{s.close()}catch{}},t.signal.addEventListener("abort",o,{once:!0})));try{e.write(`CodeVibe (orchestration mode, non-TTY fallback)
463
+ `);for await(let a of s){if(t.signal?.aborted)break;let c=a.trimEnd();if(c.length===0)continue;t.onUserInput?await t.onUserInput(c):t.store.dispatch({type:"USER_INPUT",text:c});let l=t.store.getState(),d=l.conversation[l.conversation.length-1];if(d&&d.kind==="slash-output"&&d.command==="/quit")break}}finally{if(t.signal&&o)try{t.signal.removeEventListener("abort",o)}catch{}s.close(),i()}}var bo=h(require("path"));function z(t,e,r){return{command:t,output:e,sideEffect:r}}var Ro=[{name:"/status",blurb:"Show current task state, running implementor, gates pending.",handler:()=>z("/status","No tasks running. Mode: orchestration.")},{name:"/audit",blurb:"Display audit timeline (last 50 events, paginated).",handler:()=>z("/audit","Audit timeline \u2014 coming online with CP-1.c.")},{name:"/continue",blurb:"Continuation handoff (CP-6).",handler:()=>z("/continue","Continuation handoff ships in CP-6 \u2014 coming soon.")},{name:"/reviewers",blurb:"Display current reviewer-quorum config (read-only).",handler:()=>z("/reviewers","Reviewer-quorum read \u2014 coming online with CP-1.b/c.")},{name:"/reviewer-setup",blurb:"Configure reviewer quorum (CP-3).",handler:()=>z("/reviewer-setup","Reviewer-quorum setup launches in CP-3.")},{name:"/help",blurb:"Show this help text.",handler:()=>{let t=["Available commands:"];for(let e of Ro)t.push(` ${e.name.padEnd(22)} ${e.blurb}`);return t.push(` ${"/attach <task-id>".padEnd(22)} (DEFERRED to CP-1.1)`),t.push(` ${"/task <request>".padEnd(22)} (Pro/Max only; deterministic shortcut)`),t.push(` ${"/quit".padEnd(22)} Exit shell.`),z("/help",t.join(`
464
+ `))}},{name:"/cache-clear",blurb:"Flush planner cache for current user.",handler:()=>z("/cache-clear","Planner cache cleared.")},{name:"/structural-summary",blurb:"Display / regenerate the structural summary.",handler:t=>{if(t.includes("--regenerate"))return{command:"/structural-summary",output:"Regenerating structural summary...",sideEffect:{kind:"REGENERATE_STRUCTURAL_SUMMARY"}};if(t.includes("--include-bodies")){let e=t.indexOf("--include-bodies")+1,r=t[e];return r?bo.isAbsolute(r)?{command:"/structural-summary",output:`Opting into body inclusion for ${r}...`,sideEffect:{kind:"OPT_IN_BODY_PATH",path:r}}:z("/structural-summary",`Path must be absolute (got: ${r}). Example: /structural-summary --include-bodies /Users/me/Workspace/myrepo/src`):z("/structural-summary","Usage: /structural-summary --include-bodies <absolute-path>")}return z("/structural-summary","PENDING \u2014 entrypoint pulls from store.structuralSummary")}},{name:"/task",blurb:"Deterministic shortcut for command-shaped requests (Pro/Max only).",handler:t=>t.length===0?z("/task","Usage: /task <implementation-request>. Pro/Max only; runs without planner classification."):z("/task","/task deterministic-shortcut \u2014 implementor spawn lands with CP-1.c.")},{name:"/quit",blurb:"Exit CodeVibe shell.",handler:()=>z("/quit","Exiting CodeVibe.",{kind:"EXIT"})}];function jn(t){let e=t.trim();if(!e.startsWith("/"))throw new Error(`routeSlashCommand called with non-slash input: ${t}`);let[r,...n]=e.split(/\s+/);if(r==="/attach")return z(r,"Unknown command. /attach ships in CP-1.1 \u2014 see /help for the current catalog.");let i=Ro.find(s=>s.name===r);return i?i.handler(n):z(r,`Unknown command: ${r}. Type /help for available commands.`)}function qn(t){return{storeAction:{type:"SLASH_OUTPUT",command:t.command,output:t.output},exit:t.sideEffect?.kind==="EXIT"}}Te();re();N();var Ao=h(require("fs/promises")),_o=h(require("path")),xo=h(require("os"));N();function ru(){return(process.env.VITEST==="true"||process.env.NODE_ENV==="test")&&process.env.CODEVIBE_HOME_OVERRIDE?process.env.CODEVIBE_HOME_OVERRIDE:xo.homedir()}function Io(){return _o.join(ru(),".codevibe","cohort-flags.json")}async function Jn(t,e){let r=Io();try{let n=await Ao.readFile(r,"utf8"),s=JSON.parse(n)[t];return typeof s!="boolean"?!1:s}catch(n){return n?.code==="ENOENT"?!1:n instanceof SyntaxError?(u.debug(`[cohort-flag] Malformed cohort-flags.json \u2014 treating ${t} as false`,{filePath:r}),!1):(u.debug(`[cohort-flag] Read error \u2014 treating ${t} as false`,{filePath:r,error:n?.message}),!1)}}var nu="new-event-types-enabled";async function Kr(t,e){if(!await e.getCohortFlag(nu,t.sessionId)){u.debug(`[emit-shell-event] Skipping ${t.type} emit \u2014 new-event-types-enabled cohort flag off`,{sessionId:t.sessionId,type:t.type});return}if(t.sessionId.startsWith("cp1a-local-")){u.warn(`[emit-shell-event] Refusing ${t.type} emit \u2014 CP-1.a stub sessionId in play AND cohort flag on. CP-1.b replaces buildStubSession() with resumeOrCreateSession(); ignore until then.`,{sessionId:t.sessionId,type:t.type});return}let n=await e.getSessionKey(t.sessionId);if(!n){u.warn("[emit-shell-event] Refusing to emit \u2014 no session key found (fail-closed per \xA73 LOCK + Stage 2 r1 HIGH-2)",{sessionId:t.sessionId,type:t.type});return}let i,s;t.content&&(i=$.encryptContent(t.content,n)),t.metadata&&(s={encrypted:$.encryptMetadata(t.metadata,n)});let o={sessionId:t.sessionId,type:t.type,source:t.source,content:i??"",isEncrypted:t.isEncrypted};s!==void 0&&(o.metadata=s),t.timestamp&&(o.timestamp=t.timestamp),await e.appsyncClient.createEvent(o),u.debug("[emit-shell-event] Emitted",{sessionId:t.sessionId,type:t.type,isEncrypted:!0})}function Gt(t){return e=>Kr(e,{appsyncClient:t,getSessionKey:r=>k.getSessionKey(r),getCohortFlag:Jn})}function Ge(){return{CODEVIBE_CHILD_PROCESS:"1",CODEVIBE_PROCESS_ROLE:"implementor",QUORUM_REVIEWER_SUBPROCESS:"1"}}function Yn(t,e){return{...t,CODEVIBE_PROCESS_ROLE:e}}var ce=h(require("fs/promises")),Br=h(require("path")),Po=h(require("os")),ae=require("zod");N();function iu(){return(process.env.VITEST==="true"||process.env.NODE_ENV==="test")&&process.env.CODEVIBE_HOME_OVERRIDE?process.env.CODEVIBE_HOME_OVERRIDE:Po.homedir()}function Xn(){return Br.join(iu(),".codevibe","last-mode.json")}var su=ae.z.object({schemaVersion:ae.z.literal(1),mode:ae.z.union([ae.z.literal("companion"),ae.z.literal("orchestration")]),pickedAt:ae.z.string(),pickedByTier:ae.z.union([ae.z.literal("PRO"),ae.z.literal("MAX")])});async function Qn(t){let e=Xn(),r;try{r=await ce.stat(e)}catch(a){return a?.code!=="ENOENT"&&u.debug("[sticky-preference] stat error \u2014 treating as missing",{filePath:e,error:a?.message}),null}if((r.mode&63)!==0)return process.stderr.write(`last-mode.json has loose permissions; ignoring
465
+ `),null;let n;try{n=await ce.readFile(e,"utf8")}catch(a){return u.debug("[sticky-preference] Read error \u2014 falling back to prompt",{filePath:e,error:a?.message}),null}let i;try{i=JSON.parse(n)}catch(a){return u.debug("[sticky-preference] Malformed JSON \u2014 falling back to prompt",{filePath:e,error:a?.message}),null}let s=su.safeParse(i);if(!s.success)return u.debug("[sticky-preference] Schema mismatch \u2014 falling back to prompt",{filePath:e,issues:s.error.issues}),null;let o=s.data;return t==="FREE"?(u.debug("[sticky-preference] Tier downgrade to FREE invalidates sticky \u2014 falling back to prompt",{filePath:e,pickedByTier:o.pickedByTier}),null):o.mode}async function Zn(t){let e=Xn(),r=Br.dirname(e);await ce.mkdir(r,{recursive:!0});let n={schemaVersion:1,mode:t.mode,pickedAt:new Date().toISOString(),pickedByTier:t.pickedByTier};await ce.writeFile(e,JSON.stringify(n,null,2),{encoding:"utf8",mode:384});try{await ce.chmod(e,384)}catch{}u.debug("[sticky-preference] Wrote",{filePath:e,mode:t.mode})}var St=class extends Error{constructor(e){super(e),this.name="TierError"}};async function ei(t,e,r=ou()){if(t.mode==="orchestration"&&e==="FREE")throw new St("Orchestration Mode requires Pro or Max \u2014 upgrade at quantiya.ai/codevibe/pricing");if(t.mode)return t.mode;if(e==="FREE")return"companion";let n=await r.readStickyPreference(e);if(n)return n;let i=await r.promptUserForMode(e);return await r.writeStickyPreference({mode:i,pickedByTier:e}),i}function ou(){return{readStickyPreference:t=>Qn(t),writeStickyPreference:Zn,promptUserForMode:au}}async function au(t){let r=require("readline").createInterface({input:process.stdin,output:process.stdout});try{for(process.stdout.write(`
466
+ CodeVibe \u2014 choose mode (${t} tier):
467
+ `),process.stdout.write(` [1] Companion (route to local agent wrapper)
468
+ `),process.stdout.write(` [2] Orchestration (CodeVibe-owned shell)
469
+ `);;){let i=(await new Promise(s=>{r.question("Mode [1/2]: ",s)})).trim();if(i==="1"||i.toLowerCase()==="companion")return"companion";if(i==="2"||i.toLowerCase()==="orchestration")return"orchestration";process.stdout.write(`Please type 1 or 2.
470
+ `)}}finally{r.close()}}async function Do(t){let e=Gn({session:t.session}),r=Gt(t.appsyncClient);t.plannerAdapter&&t.plannerAdapter.setActiveSession(t.session.sessionId);let n=Or();await No({store:e,args:t,emitShellEventBound:r,generator:n}),await r({sessionId:t.session.sessionId,type:"MODE_SELECTED",source:"DESKTOP",isEncrypted:!0,metadata:{mode:"orchestration"}}).catch(f=>{u.warn("[orchestration-shell] emit MODE_SELECTED failed (non-fatal)",{error:f.message})}),Ge();let i=null;if(!t.session.sessionId.startsWith("cp1a-local-"))try{i=t.appsyncClient.subscribeToEvents(t.session.sessionId,f=>{cu(f,e)},f=>{u.warn("[orchestration-shell] subscribeToEvents error (non-fatal)",{error:f.message})})}catch(f){u.warn("[orchestration-shell] subscribeToEvents startup failed (non-fatal)",{error:f.message})}let s=async f=>{await lu({text:f,store:e,args:t,emitShellEventBound:r,generator:n})},o=!1,a=async()=>{if(!o){o=!0;try{t.plannerCache&&await t.plannerCache.flush()}catch(f){u.warn("[orchestration-shell] planner cache flush on teardown failed",{error:f.message})}try{t.plannerAdapter&&t.plannerAdapter.setActiveSession(null)}catch{}}},c=null,l=null,d=new Set,p=f=>{a().catch(()=>{}).finally(()=>{u.info(`[orchestration-shell] caught ${f}, planner teardown complete`);try{c&&(c(),c=null)}catch{}try{l&&(l.abort(),l=null)}catch{}try{process.removeListener(f,p),d.delete(f)}catch{}try{process.kill(process.pid,f)}catch{let m=f==="SIGTERM"?143:130;process.exit(m)}})};process.once("SIGINT",p),d.add("SIGINT"),process.once("SIGTERM",p),d.add("SIGTERM");try{if(!process.stdout.isTTY||process.env.CODEVIBE_NO_TUI==="1"){l=new AbortController;try{await ko({store:e,onUserInput:s,signal:l.signal})}finally{l=null}return}await ro();let{ink:f}=x(),{waitUntilExit:m,unmount:S}=f.render(Co.createElement(wo,{store:e,tier:t.tier,onUserInput:s,appsyncClient:t.appsyncClient,getSessionKey:g=>k.getSessionKey(g)}));c=S;let y=e.subscribe(g=>{let A=g.conversation[g.conversation.length-1];A&&A.kind==="slash-output"&&A.command==="/quit"&&a().finally(()=>{try{c&&(c(),c=null)}catch{}})});try{await m()}finally{y(),c=null}}finally{try{i&&(i(),i=null)}catch{}for(let f of d)process.removeListener(f,p);d.clear(),await a()}}function cu(t,e){if(t.type!=="INTERACTIVE_PROMPT")return;let r=null;if(t.metadata&&typeof t.metadata=="object")r=t.metadata;else if(typeof t.metadata=="string")try{let l=JSON.parse(t.metadata);l&&typeof l=="object"&&!Array.isArray(l)&&(r=l)}catch{return}if(!r)return;let n=r.prompt_kind;if(n!=="orchestration_escalated_gate"&&n!=="orchestration_final_approval")return;let i=io(t);if(i){e.dispatch({type:"GATE_PROMPT_RECEIVED",envelope:i});return}let s=n==="orchestration_escalated_gate"?5:2,o=r.payload,a=o&&typeof o=="object"&&o!==null?o.options:void 0,c=Array.isArray(a)?a.length:0;u.error("[orchestration-shell] malformed gate prompt \u2014 extractor returned null",{eventId:t.eventId,promptKind:n,expected:s,actual:c}),e.dispatch({type:"SHELL_ADVISORY",source:"shell",text:`Orchestration prompt malformed (expected ${s} options, got ${c}). The gate is still active in the engine \u2014 resolve it from another device or restart this orchestration session.`})}async function lu(t){let{text:e,store:r,args:n,emitShellEventBound:i,generator:s,addBodyPathFn:o=Dr,regenerateStructuralSummaryFn:a=uu,classifyFn:c}=t;if(e.startsWith("/")){let y=jn(e);if(y.sideEffect?.kind==="REGENERATE_STRUCTURAL_SUMMARY")try{a({store:r,args:n,emitShellEventBound:i,generator:s})}catch(A){u.warn("[orchestration-shell] regenerate dispatch failed",{error:A.message}),r.dispatch({type:"STRUCTURAL_SUMMARY_FAILED",error:A.message})}else if(y.sideEffect?.kind==="OPT_IN_BODY_PATH"){let A=y.sideEffect.path;try{await o(A,n.tier)}catch(b){let T=b instanceof C?b.message:`Failed to persist opt-in for ${A}: ${b.message}`;y.output=T,u.warn("[orchestration-shell] OPT_IN_BODY_PATH side-effect failed",{path:A,error:T})}}else y.command==="/structural-summary"&&!y.sideEffect&&y.output==="PENDING \u2014 entrypoint pulls from store.structuralSummary"&&(y.output=du(r.getState().structuralSummary,r.getState().structuralSummaryError,n.tier));let g=qn(y);if(r.dispatch(g.storeAction),g.exit){r.dispatch({type:"EXIT"});return}await i({sessionId:n.session.sessionId,type:"SLASH_COMMAND_INVOKED",source:"DESKTOP",isEncrypted:!0,metadata:{command:y.command}}).catch(()=>{});return}r.dispatch({type:"USER_INPUT",text:e});let l=n.plannerAdapter?n.plannerAdapter.classify.bind(n.plannerAdapter):void 0,d=c??l;if(!d)return;let p=r.getState(),f=p.pendingClarification?.rounds?.filter(y=>typeof y.answer=="string").map(y=>({question:y.question,answer:y.answer}))??[],m={prompt:p.pendingClarification?.originalPrompt??e,clarifications:f,sessionContext:{sessionId:n.session.sessionId,userId:n.session.userId,tier:n.tier,currentTaskState:"none",structuralSummaryDigest:p.structuralSummary?.sha256??"",recentEventCount:p.conversation.length},budgetHint:{wallClockMsRemaining:3e4,reviseAttempts:0}},S;try{S=await d(m)}catch(y){let g=y?.message??String(y),A=y?.name??"Error";u.warn("[orchestration-shell] planner classify failed",{error:g,name:A}),r.dispatch({type:"SLASH_OUTPUT",command:"planner-error",output:`Planner unavailable: ${g}`});return}r.dispatch({type:"PLANNER_DECISION",decision:S})}async function No(t){let{store:e,args:r,emitShellEventBound:n,generator:i}=t,s=Date.now();try{let o=await Lt(r.tier),a=await i.generate({rootPaths:[process.cwd()],ignoreFile:To.join(Oo.homedir(),".codevibe","structural-summary.ignore"),includeBodies:o?.bodyInclusionPaths??[],userId:r.session.userId,tier:r.tier}),c=Date.now()-s;if(e.dispatch({type:"STRUCTURAL_SUMMARY_GENERATED",summary:a,elapsedMs:c}),await n({sessionId:r.session.sessionId,type:"STRUCTURAL_SUMMARY_GENERATED",source:"DESKTOP",isEncrypted:!0,metadata:{repoCount:a.repos.length,totalFileCount:a.totalFileCount,totalBytes:a.totalBytes,sha256:a.sha256}}).catch(l=>{u.warn("[orchestration-shell] emit STRUCTURAL_SUMMARY_GENERATED failed (non-fatal)",{error:l.message})}),c>2e3&&(n({sessionId:r.session.sessionId,type:"NOTIFICATION",source:"DESKTOP",isEncrypted:!0,metadata:{event:"structural_summary_slow",elapsedMs:Math.round(c)}}).catch(()=>{}),u.warn("[orchestration-shell] structural summary slow",{elapsedMs:Math.round(c)})),a.privacyEnvelope.budgetExceeded){let l=a.privacyEnvelope.budgetReason??"fileCount";n({sessionId:r.session.sessionId,type:"NOTIFICATION",source:"DESKTOP",isEncrypted:!0,metadata:{event:"structural_summary_truncated",reason:l}}).catch(()=>{}),u.warn("[orchestration-shell] structural summary truncated",{reason:l})}}catch(o){u.warn("[orchestration-shell] Structural summary generation failed; planner context will be empty",{error:o.message}),e.dispatch({type:"STRUCTURAL_SUMMARY_FAILED",error:o.message})}}async function uu(t){try{await No(t)}catch(e){u.warn("[orchestration-shell] regenerate inner-handler caught",{error:e.message}),t.store.dispatch({type:"STRUCTURAL_SUMMARY_FAILED",error:e.message})}}function du(t,e,r){if(e)return`Structural summary failed: ${e}`;if(!t)return"Structural summary not yet generated. Try /structural-summary --regenerate.";let n=t.privacyEnvelope.bodyInclusionPaths,i=[`Structural summary (tier: ${r}):`,` Repos: ${t.repos.length}`,` Total files: ${t.totalFileCount}`,` Total bytes: ${t.totalBytes}`,` sha256: ${t.sha256.slice(0,16)}...`];return n.length>0?i.push(` Body opt-in paths (Max): ${n.join(", ")}`):i.push(" Body opt-in paths: (none)"),i.join(`
471
+ `)}var Wo=require("child_process"),Go=require("child_process"),Vo=h(require("path")),Ho=h(require("fs/promises")),zo=h(require("os"));N();_t();function $o(t){if(t.flag){let r=t.healthy.find(n=>n.kind===t.flag);return r?{agent:r}:{flagMissing:{requested:t.flag}}}if(t.healthy.length===1)return{agent:t.healthy[0]};let e=t.preferred?Math.max(0,t.healthy.findIndex(r=>r.kind===t.preferred)):0;return{needsPicker:{healthy:t.healthy,defaultIndex:e}}}var te=h(require("fs/promises")),Fr=h(require("path")),Mo=h(require("os")),Ve=require("zod");N();function pu(){return(process.env.VITEST==="true"||process.env.NODE_ENV==="test")&&process.env.CODEVIBE_HOME_OVERRIDE?process.env.CODEVIBE_HOME_OVERRIDE:Mo.homedir()}function ti(){return Fr.join(pu(),".codevibe","companion-preference.json")}var mu=Ve.z.object({lastAgent:Ve.z.union([Ve.z.literal("CLAUDE"),Ve.z.literal("GEMINI"),Ve.z.literal("CODEX")]),lastUsedAt:Ve.z.string()});async function Uo(){let t=ti(),e,r;try{r=await te.stat(t)}catch(s){return s?.code!=="ENOENT"&&u.debug("[companion-preference] stat error \u2014 treating as missing",{filePath:t,error:s?.message}),null}if((r.mode&63)!==0)return process.stderr.write(`companion-preference.json has loose permissions; ignoring
472
+ `),null;try{e=await te.readFile(t,"utf8")}catch(s){return u.debug("[companion-preference] read error \u2014 treating as missing",{filePath:t,error:s?.message}),null}let n;try{n=JSON.parse(e)}catch{return null}let i=mu.safeParse(n);return i.success?i.data:null}async function Lo(t){let e=ti(),r=Fr.dirname(e);await te.mkdir(r,{recursive:!0}),await te.writeFile(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384});try{await te.chmod(e,384)}catch{}}async function Ko(){let t=ti();try{await te.unlink(t)}catch(e){e?.code!=="ENOENT"&&u.debug("[companion-preference] unlink error",{filePath:t,error:e?.message})}}var Bo=h(require("readline"));async function Fo(t){let e=t.output??process.stdout,r=t.input??process.stdin,n=Bo.createInterface({input:r,output:e});try{for(e.write(`
473
+ CodeVibe \u2014 choose an agent:
474
+ `),t.healthy.forEach((i,s)=>{let o=s===t.defaultIndex?"*":" ";e.write(` ${o} [${s+1}] ${i.kind.padEnd(8)} ${i.binPath}
475
+ `)});;){let s=(await new Promise(a=>{n.question(`Agent [1-${t.healthy.length}] (default ${t.defaultIndex+1}): `,a)})).trim();if(s==="")return t.healthy[t.defaultIndex];let o=Number.parseInt(s,10);if(Number.isInteger(o)&&o>=1&&o<=t.healthy.length)return t.healthy[o-1];e.write(`Please type a number between 1 and ${t.healthy.length}.
476
+ `)}}finally{n.close()}}var Wr=class extends Error{constructor(e){super(e),this.name="NoAgentInstalledError"}},fu={CLAUDE:"codevibe-claude",GEMINI:"codevibe-gemini",CODEX:"codevibe-codex"};function gu(t){try{return(0,Go.execSync)(`command -v ${fu[t]}`,{stdio:["ignore","pipe","ignore"],shell:"/bin/sh"}).toString("utf8").trim()||null}catch{return null}}async function yu(t,e,r=hu){let n=Vo.join(zo.homedir(),`.codevibe-${t.toLowerCase()}`);try{if(!(await Ho.stat(n)).isDirectory())return!1}catch{return!1}return await r(e)}async function hu(t){let{spawn:e}=await import("node:child_process");return new Promise(r=>{let n=!1,i=a=>{n||(n=!0,r(a))},s;try{s=e(t,["--version"],{stdio:["ignore","ignore","ignore"]})}catch{i(!1);return}let o=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}i(!1)},2e3);s.once("exit",a=>{clearTimeout(o),i(a===0)}),s.once("error",()=>{clearTimeout(o),i(!1)})})}async function jo(t){t.forgetAgent&&await Ko();let e=t.detect??Z,r=t.resolveBinPath??gu,n=e(),i=[];for(let p of n){let f=r(p);if(!f)continue;let m=await yu(p,f,t.versionProbe);i.push({kind:p,binPath:f,healthy:m})}let s=i.filter(p=>p.healthy);if(s.length===0)throw new Wr("No CodeVibe-aware agent wrapper found. Install at quantiya.ai/codevibe.");let o=await Uo(),a=$o({healthy:s,flag:t.agent,preferred:o?.lastAgent});if(a.flagMissing)throw new Wr(`Agent ${a.flagMissing.requested} not found among CodeVibe-aware wrappers.`);let c;if(a.agent)c=a.agent;else if(a.needsPicker)c=await Fo({healthy:a.needsPicker.healthy,defaultIndex:a.needsPicker.defaultIndex});else throw new Error("Internal error: resolveAgent returned neither agent nor picker");if(await Lo({lastAgent:c.kind,lastUsedAt:new Date().toISOString()}).catch(p=>{u.warn("[companion-mode] persistCompanionPreference failed (non-fatal)",{error:p.message})}),t.emitter&&t.session)try{await t.emitter({sessionId:t.session.sessionId,type:"MODE_SELECTED",source:"DESKTOP",isEncrypted:!0,metadata:{mode:"companion",agent:c.kind}})}catch(p){u.warn("[companion-mode] MODE_SELECTED emit failed (non-fatal)",{error:p.message})}let l=Ge();for(let[p,f]of Object.entries(l))process.env[p]=f;(t.execFile??Wo.execFileSync)(c.binPath,t.passthrough,{stdio:"inherit"})}0&&(module.exports={AgentType,AppSyncClient,AppSyncGraphQLError,AuditKeys,AuthService,CryptoError,CryptoService,DeliveryStatus,ENCRYPTION_VERSION,EventSource,EventType,KeychainError,KeychainManager,Logger,Planner,Reviewer,ReviewerRole,SessionStatus,StructuralSummary,TierError,V1_ORCHESTRATION_OPTIONS,V1_ORCHESTRATION_PROMPT_KIND,applyPerSessionOrchestrationOverride,authService,createLogger,createShellEventEmitter,cryptoService,detectInstalledAgents,emitShellEvent,errorWasBeaconed,fireAuthCompletedBeacon,fireAuthFailedBeacon,getConfig,getEnvironment,getErrorReason,keychainManager,loadConfig,logger,mapOptionNumberToUserDecisionKind,mapOptionToUserDecisionKind,markErrorBeaconed,mutations,normalizeSnapshot,parseInteractivePrompt,pickMode,prepareSessionEncryption,processMarkers,pushDetectedAgents,queries,registerDeviceEncryptionKey,rekeySessionForNewDevices,resumeOrCreateSession,runAuthCli,runCompanionMode,runOrchestrationCli,runOrchestrationShell,startDeviceKeyWatcher,subscriptions,withRoleMarker});