@quantiya/codevibe-claude-plugin 2.0.70 → 2.0.71

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.
@@ -12,7 +12,7 @@ ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,Y3)}`:s+=` ${n}`),s}log
12
12
  (keytar load error: ${tombstoneKeytarError})`:"")),w.warn("[keychain-backend] migrated-to-keyring tombstone but keyring unreachable \u2014 failing closed");return}let optedIn=process.env.CODEVIBE_ALLOW_FILE_KEYCHAIN==="1";if(optedIn){c$(["","\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).",""]),w.warn("[keychain-backend] Using file-based storage at ~/.codevibe (CODEVIBE_ALLOW_FILE_KEYCHAIN=1 explicit opt-in)"),g_();return}if(hQ()){mQ();return}let keytarLoadError=null;try{let nodeRequire=eval("require");Vn=nodeRequire("keytar")}catch(t){keytarLoadError=t instanceof Error?t.message:String(t),Vn=null}if(Vn){if(ag()){Vn=null,s$("no_keyring_service");return}Yo="keytar",w.info("[keychain-backend] Using keytar (OS-native keyring)"),Iv();return}if(ag()){s$("keytar_load_failed");return}if(keytarLoadError&&n$(keytarLoadError)){Is=new zn(o$(keytarLoadError,i$()));return}Is=new zn(["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(`
13
13
  `))}function cg(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_")}function Av(t){try{return Gt.statSync(t),"present"}catch(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"?"absent":"error"}}function yQ(t){return Jn.join(m_,`${cg(t)}.json`)}async function bp(t,e){let r=Ti({lockDir:vc(`keychain-file-${cg(t)}`)}),n;try{n=await r.acquire()}catch(i){throw new zn(`Could not acquire the CodeVibe credential file-store lock (another codevibe process may be mutating credentials, or a migration is in progress). Re-run when the machine is idle. (${i.name||"error"})`)}try{return await e()}finally{try{await n.release()}catch{}}}function d$(t){let e=null;try{e=Gt.openSync(t,"r"),Gt.fsyncSync(e)}catch{}finally{if(e!==null)try{Gt.closeSync(e)}catch{}}}function u$(t,e,r){let n=`${t}.tmp-${process.pid}`;Gt.writeFileSync(n,e,{mode:r});try{let i=Gt.openSync(n,"r");try{Gt.fsyncSync(i)}finally{Gt.closeSync(i)}}catch(i){try{Gt.unlinkSync(n)}catch{}throw i}Gt.renameSync(n,t);try{Gt.chmodSync(t,r)}catch{}d$(Jn.dirname(t))}function p$(t,e){u$(yQ(t),JSON.stringify(e,null,2),384)}function lg(){if(gQ(),Yo===null)throw Is??new zn("Keychain backend not initialized")}function Sp(){return lg(),Yo}async function y_(t,e){if(lg(),Yo==="keytar"&&Vn)return Vn.getPassword(t,e);let r=Rp(t);if(r.kind==="unreadable")throw new zn(`Cannot read the file-backed credential store (${r.error}); refusing to report it as empty (that could fork a new device identity). Retry when the file is readable.`);return(r.kind==="store"?r.data:{})[e]??null}async function vp(t,e){return y_(t,e)}function h$(t,e){let r=Ip(t);if(r==="present")throw new zn(e);if(r==="error")throw new zn("CodeVibe could not verify whether this machine has migrated its credentials to the OS keyring (the migration tombstone could not be read). Refusing to write to the file backend, which could fork the device identity. Fix the ~/.codevibe permissions and retry.")}function f$(t){let e=Rp(t);if(e.kind==="unreadable")throw new zn(`Cannot read the file-backed credential store (${e.error}); refusing to write, which would drop the other stored credentials. Retry when the file is readable.`);return e.kind==="store"?e.data:{}}async function w_(t,e,r){if(lg(),Yo==="keytar"&&Vn){await Vn.setPassword(t,e,r);return}h$(t,"This machine migrated its CodeVibe credentials to the OS keyring; the file backend is retired. Restart codevibe so new credentials go to the keyring.");let n=f$(t);n[e]=r,p$(t,n)}async function kp(t,e,r){if(lg(),Yo==="keytar"&&Vn){await Vn.setPassword(t,e,r);return}await bp(t,()=>w_(t,e,r))}async function Ep(t,e){return lg(),Yo==="keytar"&&Vn?Vn.deletePassword(t,e):bp(t,()=>{h$(t,"This machine migrated its CodeVibe credentials to the OS keyring; the file backend is retired. Restart codevibe so credentials are cleared from the keyring.");let r=f$(t);return e in r?(delete r[e],p$(t,r),!0):!1})}function m$(t){return Jn.join(Ec.homedir(),".codevibe",`${cg(t)}.json`)}function Rp(t){let e=m$(t);try{Gt.statSync(e)}catch(i){let o=i.code;return o==="ENOENT"||o==="ENOTDIR"?{kind:"absent"}:{kind:"unreadable",error:o||i.name||"error"}}let r;try{r=Gt.readFileSync(e,"utf-8")}catch(i){return{kind:"unreadable",error:i.code||i.name||"error"}}let n;try{n=JSON.parse(r)}catch{return{kind:"corrupt",raw:r}}return n&&typeof n=="object"&&!Array.isArray(n)?{kind:"store",data:n,raw:r}:{kind:"corrupt",raw:r}}function g$(t){let e=m$(t),r=new Date().toISOString().replace(/[:.]/g,"-"),n=`${e}.migrated-backup-${r}`;try{Gt.renameSync(e,n)}catch(i){let o=i.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw i}try{Gt.chmodSync(n,384)}catch{}return d$(Jn.dirname(e)),n}function Tv(){try{let nodeRequire=eval("require");return nodeRequire("keytar")}catch{return null}}function b_(t){return Jn.join(Ec.homedir(),".codevibe",`.migrated-to-keyring-${cg(t)}`)}function Hbe(t){return Av(b_(t))==="present"}function Ip(t){return Av(b_(t))}function y$(t){let e=Jn.join(Ec.homedir(),".codevibe");Gt.mkdirSync(e,{recursive:!0,mode:448}),u$(b_(t),`migrated ${new Date().toISOString()}
14
14
  `,384)}var Ec,Jn,Gt,zn,Yo,Vn,m_,Is,a$,Ap=D(()=>{"use strict";Ec=F(require("os")),Jn=F(require("path")),Gt=F(require("fs"));Ye();zl();Rs();kc();zn=class extends Error{constructor(e){super(e),this.name="KeychainBackendUnavailableError"}},Yo=null,Vn=null,m_="",Is=null,a$=!1});function dg(t){if(t.length===0||t.length>32)throw new As(`P-256 private key scalar must contain 1 to 32 bytes, got ${t.length}`);if(t.length===32)return Buffer.from(t);let e=Buffer.alloc(32);return t.copy(e,32-t.length),e}var Io,As,Pp,wQ,Tp,Xe,_p=D(()=>{"use strict";Io=F(require("crypto")),As=class extends Error{constructor(e){super(e),this.name="CryptoError"}},Pp=1,wQ="CodeVibe E2E v1";Tp=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}generateKeyPair(){let e=Io.createECDH("prime256v1");e.generateKeys();let n=e.getPublicKey().subarray(1).toString("base64");return{privateKey:dg(e.getPrivateKey()).toString("base64"),publicKey:n}}generateSessionKey(){return Io.randomBytes(32).toString("base64")}deriveSharedKey(e,r){try{let n=Io.createECDH("prime256v1"),i=Buffer.from(e,"base64");n.setPrivateKey(i);let o=Buffer.from(r,"base64"),s=o.length===65&&o[0]===4?o:Buffer.concat([Buffer.from([4]),o]),a=n.computeSecret(s),c=Io.hkdfSync("sha256",a,Buffer.alloc(0),Buffer.from(wQ,"utf8"),32);return Buffer.from(c)}catch(n){throw new As(`Failed to derive shared key: ${n}`)}}encryptSessionKey(e,r){let n=this.generateKeyPair(),i=this.deriveSharedKey(n.privateKey,r),o=Buffer.from(e,"base64");return{encryptedKey:this.encrypt(o,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=Io.randomBytes(12),i=Io.createCipheriv("aes-256-gcm",r,n),o=Buffer.concat([i.update(e),i.final()]),s=i.getAuthTag();return Buffer.concat([n,o,s])}decrypt(e,r){let n=e.subarray(0,12),i=e.subarray(e.length-16),o=e.subarray(12,e.length-16),s=Io.createDecipheriv("aes-256-gcm",r,n);s.setAuthTag(i);try{return Buffer.concat([s.update(o),s.final()])}catch{throw new As("Decryption failed: Invalid ciphertext or authentication tag")}}serializePrivateKey(e){return e}deserializePrivateKey(e){return e}},Xe=Tp.getInstance()});function S_(t,e,r,n,i=!0){if(!i)return null;if(t){let o=Xe.encryptContent(r,t),s=n==null?n:{encrypted:Xe.encryptMetadata(n,t)};return{content:o,metadata:s,isEncrypted:!0}}return e?null:{content:r,metadata:n,isEncrypted:!1}}var b$=D(()=>{"use strict";_p()});function SQ(t){let e=Buffer.from(t.subarray(0,16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=e.toString("hex");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function fa(t){let e=(0,Pv.createHash)("sha256").update(bQ).update(Buffer.from(t,"utf8")).digest();return SQ(e)}function ug(){return(0,Pv.randomBytes)(32).toString("hex")}var Pv,_v,bQ,Cv=D(()=>{"use strict";Pv=require("crypto"),_v="codevibe.e1.openprompt.promptid.v1",bQ=Buffer.from(`${_v}\0`,"utf8")});var Dn=D(()=>{"use strict";_p();b$();Cv()});var xv,S$,v$,ma,Pi,vQ,Jl,_e,v_=D(()=>{"use strict";xv=F(require("os")),S$=require("crypto"),v$=require("uuid");Ap();Dn();Rs();Ye();ma=class extends Error{constructor(e){super(e),this.name="KeychainError"}},Pi="device-identity",vQ="tokens-",Jl=class t{constructor(){this.deviceIdentity=null;this.sessionKeyCache=new Map;this.isRegistered=!1;this._serviceName=null}get serviceName(){return this._serviceName||(this._serviceName=Bt().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 vp(this.serviceName,Pi);return e?(this.deviceIdentity=JSON.parse(e),w.info(`[KeychainManager] Loaded device identity: ${this.deviceIdentity.deviceId}`),this.deviceIdentity):null}async setDeviceIdentity(e){try{await kp(this.serviceName,Pi,JSON.stringify(e)),this.deviceIdentity=e,w.info(`[KeychainManager] Saved device identity: ${e.deviceId}`)}catch(r){throw w.error(`[KeychainManager] Failed to save device identity: ${r}`),new ma(`Failed to save device identity: ${r}`)}}async getOrCreateDeviceIdentity(){let e=await this.getDeviceIdentity();return e||bp(this.serviceName,async()=>{let r=await y_(this.serviceName,Pi);if(r){let o=JSON.parse(r);return this.deviceIdentity=o,w.info(`[KeychainManager] Adopted concurrently-created device identity: ${o.deviceId}`),o}let n=Xe.generateKeyPair(),i={deviceId:(0,v$.v4)().toUpperCase(),privateKey:n.privateKey,publicKey:n.publicKey,createdAt:new Date().toISOString()};return await w_(this.serviceName,Pi,JSON.stringify(i)),this.deviceIdentity=i,w.info(`[KeychainManager] Generated new device identity: ${i.deviceId}`),i})}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 Ep(this.serviceName,Pi),this.deviceIdentity=null,this.sessionKeyCache.clear(),this.isRegistered=!1,w.info("[KeychainManager] Deleted device identity")}catch(e){throw w.error(`[KeychainManager] Failed to delete device identity: ${e}`),new ma(`Failed to delete device identity: ${e}`)}}getTokenAccount(e){return`${vQ}${e}`}async getTokens(e="production"){let r=await vp(this.serviceName,this.getTokenAccount(e));if(!r)return null;let n=JSON.parse(r);return w.debug(`[KeychainManager] Loaded tokens for ${e}`),n}async setTokens(e,r="production"){try{await kp(this.serviceName,this.getTokenAccount(r),JSON.stringify(e)),w.info(`[KeychainManager] Saved tokens for ${r}`,{userId:e.userId,email:e.email})}catch(n){throw w.error(`[KeychainManager] Failed to save tokens: ${n}`),new ma(`Failed to save tokens: ${n}`)}}async deleteTokens(e="production"){try{let r=await Ep(this.serviceName,this.getTokenAccount(e));return r&&w.info(`[KeychainManager] Deleted tokens for ${e}`),r}catch(r){return w.error(`[KeychainManager] Failed to delete tokens: ${r}`),!1}}isTokenExpired(e){return Date.now()>=e.expiresAt-3e5}async getSessionKey(e,r,n){let i=this.sessionKeyCache.get(e),o=n??null;if(r===void 0)return i?i.key:null;if(r.length===0)return o===null&&i?.sessionKeyGen===null?i.key:null;if(i&&i.sessionKeyGen===o)return i.key;let s=await this.getDeviceId(),a=r.find(d=>d.deviceId===s);if(!a)return w.warn(`[KeychainManager] Device ${s} not found in encryptedKeys`),null;let c=await this.getDevicePrivateKey(),l=Xe.decryptSessionKey(a,c);return this.sessionKeyCache.set(e,{sessionKeyGen:o,key:l}),w.info(`[KeychainManager] Decrypted and cached session key for ${e}`),l}createSessionKey(e,r){let n=Xe.generateSessionKey(),i=[],o=[];for(let s of e)try{let a=Xe.encryptSessionKey(n,s.publicKey);i.push({deviceId:s.deviceId,encryptedKey:a.encryptedKey,ephemeralPublicKey:a.ephemeralPublicKey,recipientPublicKeySha256:(0,S$.createHash)("sha256").update(s.publicKey,"utf8").digest("hex")})}catch(a){w.warn("[KeychainManager] Skipping device with invalid public key",{deviceId:s.deviceId,error:a instanceof Error?a.message:String(a)}),o.push(s.deviceId);try{r?.onDeviceSkipped?.(o.length)}catch{}}if(i.length===0)throw new As(`Failed to encrypt session key for any of ${e.length} devices`);return w.info("[KeychainManager] Created session key",{encryptedCount:i.length,skippedCount:o.length,totalCount:e.length}),{sessionKey:n,encryptedKeys:i,skippedDeviceIds:o}}cacheSessionKey(e,r,n){this.sessionKeyCache.set(e,{sessionKeyGen:n??null,key:r})}getCachedSessionKey(e){return this.sessionKeyCache.get(e)?.key??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 xv.hostname()||"CLI Client"}getDevicePlatform(){let e=xv.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,w.info("[KeychainManager] Cleared all data")}},_e=Jl.getInstance()});var k$={};jr(k$,{KeychainError:()=>ma,KeychainManager:()=>Jl,keychainManager:()=>_e});var Nn=D(()=>{"use strict";v_()});function Cp(t){return{ownerToken:t.ownerToken,promptId:t.promptId,producerKind:t.producerKind,mobileActionable:t.mobileActionable}}function pg(t){let e=ug(),r={promptId:fa(e),ownerToken:e,sessionId:t.sessionId,producerKind:t.producerKind,...t.agentType!==void 0&&{agentType:t.agentType},...t.title!==void 0&&{title:t.title},mobileActionable:t.mobileActionable,raisedAtMs:t.nowMs??Date.now()};return{record:r,fields:Cp(r)}}var E$=D(()=>{"use strict";Dn()});function k_(t,e,r=!1){return t!==void 0&&e===t&&!r}function E_(t,e=!1){return!e&&(!t.record.mobileActionable||t.contentPlain!==void 0)}var Rc,R$=D(()=>{"use strict";Rc=class{constructor(){this.active=new Map}isPublishing(e){return this.active.has(e)}async run(e,r){let n,i=new Promise(s=>{n=s}),o=this.active.get(e)??new Set;o.add(i),this.active.set(e,o);try{return await r()}finally{o.delete(i),o.size===0&&this.active.delete(e),n()}}async waitFor(e){for(;this.active.has(e);)await Promise.all(this.active.get(e))}}});var R_=D(()=>{"use strict";E$();R$()});var ga,xp,fg,Yl=D(()=>{"use strict";ga=(I=>(I.USER_PROMPT="USER_PROMPT",I.ASSISTANT_RESPONSE="ASSISTANT_RESPONSE",I.TOOL_USE="TOOL_USE",I.NOTIFICATION="NOTIFICATION",I.INTERACTIVE_PROMPT="INTERACTIVE_PROMPT",I.PROMPT_RESPONSE="PROMPT_RESPONSE",I.REASONING="REASONING",I.MODE_SELECTED="MODE_SELECTED",I.PLANNER_DECISION="PLANNER_DECISION",I.PLANNER_CACHE_HIT="PLANNER_CACHE_HIT",I.PLANNER_DEGRADED="PLANNER_DEGRADED",I.PLANNER_OUTAGE="PLANNER_OUTAGE",I.PLANNER_RECOVERED="PLANNER_RECOVERED",I.SLASH_COMMAND_INVOKED="SLASH_COMMAND_INVOKED",I.STRUCTURAL_SUMMARY_GENERATED="STRUCTURAL_SUMMARY_GENERATED",I.LOCAL_AUTHORITY_REFUSAL="LOCAL_AUTHORITY_REFUSAL",I.CONTINUATION_PACKET_WRITTEN="CONTINUATION_PACKET_WRITTEN",I.CONTINUATION_PACKET_FAILED="CONTINUATION_PACKET_FAILED",I.TEAM_DECOMPOSED="TEAM_DECOMPOSED",I.TEAM_TRACK_STATUS="TEAM_TRACK_STATUS",I.TEAM_GROUP_RESOLVED="TEAM_GROUP_RESOLVED",I.ADAPTER_PROGRESS="ADAPTER_PROGRESS",I.TOOL_ACTIVITY="TOOL_ACTIVITY",I))(ga||{}),xp=(r=>(r.DESKTOP="DESKTOP",r.MOBILE="MOBILE",r))(xp||{}),fg=(n=>(n.SENT="SENT",n.DELIVERED="DELIVERED",n.EXECUTED="EXECUTED",n))(fg||{})});function T$(t,e,r){let n=Ql.get(t);if(!n||r-n.windowStartMs>=EQ||r<n.windowStartMs){if(Ql.delete(t),Ql.size>=AQ){let i=Ql.keys().next().value;i!==void 0&&Ql.delete(i)}n={windowStartMs:r,count:0,toolUseAboveThreshold:0,suppressed:0,logged:!1},Ql.set(t,n)}if(n.count+=1,n.count<=I$||IQ.has(e))return!1;if(e==="REASONING")return n.suppressed+=1,!0;if(e==="TOOL_USE"){n.toolUseAboveThreshold+=1;let i=n.toolUseAboveThreshold%RQ===0;return i||(n.suppressed+=1),!i}return!1}function P$(t){let e=Ql.get(t);if(e&&!e.logged)return e.logged=!0,e}function Ov(t){return!t||typeof t.eventId=="string"&&t.eventId.startsWith("local-throttled-")?!1:typeof t.writerAuthenticated=="boolean"}var EQ,I$,RQ,A$,IQ,Ql,AQ,A_=D(()=>{"use strict";Yl();EQ=Number(process.env.CODEVIBE_THROTTLE_WINDOW_MS)||1e4,I$=Number(process.env.CODEVIBE_THROTTLE_EVENTS_PER_WINDOW)||50,RQ=Number(process.env.CODEVIBE_THROTTLE_TOOL_USE_KEEP_EVERY)||10,A$=I$,IQ=new Set(["USER_PROMPT","ASSISTANT_RESPONSE","INTERACTIVE_PROMPT","PROMPT_RESPONSE","NOTIFICATION","TEAM_DECOMPOSED","TEAM_TRACK_STATUS","TEAM_GROUP_RESOLVED","TOOL_ACTIVITY"]),Ql=new Map,AQ=2e3});function TQ(){if(process.platform!=="linux")return!1;try{let t=C$.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(t)}catch{return!1}}async function Op(t,e,r){try{return await fetch(t,e)}catch(n){let i=n?.cause?.code,o=n?.cause?.message,s=i||o||n?.message||"unknown",a=PQ(i),c=r?`${r}: `:"",l=`Node ${process.version} on ${process.platform}`,d=[`${c}Cannot reach ${t}`,` Underlying error: ${s}`];a&&d.push(` Suggested fix: ${a}`),d.push(` Platform: ${l}`);let u=new Error(d.join(`
15
- `));throw u.cause=n,u}}function PQ(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 _$,C$,T_=D(()=>{"use strict";_$=F(require("dns")),C$=F(require("fs"));if(TQ())try{_$.setDefaultResultOrder("ipv4first")}catch{}});var qt,tt,Ao,P_=D(()=>{"use strict";qt={getCompanionSyncState:`
15
+ `));throw u.cause=n,u}}function PQ(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 _$,C$,T_=D(()=>{"use strict";_$=F(require("dns")),C$=F(require("fs"));if(TQ())try{_$.setDefaultResultOrder("ipv4first")}catch{}});var qt,et,Ao,P_=D(()=>{"use strict";qt={getCompanionSyncState:`
16
16
  query GetCompanionSyncState {
17
17
  getCompanionSyncState
18
18
  }
@@ -285,7 +285,7 @@ ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,Y3)}`:s+=` ${n}`),s}log
285
285
  query GetTaskReviewSummary($taskId: ID!, $gateId: ID!) {
286
286
  getTaskReviewSummary(taskId: $taskId, gateId: $gateId)
287
287
  }
288
- `},tt={recordExecutionEvent:`
288
+ `},et={recordExecutionEvent:`
289
289
  mutation RecordExecutionEvent($input: RecordExecutionEventInput!) {
290
290
  recordExecutionEvent(input: $input)
291
291
  }
@@ -767,7 +767,7 @@ ${n.stack}`)):typeof n=="object"?s+=` ${JSON.stringify(n,Y3)}`:s+=` ${n}`),s}log
767
767
  `)).digest("hex"),entries:u.length,durationMs:Date.now()-r}}catch{return o()}}async function OG(t){let e=await eC(t.rootPaths),n=((await Cc(t.tier))?.bodyInclusionPaths??[]).slice().sort(),i=vt.join(nk(),".codevibe","structural-summary.ignore"),o="absent";try{let a=await xt.readFile(i,"utf8");o=To.createHash("sha256").update(a,"utf8").digest("hex")}catch{}let s={rootPaths:e,tier:t.tier,bodyInclusionPaths:n,ignoreFileHash:o,generatorSchemaVersion:pX,caps:hX};return To.createHash("sha256").update(JSON.stringify(s,TX),"utf8").digest("hex")}function TX(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}async function eC(t){let e=await Promise.all(t.map(ba));return DG(e)}function DG(t){let e=new Set,r=[];for(let n of t.map(i=>vt.resolve(i)).sort(PX))e.has(n)||(e.add(n),r.push(n));return r}function PX(t,e){return t<e?-1:t>e?1:0}async function NG(t){let e=await ba(t.workspaceRoot),r=await eC(t.rootPaths.length>0?t.rootPaths:[e]),n=await Promise.all(r.map(u=>EG(u))),i=r.map((u,p)=>_X(u,n[p])),o=n[0]??await EG(e),s=await OG({rootPaths:r,tier:t.tier});function a(u,p=!1){return{fresh:!1,reason:u,git:o,rootFreshness:i,liveInputHash:s,inputHashChanged:p}}if(!t.cached)return a("missing");let c=t.cached.metadata.summaryInputHash!==s;if(!CX(t.cached.metadata))return a("metadata-schema-mismatch",!0);let l=DG(t.cached.metadata.rootPaths);if(!xX(l,r))return a("root-set-mismatch",c);if(c)return a("input-hash-mismatch",!0);let d=new Map(t.cached.metadata.rootFreshness.map(u=>[vt.resolve(u.rootPath),u]));for(let u of i){let p=d.get(vt.resolve(u.rootPath));if(!p)return a("root-set-mismatch");if(!u.isGitRepo||!p.isGitRepo)return a("not-git");if(p.gitTopLevel!==u.gitTopLevel)return a("git-root-mismatch");if(!u.clean)return a("dirty-tree");if(p.head!==u.head)return a("head-moved");if(p.clean!==!0)return a("cached-was-dirty")}return{fresh:!0,reason:"fresh",git:o,rootFreshness:i,liveInputHash:s,inputHashChanged:!1}}function _X(t,e){return{rootPath:vt.resolve(t),...e.gitTopLevel?{gitTopLevel:e.gitTopLevel}:{},isGitRepo:e.isGitRepo,...e.head?{head:e.head}:{},clean:e.clean}}function CX(t){return t.schemaVersion===2}function xX(t,e){return t.length!==e.length?!1:t.every((r,n)=>r===e[n])}async function nd(t){let{workspaceRoot:e,rootPaths:r,tier:n,userId:i,generator:o,probeFreshnessFn:s=NG,loadContextStoreFn:a=ik,writeContextStoreFn:c=CG,purgeContextStoreFilesStrictFn:l=vX}=t,d=await ba(e),u=await eC(r.length>0?r:[d]),p=$p(d),h=null;try{h=await a(p)}catch(f){w.debug("[context-store] cached load threw \u2014 treating as missing",{workspaceId:p,error:f.message}),h=null}let m;try{m=await s({workspaceRoot:d,rootPaths:u,tier:n,cached:h})}catch(f){return{digest:"",workspaceId:p,recomputed:!1,reason:"missing",summary:null,error:`freshness probe failed: ${f.message}`}}if(m.fresh&&h)return{digest:h.digest||h.summary.sha256,workspaceId:p,recomputed:!1,reason:"fresh",summary:h.summary,error:null};try{m.inputHashChanged&&await l(Gp(p));let f=await Cc(n),g=await o.generate({rootPaths:u,ignoreFile:vt.join(nk(),".codevibe","structural-summary.ignore"),includeBodies:f?.bodyInclusionPaths??[],userId:i,tier:n}),y={schemaVersion:2,workspaceRoot:d,rootPaths:u,rootFreshness:m.rootFreshness,summaryInputHash:m.liveInputHash,summarySha256:g.sha256,writtenAt:new Date().toISOString()};return await c({workspaceId:p,summary:g,metadata:y,purgeFirst:m.inputHashChanged}),{digest:g.sha256,workspaceId:p,recomputed:!0,reason:m.reason,summary:g,error:null}}catch(f){return w.warn("[context-store] context-store refresh failed",{workspaceId:p,error:f.message}),{digest:"",workspaceId:p,recomputed:!1,reason:m.reason,summary:null,error:f.message}}}function tC(t){return{workspaceId:t.workspaceId,summary_sha256:t.summary_sha256,slice_selector:t.slice_selector??[]}}async function rC(t){let{ref:e,workspaceRoot:r,rootPaths:n,tier:i,userId:o,generator:s,ensureFreshFn:a=nd}=t,c=await ba(r),l=await a({workspaceRoot:c,rootPaths:n,tier:i,userId:o,generator:s});if(l.error||!l.summary)throw new Error(`context_ref resolve: context store refresh failed for workspaceId ${e.workspaceId} (reason: ${l.reason}; error: ${l.error??"summary unavailable"})`);if(l.workspaceId!==e.workspaceId)throw new Error(`context_ref resolve: refreshed workspaceId ${l.workspaceId} does not match ref workspaceId ${e.workspaceId}`);let d=l.summary.sha256!==e.summary_sha256,u=MG(l.summary,e.slice_selector,c);return{workspaceId:e.workspaceId,summary_sha256:l.summary.sha256,repos:u,refreshedFromDrift:d}}function MG(t,e,r){if(!e||e.length===0)return t.repos;let n=new Map;for(let o of e)n.set(o.repo_id,o.paths);let i=[];for(let o of t.repos){let s=OX(t,o,r),a=n.get(s);if(a!==void 0){if(a.length===0){i.push(o);continue}i.push({...o,directoryTree:DX(o.directoryTree,a)})}}return i}function OX(t,e,r){let n=r??t.rootPaths[0]??e.rootPath,i=vt.relative(n,e.rootPath);return PG(i)}function DX(t,e){let r=e.map(rk);function n(s){return rk(vt.relative(t.path,s.path)||".")}function i(s){let a=n(s),c=r.some(d=>a===d||RG(d,a)),l=r.some(d=>d===a||RG(a,d));if(c)return s;if(l){let d=s.children.map(i).filter(u=>u!==null);return{...s,children:d}}return null}return i(t)??{...t,children:[]}}function RG(t,e){return t==="."?e!==".":e.startsWith(t+"/")}var xt,Tg,vt,IG,To,AG,TG,rd,J_,bG,Ag,pX,hX,Pg,_g,Cg,xg,fX,_G,gX,yX,z_,kX,SG,EX,vG,AX,xc=D(()=>{"use strict";xt=F(require("fs/promises")),Tg=require("fs"),vt=F(require("path")),IG=F(require("os")),To=F(require("crypto")),AG=require("child_process"),TG=require("util");Ye();Nn();Dn();Or();tk();rd=(0,TG.promisify)(AG.execFile),J_=448,bG=384,Ag=null;pX=1,hX={fileCountCap:5e4,bodyByteCap:64*1024*1024,maxDepth:12},Pg="summary.json",_g="digest.txt",Cg="metadata.json",xg="repo-state.json",fX=/^[0-9a-f]{64}$/;_G=1,gX="codevibe-context-store-at-rest-v1",yX="context-store",z_=null;kX=720*60*60*1e3,SG=64,EX=vt.join(".codevibe","context"),vG=!1;AX=3e3});function sC(t,e){let r=LX.safeParse(t);return r.success?r.data:e()}function aC(t,e){let{id:r,scope:n,stream:i}=e,o=sC(t,e.invalid);if(o.operationId!==r||o.sessionId!==n.sessionId||o.sessionGenerationId!==n.sessionGenerationId||o.provider!==i.provider||o.streamSha256!==i.streamSha256||!BG.safeParse({byteOffset:o.byteOffset,anchor:o.anchor,discardUntilNewline:o.discardUntilNewline}).success||o.skippedBytes>o.byteOffset||o.lastGap&&o.lastGap.endOffset>o.byteOffset||o.lastFrame&&(o.lastFrame.endOffset!==o.byteOffset||o.lastFrame.provider!==i.provider||o.lastFrame.streamSha256!==i.streamSha256||o.discardUntilNewline||JSON.stringify(ok(o.lastFrame))!==JSON.stringify(o.anchor)))return e.invalid();let s=0,a=new Set;for(let[c,l]of o.entries.entries()){let d={provider:l.frame.provider,streamSha256:l.frame.streamSha256,occurrence:l.frame.occurrence,sourceSha256:l.frame.sourceSha256};if(d.provider!==i.provider||d.streamSha256!==i.streamSha256||l.operationId!==e.identify(d)||a.has(l.operationId)||l.frame.startOffset<s||(l.state==="PREPARING"?c!==o.entries.length-1||l.frame.startOffset!==o.byteOffset:l.frame.endOffset>o.byteOffset))return e.invalid();a.add(l.operationId),s=l.frame.endOffset}return o}function FG(t){let{id:e,scope:r,stream:n}=t,i=l=>aC(l,t),o=()=>t.read(i),s=async()=>await o()??t.missing(),a=async(l,d)=>{let u=i(l);await d(),await t.write(u)},c=async l=>{let d=await o();if(!d)return;let u=d.entries.find(p=>p.state==="PREPARING");u&&await t.exists(u.operationId)&&(u.state="READY",d.byteOffset=u.frame.endOffset,d.lastFrame=u.frame,d.anchor=ok(u.frame),d.discardUntilNewline=!1,d.projection=u.projectionAfter,await a(d,l));for(let p of[...d.entries])p.state==="SETTLED"&&(await l(),await t.acknowledge(p.operationId),d.entries=d.entries.filter(h=>h.operationId!==p.operationId),await a(d,l))};return Object.freeze({open:async l=>{let d=typeof l=="number"?{byteOffset:l,anchor:null,discardUntilNewline:!1}:{...l,anchor:l?.anchor?{...l.anchor}:null};return t.locked(async u=>{if(!Number.isSafeInteger(d.byteOffset)||d.byteOffset<0)return t.invalid();let p=await o();if(p)return p;let h=BG.safeParse(d);if(!h.success)return t.invalid();let m={schemaVersion:1,kind:"SOURCE_CURSOR",operationId:e,...r,...n,...h.data,skippedBytes:0,lastGap:null,lastFrame:null,projection:null,entries:[]};return await a(m,u),m})},load:()=>t.locked(o),admit:async(l,d,u)=>{let p=oC.safeParse(l);if(!p.success)return t.invalid();let h=p.data;return h.provider!==n.provider||h.streamSha256!==n.streamSha256||d!==null&&typeof d!="function"||u!==void 0&&!iC.safeParse(u).success?t.invalid():t.locked(async m=>{await c(m);let f=await s();if(h.endOffset<=f.byteOffset)return f.lastFrame&&h.endOffset===f.byteOffset&&JSON.stringify(h)!==JSON.stringify(f.lastFrame)?t.invalid():null;if(h.startOffset!==f.byteOffset||f.discardUntilNewline)return t.invalid();let g=u===void 0?f.projection:u,y={provider:h.provider,streamSha256:h.streamSha256,occurrence:h.occurrence,sourceSha256:h.sourceSha256},S=t.identify(y),b=f.entries.find(v=>v.state==="PREPARING");return b&&(b.operationId!==S||JSON.stringify(b.frame)!==JSON.stringify(h)||b.projectionAfter!==g)?t.invalid():d===null?b?t.invalid():(f.byteOffset=h.endOffset,f.lastFrame=h,f.anchor=ok(h),f.projection=g,await a(f,m),null):(b||(b={frame:h,operationId:S,state:"PREPARING",projectionAfter:g},f.entries.push(b),await a(f,m)),await t.prepare(y,d)!==S?t.invalid():(b.state="READY",f.byteOffset=h.endOffset,f.lastFrame=h,f.anchor=ok(h),f.projection=g,await a(f,m),S))})},skip:async l=>{let d=LG.safeParse(l);if(!d.success)return t.invalid();let u=d.data;await t.locked(async p=>{await c(p);let h=await s();if(u.endOffset<=h.byteOffset)return u.endOffset===h.byteOffset&&JSON.stringify(h.lastGap)!==JSON.stringify(u)?t.invalid():void 0;if(u.startOffset!==h.byteOffset||h.entries.some(m=>m.state==="PREPARING"))return t.invalid();h.byteOffset=u.endOffset,h.anchor=u.anchor,h.discardUntilNewline=u.discardUntilNewline,h.skippedBytes+=u.endOffset-u.startOffset,h.lastGap=u,h.lastFrame=null,h.projection=null,await a(h,p)})},recover:()=>t.locked(c),drain:(l=64,d)=>t.drainLocked(async()=>{if(!Number.isSafeInteger(l)||l<1||l>256)return t.invalid();await t.locked(c);let u=0;for(;u<l;){if(d?.aborted)throw d.reason??new Error("Aborted");let p=await t.locked(async()=>(await s()).entries.find(m=>m.state==="READY"));if(!p)break;let h=await t.retry(p.operationId,d);await t.locked(async m=>{let f=await s(),g=f.entries.find(y=>y.operationId===p.operationId);g&&(g.state="SETTLED",g.outcome=h.status,await a(f,m),await m(),await t.acknowledge(g.operationId),f.entries=f.entries.filter(y=>y.operationId!==g.operationId),await a(f,m))}),u++}return u})})}var br,Zo,Sa,sk,nC,iC,ak,NX,oC,LG,BG,ok,MX,LX,ck=D(()=>{"use strict";br=require("zod"),Zo=64*1024,Sa=br.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),sk=br.z.string().regex(/^[a-f0-9]{64}$/),nC=br.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/),iC=br.z.string().refine(t=>Buffer.byteLength(t)<=16*1024).nullable(),ak=br.z.object({startOffset:Sa,endOffset:Sa,sha256:sk}).strict().refine(t=>t.endOffset>t.startOffset&&t.endOffset-t.startOffset<=Zo),NX=br.z.object({provider:br.z.enum(["codex","claude","agy"]),streamSha256:sk,occurrence:br.z.string().regex(/^[A-Za-z0-9_:-]{1,256}$/),sourceSha256:sk}).strict(),oC=NX.extend({startOffset:Sa,endOffset:Sa,anchor:ak.optional()}).strict().refine(t=>t.endOffset>t.startOffset&&(t.anchor?t.anchor.endOffset===t.endOffset&&t.anchor.startOffset>=t.startOffset:t.endOffset-t.startOffset<=Zo)),LG=br.z.object({startOffset:Sa,endOffset:Sa,anchor:ak,reason:br.z.enum(["BACKLOG_LIMIT","OVERSIZED_RECORD","PARTIAL_RECORD","MALFORMED_RECORD","EMPTY_RECORD"]),discardUntilNewline:br.z.boolean()}).strict().refine(t=>t.endOffset>t.startOffset&&t.anchor.endOffset===t.endOffset&&t.anchor.startOffset>=t.startOffset&&(!t.discardUntilNewline||["BACKLOG_LIMIT","OVERSIZED_RECORD","PARTIAL_RECORD"].includes(t.reason))),BG=br.z.object({byteOffset:Sa,anchor:ak.nullable(),discardUntilNewline:br.z.boolean()}).strict().refine(t=>t.byteOffset===0?t.anchor===null&&!t.discardUntilNewline:t.anchor?.endOffset===t.byteOffset),ok=t=>t.anchor??{startOffset:t.startOffset,endOffset:t.endOffset,sha256:t.sourceSha256},MX=br.z.object({frame:oC,operationId:nC,state:br.z.enum(["PREPARING","READY","SETTLED"]),projectionAfter:iC,outcome:br.z.enum(["ACCEPTED","OMITTED"]).optional()}).strict().refine(t=>t.state==="SETTLED"==(t.outcome!==void 0)),LX=br.z.object({schemaVersion:br.z.literal(1),kind:br.z.literal("SOURCE_CURSOR"),operationId:nC,sessionId:br.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),sessionGenerationId:nC,provider:br.z.enum(["codex","claude","agy"]),streamSha256:sk,byteOffset:Sa,anchor:ak.nullable(),discardUntilNewline:br.z.boolean(),skippedBytes:Sa,lastGap:LG.nullable(),projection:iC,lastFrame:oC.nullable(),entries:br.z.array(MX).max(256)}).strict()});function $G(t){let{source:e,lanes:r,laneStreams:n}=t,i=async()=>{for(let a of r)await a.recover()},o=a=>({byteOffset:a.byteOffset,anchor:a.anchor?{...a.anchor}:null,discardUntilNewline:a.discardUntilNewline}),s=a=>{let c=[...a].sort((l,d)=>l.byteOffset-d.byteOffset);return c.length===2&&c[0].byteOffset===c[1].byteOffset&&JSON.stringify(o(c[0]))!==JSON.stringify(o(c[1]))?t.invalid():o(c[0])};return Object.freeze({open:a=>{let c=typeof a=="number"?a:o(a);return t.locked(async()=>{await i();let d=(await Promise.all(r.map(h=>h.load()))).filter(h=>h!==null);if(d.length===1&&(d[0].lastFrame!==null||d[0].entries.length!==0||d[0].skippedBytes!==0||d[0].projection!==null))return t.invalid();let u=d.length?s(d):c,p=[];for(let h of r)p.push(await h.open(u));return s(p)})},admit:(a,c)=>{if(!a||a.provider!==e.provider||a.streamSha256!==e.streamSha256||!Array.isArray(c)||c.length!==2||c.some(u=>u!==null&&typeof u!="function"))return t.invalid();let l={...a,...a.anchor&&{anchor:{...a.anchor}}},d=[...c];return t.locked(async()=>{let u=[null,null];for(let p of[0,1])u[p]=await r[p].admit({...l,streamSha256:n[p]},d[p]);return u})},skip:a=>{let c={...a,anchor:{...a.anchor}};return t.locked(async()=>{for(let l of r)await l.skip(c)})},recover:()=>t.locked(i),drain:async(a=64,c)=>{let l=0,d,u=!1;for(let p of r){if(c?.aborted)throw c.reason??new Error("Aborted");try{l+=await p.drain(a,c)}catch(h){u=!0,d??=h}}if(u)throw d;return l}})}var GG=D(()=>{"use strict"});function cC(t,e){let r=$X.safeParse(t);if(!r.success)return e();let n=r.data;if(n.nextSequence-n.settledThrough-1!==n.entries.length)return e();let i=new Set;for(let[o,s]of n.entries.entries()){if(s.sequence!==n.settledThrough+o+1||i.has(s.operationId)||s.state==="SETTLED"&&o!==0)return e();if(i.add(s.operationId),s.state==="STAGED"){let a=Mn("CREATE_EVENT",s.input);if(a.sessionId!==n.sessionId||a.sessionGenerationId!==n.sessionGenerationId||a.clientOperationId!==s.operationId||a.isEncrypted!==!0||a.type==="TOOL_ACTIVITY")return e()}}return n}function HG(t){let e=async()=>await t.read()??{schemaVersion:1,kind:"SHELL_SOURCE",operationId:t.id,...t.scope,nextSequence:1,settledThrough:0,entries:[]},r=async(o,s)=>{await s(),await t.write(cC(o,t.invalid))},n=()=>t.locked(async o=>{let s=await e(),a=s.entries[0];a?.state==="SETTLED"&&(await o(),await t.acknowledge(a.operationId),s.settledThrough=a.sequence,s.entries.shift(),await r(s,o))}),i=async o=>{if(o?.aborted)throw o.reason??new Error("Aborted");await n();let s=await t.locked(async()=>(await e()).entries[0]);if(!s)return null;if(s.state==="OMITTED")return await t.locked(async c=>{let l=await e(),d=l.entries[0];if(!d||d.state!=="OMITTED"||d.sequence!==s.sequence||d.operationId!==s.operationId)return t.invalid();l.settledThrough=s.sequence,l.entries.shift(),await r(l,c)}),{sequence:s.sequence,result:{status:"OMITTED",reason:"SYNC_QUOTA_EXHAUSTED"}};if(s.state!=="STAGED"||await t.prepare(s.input)!==s.operationId)return t.invalid();let a=await t.retry(s.operationId,o);return await t.locked(async c=>{let l=await e(),d=l.entries[0];if(!d||d.sequence!==s.sequence||d.operationId!==s.operationId)return t.invalid();l.entries[0]={sequence:s.sequence,operationId:s.operationId,state:"SETTLED"},await r(l,c)}),await n(),{sequence:s.sequence,result:a}};return Object.freeze({recover:n,append:async o=>{let s=Mn("CREATE_EVENT",o);delete s.source;let a=s;if(a.sessionId!==t.scope.sessionId||a.sessionGenerationId!==t.scope.sessionGenerationId||a.isEncrypted!==!0||a.type==="TOOL_ACTIVITY")return t.invalid();let c=(0,UG.createHash)("sha256").update((0,lk.canonicalize)(a)).digest("hex"),l=p=>{let h=p.entries.find(m=>m.operationId===a.clientOperationId);return h?h.state==="SETTLED"||(h.state==="STAGED"?(0,lk.canonicalize)(h.input)!==(0,lk.canonicalize)(a):h.fingerprint!==c)?t.collision():{sourceId:t.id,sequence:h.sequence,operationId:h.operationId}:null},d=await t.locked(async()=>l(await e()));if(d)return d;let u=await t.omitNewPayload?.()===!0;return t.locked(async p=>{let h=await e(),m=l(h);if(m)return m;if(h.entries.length>=64||h.nextSequence===Number.MAX_SAFE_INTEGER)return t.full();let f={sourceId:t.id,sequence:h.nextSequence++,operationId:a.clientOperationId};return h.entries.push(u?{sequence:f.sequence,operationId:f.operationId,state:"OMITTED",fingerprint:c}:{sequence:f.sequence,operationId:f.operationId,state:"STAGED",input:a}),await r(h,p),f})},deliver:async(o,s)=>{let a=BX.safeParse(o);if(!a.success||a.data.sourceId!==t.id)return t.invalid();let c=a.data;return t.drainLocked(async()=>{await n();let l=await t.locked(e);if(c.sequence<=l.settledThrough)return null;let d=l.entries.find(u=>u.sequence===c.sequence);if(!d||d.operationId!==c.operationId)return t.collision();if(d.state==="OMITTED"&&d.sequence!==l.entries[0].sequence)return{status:"OMITTED",reason:"SYNC_QUOTA_EXHAUSTED"};for(;;){let u=await i(s);if(!u||u.sequence>c.sequence)return null;if(u.sequence===c.sequence)return u.result}})},drain:(o=64,s)=>t.drainLocked(async()=>{if(!Number.isSafeInteger(o)||o<1||o>64)return t.invalid();let a=0;for(;a<o&&await i(s);)a++;return a})})}var lk,UG,yn,id,Up,BX,FX,$X,WG=D(()=>{"use strict";lk=require("json-freeze"),UG=require("node:crypto"),yn=require("zod");Ln();id=yn.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),Up=yn.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),BX=yn.z.object({sourceId:id,sequence:Up.positive(),operationId:id}).strict(),FX=yn.z.discriminatedUnion("state",[yn.z.object({sequence:Up.positive(),operationId:id,state:yn.z.literal("STAGED"),input:yn.z.unknown()}).strict(),yn.z.object({sequence:Up.positive(),operationId:id,state:yn.z.literal("OMITTED"),fingerprint:yn.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),yn.z.object({sequence:Up.positive(),operationId:id,state:yn.z.literal("SETTLED")}).strict()]),$X=yn.z.object({schemaVersion:yn.z.literal(1),kind:yn.z.literal("SHELL_SOURCE"),operationId:id,sessionId:yn.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),sessionGenerationId:id,nextSequence:Up.positive(),settledThrough:Up,entries:yn.z.array(FX).max(64)}).strict()});function Lg(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function dk(t,e){return Object.keys(t).every(r=>e.has(r))}function va(t){return typeof t=="string"&&GX.test(t)}function qX(t){return typeof t=="string"&&t.length>0&&Number.isFinite(Date.parse(t))}function lC(t){return Number.isSafeInteger(t)&&t>=0}function KX(t,e){if(t===void 0)return!0;let r=Lg(t);if(!r||!dk(r,new Set(["ciphertextB64","keyVersion","sessionId"])))return!1;let n=r.ciphertextB64;return typeof n=="string"&&n.length>0&&UX.test(n)&&Buffer.from(n,"base64").toString("base64")===n&&r.keyVersion===1&&r.sessionId===e}function jX(t){let e=Lg(t);if(!e||typeof e.kind!="string")return!1;let r=HX[e.kind];return!r||!dk(e,r)?!1:e.kind==="open_new_round"?va(e.nextGateId)&&lC(e.nextRound):e.kind==="restart_proposal"?va(e.nextProposalId)&&va(e.nextGateId)&&lC(e.nextRound):e.kind==="continuation_selected"?typeof e.offerId=="string"&&e.offerId.length>0&&["CLAUDE","CODEX","ANTIGRAVITY"].includes(String(e.targetAgent))&&va(e.nextGateId)&&lC(e.nextRound):e.kind==="continuation_declined"?typeof e.offerId=="string"&&e.offerId.length>0:e.kind==="group_revert_restart"?va(e.claimToken)&&typeof e.restartGroupId=="string"&&KG.test(e.restartGroupId):e.kind==="group_keep"||e.kind==="group_revert"||e.kind==="group_revert_abort"?va(e.claimToken):!0}function dC(t,e){return typeof t!="string"||!jX(e)?null:jG.get(`${t}\0${String(e.kind)}`)??null}function Oc(t,e){if(t.sessionId!==e||t.type!=="NOTIFICATION"||t.source!=="DESKTOP"||t.emittedBy!=="SYSTEM"||t.writerAuthenticated!==!1||t.isEncrypted!==!1||t.writerEventKind!=null||t.writerSessionGenerationId!=null||typeof t.promptId!="string"||typeof t.content!="string")return null;let r=Lg(t.metadata);if(!r||!dk(r,new Set(["schema","message","gateResolution"]))||r.schema!=="codevibe.gate_resolution.v1"||r.message!==t.content)return null;let n=Lg(r.gateResolution),i=Lg(n?.effectRecipe);if(!n||!i||typeof i.kind!="string"||i.kind.length===0)return null;let o=n.subjectKind,s=o==="task"?new Set([...qG,"gateId","taskId"]):o==="task_group"?new Set([...qG,"taskGroupId","groupGeneration"]):null;if(!s||!dk(n,s)||n.resolved!==!0||n.promptId!==t.promptId||!va(n.decisionClaimId)||typeof n.decision!="string"||n.decision.length===0||!qX(n.resolvedAt)||n.resolvedAt!==t.timestamp||!KX(n.notesEncrypted,t.sessionId))return null;let a=dC(n.decision,i);if(WX.has(n.decision)&&!a)return null;let c=a??"Resolved";return a&&!t.content.endsWith(` \u2014 Resolved \xB7 ${a}`)||a&&(n.decision==="ACCEPT_WITH_NOTES"||n.decision==="REJECT_WITH_NOTES"||n.decision==="CONTINUE_WITH")!==(n.notesEncrypted!==void 0)?null:o==="task"?!va(n.subjectId)||n.subjectId!==n.taskId||n.gateId!==t.promptId||!va(n.gateId)?null:{eventId:t.eventId,sessionId:t.sessionId,promptId:t.promptId,decisionClaimId:n.decisionClaimId,subjectKind:"TASK",subjectId:n.subjectId,decision:n.decision,label:c,resolvedAt:n.resolvedAt,effectRecipe:i,gateId:n.gateId,taskId:n.taskId,...n.notesEncrypted?{notesEncrypted:n.notesEncrypted}:{}}:typeof n.subjectId!="string"||!KG.test(n.subjectId)||n.subjectId!==n.taskGroupId||t.promptId!==`group-escalation:${n.subjectId}`||!Number.isSafeInteger(n.groupGeneration)||n.groupGeneration<1?null:{eventId:t.eventId,sessionId:t.sessionId,promptId:t.promptId,decisionClaimId:n.decisionClaimId,subjectKind:"TASK_GROUP",subjectId:n.subjectId,decision:n.decision,label:c,resolvedAt:n.resolvedAt,effectRecipe:i,taskGroupId:n.taskGroupId,groupGeneration:n.groupGeneration,...n.notesEncrypted?{notesEncrypted:n.notesEncrypted}:{}}}var GX,KG,UX,qG,HX,jG,WX,Bg=D(()=>{"use strict";GX=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,KG=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,UX=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,qG=new Set(["decisionClaimId","promptId","subjectKind","subjectId","decision","resolved","resolvedAt","effectRecipe","notesEncrypted"]),HX={authorize_task:new Set(["kind"]),final_approval_cancelled:new Set(["kind"]),terminate_gate:new Set(["kind"]),open_new_round:new Set(["kind","nextGateId","nextRound"]),restart_proposal:new Set(["kind","nextProposalId","nextGateId","nextRound"]),abort_task:new Set(["kind"]),continuation_selected:new Set(["kind","offerId","targetAgent","nextGateId","nextRound"]),continuation_declined:new Set(["kind","offerId"]),group_keep:new Set(["kind","claimToken"]),group_revert:new Set(["kind","claimToken"]),group_revert_restart:new Set(["kind","claimToken","restartGroupId"]),group_revert_abort:new Set(["kind","claimToken"]),apply_retry_started:new Set(["kind"]),apply_discarded:new Set(["kind"])},jG=new Map([["APPROVE\0authorize_task","Approved"],["CANCEL\0final_approval_cancelled","Cancelled"],["ACCEPT\0terminate_gate","Accepted"],["ACCEPT_WITH_NOTES\0terminate_gate","Accepted with notes"],["REJECT_WITH_NOTES\0open_new_round","Changes requested"],["REJECT_RESTART\0restart_proposal","Restart requested"],["ABORT_TASK\0abort_task","Task aborted"],["CONTINUE_WITH\0continuation_selected","Continuation selected"],["CANCEL\0continuation_declined","Continuation declined"],["ACCEPT\0group_keep","Team changes kept"],["ACCEPT_WITH_NOTES\0group_keep","Team changes kept with notes"],["REJECT_WITH_NOTES\0group_revert","Team changes rejected"],["REJECT_RESTART\0group_revert_restart","Team restart requested"],["ABORT_TASK\0group_revert_abort","Team aborted"],["RETRY_AS_NEW_TASK\0apply_retry_started","Retry as a new task"],["DISCARD\0apply_discarded","Discard"]]),WX=new Set([...jG.keys()].map(t=>t.slice(0,t.indexOf("\0"))))});function hC(t,e){let{sessionId:r,promptId:n,state:i,actionable:o,decisionClaimId:s,resolutionEventId:a,resolutionTimestamp:c}=t;return Object.freeze({sessionId:r,promptId:n,state:i,actionable:o,decisionClaimId:s,resolutionEventId:a,resolutionTimestamp:c,resolutionEvent:e})}function Fg(t,e){(!pC(t.sessionId)||!pC(t.sessionGenerationId)||typeof t.promptId!="string"||!/^[A-Za-z0-9_:-]{1,256}$/.test(t.promptId))&&e()}function ZG(t,e,r){if(Fg(e,r),typeof t!="string"||Buffer.byteLength(t)>2048)return r();let n;try{n=JSON.parse(t)}catch{return r()}if(!XG(n)||Object.keys(n).length!==uC.length||Object.keys(n).some(i=>!uC.includes(i))||n.sessionId!==e.sessionId||n.sessionGenerationId!==e.sessionGenerationId||n.promptId!==e.promptId||n.actionable!==!1||!["NOT_FOUND","CLAIMED","RESOLVED"].includes(n.state))return r();if(n.state==="NOT_FOUND"){if(uC.slice(5).some(i=>n[i]!==null))return r()}else{if(!pC(n.decisionClaimId)||typeof n.resolutionEventId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n.resolutionEventId))return r();if(n.state==="CLAIMED"){if(n.resolutionTimestamp!==null||n.resolutionEventDigest!==null||n.exactFetchCapability!==null)return r()}else if(!JX(n.resolutionTimestamp)||typeof n.resolutionEventDigest!="string"||!/^[a-f0-9]{64}$/.test(n.resolutionEventDigest)||n.exactFetchCapability!==null&&!zX(n.exactFetchCapability))return r()}return Object.freeze(n)}function e1(t,e,r){if(!XG(t)||e.state!=="RESOLVED"||VG.some(a=>typeof t[a]!="string")||JG.some(a=>typeof t[a]!="boolean")||zG.some(a=>a in t&&typeof t[a]!="string")||Object.keys(t).some(a=>![...VG,...zG,...JG].includes(a)))return r();let n=(0,QG.canonicalize)(t);if(Buffer.byteLength(n)>350*1024||(0,YG.createHash)("sha256").update(n).digest("hex")!==e.resolutionEventDigest||t.sessionId!==e.sessionId||t.eventId!==e.resolutionEventId||t.timestamp!==e.resolutionTimestamp||t.promptId!==e.promptId||t.sessionGenerationId!==void 0&&t.sessionGenerationId!==e.sessionGenerationId)return r();let i;try{i=JSON.parse(t.metadata)}catch{return r()}let o={...t,metadata:i},s=Oc(o,e.sessionId);return!s||s.promptId!==e.promptId||s.decisionClaimId!==e.decisionClaimId||s.eventId!==e.resolutionEventId||s.resolvedAt!==e.resolutionTimestamp?r():o}var YG,QG,VX,uC,VG,zG,JG,XG,pC,zX,JX,fC=D(()=>{"use strict";YG=require("node:crypto"),QG=require("json-freeze");Bg();VX=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,uC=["sessionId","sessionGenerationId","promptId","state","actionable","decisionClaimId","resolutionEventId","resolutionTimestamp","resolutionEventDigest","exactFetchCapability"],VG=["sessionId","timestamp","eventId","type","source","content","metadata","promptId","emittedBy"],zG=["sessionGenerationId","syncNativeKind","syncControlClass"],JG=["isEncrypted","writerAuthenticated"],XG=t=>!!t&&typeof t=="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(t)),pC=t=>typeof t=="string"&&VX.test(t),zX=t=>typeof t=="string"&&/^[A-Za-z0-9_-]{43}$/.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t,JX=t=>typeof t=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(t)&&Number.isFinite(Date.parse(t))&&new Date(t).toISOString()===t});function sn(){throw new Tt("INVALID_SYNC_READ_INPUT")}function Xt(){throw new Tt("INVALID_SYNC_READ_RESPONSE")}function QX(t,e){if(!ci(e,["message"])||typeof e.message!="string")return!1;let r=e.message.toLowerCase();return[500,502,503,504].includes(t)&&r==="internal server error"||t===429&&r==="too many requests"}function Gg(t){return(!sd(t)||t.ok!==!1||typeof t.errorCode!="string"||Object.keys(t).some(e=>!["ok","errorCode","retryAfterMs"].includes(e))||t.retryAfterMs!==void 0&&(!Number.isSafeInteger(t.retryAfterMs)||t.retryAfterMs<0))&&Xt(),new Tt("SYNC_READ_UNAVAILABLE",YX.has(t.errorCode)?t.errorCode:void 0,t.retryAfterMs)}var Po,Oi,od,t1,Vr,Dc,sd,ci,$g,YX,Tt,Nc,Hp=D(()=>{"use strict";Po=require("node:crypto"),Oi=require("json-freeze");Xl();fC();od=/^[A-Za-z0-9_-]{1,256}$/,t1=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Vr=t=>(0,Po.createHash)("sha256").update(t).digest("hex"),Dc=t=>typeof t=="string"&&/^[A-Za-z0-9_-]{43}$/.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t,sd=t=>!!t&&typeof t=="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(t)),ci=(t,e)=>sd(t)&&Object.keys(t).sort().join(",")===e.sort().join(","),$g=t=>typeof t=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(t)&&Number.isFinite(Date.parse(t))&&new Date(t).toISOString()===t,YX=new Set(["UNAUTHORIZED","INVALID_REQUEST","UPDATE_REQUIRED","AUTHORITY_UNAVAILABLE","SESSION_HISTORY_UNAVAILABLE","EVENT_FETCH_UNAVAILABLE","GATE_RESOLUTION_UNAVAILABLE","DESKTOP_IDENTITY_INVALID","DESKTOP_PROOF_INVALID","DESKTOP_SESSION_STALE","DESKTOP_REGISTRATION_EXPIRED","DESKTOP_AUTHORITY_UNAVAILABLE","DESKTOP_REGISTRY_CONTENTION","CONNECTION_RETRY_AFTER","HISTORY_RETRY_AFTER","EXACT_FETCH_RETRY_AFTER","CONTROL_BREAKER_CONTENTION"]),Tt=class extends Error{constructor(r,n,i){super(r);this.code=r;this.backendCode=n;this.retryAfterMs=i;this.name="SyncReadClientError"}};Nc=class{constructor(e){this.deps=e;let r;try{r=new URL(e.endpoint)}catch{return sn()}(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||typeof e.userId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(e.userId)||!ci(e.sessionScope,["sessionId","sessionGenerationId"])||typeof e.sessionScope.sessionId!="string"||!od.test(e.sessionScope.sessionId)||typeof e.sessionScope.sessionGenerationId!="string"||!t1.test(e.sessionScope.sessionGenerationId))&&sn(),this.endpoint=r.origin,this.scope=Object.freeze({...e.sessionScope})}now(){return(this.deps.now??Date.now)()}fence(e){if(this.deps.assertAccount(),e?.aborted)throw e.reason??new Error("Aborted")}credential(e){return(!ci(e,["sessionId","sessionGenerationId","credential","expiresAtEpochMs"])||e.sessionId!==this.scope.sessionId||e.sessionGenerationId!==this.scope.sessionGenerationId||!Dc(e.credential)||!Number.isSafeInteger(e.expiresAtEpochMs)||e.expiresAtEpochMs<=this.now())&&sn(),{...e}}event(e){let r=sd(e)&&e.source==="MOBILE"&&["USER_PROMPT","PROMPT_RESPONSE"].includes(e.type),n=sd(e)&&e.deliveryStatus==="SENT"?"0":sd(e)&&e.deliveryStatus==="DELIVERED"?"1":sd(e)&&e.deliveryStatus==="EXECUTED"?"2":void 0,i=r&&e.syncLegacyProjection===1&&e.syncLifecycleVersion===void 0&&e.syncVisibility==="VISIBLE_METERED"&&e.syncEventRevision===n&&e.syncOperationId===void 0&&e.syncImmutableIdentityDigest===void 0;return(!sd(e)||typeof e.eventId!="string"||!od.test(e.eventId)||e.sessionId!==this.scope.sessionId||e.sessionGenerationId!==this.scope.sessionGenerationId||!$g(e.timestamp)||typeof e.type!="string"||!/^[A-Z][A-Z0-9_]{0,63}$/.test(e.type)||!["DESKTOP","MOBILE"].includes(e.source)||e.syncLegacyProjection!==void 0&&!i||r&&e.syncLifecycleVersion!==1&&!i||e.content!==void 0&&typeof e.content!="string"||e.metadata!==void 0&&typeof e.metadata!="string"||e.isEncrypted!==void 0&&typeof e.isEncrypted!="boolean"||e.isEncrypted===!0&&e.encryptionVersion!==1&&!(i&&e.encryptionVersion===void 0)||Buffer.byteLength(JSON.stringify(e))>350*1024)&&Xt(),Object.freeze(e)}async request(e,r,n,i,o,s,a,c){this.fence(c);let l=await this.deps.getSigningKey();this.fence(c);let d=await this.deps.getToken(c);this.fence(c),(!/^[A-Za-z0-9_.-]+$/.test(d)||d.length>8192)&&sn();let{credential:u,requestSha256:p,...h}=i,m={...h,...u!==void 0&&{credentialSha256:Vr(u)},...p!==void 0&&{requestSha256:p}},f=ya("codevibe-desktop-sync-v1\0"+(0,Oi.canonicalize)({userId:this.deps.userId,action:o,payload:m}),l),g=Buffer.from(JSON.stringify({kind:"DESKTOP_SESSION",...h,...u!==void 0&&{credential:u},signature:f})).toString("base64url");(g.length>2048||n!==void 0&&Buffer.byteLength(n)>2048)&&sn();let y=new AbortController,S=()=>y.abort(c?.reason??new Error("Aborted"));c?.addEventListener("abort",S,{once:!0});let b=setTimeout(()=>y.abort(new Tt("SYNC_READ_UNAVAILABLE")),15e3);b.unref?.();let v;try{this.fence(c);let R=await(this.deps.fetch??globalThis.fetch)(this.endpoint+r,{method:e,body:n,redirect:"error",signal:y.signal,headers:{authorization:"Bearer "+d,"content-type":"application/json","cache-control":"no-store","x-codevibe-sync-proof":g,...a}});this.fence(c);let E=R.ok?s:2048,I=R.headers.get("content-length");I!==null&&(!/^(0|[1-9][0-9]*)$/.test(I)||Number(I)>E)&&Xt(),(!/^application\/json(?:\s*;|$)/i.test(R.headers.get("content-type")??"")||!R.body)&&Xt(),v=R.body.getReader();let k=0,P=[];for(;;){let T=await v.read();if(this.fence(c),T.done)break;k+=T.value.byteLength,k>E&&Xt(),P.push(T.value)}let A,C;try{A=new TextDecoder("utf8",{fatal:!0}).decode(Buffer.concat(P)),C=JSON.parse(A)}catch{return Xt()}if(!R.ok)throw QX(R.status,C)?new Tt("SYNC_READ_UNAVAILABLE"):Gg(C);return{text:A,value:C}}finally{y.abort(),clearTimeout(b),c?.removeEventListener("abort",S);try{await v?.cancel()}finally{v?.releaseLock()}}}async socketProof(e,r,n,i){this.fence(i);let o=this.credential(r);(!["CONNECT","HELLO","HEARTBEAT"].includes(e)||(e==="HEARTBEAT"?!Number.isSafeInteger(n)||n<1:n!==void 0))&&sn();let s=await this.deps.getSigningKey();this.fence(i);let a=e==="CONNECT"?await this.deps.getToken(i):void 0;this.fence(i),a!==void 0&&(!/^[A-Za-z0-9_.-]+$/.test(a)||a.length>8192)&&sn();let c={...this.scope,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),...n!==void 0&&{connectionGeneration:n}};(!Number.isSafeInteger(c.issuedAtEpochMs)||c.issuedAtEpochMs<0||c.issuedAtEpochMs>253402289999e3)&&sn();let l=ya("codevibe-desktop-sync-v1\0"+(0,Oi.canonicalize)({userId:this.deps.userId,action:e,payload:{...c,credentialSha256:Vr(o.credential)}}),s),d=Object.freeze({kind:"DESKTOP_SESSION",...c,credential:o.credential,signature:l}),u=Buffer.from(JSON.stringify(d)).toString("base64url");return u.length>2048&&sn(),Object.freeze({input:d,...a!==void 0&&{headers:Object.freeze({Authorization:"Bearer "+a,"X-CodeVibe-Sync-Proof":u})}})}async register(e,r){(!ci(e,["clientOperationId","issuedAtEpochMs"])||!t1.test(e.clientOperationId)||!Number.isSafeInteger(e.issuedAtEpochMs)||e.issuedAtEpochMs<0||e.issuedAtEpochMs>253402300739e3)&&sn();let n={...this.scope,...e},{value:i}=await this.request("POST","/v1/desktop-session/register","{}",n,"REGISTER",2048,{},r);(!ci(i,["ok","receipt","replay"])||i.ok!==!0||typeof i.replay!="boolean")&&Xt();try{return Object.freeze(this.credential(i.receipt))}catch{return Xt()}}async history(e,r,n){let i=this.credential(e);r!==void 0&&!Dc(r)&&sn();let o=JSON.stringify({...this.scope,...r!==void 0&&{nextToken:r}}),s="/v1/event-history",a=Vr((0,Oi.canonicalize)({method:"POST",path:s,body:o})),{value:c}=await this.request("POST",s,o,{...this.scope,credential:i.credential,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),requestSha256:a},"READ",384*1024,{},n);(!ci(c,["version","sessionId","sessionGenerationId","items","nextToken"])||c.version!==1||c.sessionId!==this.scope.sessionId||c.sessionGenerationId!==this.scope.sessionGenerationId||!Array.isArray(c.items)||c.items.length>100||c.nextToken!==null&&!Dc(c.nextToken))&&Xt();let l=c.items.map(d=>this.event(d));return(l.some((d,u)=>u>0&&d.timestamp>=l[u-1].timestamp)||new Set(l.map(d=>d.eventId)).size!==l.length)&&Xt(),Object.freeze({...this.scope,version:1,items:Object.freeze(l),nextToken:c.nextToken})}async exact(e,r,n){let i=this.credential(e);(!ci(r,["eventId","capability","eventSha256"])||typeof r.eventId!="string"||!od.test(r.eventId)||!Dc(r.capability)||typeof r.eventSha256!="string"||!/^[a-f0-9]{64}$/.test(r.eventSha256))&&sn();let o={...r},s=`/v1/sessions/${this.scope.sessionGenerationId}/events/${o.eventId}`,a=Vr((0,Oi.canonicalize)({method:"GET",path:s,capabilitySha256:Vr(o.capability)})),c=await this.request("GET",s,void 0,{...this.scope,credential:i.credential,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),requestSha256:a},"READ",350*1024,{"x-codevibe-sync-capability":o.capability},n);Vr(c.text)!==o.eventSha256&&Xt();let l=this.event(c.value);return l.eventId!==o.eventId&&Xt(),l}async gateResolution(e,r,n){this.fence(n);let i=this.credential(e),o={...this.scope,promptId:r};if(Fg(o,sn),!this.deps.resolutionQuery)throw new Tt("SYNC_READ_UNAVAILABLE");let s=await this.deps.getSigningKey();this.fence(n),await this.deps.getToken(n),this.fence(n);let a={...this.scope,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now()};(!Number.isSafeInteger(a.issuedAtEpochMs)||a.issuedAtEpochMs<0||a.issuedAtEpochMs>253402289999e3)&&sn();let c=ya("codevibe-desktop-sync-v1\0"+(0,Oi.canonicalize)({userId:this.deps.userId,action:"READ",payload:{...a,credentialSha256:Vr(i.credential),requestSha256:Vr((0,Oi.canonicalize)({fieldName:"getGateResolutionV2",input:o}))}}),s),l=JSON.stringify({kind:"DESKTOP_SESSION",...a,credential:i.credential,signature:c}),d={...o,desktopProof:l};Buffer.byteLength(JSON.stringify(d))>2048&&sn();let u=new AbortController,p=()=>u.abort(n?.reason??new Error("Aborted"));n?.addEventListener("abort",p,{once:!0}),n?.aborted&&p();let h=setTimeout(()=>u.abort(new Tt("SYNC_READ_UNAVAILABLE")),15e3);h.unref?.();let m;try{this.fence(u.signal),m=await this.deps.resolutionQuery(d,u.signal),this.fence(u.signal)}finally{clearTimeout(h),n?.removeEventListener("abort",p),u.abort()}let f=ZG(m,o,Xt);if(f.state!=="RESOLVED")return hC(f,null);let g;if(f.exactFetchCapability!==null){let S=`/v1/sessions/${o.sessionGenerationId}/events/${f.resolutionEventId}`,b=Vr((0,Oi.canonicalize)({method:"GET",path:S,capabilitySha256:Vr(f.exactFetchCapability)})),v=await this.request("GET",S,void 0,{...this.scope,credential:i.credential,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),requestSha256:b},"READ",350*1024,{"x-codevibe-sync-capability":f.exactFetchCapability},n);Vr(v.text)!==f.resolutionEventDigest&&Xt(),g=v.value}else{let S="/v1/event-history",b=JSON.stringify({...this.scope,resolutionTarget:{promptId:r,eventId:f.resolutionEventId,timestamp:f.resolutionTimestamp,eventDigest:f.resolutionEventDigest}}),v=Vr((0,Oi.canonicalize)({method:"POST",path:S,body:b})),{value:R}=await this.request("POST",S,b,{...this.scope,credential:i.credential,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),requestSha256:v},"READ",384*1024,{},n);(!ci(R,["version","kind","sessionId","sessionGenerationId","items","nextToken"])||R.version!==1||R.kind!=="GATE_RESOLUTION"||R.sessionId!==o.sessionId||R.sessionGenerationId!==o.sessionGenerationId||!Array.isArray(R.items)||R.items.length!==1||R.nextToken!==null)&&Xt(),g=R.items[0]}let y=e1(g,f,Xt);return this.fence(n),hC(f,y)}async pendingInputs(e,r,n){let i=this.credential(e);r!==void 0&&!Dc(r)&&sn();let o="/v1/event-history",s=JSON.stringify({...this.scope,pendingInputs:!0,...r!==void 0&&{nextToken:r}}),a=Vr((0,Oi.canonicalize)({method:"POST",path:o,body:s})),{value:c}=await this.request("POST",o,s,{...this.scope,credential:i.credential,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),requestSha256:a},"READ",32*1024,{},n);(!ci(c,["version","kind","sessionId","sessionGenerationId","items","nextToken"])||c.version!==1||c.kind!=="PENDING_INPUTS"||c.sessionId!==this.scope.sessionId||c.sessionGenerationId!==this.scope.sessionGenerationId||!Array.isArray(c.items)||c.items.length>32||c.nextToken!==null&&(!Dc(c.nextToken)||c.nextToken===r))&&Xt();let l=c.items.map(d=>((!ci(d,["eventId","timestamp"])||typeof d.eventId!="string"||!od.test(d.eventId)||!$g(d.timestamp))&&Xt(),Object.freeze({eventId:d.eventId,timestamp:d.timestamp})));return(new Set(l.map(d=>d.eventId)).size!==l.length||l.some((d,u)=>u>0&&d.timestamp+"#"+Vr(d.eventId)<=l[u-1].timestamp+"#"+Vr(l[u-1].eventId))||c.nextToken!==null&&l.length===0)&&Xt(),Object.freeze({...this.scope,version:1,kind:"PENDING_INPUTS",items:Object.freeze(l),nextToken:c.nextToken})}async legacyPendingInputs(e,r,n){let i=this.credential(e);r!==void 0&&!Dc(r)&&sn();let o="/v1/event-history",s=JSON.stringify({...this.scope,pendingInputs:"LEGACY",...r!==void 0&&{nextToken:r}}),a=Vr((0,Oi.canonicalize)({method:"POST",path:o,body:s})),{value:c}=await this.request("POST",o,s,{...this.scope,credential:i.credential,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),requestSha256:a},"READ",32*1024,{},n);(!ci(c,["version","kind","sessionId","sessionGenerationId","items","nextToken"])||c.version!==1||c.kind!=="LEGACY_PENDING_INPUTS"||c.sessionId!==this.scope.sessionId||c.sessionGenerationId!==this.scope.sessionGenerationId||!Array.isArray(c.items)||c.items.length>32||c.nextToken!==null&&(!Dc(c.nextToken)||c.nextToken===r))&&Xt();let l=c.items.map(d=>((!ci(d,["eventId","timestamp"])||typeof d.eventId!="string"||!od.test(d.eventId)||!$g(d.timestamp))&&Xt(),Object.freeze({eventId:d.eventId,timestamp:d.timestamp})));return(new Set(l.map(d=>d.eventId)).size!==l.length||l.some((d,u)=>u>0&&d.timestamp+"#"+Vr(d.eventId)<=l[u-1].timestamp+"#"+Vr(l[u-1].eventId)))&&Xt(),Object.freeze({...this.scope,version:1,kind:"LEGACY_PENDING_INPUTS",items:Object.freeze(l),nextToken:c.nextToken})}async pendingInput(e,r,n){let i=await this.coordinateEvent(e,r,n);return i&&(i.source!=="MOBILE"||!["USER_PROMPT","PROMPT_RESPONSE"].includes(i.type)||!["SENT","DELIVERED","EXECUTED"].includes(i.deliveryStatus)||typeof i.syncEventRevision!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(i.syncEventRevision)||BigInt(i.syncEventRevision)>(1n<<63n)-1n)&&Xt(),i}async recoverExact(e,r,n){let i={...r},o=await this.recoverCurrent(e,i,n);if(!o)throw new Tt("SYNC_READ_UNAVAILABLE","EVENT_FETCH_UNAVAILABLE");return(o.syncEventRevision!==i.eventRevision||Vr((0,Oi.canonicalize)(o))!==i.eventSha256)&&Xt(),o}async recoverCurrent(e,r,n){let i={...r},o=await this.targetedEvent(e,i,n);return o?((typeof o.syncEventRevision!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(o.syncEventRevision)||BigInt(o.syncEventRevision)>(1n<<63n)-1n||BigInt(o.syncEventRevision)<BigInt(i.eventRevision)||o.syncEventRevision===i.eventRevision&&Vr((0,Oi.canonicalize)(o))!==i.eventSha256)&&Xt(),o):null}async executionReceipt(e,r,n){let i={...r},o=await this.recoverCurrent(e,i,n);return o?((o.source!=="MOBILE"||!["USER_PROMPT","PROMPT_RESPONSE"].includes(o.type)||!["SENT","DELIVERED","EXECUTED"].includes(o.deliveryStatus)||typeof o.syncEventRevision!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(o.syncEventRevision)||BigInt(o.syncEventRevision)>(1n<<63n)-1n||BigInt(o.syncEventRevision)<BigInt(i.eventRevision))&&Xt(),o.deliveryStatus==="EXECUTED"?Object.freeze({...this.scope,eventId:o.eventId,timestamp:o.timestamp,source:"MOBILE",type:o.type,deliveryStatus:"EXECUTED"}):null):null}async targetedEvent(e,r,n){return(!ci(r,["eventId","timestamp","eventRevision","eventSha256"])||typeof r.eventId!="string"||!od.test(r.eventId)||!$g(r.timestamp)||typeof r.eventRevision!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(r.eventRevision)||BigInt(r.eventRevision)>(1n<<63n)-1n||typeof r.eventSha256!="string"||!/^[a-f0-9]{64}$/.test(r.eventSha256))&&sn(),this.coordinateEvent(e,{eventId:r.eventId,timestamp:r.timestamp},n)}async coordinateEvent(e,r,n){let i=this.credential(e);(!ci(r,["eventId","timestamp"])||typeof r.eventId!="string"||!od.test(r.eventId)||!$g(r.timestamp))&&sn();let o={...r},s="/v1/event-history",a=JSON.stringify({...this.scope,target:{eventId:o.eventId,timestamp:o.timestamp}}),c=Vr((0,Oi.canonicalize)({method:"POST",path:s,body:a})),{value:l}=await this.request("POST",s,a,{...this.scope,credential:i.credential,clientOperationId:(0,Po.randomUUID)(),issuedAtEpochMs:this.now(),requestSha256:c},"READ",384*1024,{},n);if((!ci(l,["version","sessionId","sessionGenerationId","items","nextToken"])||l.version!==1||l.sessionId!==this.scope.sessionId||l.sessionGenerationId!==this.scope.sessionGenerationId||!Array.isArray(l.items)||l.items.length>1||l.nextToken!==null)&&Xt(),l.items.length===0)return null;let d=this.event(l.items[0]);return(d.eventId!==o.eventId||d.timestamp!==o.timestamp)&&Xt(),d}}});function Wp(t,e){let r=XX.safeParse(t);if(!r.success)return e();let n=r.data;return n.state==="READY"&&(n.receipt.sessionId!==n.sessionId||n.receipt.sessionGenerationId!==n.sessionGenerationId||n.receipt.expiresAtEpochMs<=n.createdAtEpochMs||Buffer.from(n.receipt.credential,"base64url").toString("base64url")!==n.receipt.credential)?e():n}function s1(t){let e=i=>{if(i?.aborted)throw i.reason??new Error("Aborted")},r=()=>Wp({schemaVersion:1,kind:"DESKTOP_REGISTRATION",operationId:t.id,...t.scope,state:"PENDING",clientOperationId:(0,n1.randomUUID)(),createdAtEpochMs:t.now()},t.invalid),n=async(i,o)=>{await o(),await t.write(Wp(i,t.invalid))};return Object.freeze({credential:(i,o=!1)=>t.locked(async s=>{e(i);let a=await t.read();if(await s(),e(i),a?.state==="READY"&&a.receipt.expiresAtEpochMs>t.now()&&!o)return Object.freeze({...a.receipt});(!a||a.state==="READY"&&a.receipt.expiresAtEpochMs<=t.now())&&(a=r(),await n(a,s));let c={clientOperationId:a.clientOperationId,issuedAtEpochMs:t.now()};if(!i1.safeParse(c.issuedAtEpochMs).success)return t.invalid();e(i),await s();let l;try{l=await t.register(c,i)}catch(h){if(e(i),await s(),h instanceof Tt&&h.backendCode==="DESKTOP_REGISTRATION_EXPIRED"){let m=await t.read();if(!m||m.clientOperationId!==a.clientOperationId||m.state!==a.state)return t.invalid();await n(r(),s)}throw h}e(i),await s();let d=uk.safeParse(l);if(!d.success||d.data.sessionId!==t.scope.sessionId||d.data.sessionGenerationId!==t.scope.sessionGenerationId||d.data.expiresAtEpochMs<=t.now())return t.invalid();let u=await t.read();if(!u||u.clientOperationId!==a.clientOperationId||u.state!==a.state||u.state==="READY"&&u.receipt.credential!==d.data.credential)return t.invalid();let p=Wp({...u,state:"READY",receipt:d.data},t.invalid);return await n(p,s),e(i),Object.freeze({...d.data})}),invalidate:i=>{let o=uk.safeParse(i);if(!o.success)return Promise.reject(new Tt("INVALID_SYNC_READ_INPUT"));let s=o.data;return t.locked(async a=>{let c=await t.read();return!c||c.state!=="READY"||c.receipt.sessionId!==s.sessionId||c.receipt.sessionGenerationId!==s.sessionGenerationId||c.receipt.credential!==s.credential?!1:(await n(r(),a),!0)})},renew:(i,o)=>t.locked(async s=>{let a=uk.safeParse(i),c=await t.read();return!a.success||!c||c.state!=="READY"||c.receipt.credential!==a.data.credential||c.sessionId!==a.data.sessionId||c.sessionGenerationId!==a.data.sessionGenerationId||!gC.safeParse(o).success||o<=t.now()||o>t.now()+1086e4?t.invalid():(o>c.receipt.expiresAtEpochMs&&(c.receipt={...c.receipt,expiresAtEpochMs:o},await n(c,s)),await s(),Object.freeze({...c.receipt}))})})}function yC(t,e){let r=!1,n,i=new Map,o=(a,c)=>{if(r)return Promise.reject(new Tt("SYNC_READ_UNAVAILABLE"));let l=new AbortController,d=()=>l.abort(c?.reason??new Error("Aborted"));c?.addEventListener("abort",d,{once:!0}),c?.aborted&&d();let u=Promise.resolve().then(()=>{if(l.signal.aborted)throw l.signal.reason;return a(l.signal)}).finally(()=>{c?.removeEventListener("abort",d),i.delete(u)});return i.set(u,l),u},s=async(a,c)=>{let l=await e.credential(c);try{return await a(l)}catch(d){throw c?.aborted?c.reason:(d instanceof Tt&&d.backendCode==="DESKTOP_SESSION_STALE"&&await e.invalidate(l),d)}};return Object.freeze({credential:(a,c=!1)=>o(l=>e.credential(l,c),a),renew:(a,c)=>o(async l=>{if(l.aborted)throw l.reason;return e.renew({...a},c)}),history:(a,c)=>o(l=>s(d=>t.history(d,a,l),l),c),gateResolution:(a,c)=>o(l=>s(d=>t.gateResolution(d,a,l),l),c),pendingInputs:(a,c)=>o(l=>s(d=>t.pendingInputs(d,a,l),l),c),legacyPendingInputs:(a,c)=>o(l=>s(d=>t.legacyPendingInputs(d,a,l),l),c),pendingInput:(a,c)=>{let l={...a};return o(d=>s(u=>t.pendingInput(u,l,d),d),c)},exact:(a,c)=>{let l={...a};return o(d=>s(u=>t.exact(u,l,d),d),c)},recoverExact:(a,c)=>{let l={...a};return o(d=>s(u=>t.recoverExact(u,l,d),d),c)},recoverCurrent:(a,c)=>{let l={...a};return o(d=>s(u=>t.recoverCurrent(u,l,d),d),c)},executionReceipt:(a,c)=>{let l={...a};return o(d=>s(u=>t.executionReceipt(u,l,d),d),c)},close:()=>{if(n)return n;r=!0;for(let a of i.values())a.abort(new Tt("SYNC_READ_UNAVAILABLE"));return n=Promise.allSettled([...i.keys()]).then(()=>{}),n}})}var n1,so,mC,gC,i1,o1,uk,r1,XX,wC=D(()=>{"use strict";n1=require("node:crypto"),so=require("zod");Hp();mC=so.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),gC=so.z.number().int().nonnegative().max(253402300799e3),i1=gC.max(253402300799e3-108e5),o1={sessionId:so.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),sessionGenerationId:mC},uk=so.z.object({...o1,credential:so.z.string().regex(/^[A-Za-z0-9_-]{43}$/),expiresAtEpochMs:gC}).strict(),r1={schemaVersion:so.z.literal(1),kind:so.z.literal("DESKTOP_REGISTRATION"),operationId:mC,...o1,clientOperationId:mC,createdAtEpochMs:i1},XX=so.z.discriminatedUnion("state",[so.z.object({...r1,state:so.z.literal("PENDING")}).strict(),so.z.object({...r1,state:so.z.literal("READY"),receipt:uk}).strict()])});function Hg(t){let e=eZ.safeParse(t);return!e.success||new Set(e.data.entries.map(r=>r.target.eventId)).size!==e.data.entries.length||e.data.entries.some(r=>r.remoteExecuted&&r.state!=="DISPATCHING"||r.localExecuted&&r.state==="RECEIVED")?li():e.data}function c1(t){let e=async()=>{let o=await t.read()??{schemaVersion:1,kind:"DESKTOP_INBOUND",operationId:t.id,...t.scope,entries:[]},s=Hg(o);return s.operationId!==t.id||s.sessionId!==t.scope.sessionId||s.sessionGenerationId!==t.scope.sessionGenerationId?li():s},r=async(o,s)=>{await s(),await t.write(Hg(o))},n=o=>{if(o?.aborted)throw o.reason??new Error("Aborted")},i=async(o,s)=>{let a=o.source==="MOBILE"&&["USER_PROMPT","PROMPT_RESPONSE"].includes(o.type);if(o.sessionId!==t.scope.sessionId||o.sessionGenerationId!==t.scope.sessionGenerationId||!s&&!a||a&&!["SENT","DELIVERED"].includes(o.deliveryStatus))return li();let c=qp.parse({eventId:o.eventId,timestamp:o.timestamp,eventRevision:o.syncEventRevision,eventSha256:(0,pk.createHash)("sha256").update((0,Mc.canonicalize)(o)).digest("hex")}),l=a&&o.deliveryStatus==="DELIVERED";return t.locked(async d=>{let u=await e(),p=u.entries.find(h=>h.target.eventId===c.eventId);if(p)return p.target.timestamp!==c.timestamp||BigInt(c.eventRevision)<BigInt(p.target.eventRevision)||c.eventRevision===p.target.eventRevision&&c.eventSha256!==p.target.eventSha256?li():p.state!=="RECEIVED"?"RETAINED":(p.target=c,l&&(p.state="UNCERTAIN"),await r(u,d),l?"RETAINED":"RECEIVED");if(s)return li();if(u.entries.length>=64)throw new Ug("SYNC_INBOUND_FULL");return u.entries.push({target:c,state:l?"UNCERTAIN":"RECEIVED",remoteExecuted:!1,localExecuted:!1}),await r(u,d),l?"RETAINED":"RECEIVED"})};return Object.freeze({stageDiscovered:o=>i(o,!1),refreshReceived:o=>i(o,!0),retainMissing:o=>{let s=qp.parse(o);return t.locked(async a=>{let c=await e(),l=c.entries.find(d=>d.target.eventId===s.eventId);if(!l||l.target.timestamp!==s.timestamp)return li();l.state==="RECEIVED"&&(l.state="UNCERTAIN",await r(c,a))})},stage:async o=>{let s=qp.safeParse(o);if(!s.success)return li();let a=s.data;return t.locked(async c=>{let l=await e(),d=l.entries.find(u=>u.target.eventId===a.eventId);if(d)return d.target.timestamp!==a.timestamp?li():BigInt(a.eventRevision)<BigInt(d.target.eventRevision)?"RETAINED":a.eventRevision===d.target.eventRevision&&a.eventSha256!==d.target.eventSha256?li():d.state==="RECEIVED"?"RECEIVED":"RETAINED";if(l.entries.length>=64)throw new Ug("SYNC_INBOUND_FULL");return l.entries.push({target:a,state:"RECEIVED",remoteExecuted:!1,localExecuted:!1}),await r(l,c),"RECEIVED"})},recoverable:()=>t.dispatchLocked(async o=>t.locked(async s=>{let a=await e(),c=!1;for(let l of[...a.entries])l.state==="DISPATCHING"&&(l.remoteExecuted?a.entries=a.entries.filter(d=>d!==l):l.state="UNCERTAIN",c=!0);return await o(),c&&await r(a,s),{pending:Object.freeze(a.entries.filter(l=>l.state==="RECEIVED").map(l=>Object.freeze({...l.target}))),uncertain:a.entries.filter(l=>l.state==="UNCERTAIN"&&!l.localExecuted).length}})),pendingAcknowledgements:()=>t.locked(async()=>{let o=await e();return Object.freeze(o.entries.filter(s=>s.state==="HANDED_OFF"||s.state==="UNCERTAIN").map(s=>Object.freeze({...s.target})))}),hasCompletedHandoff:o=>t.locked(async()=>{let s=qp.parse(o);return(await e()).entries.some(c=>c.localExecuted&&(c.state==="HANDED_OFF"||c.state==="UNCERTAIN")&&(0,Mc.canonicalize)(c.target)===(0,Mc.canonicalize)(s))}),markExecutedLocally:async o=>{if(o.sessionId!==t.scope.sessionId||o.sessionGenerationId!==t.scope.sessionGenerationId||o.source!=="MOBILE"||!["USER_PROMPT","PROMPT_RESPONSE"].includes(o.type)||o.deliveryStatus!=="EXECUTED"||!hk.safeParse(o.eventId).success||!bC.safeParse(o.timestamp).success)return!1;let s={...o};return t.locked(async a=>{let c=await e(),l=c.entries.find(d=>d.target.eventId===s.eventId&&d.target.timestamp===s.timestamp);return!l||l.state==="RECEIVED"?!1:(l.localExecuted||(l.localExecuted=!0,await r(c,a)),!0)})},dispatch:(o,s,a)=>t.dispatchLocked(async c=>{if(n(a),await c(),o.sessionId!==t.scope.sessionId||o.sessionGenerationId!==t.scope.sessionGenerationId||o.source!=="MOBILE"||!["USER_PROMPT","PROMPT_RESPONSE"].includes(o.type)||!["SENT","DELIVERED"].includes(o.deliveryStatus))return li();let l=qp.parse({eventId:o.eventId,timestamp:o.timestamp,eventRevision:o.syncEventRevision,eventSha256:(0,pk.createHash)("sha256").update((0,Mc.canonicalize)(o)).digest("hex")});if(!await t.locked(async p=>{let h=await e(),m=h.entries.find(f=>f.target.eventId===o.eventId);return!m||(0,Mc.canonicalize)(m.target)!==(0,Mc.canonicalize)(l)?li():m.state!=="RECEIVED"?(m.state==="DISPATCHING"&&(m.remoteExecuted?h.entries=h.entries.filter(f=>f!==m):m.state="UNCERTAIN",await r(h,p)),!1):(n(a),m.state="DISPATCHING",await r(h,p),!0)}))return"RETAINED";let u=p=>t.locked(async h=>{let m=await e(),f=m.entries.find(g=>g.target.eventId===o.eventId);if(!f||f.state!=="DISPATCHING")return li();f.remoteExecuted?m.entries=m.entries.filter(g=>g!==f):f.state=p,await c(),await r(m,h)});try{n(a),await c(),n(a)}catch(p){throw await u("RECEIVED"),p}try{await s()}catch(p){throw await u("UNCERTAIN"),p}return await u("HANDED_OFF"),"HANDED_OFF"}),releaseNonInput:o=>t.locked(async s=>{if(o.sessionId!==t.scope.sessionId||o.sessionGenerationId!==t.scope.sessionGenerationId||o.source==="MOBILE"&&["USER_PROMPT","PROMPT_RESPONSE"].includes(o.type))return li();let a=await e(),c=a.entries.find(l=>l.target.eventId===o.eventId);if(!c||c.state!=="RECEIVED"||c.target.timestamp!==o.timestamp||c.target.eventRevision!==o.syncEventRevision||c.target.eventSha256!==(0,pk.createHash)("sha256").update((0,Mc.canonicalize)(o)).digest("hex"))return li();a.entries=a.entries.filter(l=>l!==c),await r(a,s)}),acknowledgeExecuted:async o=>{if(o.sessionId!==t.scope.sessionId||o.sessionGenerationId!==t.scope.sessionGenerationId||o.source!=="MOBILE"||!["USER_PROMPT","PROMPT_RESPONSE"].includes(o.type)||o.deliveryStatus!=="EXECUTED"||!hk.safeParse(o.eventId).success||!bC.safeParse(o.timestamp).success)return!1;let s={...o};return t.locked(async a=>{let c=await e(),l=c.entries.find(d=>d.target.eventId===s.eventId&&d.target.timestamp===s.timestamp);return l?(l.state==="DISPATCHING"?l.remoteExecuted=!0:c.entries=c.entries.filter(d=>d!==l),await r(c,a),!0):!1})}})}var pk,Mc,di,hk,a1,bC,qp,ZX,eZ,Ug,li,l1=D(()=>{"use strict";pk=require("node:crypto"),Mc=require("json-freeze"),di=require("zod"),hk=di.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),a1=di.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),bC=di.z.string().regex(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/).refine(t=>Number.isFinite(Date.parse(t))&&new Date(t).toISOString()===t),qp=di.z.object({eventId:hk,timestamp:bC,eventRevision:di.z.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(t=>BigInt(t)<=(1n<<63n)-1n),eventSha256:di.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),ZX=di.z.object({target:qp,state:di.z.enum(["RECEIVED","DISPATCHING","HANDED_OFF","UNCERTAIN"]),remoteExecuted:di.z.boolean(),localExecuted:di.z.boolean().default(!1)}).strict(),eZ=di.z.object({schemaVersion:di.z.literal(1),kind:di.z.literal("DESKTOP_INBOUND"),operationId:a1,sessionId:hk,sessionGenerationId:a1,entries:di.z.array(ZX).max(64)}).strict(),Ug=class extends Error{constructor(r){super(r);this.code=r;this.name="SyncInboundError"}},li=()=>{throw new Ug("SYNC_INBOUND_INVALID")}});function Wg(t){let e=nZ.parse(t);if(new Set(e.entries.map(n=>n.eventId)).size!==e.entries.length)throw Error("SYNC_DEFERRED_INPUT_INVALID");let r=new Set;for(let n of e.entries){if(!n.notice)continue;let i=n.notice;if(i.state==="STAGED"&&(i.input.sessionId!==e.sessionId||i.input.sessionGenerationId!==e.sessionGenerationId))throw Error("SYNC_DEFERRED_INPUT_INVALID");let o=i.state==="STAGED"?i.input.clientOperationId:i.operationId;if(r.has(o))throw Error("SYNC_DEFERRED_INPUT_INVALID");r.add(o)}return e}function ad(t){return(0,d1.createHash)("sha256").update(t.notice===void 0?t.payloadJson:"codevibe-deferred-notice-v1\0"+(0,u1.canonicalize)({payloadJson:t.payloadJson,notice:t.notice})).digest("hex")}function vC(t){return h1.parse(t)}function fk(t,e){return t.sessionId===e.sessionId&&t.sessionGenerationId===e.sessionGenerationId}var Zr,d1,u1,p1,SC,tZ,rZ,h1,nZ,mk=D(()=>{"use strict";Zr=require("zod"),d1=require("node:crypto"),u1=require("json-freeze");Ln();p1=Zr.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),SC=Zr.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),tZ=Zr.z.string().regex(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/).refine(t=>Number.isFinite(Date.parse(t))&&new Date(t).toISOString()===t),rZ=Zr.z.discriminatedUnion("state",[Zr.z.object({state:Zr.z.literal("STAGED"),input:Zr.z.unknown().transform(t=>{let e=Mn("CREATE_EVENT",t);if(e.type!=="NOTIFICATION"||ed.some(r=>r in e))throw Error("SYNC_DEFERRED_INPUT_INVALID");return delete e.source,e})}).strict(),Zr.z.object({state:Zr.z.literal("SETTLED"),operationId:SC,status:Zr.z.enum(["ACCEPTED","OMITTED"])}).strict()]),h1=Zr.z.object({eventId:p1,timestamp:tZ,type:Zr.z.enum(["USER_PROMPT","PROMPT_RESPONSE"]),payloadJson:Zr.z.string().max(512*1024).refine(t=>{try{return Buffer.byteLength(t)<=512*1024&&typeof JSON.parse(t)=="object"&&JSON.parse(t)!==null}catch{return!1}}),notice:rZ.optional()}).strict(),nZ=Zr.z.object({schemaVersion:Zr.z.literal(1),kind:Zr.z.literal("DEFERRED_INPUTS"),operationId:SC,sessionId:p1,sessionGenerationId:SC,provider:Zr.z.enum(["codex","claude","agy"]),nativeSessionSha256:Zr.z.string().regex(/^[a-f0-9]{64}$/),entries:Zr.z.array(h1).max(64)}).strict()});function gk(t){let e=iZ.parse(t);if(new Set(e.entries.map(r=>r.token)).size!==e.entries.length||e.entries.some(r=>r.token!==b1(r.target)))throw Error("SYNC_MOBILE_ECHO_INVALID");return e}function S1(t){return Object.freeze({arm:(r,n,i)=>{let o=g1.parse(r),s=kC(n,i.normalization),a=w1.parse({token:b1(o),target:o,normalized:s,armedAt:i.nowMs,expiresAt:i.nowMs+i.windowMs,clockPrecisionMs:i.clockPrecisionMs??1,allowSuffix:i.allowSuffix,normalization:i.normalization,claim:null,claimedEchoSha256:null});return t.assertAdmission(),t.mutate(async(c,l)=>{t.assertAdmission();let d=c.entries.find(u=>u.token===a.token);if(d)return d.normalized!==a.normalized||d.allowSuffix!==a.allowSuffix||d.clockPrecisionMs!==a.clockPrecisionMs||d.normalization!==a.normalization?t.collision():void 0;if(c.entries.length>=64)return t.full();c.entries.push(a),await l()})},claim:(r,n,i)=>{let o=y1.parse(r),s=c=>(0,EC.createHash)("sha256").update(kC(n,c.normalization)).digest("hex"),a=Date.parse(i);if(!Number.isFinite(a))throw Error("SYNC_MOBILE_ECHO_TIMESTAMP_INVALID");return t.mutate(async(c,l)=>{let d=c.entries.find(p=>p.claim?.streamSha256===o.streamSha256&&p.claim?.occurrence===o.occurrence);if(d)return JSON.stringify(d.claim)!==JSON.stringify(o)||d.claimedEchoSha256!==s(d)?t.collision():!0;let u=c.entries.find(p=>{let h=kC(n,p.normalization);return!p.claim&&a>=Math.floor(p.armedAt/p.clockPrecisionMs)*p.clockPrecisionMs&&a<=p.expiresAt&&(p.normalized===h||p.allowSuffix&&h.length>=16&&h.length/p.normalized.length>=.35&&p.normalized.endsWith(h))});return u?(u.claim=o,u.claimedEchoSha256=s(u),await l(),!0):!1})},reconcile:(r,n)=>(qg.parse(r),Kg.parse(n),t.mutate(async(i,o)=>{let s=i.entries.length;i.entries=i.entries.filter(c=>!c.claim||c.claim.streamSha256!==r||c.claim.endOffset>n);let a=s-i.entries.length;return a&&await o(),a}))})}var Dr,EC,qg,m1,f1,Kg,g1,y1,w1,iZ,kC,b1,v1=D(()=>{"use strict";Dr=require("zod"),EC=require("node:crypto"),qg=Dr.z.string().regex(/^[a-f0-9]{64}$/),m1=Dr.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),f1=Dr.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),Kg=Dr.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),g1=Dr.z.object({eventId:m1,timestamp:Dr.z.string().datetime({offset:!0}),type:Dr.z.enum(["USER_PROMPT","PROMPT_RESPONSE"]),lane:Dr.z.enum(["primary","follow_up","free_form"])}).strict(),y1=Dr.z.object({streamSha256:qg,occurrence:Dr.z.string().regex(/^[A-Za-z0-9_:-]{1,256}$/),sourceSha256:qg,startOffset:Kg,endOffset:Kg}).strict().refine(t=>t.endOffset>t.startOffset),w1=Dr.z.object({token:qg,target:g1,normalized:Dr.z.string().min(1).max(256*1024),armedAt:Kg,expiresAt:Kg,clockPrecisionMs:Dr.z.union([Dr.z.literal(1),Dr.z.literal(1e3)]),normalization:Dr.z.enum(["trim","whitespace"]),allowSuffix:Dr.z.boolean(),claim:y1.nullable(),claimedEchoSha256:qg.nullable()}).strict().refine(t=>Buffer.byteLength(t.normalized)<=256*1024&&t.expiresAt>=t.armedAt&&t.expiresAt-t.armedAt<=6e4&&t.claim===null==(t.claimedEchoSha256===null)),iZ=Dr.z.object({schemaVersion:Dr.z.literal(1),kind:Dr.z.literal("MOBILE_ECHOES"),operationId:f1,sessionId:m1,sessionGenerationId:f1,provider:Dr.z.enum(["codex","claude","agy"]),entries:Dr.z.array(w1).max(64)}).strict(),kC=(t,e)=>e==="trim"?t.trim():t.replace(/\s+/g," ").trim(),b1=t=>(0,EC.createHash)("sha256").update(JSON.stringify(t)).digest("hex")});function Vg(t){let e=sZ.parse(t);if(new Set(e.entries.map(r=>r.promptId)).size!==e.entries.length||e.entries.some(r=>r.status==="REFRESHED"&&(r.checkAfter<r.checkedAt||r.checkAfter>r.checkedAt+864e5)))throw Error("SYNC_PROMPT_RETENTION_INVALID");return e}function E1(t){return Object.freeze({run:(r,n,i,o=Date.now)=>{let s=[...new Set(ui.z.array(jg).max(4096).parse(r))].sort();return t.runExclusive(async a=>{let c=await t.read(),l=new Set(s),d=async()=>{await a(),await t.write(Vg(c)),await a()},u=c.entries.filter(g=>l.has(g.promptId)||g.status==="RERAISE_REQUIRED");u.length!==c.entries.length&&(c.entries=u,await d());let p=async g=>{await a();let y=c.entries.find(b=>b.promptId===g);if(y?.status!=="RERAISE_REQUIRED")throw Error("SYNC_PROMPT_RETENTION_INVALID");let S=await i(g,y.reRaiseToken);if(await a(),S==="RETRY")throw Error("SYNC_PROMPT_RERAISE_PENDING");if(S!=="CLOSED"&&S!=="RERAISED"&&S!=="OMITTED")throw Error("SYNC_PROMPT_RETENTION_INVALID");c.entries=c.entries.filter(b=>b.promptId!==g),await d()},h=c.cursor===null?0:s.findIndex(g=>g>c.cursor),m=h<0?0:h,f=[...s.slice(m),...s.slice(0,m)];for(let g of f){let y=yk.parse(o()),S=c.entries.find(E=>E.promptId===g);if(S?.status==="REFRESHED"&&y>=S.checkedAt&&y<S.checkAfter)continue;if(!S&&c.entries.length>=4096)throw Error("SYNC_JOURNAL_FULL");if(c.cursor=g,await d(),S?.status==="RERAISE_REQUIRED"){await p(g);continue}await a();let b=Lv(await n(g),g);await a();let v=yk.parse(o()),R=b.status==="RERAISE_REQUIRED"?{...b,reRaiseToken:(0,k1.randomUUID)()}:{...b,checkedAt:v,checkAfter:Math.max(v,Math.min(v+864e5,b.expiresAt*1e3-864e5))};c.entries=c.entries.filter(E=>E.promptId!==g),c.entries.push(R),await d(),b.status==="RERAISE_REQUIRED"&&await p(g)}})},remove:()=>t.runExclusive(async r=>{await r(),await t.remove(),await r()})})}var ui,k1,jg,RC,yk,oZ,sZ,R1=D(()=>{"use strict";ui=require("zod"),k1=require("node:crypto");Ln();jg=ui.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),RC=ui.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),yk=ui.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),oZ=ui.z.union([ui.z.object({promptId:jg,status:ui.z.literal("REFRESHED"),checkedAt:yk,checkAfter:yk,expiresAt:ui.z.number().int().positive().max(253402300799)}).strict(),ui.z.object({promptId:jg,status:ui.z.literal("RERAISE_REQUIRED"),reRaiseToken:RC}).strict()]),sZ=ui.z.object({schemaVersion:ui.z.literal(1),kind:ui.z.literal("PROMPT_RETENTION"),operationId:RC,sessionId:jg,sessionGenerationId:RC,cursor:jg.nullable(),entries:ui.z.array(oZ).max(4096)}).strict()});function cd(t,e){let r=cZ.safeParse(t);if(!r.success)return e();let n=r.data;if(n.state==="STAGED"){let i=Mn("CREATE_EVENT",n.input);if(i.sessionId!==n.sessionId||i.sessionGenerationId!==n.sessionGenerationId||i.clientOperationId!==n.writeId||i.promptId!==n.promptId||i.type!==n.eventType)return e()}else n.result.status==="ACCEPTED"&&(n.result.receipt=Ps(n.result.receipt,{sessionId:n.sessionId,type:n.eventType}));return n}function T1(t){let e=async(r,n,i)=>{if(await n(),r.state==="SETTLED")return await t.acknowledge(r.writeId),await n(),r.result;if(await t.prepare(r.input)!==r.writeId)return t.invalid();await n();let o=await t.retry(r.writeId,i);await n();let{input:s,...a}=r,c=cd({...a,state:"SETTLED",result:o},t.invalid);return await t.write(c),await n(),await t.acknowledge(r.writeId),await n(),o};return Object.freeze({publish:(r,n,i={})=>{if(!/^[a-f0-9]{64}$/.test(r)||typeof n!="function"||i.reRaiseToken!==void 0&&!Kp.safeParse(i.reRaiseToken).success)return t.invalid();let o=i.reRaiseToken??null,s=i.signal;return t.locked(async a=>{let c=async()=>{if(s?.aborted)throw s.reason??Error("Aborted");t.assertAdmission(),await a(),await t.assertOpen(),await a()};await c();let l=await t.read();if(l?.state==="SETTLED"){if(await c(),await t.acknowledge(l.writeId),await c(),l.sourceSha256===r&&(l.result.status==="OMITTED"||o===null||o===l.reRaiseToken))return l.result;l=null}if(l&&l.sourceSha256!==r)return t.collision();if(!l){let u=(0,A1.randomUUID)(),p=Mn("CREATE_EVENT",await n(u));delete p.source,await c();let h={schemaVersion:1,kind:"PROMPT_PUBLICATION",operationId:t.id,...t.scope,promptId:t.promptId,sourceSha256:r,writeId:u,reRaiseToken:o,eventType:p.type,state:"STAGED",input:p};l=cd(h,t.invalid),await t.write(l),await c()}if(l.state!=="STAGED")return t.invalid();let d=await e(l,c,s);return d.status==="ACCEPTED"&&o!==null&&o!==l.reRaiseToken?t.pending():d})},settle:r=>t.locked(async n=>{let i=async()=>{if(r?.aborted)throw r.reason??Error("Aborted");await n()};await i();let o=await t.read();return await i(),o?e(o,i,r):null}),close:()=>t.locked(async r=>{await r();let n=await t.read();return n?n.state==="STAGED"?t.pending():(await t.acknowledge(n.writeId),await r(),await t.remove(),await r(),!0):!1})})}var A1,en,Kp,I1,aZ,cZ,P1=D(()=>{"use strict";A1=require("node:crypto"),en=require("zod");Ln();Kp=en.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),I1={schemaVersion:en.z.literal(1),kind:en.z.literal("PROMPT_PUBLICATION"),operationId:Kp,sessionId:en.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),sessionGenerationId:Kp,promptId:Kp,sourceSha256:en.z.string().regex(/^[a-f0-9]{64}$/),eventType:en.z.enum(["INTERACTIVE_PROMPT","NOTIFICATION"]),writeId:Kp,reRaiseToken:Kp.nullable()},aZ=en.z.discriminatedUnion("status",[en.z.object({status:en.z.literal("ACCEPTED"),receipt:en.z.unknown()}).strict(),en.z.object({status:en.z.literal("OMITTED"),reason:en.z.literal("SYNC_QUOTA_EXHAUSTED")}).strict()]),cZ=en.z.discriminatedUnion("state",[en.z.object({...I1,state:en.z.literal("STAGED"),input:en.z.unknown()}).strict(),en.z.object({...I1,state:en.z.literal("SETTLED"),result:aZ}).strict()])});function jp(){throw new ve("INVALID_SYNC_INPUT")}function Vp(t){(!AC(t)||Reflect.ownKeys(t).some(n=>typeof n!="string"))&&jp();let e={};for(let[n,i]of Object.entries(Object.getOwnPropertyDescriptors(t)))(!i.enumerable||!("value"in i)||typeof i.value!="string")&&jp(),e[n]=i.value;let r=["clientOperationId","sessionId","promptId","producerKind",...e.producerKind==="PLUGIN_APPROVAL"?["ownerToken"]:["sessionGenerationId","expectedSessionKeyGen"]];return(Object.keys(e).length!==r.length||Object.keys(e).some(n=>!r.includes(n))||!IC.test(e.clientOperationId)||!lZ.test(e.sessionId)||!IC.test(e.promptId))&&jp(),e.producerKind==="PLUGIN_APPROVAL"?(!/^[A-Za-z0-9_-]{32,128}$/.test(e.ownerToken)||e.promptId!==fa(e.ownerToken))&&jp():(e.producerKind!=="CORE_OFFER"||!IC.test(e.sessionGenerationId)||!/^[A-Za-z0-9_-]{1,128}$/.test(e.expectedSessionKeyGen))&&jp(),Object.freeze(e)}function bk(t,e){(typeof t!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t))&&jp();let r=Vp({...e,clientOperationId:_1}),{clientOperationId:n,...i}=r;return Object.freeze({...i,clientOperationId:(0,wk.v5)((0,C1.canonicalize)({userId:t,...i}),_1)})}function Sk(t,e,r){if(!AC(t)||Object.keys(t).sort().join(",")!=="input,kind,operationId,schemaVersion"||t.schemaVersion!==1||t.kind!=="PROMPT_RESOLUTION")return r();let n;try{n=Vp(t.input)}catch{return r()}let{clientOperationId:i,...o}=n;return t.operationId!==i||bk(e,o).clientOperationId!==i?r():{schemaVersion:1,kind:"PROMPT_RESOLUTION",operationId:i,input:n}}function x1(t,e){let r=()=>{throw new ve("INVALID_SYNC_RECEIPT")};if(typeof t=="string"){Buffer.byteLength(t)>2048&&r();try{t=JSON.parse(t)}catch{r()}}(!AC(t)||Object.keys(t).sort().join(",")!=="controlClass,promptId,sessionId,state")&&r();let n=t;return(n.sessionId!==e.sessionId||n.promptId!==e.promptId||n.state!=="RESOLVED"||n.controlClass!=="PROMPT_OWNERSHIP")&&r(),Object.freeze({...n})}var wk,C1,IC,lZ,_1,AC,TC=D(()=>{"use strict";wk=require("uuid"),C1=require("json-freeze");Cv();Ln();IC=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,lZ=/^[A-Za-z0-9_-]{1,256}$/,_1=(0,wk.v5)("codevibe:sync:prompt-resolution:v1",wk.v5.URL);AC=t=>!!t&&typeof t=="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(t))});function M1(t,e,r){if(!t||typeof t!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(t))||Reflect.ownKeys(t).length!==e.length)return r();let n={};for(let i of Reflect.ownKeys(t)){if(typeof i!="string"||!e.includes(i))return r();let o=Object.getOwnPropertyDescriptor(t,i);if(!o.enumerable||!("value"in o)||typeof o.value!="string")return r();n[i]=o.value}return n}function Ek(t){let e=M1(t,PC,_C);return!O1.test(e.clientOperationId)||!O1.test(e.sessionGenerationId)||!/^[A-Za-z0-9_-]{1,256}$/.test(e.sessionId)||!/^[A-Za-z0-9_-]{1,128}$/.test(e.expectedSessionKeyGen)?_C():Object.freeze(e)}function ld(t,e){if(typeof t!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t))return _C();let r=Ek({...e,clientOperationId:D1}),{clientOperationId:n,...i}=r;return Object.freeze({...i,clientOperationId:(0,vk.v5)((0,N1.canonicalize)({userId:t,...i}),D1)})}function zg(t,e){let r=()=>{throw new ve("INVALID_SYNC_RECEIPT")};if(typeof t=="string"){if(Buffer.byteLength(t)>2048)return r();try{t=JSON.parse(t)}catch{return r()}}let n=M1(t,[...PC,"state","controlClass"],r);return PC.some(i=>n[i]!==e[i])||n.state!=="RETIRED"||n.controlClass!=="SESSION_RETIREMENT"?r():Object.freeze(n)}function Rk(t,e,r){if(!t||typeof t!="object"||Array.isArray(t))return r();let n=t;if(Object.keys(n).sort().join(",")!=="input,kind,operationId,schemaVersion,toolOutbox"||n.schemaVersion!==1||n.kind!=="SESSION_RETIREMENT")return r();let i;try{i=Ek(n.input)}catch{return r()}let{clientOperationId:o,...s}=i;if(n.operationId!==o||ld(e,s).clientOperationId!==o)return r();let a=null;if(n.toolOutbox!==null){let c=n.toolOutbox;if(!c||typeof c!="object"||Object.keys(c).sort().join(",")!=="agent,root"||!["codex","claude"].includes(c.agent)||typeof c.root!="string"||c.root.includes("\0")||Buffer.byteLength(c.root)>4096||!kk.isAbsolute(c.root)||kk.resolve(c.root)!==c.root)return r();a=Object.freeze({agent:c.agent,root:c.root})}return Object.freeze({schemaVersion:1,kind:"SESSION_RETIREMENT",operationId:o,input:i,toolOutbox:a})}var vk,N1,kk,O1,PC,D1,_C,CC=D(()=>{"use strict";vk=require("uuid"),N1=require("json-freeze");Ln();kk=F(require("node:path")),O1=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,PC=["clientOperationId","expectedSessionKeyGen","sessionGenerationId","sessionId"],D1=(0,vk.v5)("codevibe:sync:session-retirement:v1",vk.v5.URL),_C=()=>{throw new ve("INVALID_SYNC_INPUT")}});function Ik(t){return(typeof t!="string"||!Jg.test(t))&&Ce(),t.toLowerCase()}function Ak(t,e){let r=Mn(t,e);return delete r.source,r}function B1(t){if(t.state==="PENDING")throw new Ge("SYNC_OPERATION_PENDING");return t.state==="ACCEPTED"?{status:"ACCEPTED",receipt:t.receipt}:{status:"OMITTED",reason:t.reason}}function wn(t,e){let r=(0,hi.createHash)("sha256").update(t).update(JSON.stringify(e)).digest().subarray(0,16);r[6]=r[6]&15|128,r[8]=r[8]&63|128;let n=r.toString("hex");return[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join("-")}var hi,Lt,$1,pi,_o,Ge,Jg,DC,dZ,Lc,uZ,zp,L1,Ce,ka,xC,F1,OC,Bc,Tk=D(()=>{"use strict";hi=require("node:crypto"),Lt=require("node:fs"),$1=F(require("node:os")),pi=F(require("node:path")),_o=require("json-freeze");kc();_p();xc();Ln();ck();GG();WG();wC();l1();mk();v1();R1();P1();TC();CC();Ge=class extends Error{constructor(r){super(r);this.code=r;this.name="SyncJournalError"}},Jg=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DC=1024*1024,dZ=2*DC,Lc=256,uZ=32*1024*1024,zp=16,L1=32*1024,Ce=()=>{throw new Ge("SYNC_JOURNAL_INVALID")},ka=t=>t?.code;xC=(t,e)=>(0,hi.createHash)("sha256").update((0,_o.canonicalize)({action:t,input:e})).digest("hex");F1=(t,e)=>wn("codevibe-sync-source-cursor-v1\0",[t.sessionId,t.sessionGenerationId,e.provider,e.streamSha256]),OC=t=>wn("codevibe-sync-shell-source-v1\0",[t.sessionId,t.sessionGenerationId]),Bc=class{constructor(e){this.options=e;if((typeof e.userId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(e.userId)||!["development","production"].includes(e.environment))&&Ce(),this.scope=(0,hi.createHash)("sha256").update(`${e.environment}\0${e.userId}`).digest("hex"),this.directory=pi.join(pi.resolve(e.root??pi.join($1.homedir(),".codevibe","sync-operations")),this.scope),e.sessionScope!==void 0){let{sessionId:r,sessionGenerationId:n}=e.sessionScope;(typeof r!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(r)||typeof n!="string"||!Jg.test(n))&&Ce(),this.sessionScope=Object.freeze({sessionId:r,sessionGenerationId:n.toLowerCase()})}}async create(e,r){return this.retry(await this.prepareCreate(e,r),r)}async update(e,r){return this.retry(await this.prepareUpdate(e,r),r)}async prepareCreate(e,r){return this.prepare("CREATE_EVENT",e,r)}async prepareUpdate(e,r){return this.prepare("UPDATE_EVENT",e,r)}async prepareSourceCreate(e,r,n){let i=this.sourceOperationId(e);if(typeof r!="function")return Ce();if(n?.aborted)throw n.reason??new Error("Aborted");this.options.assertAccount(),await this.ensureDirectory();let o=await this.lock(`send-${i}.lockdir`).acquire();try{let s=await this.withStore(c=>this.read(i,c));if(s){if(this.requireScope(s),s.action!=="CREATE_EVENT")throw new Ge("SYNC_OPERATION_COLLISION");return i}let a=await r(i);if(this.options.assertAccount(),!a||a.clientOperationId!==i||a.writerAttestation!==void 0)return Ce();if(!await o.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");return await this.prepareCreate(a,n)}finally{await o.release()}}sourceStream(e){let r=this.sessionScope;if(!r||!e||Object.keys(e).sort().join(",")!=="provider,streamSha256"||!["codex","claude","agy"].includes(e.provider)||typeof e.streamSha256!="string"||!/^[a-f0-9]{64}$/.test(e.streamSha256))return Ce();let n=Object.freeze({provider:e.provider,streamSha256:e.streamSha256}),i=F1(r,n),o=async(s,a)=>{this.options.assertAccount(),await this.ensureDirectory();let c=await this.lock(s).acquire(),l=async()=>{if(this.options.assertAccount(),!await c.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{let d=await a(l);return await l(),d}finally{await c.release()}};return FG({id:i,scope:r,stream:n,invalid:Ce,missing:()=>{throw new Ge("SYNC_JOURNAL_MISSING")},locked:s=>o(`source-${i}.lockdir`,s),drainLocked:s=>o(`source-drain-${i}.lockdir`,s),read:s=>this.withStore(a=>this.readValue(i,a,".cursor",s)),write:s=>this.withStore(async a=>{let c=this.seal(s,a);await this.checkCapacity(Buffer.byteLength(c),i+".cursor"),await this.write(i,c,".cursor")}),identify:s=>this.sourceOperationId(s),prepare:(s,a)=>this.prepareSourceCreate(s,a),exists:s=>this.withStore(async a=>{let c=await this.read(s,a);if(!c)return!1;if(this.requireScope(c),c.action!=="CREATE_EVENT")throw new Ge("SYNC_OPERATION_COLLISION");return!0}),retry:(s,a)=>this.retry(s,a),acknowledge:s=>this.acknowledge(s)})}sourcePair(e){let r=this.sessionScope;if(this.sourceStream(e),!r)return Ce();let n=Object.freeze({provider:e.provider,streamSha256:e.streamSha256}),i=[0,1].map(a=>(0,hi.createHash)("sha256").update("codevibe-sync-source-pair-v1\0").update(JSON.stringify([n.provider,n.streamSha256,a])).digest("hex")),o=i.map(a=>this.sourceStream({provider:n.provider,streamSha256:a})),s=wn("codevibe-sync-source-pair-lock-v1\0",[r.sessionId,r.sessionGenerationId,n.provider,n.streamSha256]);return $G({source:n,lanes:o,laneStreams:i,invalid:Ce,locked:async a=>{this.options.assertAccount(),await this.ensureDirectory();let c=await this.lock(`source-pair-${s}.lockdir`).acquire();try{let l=await a();if(this.options.assertAccount(),!await c.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");return l}finally{await c.release()}}})}shellSource(){let e=this.sessionScope;if(!e)return Ce();let r=OC(e),n=async(i,o)=>{this.options.assertAccount(),await this.ensureDirectory();let s=await this.lock(i).acquire(),a=async()=>{if(this.options.assertAccount(),!await s.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{let c=await o(a);return await a(),c}finally{await s.release()}};return HG({id:r,scope:e,invalid:Ce,full:()=>{throw new Ge("SYNC_JOURNAL_FULL")},collision:()=>{throw new Ge("SYNC_OPERATION_COLLISION")},locked:i=>n(`shell-source-${r}.lockdir`,i),drainLocked:i=>n(`shell-drain-${r}.lockdir`,i),read:()=>this.withStore(i=>this.readShellSource(r,i)),write:i=>this.withStore(async o=>{let s=this.seal(i,o);await this.checkCapacity(Buffer.byteLength(s),r+".shell"),await this.write(r,s,".shell")}),prepare:i=>this.prepareCreate(i),retry:(i,o)=>this.retry(i,o),omitNewPayload:this.options.omitNewPayload,acknowledge:i=>this.acknowledge(i)})}async shellSources(){return this.withStore(async e=>{let r=[];for(let n of await this.recordNames(".shell")){let i=n.slice(0,-6),o=await this.readShellSource(i,e);if(!o)throw new Ge("SYNC_JOURNAL_MISSING");this.matchesScope(o)&&r.push({sourceId:i,sessionId:o.sessionId,sessionGenerationId:o.sessionGenerationId,pendingCount:o.entries.length})}return r.sort((n,i)=>n.sourceId.localeCompare(i.sourceId))})}desktopRegistration(e,r=Date.now){let n=this.sessionScope;if(!n||typeof e!="function")return Ce();let i=wn("codevibe-sync-desktop-registration-v1\0",[n.sessionId,n.sessionGenerationId]);return s1({id:i,scope:n,now:r,invalid:Ce,register:e,locked:async o=>{this.options.assertAccount(),await this.ensureDirectory();let s=await this.lock(`registration-${i}.lockdir`).acquire(),a=async()=>{if(this.options.assertAccount(),!await s.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{let c=await o(a);return await a(),c}finally{await s.release()}},read:()=>this.withStore(o=>this.readValue(i,o,".desktop",s=>{let a=Wp(s,Ce);return a.operationId!==i?Ce():(this.requireScope(a),a)})),write:o=>this.withStore(async s=>{let a=this.seal(o,s);await this.checkCapacity(Buffer.byteLength(a),i+".desktop"),await this.write(i,a,".desktop")})})}async removeDesktopRegistration(){let e=this.sessionScope;if(!e)return Ce();let r=wn("codevibe-sync-desktop-registration-v1\0",[e.sessionId,e.sessionGenerationId]);this.options.assertAccount(),await this.ensureDirectory();let n=await this.lock(`registration-${r}.lockdir`).acquire();try{return await this.withStore(async i=>{let o=await this.readValue(r,i,".desktop",s=>Wp(s,Ce));if(!o)return!1;if(o.operationId!==r)return Ce();if(this.requireScope(o),this.options.assertAccount(),!await n.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");return await Lt.promises.unlink(this.file(r,".desktop")),await this.syncDirectory(this.directory),!0})}finally{await n.release()}}deferredInputs(e,r){let n=this.sessionScope;if(!n||!["codex","claude","agy"].includes(e)||!/^[a-f0-9]{64}$/.test(r))return Ce();let i=wn("codevibe-sync-deferred-inputs-v1\0",[n.sessionId,n.sessionGenerationId,e,r]),o=async a=>{let c=await this.readValue(i,a,".deferred",Wg);return c&&(c.operationId!==i||!fk(c,n)||c.provider!==e||c.nativeSessionSha256!==r)?Ce():c??{schemaVersion:1,kind:"DEFERRED_INPUTS",operationId:i,...n,provider:e,nativeSessionSha256:r,entries:[]}},s=async(a,c)=>{if(Wg(a),!a.entries.length){try{await Lt.promises.unlink(this.file(i,".deferred")),await this.syncDirectory(this.directory)}catch(d){if(ka(d)!=="ENOENT")throw d}return}let l=this.seal(a,c);await this.checkCapacity(Buffer.byteLength(l),i+".deferred"),await this.write(i,l,".deferred")};return Object.freeze({read:()=>this.withStore(async a=>Object.freeze((await o(a)).entries.map(c=>Object.freeze({...c})))),put:(a,c)=>{this.options.assertDeferredAdmission?.();let l=vC(a);return c!==void 0&&!/^[a-f0-9]{64}$/.test(c)?Ce():this.withStore(async d=>{let u=await o(d),p=u.entries.find(h=>h.eventId===l.eventId);if(p&&(p.timestamp!==l.timestamp||p.type!==l.type))return Ce();if(p?c!==ad(p):c!==void 0)throw new Ge("SYNC_OPERATION_COLLISION");if(p?.notice){let h=l.notice,m=p.notice;if(!h||(m.state==="SETTLED"?(0,_o.canonicalize)(h)!==(0,_o.canonicalize)(m):h.state==="STAGED"?(0,_o.canonicalize)(h.input)!==(0,_o.canonicalize)(m.input):h.operationId!==m.input.clientOperationId))throw new Ge("SYNC_OPERATION_COLLISION")}if(!p&&u.entries.length>=64)throw new Ge("SYNC_JOURNAL_FULL");p?u.entries[u.entries.indexOf(p)]=l:u.entries.push(l),this.options.assertDeferredAdmission?.(),await s(u,d)})},remove:(a,c)=>{let{payloadJson:l,...d}=vC({...a,payloadJson:"{}"});return c!==void 0&&!/^[a-f0-9]{64}$/.test(c)?Ce():this.withStore(async u=>{let p=await o(u),h=p.entries.find(m=>m.eventId===d.eventId);if(h){if(h.timestamp!==d.timestamp||h.type!==d.type)return Ce();if(c!==void 0&&c!==ad(h))throw new Ge("SYNC_OPERATION_COLLISION");if(h.notice&&(h.notice.state==="STAGED"||await this.read(h.notice.operationId,u)))throw new Ge("SYNC_OPERATION_PENDING");p.entries=p.entries.filter(m=>m!==h),await s(p,u)}})},runExclusive:async a=>{this.options.assertAccount(),await this.ensureDirectory();let c=await this.lock("deferred-dispatch-"+i+".lockdir").acquire(),l=async()=>{if(this.options.assertAccount(),!await c.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{await l();let d=await a(l);return await l(),d}finally{await c.release()}}})}mobileEchoes(e){let r=this.sessionScope;if(!r||!["codex","claude","agy"].includes(e))return Ce();let n=wn("codevibe-sync-mobile-echo-v1\0",[r.sessionId,r.sessionGenerationId,e]);return S1({assertAdmission:()=>{this.options.assertAccount(),this.options.assertDeferredAdmission?.()},full:()=>{throw new Ge("SYNC_JOURNAL_FULL")},collision:()=>{throw new Ge("SYNC_OPERATION_COLLISION")},mutate:i=>this.withStore(async o=>{let s=await this.readValue(n,o,".echo",gk)??{schemaVersion:1,kind:"MOBILE_ECHOES",operationId:n,...r,provider:e,entries:[]};return s.operationId!==n||!this.matchesScope(s)||s.provider!==e?Ce():i(s,async()=>{if(gk(s),this.options.assertAccount(),s.entries.length){let a=this.seal(s,o);await this.checkCapacity(Buffer.byteLength(a),n+".echo"),await this.write(n,a,".echo")}else try{await Lt.promises.unlink(this.file(n,".echo")),await this.syncDirectory(this.directory)}catch(a){if(ka(a)!=="ENOENT")throw a}})})})}promptPublication(e){let r=this.sessionScope;if(!r||typeof e!="string"||!Jg.test(e)||e!==e.toLowerCase())return Ce();let n=wn("codevibe-sync-prompt-publication-v1\0",[r.sessionId,r.sessionGenerationId,e]),i=o=>{let s=cd(o,Ce);return s.operationId!==n||s.promptId!==e?Ce():(this.requireScope(s),s)};return T1({id:n,scope:r,promptId:e,invalid:Ce,assertAdmission:()=>{this.options.assertAccount(),this.options.assertDeferredAdmission?.()},assertOpen:async()=>{if((await this.promptResolutions()).some(o=>o.sessionId===r.sessionId&&o.promptId===e))throw new Ge("SYNC_OPERATION_PENDING")},collision:()=>{throw new Ge("SYNC_OPERATION_COLLISION")},pending:()=>{throw new Ge("SYNC_OPERATION_PENDING")},locked:async o=>{this.options.assertAccount(),await this.ensureDirectory();let s=await this.lock("prompt-publication-"+n+".lockdir").acquire(),a=async()=>{if(this.options.assertAccount(),!await s.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{await a();let c=await o(a);return await a(),c}finally{await s.release()}},read:()=>this.withStore(o=>this.readValue(n,o,".prompt",i)),write:o=>this.withStore(async s=>{i(o);let a=this.seal(o,s);await this.checkCapacity(Buffer.byteLength(a),n+".prompt"),await this.write(n,a,".prompt")}),remove:()=>this.withStore(async o=>{let s=await this.readValue(n,o,".prompt",i);if(s){if(s.state!=="SETTLED")throw new Ge("SYNC_OPERATION_PENDING");await Lt.promises.unlink(this.file(n,".prompt")),await this.syncDirectory(this.directory)}}),prepare:o=>this.prepareCreate(o),retry:(o,s)=>this.retry(o,s),acknowledge:o=>this.acknowledge(o)})}async runPromptResolution(e,r,n={}){if(typeof r!="function")return Ce();let i=Vp(e),o=i.clientOperationId,s=Sk({schemaVersion:1,kind:"PROMPT_RESOLUTION",operationId:o,input:i},this.options.userId,Ce);if(!this.matchesPromptResolutionScope(i))return Ce();this.options.assertAccount(),await this.ensureDirectory();let a=await this.lock("prompt-resolution-"+o+".lockdir").acquire(),c=async()=>{if(this.options.assertAccount(),!await a.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")},l=d=>{let u=Sk(d,this.options.userId,Ce);if(u.operationId!==o||(0,_o.canonicalize)(u)!==(0,_o.canonicalize)(s))throw new Ge("SYNC_OPERATION_COLLISION");return u};try{await c();let d=await this.withStore(async u=>{let p=await this.readValue(o,u,".resolution",l);if(p)return p;if(n.existingOnly)return null;let h=this.seal(s,u);return await this.checkCapacity(Buffer.byteLength(h),o+".resolution"),await this.write(o,h,".resolution"),s});return await c(),d?await r(d.input,c)!==!0?(await c(),!1):(await c(),await this.withStore(async u=>{await this.readValue(o,u,".resolution",l)&&(await c(),await Lt.promises.unlink(this.file(o,".resolution")),await this.syncDirectory(this.directory))}),await c(),!0):!0}finally{await a.release()}}async promptResolutions(){this.options.assertAccount();try{await Lt.promises.lstat(this.directory)}catch(e){if(ka(e)!=="ENOENT")throw e;return this.options.assertAccount(),[]}return this.withStore(async e=>{let r=[];for(let n of await this.recordNames(".resolution")){let i=n.slice(0,-11),o=await this.readValue(i,e,".resolution",s=>Sk(s,this.options.userId,Ce));if(!o||o.operationId!==i)return Ce();this.matchesPromptResolutionScope(o.input)&&r.push(o.input)}return Object.freeze(r.sort((n,i)=>n.clientOperationId.localeCompare(i.clientOperationId)))})}matchesPromptResolutionScope(e){return!this.sessionScope||e.sessionId===this.sessionScope.sessionId&&(e.producerKind==="PLUGIN_APPROVAL"||e.sessionGenerationId===this.sessionScope.sessionGenerationId)}async promptPublications(){this.options.assertAccount();try{await Lt.promises.lstat(this.directory)}catch(e){if(ka(e)!=="ENOENT")throw e;return this.options.assertAccount(),[]}return this.withStore(async e=>{let r=[];for(let n of await this.recordNames(".prompt")){let i=n.slice(0,-7),o=await this.readValue(i,e,".prompt",s=>cd(s,Ce));if(!o||o.operationId!==i||i!==wn("codevibe-sync-prompt-publication-v1\0",[o.sessionId,o.sessionGenerationId,o.promptId]))return Ce();this.matchesScope(o)&&r.push({sessionId:o.sessionId,sessionGenerationId:o.sessionGenerationId,promptId:o.promptId,state:o.state})}return r})}promptRetention(){let e=this.sessionScope;if(!e)return Ce();let r=wn("codevibe-sync-prompt-retention-v1\0",[e.sessionId,e.sessionGenerationId]);return E1({runExclusive:async n=>{this.options.assertAccount(),await this.ensureDirectory();let i=await this.lock("prompt-retention-"+r+".lockdir").acquire(),o=async()=>{if(this.options.assertAccount(),!await i.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{await o();let s=await n(o);return await o(),s}finally{await i.release()}},read:()=>this.withStore(async n=>{let i=await this.readValue(r,n,".retention",Vg);return i&&(i.operationId!==r||!this.matchesScope(i))?Ce():i??{schemaVersion:1,kind:"PROMPT_RETENTION",operationId:r,...e,cursor:null,entries:[]}}),write:n=>this.withStore(async i=>{if(Vg(n),n.operationId!==r||!this.matchesScope(n))return Ce();let o=this.seal(n,i);await this.checkCapacity(Buffer.byteLength(o),r+".retention"),await this.write(r,o,".retention")}),remove:()=>this.withStore(async n=>{let i=await this.readValue(r,n,".retention",Vg);if(i){if(i.operationId!==r||!this.matchesScope(i))return Ce();this.options.assertAccount(),await Lt.promises.unlink(this.file(r,".retention")),await this.syncDirectory(this.directory)}})})}async removeSettledPromptPublications(){if(!this.sessionScope)return Ce();if((await this.promptResolutions()).length)throw new Ge("SYNC_OPERATION_PENDING");let e=await this.withStore(async n=>{let i=[];for(let o of await this.recordNames(".prompt")){let s=o.slice(0,-7),a=await this.readValue(s,n,".prompt",c=>cd(c,Ce));if(!a||a.operationId!==s||s!==wn("codevibe-sync-prompt-publication-v1\0",[a.sessionId,a.sessionGenerationId,a.promptId]))return Ce();if(this.matchesScope(a)){if(a.state!=="SETTLED")throw new Ge("SYNC_OPERATION_PENDING");i.push(a.promptId)}}return i.sort()}),r=0;for(let n of e)await this.promptPublication(n).close()&&r++;return r}async removeMobileEchoes(){return this.sessionScope?this.withStore(async r=>{let n=[];for(let i of await this.recordNames(".echo")){let o=i.slice(0,-5),s=await this.readValue(o,r,".echo",gk);if(!s)throw new Ge("SYNC_JOURNAL_MISSING");if(s.operationId!==o||o!==wn("codevibe-sync-mobile-echo-v1\0",[s.sessionId,s.sessionGenerationId,s.provider]))return Ce();this.matchesScope(s)&&n.push(o)}for(let i of n)this.options.assertAccount(),await Lt.promises.unlink(this.file(i,".echo"));return n.length&&await this.syncDirectory(this.directory),n.length}):Ce()}async removeDeferredInputs(){let e=this.sessionScope;if(!e)return Ce();let r=(o,s)=>this.readValue(o,s,".deferred",a=>{let c=Wg(a);return c.operationId!==o||o!==wn("codevibe-sync-deferred-inputs-v1\0",[c.sessionId,c.sessionGenerationId,c.provider,c.nativeSessionSha256])?Ce():c}),n=await this.withStore(async o=>{let s=[];for(let a of await this.recordNames(".deferred")){let c=a.slice(0,-9),l=await r(c,o);l&&fk(l,e)&&s.push(c)}return s.sort()}),i=0;for(let o of n){let s=await this.lock("deferred-dispatch-"+o+".lockdir").acquire();try{await this.withStore(async a=>{let c=await r(o,a);if(c){if(!fk(c,e))return Ce();if(!c.entries.some(l=>l.notice)){if(this.options.assertAccount(),!await s.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");await Lt.promises.unlink(this.file(o,".deferred")),await this.syncDirectory(this.directory),i++}}})}finally{await s.release()}}return i}inbound(){let e=this.sessionScope;if(!e)return Ce();let r=wn("codevibe-sync-inbound-v1\0",[e.sessionId,e.sessionGenerationId]),n=async(i,o)=>{this.options.assertAccount(),await this.ensureDirectory();let s=await this.lock(i).acquire(),a=async()=>{if(this.options.assertAccount(),!await s.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{let c=await o(a);return await a(),c}finally{await s.release()}};return c1({id:r,scope:e,locked:i=>n(`inbound-record-${r}.lockdir`,i),dispatchLocked:i=>n(`inbound-dispatch-${r}.lockdir`,i),read:()=>this.withStore(i=>this.readValue(r,i,".inbox",o=>{let s=Hg(o);return s.operationId!==r?Ce():(this.requireScope(s),s)})),write:i=>this.withStore(async o=>{let s=this.seal(i,o);await this.checkCapacity(Buffer.byteLength(s),r+".inbox"),await this.write(r,s,".inbox")})})}async removeInbound(){let e=this.sessionScope;if(!e)return Ce();let r=wn("codevibe-sync-inbound-v1\0",[e.sessionId,e.sessionGenerationId]);this.options.assertAccount(),await this.ensureDirectory();let n=await this.lock(`inbound-dispatch-${r}.lockdir`).acquire();try{let i=await this.lock(`inbound-record-${r}.lockdir`).acquire();try{return await this.withStore(async o=>{let s=await this.readValue(r,o,".inbox",Hg);if(!s)return!1;if(s.operationId!==r)return Ce();if(this.requireScope(s),this.options.assertAccount(),!await n.reassertOwnership()||!await i.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");return await Lt.promises.unlink(this.file(r,".inbox")),await this.syncDirectory(this.directory),!0})}finally{await i.release()}}finally{await n.release()}}async removeEmptyShellSource(){let e=this.sessionScope;if(!e)return Ce();let r=OC(e);this.options.assertAccount(),await this.ensureDirectory();let n=await this.lock(`shell-drain-${r}.lockdir`).acquire();try{let i=await this.lock(`shell-source-${r}.lockdir`).acquire();try{return await this.withStore(async o=>{let s=await this.readShellSource(r,o);if(!s||s.entries.length!==0)return!1;if(this.requireScope(s),!await n.reassertOwnership()||!await i.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");return this.options.assertAccount(),await Lt.promises.unlink(this.file(r,".shell")),await this.syncDirectory(this.directory),!0})}finally{await i.release()}}finally{await n.release()}}async sessionRetirements(){this.options.assertAccount();try{await Lt.promises.lstat(this.directory)}catch(e){if(ka(e)!=="ENOENT")throw e;return this.options.assertAccount(),[]}return this.withStore(async e=>{let r=[];for(let n of(await this.recordNames(".retirement")).sort()){let i=n.slice(0,-11),o=await this.readValue(i,e,".retirement",s=>Rk(s,this.options.userId,Ce));if(!o||o.operationId!==i)return Ce();if(this.matchesScope(o.input)&&r.push(o),r.length>zp)throw new Ge("SYNC_JOURNAL_FULL")}return Object.freeze(r)})}async hasSessionRetirementWork(e){if(!this.sessionScope)return Ce();if((await this.sessionRetirements()).length||(await this.promptResolutions()).length)return!0;try{await Lt.promises.lstat(this.directory)}catch(r){if(ka(r)!=="ENOENT")throw r;return this.options.assertAccount(),!1}return this.withStore(async r=>(await this.retiredSourcePlan(r,e)).sources.length>0)}async runSessionRetirement(e,r,n,i={}){let o=Rk({schemaVersion:1,kind:"SESSION_RETIREMENT",operationId:e?.clientOperationId,input:e,toolOutbox:r},this.options.userId,Ce);if(!this.sessionScope||!this.matchesScope(o.input)||typeof n!="function")return Ce();let s=o.operationId;this.options.assertAccount(),await this.ensureDirectory();let a=await this.lock("retire-session-"+s+".lockdir",!0).acquire(),c=async()=>{if(this.options.assertAccount(),!a||!await a.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")},l=d=>this.readValue(s,d,".retirement",u=>{let p=Rk(u,this.options.userId,Ce);if((0,_o.canonicalize)(p)!==(0,_o.canonicalize)(o))throw new Ge("SYNC_OPERATION_COLLISION");return p});try{let d=await this.withStore(async p=>{await c();let h=await l(p);if(h||i.existingOnly)return h;let m=this.seal(o,p);if(Buffer.byteLength(m)>L1)throw new Ge("SYNC_JOURNAL_FULL");return await this.checkCapacity(Buffer.byteLength(m),s+".retirement",!0),await this.write(s,m,".retirement"),o});if(!d)return null;await c();let u=await n(d,c);return await c(),await this.withStore(async(p,h)=>{if(!await l(p))throw new Ge("SYNC_JOURNAL_MISSING");await c();let m=a;a=null,await m.release(),await h(),await Lt.promises.unlink(this.file(s,".retirement")),await this.syncDirectory(this.directory),await h()}),u}finally{await a?.release()}}async removeRetiredSources(e,r){let n=this.sessionScope;if(!n||typeof r!="function")return Ce();let i=ld(this.options.userId,{...n,expectedSessionKeyGen:e});this.options.assertAccount();try{await Lt.promises.lstat(this.directory)}catch(l){if(ka(l)!=="ENOENT")throw l;return this.options.assertAccount(),{sourcesRemoved:0,operationsRemoved:0}}let o=await this.withStore(l=>this.retiredSourcePlan(l,i.expectedSessionKeyGen));if(!o.sources.length)return{sourcesRemoved:0,operationsRemoved:0};zg(await r(i),i),this.options.assertAccount();let s=[],a=async()=>{this.options.assertAccount();for(let l of s)if(!await l.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")},c=async()=>{let d=(await Promise.allSettled(s.splice(0).reverse().map(u=>u.release()))).find(u=>u.status==="rejected");if(d?.status==="rejected")throw d.reason};try{for(let l of o.locks){this.options.assertAccount();let d=await this.lock(l,!0).acquire();if(s.push(d),this.options.assertAccount(),!await d.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")}return await this.withStore(async(l,d)=>{let u=await this.retiredSourcePlan(l,i.expectedSessionKeyGen);if(u.digest!==o.digest)throw new Ge("SYNC_OPERATION_PENDING");await a();for(let p of u.operations)this.options.assertAccount(),await Lt.promises.unlink(pi.join(this.directory,p));u.operations.length&&await this.syncDirectory(this.directory),await a(),await c(),await d();for(let p of u.sources)this.options.assertAccount(),await Lt.promises.unlink(pi.join(this.directory,p));return u.sources.length&&await this.syncDirectory(this.directory),await d(),{sourcesRemoved:u.sources.length,operationsRemoved:u.operations.length}})}finally{await c()}}async removeRetiredToolOperations(e,r,n,i){if(!this.sessionScope||!Array.isArray(e)||e.length>Lc||typeof n!="function"||typeof i?.markRetired!="function"||typeof i?.prune!="function")return Ce();let o=e.map(Ik).sort();if(new Set(o).size!==o.length)return Ce();let s=ld(this.options.userId,{...this.sessionScope,expectedSessionKeyGen:r});if(this.options.assertAccount(),!o.length)return 0;let a=async p=>{let h=[];for(let m of o){let f=await this.read(m,p);if(f){if(this.requireScope(f),f.action!=="CREATE_EVENT"||f.state==="PENDING"&&(f.input.type!=="TOOL_ACTIVITY"||f.input.expectedSessionKeyGen!==s.expectedSessionKeyGen)||f.state==="ACCEPTED"&&f.receipt.type!=="TOOL_ACTIVITY")return Ce();h.push(f)}}return{rows:h,digest:(0,hi.createHash)("sha256").update((0,_o.canonicalize)(h)).digest("hex")}},c=await this.withStore(a);zg(await n(s),s),this.options.assertAccount();let l=[],d=async()=>{let h=(await Promise.allSettled(l.splice(0).reverse().map(m=>m.release()))).find(m=>m.status==="rejected");if(h?.status==="rejected")throw h.reason},u=async()=>{this.options.assertAccount();for(let p of l)if(!await p.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};try{for(let p of o)this.options.assertAccount(),l.push(await this.lock(`send-${p}.lockdir`,!0).acquire());return await this.withStore(async(p,h)=>{let m=await a(p);if(m.digest!==c.digest)throw new Ge("SYNC_OPERATION_PENDING");await u(),await i.markRetired(),await u(),await h();for(let f of m.rows)this.options.assertAccount(),await Lt.promises.unlink(this.file(f.operationId));return m.rows.length&&await this.syncDirectory(this.directory),await u(),await d(),await h(),await i.prune(),await h(),m.rows.length})}finally{await d()}}async retiredSourcePlan(e,r){if(!this.sessionScope)return Ce();let n=[],i=[],o=[],s=new Set,a=new Set,c=new Set,l=new Map,d=p=>{let h=Ak("CREATE_EVENT",p),m=xC("CREATE_EVENT",h),f=l.get(h.clientOperationId);if(f!==void 0&&f!==m)return Ce();l.set(h.clientOperationId,m)},u=(p,h,m,f,g=[])=>{if(this.matchesScope(h)){n.push(p),o.push([p,h]);for(let y of m)s.add(y);if(n.length>Lc||s.size>Lc)throw new Ge("SYNC_JOURNAL_FULL");for(let y of f)a.add(y);for(let y of g)c.add(y)}};for(let p of(await this.recordNames(".cursor")).sort()){let h=p.slice(0,-7),m=await this.readSourceCursor(h,e);if(!m)throw new Ge("SYNC_JOURNAL_MISSING");u(p,m,m.entries.map(f=>f.operationId),[`source-drain-${h}.lockdir`],[`source-${h}.lockdir`])}for(let p of(await this.recordNames(".shell")).sort()){let h=p.slice(0,-6),m=await this.readShellSource(h,e);if(!m)throw new Ge("SYNC_JOURNAL_MISSING");if(this.matchesScope(m)&&m.entries.some(f=>f.state==="STAGED"&&f.input.expectedSessionKeyGen!==r))return Ce();if(this.matchesScope(m))for(let f of m.entries)f.state==="STAGED"&&d(f.input);u(p,m,m.entries.map(f=>f.operationId),[`shell-drain-${h}.lockdir`],[`shell-source-${h}.lockdir`])}for(let p of(await this.recordNames(".prompt")).sort()){let h=p.slice(0,-7),m=await this.readValue(h,e,".prompt",f=>cd(f,Ce));if(!m||m.operationId!==h||h!==wn("codevibe-sync-prompt-publication-v1\0",[m.sessionId,m.sessionGenerationId,m.promptId])||this.matchesScope(m)&&m.state==="STAGED"&&m.input.expectedSessionKeyGen!==r)return Ce();this.matchesScope(m)&&m.state==="STAGED"&&d(m.input),u(p,m,[m.writeId],[`prompt-publication-${h}.lockdir`])}for(let p of(await this.recordNames(".deferred")).sort()){let h=p.slice(0,-9),m=await this.readValue(h,e,".deferred",Wg);if(!m||m.operationId!==h||h!==wn("codevibe-sync-deferred-inputs-v1\0",[m.sessionId,m.sessionGenerationId,m.provider,m.nativeSessionSha256]))return Ce();let f=m.entries.flatMap(g=>g.notice?[g.notice]:[]);if(f.length){if(this.matchesScope(m)){for(let g of f)if(g.state==="STAGED"){if(g.input.expectedSessionKeyGen!==r)return Ce();d(g.input)}}u(p,m,f.map(g=>g.state==="STAGED"?g.input.clientOperationId:g.operationId),[`deferred-dispatch-${h}.lockdir`])}}for(let p of[...s].sort()){let h=await this.read(p,e);if(h){if(this.requireScope(h),h.action!=="CREATE_EVENT"||h.state==="PENDING"&&h.input.expectedSessionKeyGen!==r||l.has(p)&&l.get(p)!==h.fingerprint)return Ce();i.push(p+".json"),o.push([p+".json",h])}}if(n.length+i.length>Lc)throw new Ge("SYNC_JOURNAL_FULL");return{sources:n.sort(),operations:i,locks:[...[...a].sort(),...[...c].sort(),...[...s].sort().map(p=>`send-${p}.lockdir`)],digest:(0,hi.createHash)("sha256").update((0,_o.canonicalize)(o)).digest("hex")}}readShellSource(e,r){return this.readValue(e,r,".shell",n=>{let i=cC(n,Ce);return i.operationId!==e||OC(i)!==e?Ce():i})}sourceOperationId(e,r=this.sessionScope){return!r||!e||Object.keys(e).sort().join(",")!=="occurrence,provider,sourceSha256,streamSha256"||!["codex","claude","agy"].includes(e.provider)||typeof e.streamSha256!="string"||!/^[a-f0-9]{64}$/.test(e.streamSha256)||typeof e.sourceSha256!="string"||!/^[a-f0-9]{64}$/.test(e.sourceSha256)||typeof e.occurrence!="string"||!/^[A-Za-z0-9_:-]{1,256}$/.test(e.occurrence)?Ce():wn("codevibe-sync-desktop-source-v1\0",[r.sessionId,r.sessionGenerationId,e.provider,e.streamSha256,e.occurrence,e.sourceSha256])}matchesScope(e){return!this.sessionScope||e.sessionId===this.sessionScope.sessionId&&e.sessionGenerationId===this.sessionScope.sessionGenerationId}requireScope(e){if(!this.matchesScope(e))throw new Ge("SYNC_OPERATION_COLLISION")}async prepare(e,r,n){let i=Ak(e,r);this.requireScope(i);let o=Ik(i.clientOperationId),s=xC(e,i);if(n?.aborted)throw n.reason??new Error("Aborted");let a=await this.withStore(l=>this.read(o,l));if(a){if(this.requireScope(a),a.fingerprint!==s)throw new Ge("SYNC_OPERATION_COLLISION");return o}let c=await this.options.omitNewPayload?.(n)===!0;if(this.options.assertAccount(),n?.aborted)throw n.reason??new Error("Aborted");return await this.withStore(async l=>{let d=await this.read(o,l);if(d){if(this.requireScope(d),d.fingerprint!==s)throw new Ge("SYNC_OPERATION_COLLISION");return}let u={schemaVersion:1,operationId:o,fingerprint:s,createdAt:Date.now(),sessionId:i.sessionId,sessionGenerationId:i.sessionGenerationId,action:e},p=c?{...u,state:"OMITTED",reason:"SYNC_QUOTA_EXHAUSTED"}:{...u,state:"PENDING",input:i},h=this.seal(p,l);await this.checkCapacity(Buffer.byteLength(h)),await this.write(o,h)}),o}async retry(e,r){let n=Ik(e);this.options.assertAccount(),await this.ensureDirectory();let i=await this.lock(`send-${n}.lockdir`).acquire();try{let o=await this.withStore(c=>this.required(n,c));if(this.requireScope(o),o.state!=="PENDING")return B1(o);if(r?.aborted)throw r.reason??new Error("Aborted");if(this.options.assertAccount(),!await i.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");let s,a=Mn(o.action,o.input);try{let c=await this.options.send(o.action,Ak(o.action,o.input),r);this.options.assertAccount(),s={status:"ACCEPTED",receipt:Ps(c,a)}}catch(c){if(this.options.assertAccount(),!this.options.isQuotaDenial(c))throw c;s={status:"OMITTED",reason:"SYNC_QUOTA_EXHAUSTED"}}if(!await i.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST");return await this.withStore(async c=>{let l=await this.required(n,c);if(l.fingerprint!==o.fingerprint)throw new Ge("SYNC_OPERATION_COLLISION");if(l.state!=="PENDING")return B1(l);let d={schemaVersion:1,operationId:n,fingerprint:o.fingerprint,createdAt:o.createdAt,action:o.action,sessionId:o.sessionId,sessionGenerationId:o.sessionGenerationId},u=s.status==="ACCEPTED"?{...d,state:"ACCEPTED",receipt:s.receipt}:{...d,state:"OMITTED",reason:s.reason};return await this.write(n,this.seal(u,c)),s})}finally{await i.release()}}async pending(){return this.withStore(async e=>{let r=[];for(let n of await this.recordNames()){let i=await this.required(n.slice(0,-5),e);this.matchesScope(i)&&r.push({operationId:i.operationId,createdAt:i.createdAt,state:i.state})}return r.sort((n,i)=>n.createdAt-i.createdAt||n.operationId.localeCompare(i.operationId))})}async sourceStreams(){return this.withStore(async e=>{let r=[];for(let n of await this.recordNames(".cursor")){let i=n.slice(0,-7),o=await this.readSourceCursor(i,e);if(!o)throw new Ge("SYNC_JOURNAL_MISSING");this.matchesScope(o)&&r.push({cursorId:i,sessionId:o.sessionId,sessionGenerationId:o.sessionGenerationId,provider:o.provider,streamSha256:o.streamSha256,byteOffset:o.byteOffset,pendingCount:o.entries.length})}return r.sort((n,i)=>n.cursorId.localeCompare(i.cursorId))})}readSourceCursor(e,r){return this.readValue(e,r,".cursor",n=>{let i=sC(n,Ce),o={sessionId:i.sessionId,sessionGenerationId:i.sessionGenerationId},s={provider:i.provider,streamSha256:i.streamSha256};return e!==F1(o,s)?Ce():aC(i,{id:e,scope:o,stream:s,invalid:Ce,identify:a=>this.sourceOperationId(a,o)})})}async acknowledge(e){let r=Ik(e);await this.withStore(async n=>{let i=await this.read(r,n);if(i){if(this.requireScope(i),i.state==="PENDING")throw new Ge("SYNC_OPERATION_PENDING");await Lt.promises.unlink(this.file(r)),await this.syncDirectory(this.directory)}})}file(e,r=".json"){return pi.join(this.directory,`${e}${r}`)}lock(e,r=!1){return Ti({lockDir:pi.join(this.directory,e),ownerlessGraceMs:1/0,maxWaitMs:2e3,requireRemovalOnRelease:r})}async withStore(e){this.options.assertAccount(),await this.ensureDirectory();let r=await this.lock("store.lockdir").acquire();try{let n=await this.options.readPrivateKey();this.options.assertAccount();let i=n?Buffer.from(n,"base64"):Buffer.alloc(0);if(!n||i.toString("base64")!==n||i.length<1||i.length>32||i.every(a=>a===0))throw new Ge("SYNC_JOURNAL_IDENTITY_UNAVAILABLE");let o=dg(i),s=Buffer.from((0,hi.hkdfSync)("sha256",o,this.scope,"codevibe-sync-outbox-v1",32));i.fill(0),o.fill(0);try{let a=async()=>{if(this.options.assertAccount(),!await r.reassertOwnership())throw new Ge("SYNC_JOURNAL_LOCK_LOST")};await a();let c=await e(s,a);return this.options.assertAccount(),c}finally{s.fill(0)}}finally{await r.release()}}seal(e,r){let n=Buffer.from(JSON.stringify(e));if(n.length>DC)throw new Ge("SYNC_JOURNAL_FULL");let i=(0,hi.randomBytes)(12),o=(0,hi.createCipheriv)("aes-256-gcm",r,i);o.setAAD(Buffer.from(`${this.scope}\0${e.operationId}`));let s=Buffer.concat([o.update(n),o.final()]);return JSON.stringify({v:1,nonce:i.toString("base64"),tag:o.getAuthTag().toString("base64"),ciphertext:s.toString("base64")})}async required(e,r){let n=await this.read(e,r);if(!n)throw new Ge("SYNC_JOURNAL_MISSING");return n}async read(e,r){return this.readValue(e,r,".json",n=>this.validateRecord(n,e))}async readValue(e,r,n,i){let o;try{o=await Lt.promises.open(this.file(e,n),Lt.constants.O_RDONLY|Lt.constants.O_NOFOLLOW)}catch(s){if(ka(s)==="ENOENT")return null;throw s}try{let s=await o.stat();(!s.isFile()||s.nlink!==1||s.size>dZ||typeof process.getuid=="function"&&s.uid!==process.getuid()||(s.mode&63)!==0)&&Ce();let a=Buffer.alloc(s.size+1),c=0;for(;c<a.length;){let{bytesRead:u}=await o.read(a,c,a.length-c,c);if(!u)break;c+=u}c!==s.size&&Ce();let l=a.subarray(0,c).toString("utf8"),d;try{let u=JSON.parse(l);(Object.keys(u).sort().join(",")!=="ciphertext,nonce,tag,v"||u.v!==1||typeof u.nonce!="string"||typeof u.tag!="string"||typeof u.ciphertext!="string")&&Ce();let p=Buffer.from(u.nonce,"base64"),h=Buffer.from(u.tag,"base64");(p.length!==12||h.length!==16)&&Ce();let m=(0,hi.createDecipheriv)("aes-256-gcm",r,p);m.setAAD(Buffer.from(`${this.scope}\0${e}`)),m.setAuthTag(h);let f=Buffer.concat([m.update(Buffer.from(u.ciphertext,"base64")),m.final()]);f.length>DC&&Ce(),d=JSON.parse(f.toString("utf8"))}catch{return Ce()}return i(d)}finally{await o.close()}}validateRecord(e,r){(!e||e.schemaVersion!==1||e.operationId!==r||!/^[a-f0-9]{64}$/.test(e.fingerprint)||!Number.isSafeInteger(e.createdAt)||e.createdAt<0||!["CREATE_EVENT","UPDATE_EVENT"].includes(e.action)||typeof e.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e.sessionId)||typeof e.sessionGenerationId!="string"||!Jg.test(e.sessionGenerationId)||e.sessionGenerationId!==e.sessionGenerationId.toLowerCase())&&Ce();let n=["schemaVersion","operationId","fingerprint","createdAt","state","action","sessionId","sessionGenerationId"];return e.state==="PENDING"?((xC(e.action,Ak(e.action,e.input))!==e.fingerprint||e.input.clientOperationId!==r||e.input.sessionId!==e.sessionId||e.input.sessionGenerationId!==e.sessionGenerationId)&&Ce(),n.push("input")):e.state==="ACCEPTED"?(Ps(e.receipt,{sessionId:e.sessionId,eventId:e.receipt?.eventId,timestamp:e.receipt?.timestamp}),n.push("receipt")):e.state==="OMITTED"&&e.reason==="SYNC_QUOTA_EXHAUSTED"?n.push("reason"):Ce(),Object.keys(e).sort().join(",")!==n.sort().join(",")&&Ce(),e}async write(e,r,n=".json"){this.options.assertAccount(),await Ci(this.file(e,n),r,{requireDirectorySync:!0})}async recordNames(e=".json"){let r=[],n=0,i=await Lt.promises.opendir(this.directory);for await(let o of i){if(++n>Lc*4+zp*2+8)throw new Ge("SYNC_JOURNAL_FULL");if(o.name.endsWith(e)&&((!o.isFile()||!Jg.test(o.name.slice(0,-e.length)))&&Ce(),r.push(o.name),r.length>Lc))throw new Ge("SYNC_JOURNAL_FULL")}return r}async checkCapacity(e,r,n=!1){let i=0,o=e,s=0,a=0,c=await Lt.promises.opendir(this.directory);for await(let l of c)if((++s>Lc*4+zp*2+8||l.isSymbolicLink())&&Ce(),l.isFile()){let d=await Lt.promises.lstat(pi.join(this.directory,l.name));if((!d.isFile()||d.nlink!==1)&&Ce(),l.name===r)continue;l.name.endsWith(".retirement")&&a++,o+=d.size,i++}if(i>=Lc+(n?zp:0)||o>uZ+(n?zp*L1:0)||n&&a>=zp)throw new Ge("SYNC_JOURNAL_FULL")}async ensureDirectory(){let e=pi.parse(this.directory).root;for(let r of this.directory.slice(e.length).split(pi.sep)){let n=e;e=pi.join(e,r);try{await Lt.promises.mkdir(e,{mode:448}),await this.syncDirectory(n)}catch(o){if(ka(o)!=="EEXIST")throw o}let i=await Lt.promises.lstat(e);(!i.isDirectory()||i.isSymbolicLink())&&Ce(),e===this.directory&&((i.mode&63)!==0||typeof process.getuid=="function"&&i.uid!==process.getuid())&&Ce()}}async syncDirectory(e){let r=await Lt.promises.open(e,Lt.constants.O_RDONLY|Lt.constants.O_DIRECTORY|Lt.constants.O_NOFOLLOW);try{await r.sync()}finally{await r.close()}}}});var _k,H1,Nr,Pk,Ck,pZ,MC,hZ,fZ,mZ,W1,gZ,yZ,bn,_s,G1,U1,Yg,NC,xk,q1=D(()=>{"use strict";_k=F(require("ws")),H1=require("node:crypto"),Nr=require("zod");Hp();Pk=Nr.z.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(t=>BigInt(t)<=(1n<<63n)-1n),Ck=Nr.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),pZ=Nr.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),MC={sessionId:Nr.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),sessionGenerationId:pZ},hZ=Nr.z.object(MC).strict(),fZ=Nr.z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>Buffer.from(t,"base64url").toString("base64url")===t),mZ=Nr.z.object({version:Nr.z.literal(1),kind:Nr.z.literal("EVENT_AVAILABLE"),...MC,timestamp:Nr.z.string().regex(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/).refine(t=>Number.isFinite(Date.parse(t))&&new Date(t).toISOString()===t),eventId:Nr.z.string().regex(/^[A-Za-z0-9_-]{1,256}$/),eventRevision:Pk,eventSha256:Nr.z.string().regex(/^[a-f0-9]{64}$/),capability:fZ,usageVersion:Nr.z.object({controlGeneration:Ck,entitlementVersion:Pk,accountingGeneration:Nr.z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),periodId:Nr.z.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/),periodStartEpochMs:Pk,usageRevision:Pk}).strict()}).strict(),W1={ok:Nr.z.literal(!0),...MC,connectionGeneration:Ck.min(1),expiresAtEpochMs:Ck},gZ=Nr.z.object({...W1,kind:Nr.z.literal("hello"),heartbeatDueAtEpochMs:Ck}).strict(),yZ=Nr.z.object({...W1,kind:Nr.z.literal("heartbeat"),renewed:Nr.z.boolean(),replay:Nr.z.boolean()}).strict(),bn=()=>new Tt("SYNC_READ_UNAVAILABLE"),_s=()=>new Tt("INVALID_SYNC_READ_RESPONSE"),G1=108e5,U1=18e5,Yg=3e5,NC=15e3,xk=class{constructor(e){this.deps=e;this.abort=new AbortController;this.phase="new";this.recoveryItems=[];this.recoveryPages=0;this.legacyRecoveryActive=!1;this.legacyRecoveryComplete=!1;this.legacyRecoveryItems=[];this.acknowledgementDueAt=0;this.acknowledgementItems=[];this.tail=Promise.resolve();this.queued=0;this.seen=new Map;this.beforeHello=[];this.scope=Object.freeze(hZ.parse(e.scope));let r=new URL(e.endpoint);if(r.protocol!=="wss:"||r.username||r.password||r.search||r.hash||!["development","production"].includes(e.environment)||r.pathname!=="/"+e.environment)throw bn();this.endpoint=r.toString()}now(){return(this.deps.now??Date.now)()}fence(){if(this.deps.assertAccount(),this.abort.signal.aborted)throw bn()}sameScope(e){return e.sessionId===this.scope.sessionId&&e.sessionGenerationId===this.scope.sessionGenerationId}start(){if(this.starting)return this.starting;if(this.phase!=="new")return Promise.reject(bn());this.phase="opening";let e=new Promise((r,n)=>{this.resolveReady=r,this.rejectReady=n});return e.catch(()=>{}),this.starting=Promise.resolve().then(async()=>{try{this.fence(),this.credential=await this.deps.reader.credential(this.abort.signal,!0),this.fence();let r=await this.deps.wire.socketProof("CONNECT",this.credential,void 0,this.abort.signal);this.fence();let n=this.deps.openSocket??((o,s)=>new _k.default(o,s)),i=this.ws=n(this.endpoint,{headers:r.headers,maxPayload:2048,perMessageDeflate:!1,followRedirects:!1,handshakeTimeout:NC});i.on("error",()=>this.fail(bn())),i.on("close",()=>this.fail(bn())),i.on("message",(o,s)=>this.message(o,s)),i.on("pong",o=>{this.pingNonce&&o.equals(this.pingNonce)&&(clearTimeout(this.pongTimer),this.pongTimer=void 0,this.pingNonce=void 0)}),i.on("open",()=>{this.sendControl("hello").catch(o=>this.fail(o))}),this.deadline(),await e}catch(r){throw this.fail(r instanceof Error?r:bn()),r}}),this.starting}deadline(){clearTimeout(this.controlTimer),this.controlTimer=setTimeout(()=>this.fail(bn()),NC),this.controlTimer.unref?.()}async sendControl(e){if(this.fence(),(e==="hello"?this.phase!=="opening":this.phase!=="ready")||!this.credential||!this.ws)throw bn();this.phase=e;let r=await this.deps.wire.socketProof(e==="hello"?"HELLO":"HEARTBEAT",this.credential,e==="heartbeat"?this.generation:void 0,this.abort.signal);this.fence();let n=JSON.stringify({action:e,input:r.input});if(Buffer.byteLength(n)>2048)throw _s();this.deadline(),this.ws.send(n,i=>{i&&this.fail(bn())})}message(e,r){if(this.phase!=="closed")try{this.fence();let n=Array.isArray(e)?Buffer.concat(e):Buffer.from(e);if(r||n.byteLength>2048)throw _s();let i=JSON.parse(new TextDecoder("utf8",{fatal:!0}).decode(n));if(i?.ok===!1)throw Gg(i);if(i?.kind==="EVENT_AVAILABLE"){let a=mZ.parse(i);if(!this.sameScope(a)||!["hello","ready","heartbeat"].includes(this.phase))throw _s();if(this.phase==="hello"){if(this.beforeHello.length>=64)throw bn();this.beforeHello.push(a);return}this.enqueue(a);return}let o=this.phase==="hello"?gZ.parse(i):this.phase==="heartbeat"?yZ.parse(i):null;if(!o||!this.sameScope(o)||o.expiresAtEpochMs<=this.now()||o.expiresAtEpochMs>this.now()+G1+6e4||this.generation!==void 0&&this.generation!==o.connectionGeneration||o.kind==="hello"&&o.heartbeatDueAtEpochMs!==o.expiresAtEpochMs-G1+U1)throw _s();clearTimeout(this.controlTimer),this.controlTimer=void 0;let s=o.kind==="hello";if(this.generation=o.connectionGeneration,this.phase="ready",this.tail=this.tail.then(async()=>{if(this.fence(),this.credential=await this.deps.reader.renew(this.credential,o.expiresAtEpochMs),this.fence(),s||this.refreshStatus(),s){let c=await this.deps.inbound.recoverable();this.fence();for(let d of await this.deps.inbound.pendingAcknowledgements())await this.reconcileAcknowledgement(d);for(let d of c.pending){this.fence();let u=await this.deps.reader.recoverCurrent(d,this.abort.signal);await this.reconcileReceived(u,d)}let l=await this.deps.inbound.recoverable();this.fence(),l.uncertain&&this.deps.onUncertain?.(l.uncertain),this.acknowledgementDueAt=this.now()+Yg,this.startPings(),this.resolveReady?.(),this.scheduleDiscovery(0)}let a=o.kind==="hello"?Math.max(1,o.heartbeatDueAtEpochMs-this.now()):U1;this.heartbeatTimer=setTimeout(()=>{this.sendControl("heartbeat").catch(c=>this.fail(c))},a),this.heartbeatTimer.unref?.()}).catch(a=>this.fail(a)),s)for(let a of this.beforeHello.splice(0))this.enqueue(a)}catch(n){this.fail(n instanceof Tt?n:_s())}}enqueue(e){let r=e.eventId+":"+e.eventRevision,n=this.seen.get(r);if(n!==void 0){if(n!==e.eventSha256)throw _s();return}if(this.queued>=64)throw bn();this.seen.set(r,e.eventSha256),this.seen.size>256&&this.seen.delete(this.seen.keys().next().value),this.queued++,this.tail=this.tail.then(async()=>{this.fence();let i={eventId:e.eventId,timestamp:e.timestamp,eventRevision:e.eventRevision,eventSha256:e.eventSha256};if(await this.deps.inbound.stage(i)==="RETAINED")return;this.fence();let o;try{if(o=await this.deps.reader.exact({eventId:e.eventId,capability:e.capability,eventSha256:e.eventSha256},this.abort.signal),o.syncEventRevision!==e.eventRevision)throw _s()}catch(s){if(this.fence(),s instanceof Tt&&(s.code!=="SYNC_READ_UNAVAILABLE"||s.backendCode!==void 0&&s.backendCode!=="EVENT_FETCH_UNAVAILABLE"))throw s;o=await this.deps.reader.recoverCurrent({eventId:e.eventId,timestamp:e.timestamp,eventRevision:e.eventRevision,eventSha256:e.eventSha256},this.abort.signal)}await this.reconcileReceived(o,i)}).catch(i=>this.fail(i)).finally(()=>{this.queued--})}refreshStatus(){!this.deps.onMaintenance||this.statusRefresh||(this.statusRefresh=Promise.resolve().then(async()=>{this.fence(),await this.deps.onMaintenance(this.abort.signal)}).catch(()=>{}).finally(()=>{this.statusRefresh=void 0}))}async reconcileReceived(e,r){if(this.fence(),!e){await this.deps.inbound.retainMissing(r);return}if(!this.sameScope(e)||e.timestamp!==r.timestamp||e.eventId!==r.eventId)throw _s();e.source==="MOBILE"&&["USER_PROMPT","PROMPT_RESPONSE"].includes(e.type)&&e.deliveryStatus==="EXECUTED"?await this.deps.inbound.acknowledgeExecuted({...e,deliveryStatus:"EXECUTED"}):await this.deps.inbound.refreshReceived(e)==="RECEIVED"&&await this.deliver(e,{timestamp:e.timestamp,eventRevision:e.syncEventRevision}),this.fence()}async deliver(e,r){if(this.fence(),!this.sameScope(e)||e.timestamp!==r.timestamp||e.syncEventRevision!==r.eventRevision)throw _s();e.source==="MOBILE"&&["USER_PROMPT","PROMPT_RESPONSE"].includes(e.type)?e.deliveryStatus==="EXECUTED"?await this.deps.inbound.acknowledgeExecuted({...e,deliveryStatus:"EXECUTED"}):await this.deps.inbound.dispatch(e,()=>this.deps.onEvent(e),this.abort.signal):(await this.deps.inbound.releaseNonInput(e),this.fence(),await this.deps.onEvent(e)),this.fence()}scheduleDiscovery(e){clearTimeout(this.recoveryTimer),this.phase!=="closed"&&(this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=void 0,this.tail=this.tail.then(()=>this.discoveryStep()).catch(r=>this.fail(r))},e),this.recoveryTimer.unref?.())}async discoveryStep(){if(this.fence(),!this.acknowledgementItems.length&&this.now()>=this.acknowledgementDueAt){let e=[...await this.deps.inbound.pendingAcknowledgements()].sort((n,i)=>n.eventId<i.eventId?-1:n.eventId>i.eventId?1:0);this.fence();let r=this.acknowledgementAfter===void 0?0:e.findIndex(n=>n.eventId>this.acknowledgementAfter);this.acknowledgementItems=e.slice(r<0?0:r).concat(e.slice(0,r<0?0:r)).slice(0,8),this.acknowledgementDueAt=this.now()+Yg}if(this.acknowledgementItems.length){let e=this.acknowledgementItems[0];await this.reconcileAcknowledgement(e),this.acknowledgementAfter=e.eventId,this.acknowledgementItems=this.acknowledgementItems.slice(1),this.scheduleDiscovery(0);return}if(this.legacyRecoveryActive){await this.legacyDiscoveryStep();return}if(this.recoveryItems.length)await this.discoverCoordinate(this.recoveryItems[0]),this.recoveryItems=this.recoveryItems.slice(1);else{let e=await this.deps.reader.pendingInputs(this.recoveryCursor,this.abort.signal);this.fence(),this.recoveryItems=e.items,this.recoveryCursor=e.nextToken??void 0,this.recoveryPages++}if(this.fence(),this.recoveryItems.length||this.recoveryCursor&&this.recoveryPages<4)this.scheduleDiscovery(0);else{let e=await this.deps.inbound.recoverable();this.fence(),e.uncertain&&this.deps.onUncertain?.(e.uncertain),this.legacyRecoveryComplete?(this.recoveryPages=0,this.scheduleDiscovery(Yg)):(this.legacyRecoveryActive=!0,this.scheduleDiscovery(0))}}async reconcileAcknowledgement(e){this.fence();let r=await this.deps.reader.executionReceipt(e,this.abort.signal);if(this.fence(),!r&&this.deps.retryExecutionAcknowledgement&&await this.deps.inbound.hasCompletedHandoff(e)){this.fence();try{r=await this.deps.retryExecutionAcknowledgement(e,this.abort.signal)}catch{this.fence();return}this.fence()}r&&await this.deps.inbound.acknowledgeExecuted(r),this.fence()}async legacyDiscoveryStep(){if(this.fence(),this.legacyRecoveryItems.length)await this.discoverCoordinate(this.legacyRecoveryItems[0]),this.legacyRecoveryItems=this.legacyRecoveryItems.slice(1);else{let e=await this.deps.reader.legacyPendingInputs(this.legacyRecoveryCursor,this.abort.signal);this.fence(),this.legacyRecoveryItems=e.items,this.legacyRecoveryCursor=e.nextToken??void 0,e.nextToken===null&&(this.legacyRecoveryComplete=!0)}if(this.fence(),this.legacyRecoveryItems.length||this.legacyRecoveryCursor)this.scheduleDiscovery(0);else{this.legacyRecoveryActive=!1;let e=await this.deps.inbound.recoverable();this.fence(),e.uncertain&&this.deps.onUncertain?.(e.uncertain),this.recoveryPages=0,this.scheduleDiscovery(Yg)}}async discoverCoordinate(e){let r=await this.deps.inbound.pendingAcknowledgements();if(this.fence(),r.some(i=>i.eventId===e.eventId&&i.timestamp===e.timestamp))return;let n=await this.deps.reader.pendingInput(e,this.abort.signal);this.fence(),n&&(n.deliveryStatus==="EXECUTED"?await this.deps.inbound.acknowledgeExecuted({...n,deliveryStatus:"EXECUTED"}):await this.deps.inbound.stageDiscovered(n)==="RECEIVED"&&await this.deliver(n,{timestamp:n.timestamp,eventRevision:n.syncEventRevision}))}startPings(){this.pingTimer=setInterval(()=>{try{if(this.fence(),this.pingNonce||this.ws?.readyState!==_k.default.OPEN)throw bn();this.pingNonce=(0,H1.randomBytes)(16),this.pongTimer=setTimeout(()=>this.fail(bn()),NC),this.pongTimer.unref?.(),this.ws.ping(this.pingNonce,void 0,e=>{e&&this.fail(bn())})}catch(e){this.fail(e instanceof Error?e:bn())}},Yg),this.pingTimer.unref?.()}fail(e){if(this.phase!=="closed"){this.close();try{this.deps.onError(e instanceof Tt?e:bn())}catch{}}}history(e,r){return this.fence(),this.deps.reader.history(e,r)}close(){if(this.closing)return this.closing;this.phase="closed",this.abort.abort(bn()),this.rejectReady?.(bn()),clearTimeout(this.controlTimer),clearTimeout(this.pongTimer),clearTimeout(this.heartbeatTimer),clearTimeout(this.recoveryTimer),clearInterval(this.pingTimer);let e=this.ws;this.ws=void 0;let r=new Promise(n=>{if(!e||e.readyState===_k.default.CLOSED){n();return}e.removeAllListeners(),e.on("error",()=>{});let i=setTimeout(()=>{e.terminate()},5e3);i.unref?.(),e.once("close",()=>{clearTimeout(i),n()});try{e.close(1e3)}catch{e.terminate()}});return this.closing=Promise.allSettled([this.starting,this.tail,this.statusRefresh,this.deps.reader.close(),r]).then(()=>{this.seen.clear(),this.beforeHello.length=0,this.recoveryItems=[],this.recoveryCursor=void 0,this.acknowledgementItems=[]}),this.closing}}});var Di,Jp,LC,Qg=D(()=>{"use strict";Di="__CODEVIBE_SESSION_KEY_GEN_ABSENT__",Jp=(n=>(n.ACTIVE="ACTIVE",n.INACTIVE="INACTIVE",n.PAUSED="PAUSED",n))(Jp||{}),LC=(o=>(o.CLAUDE="CLAUDE",o.GEMINI="GEMINI",o.CODEX="CODEX",o.ANTIGRAVITY="ANTIGRAVITY",o.CODEVIBE="CODEVIBE",o))(LC||{})});var Zt,BC,FC,$C,GC,Fc,Ok=D(()=>{"use strict";Zt=require("zod"),BC=Zt.z.object({ts:Zt.z.string().min(1),id:Zt.z.string().min(1)}),FC=Zt.z.object({i:Zt.z.number().int().nonnegative(),digest:Zt.z.string().min(1)}),$C=Zt.z.object({tool:Zt.z.string().min(1),target:Zt.z.string().optional(),count:Zt.z.number().int().nonnegative(),occurrences:Zt.z.array(BC),detail:Zt.z.array(FC).optional()}),GC=Zt.z.object({windowStart:Zt.z.string().optional(),windowEnd:Zt.z.string().optional(),totalInvocations:Zt.z.number().int().nonnegative().optional(),trackId:Zt.z.string().nullable().optional(),groups:Zt.z.array($C),continues:Zt.z.boolean().optional()}),Fc=Zt.z.object({isEncrypted:Zt.z.literal(!1),clientEventId:Zt.z.string().min(1),backendSessionId:Zt.z.string().min(1),syncSessionGenerationId:Zt.z.string().uuid().optional(),windowStart:Zt.z.string().min(1),manifest:GC,invocationIds:Zt.z.array(Zt.z.string())})});function V1(t,e,r){let n=Fc.parse(r);(e!==t.sessionId||n.backendSessionId!==e||n.syncSessionGenerationId!==t.sessionGenerationId||!/^[A-Za-z0-9_-]{1,128}$/.test(n.clientEventId)||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(n.windowStart)||!Number.isFinite(Date.parse(n.windowStart))||new Date(n.windowStart).toISOString()!==n.windowStart)&&Yp();let i=(0,K1.createHash)("sha256").update("codevibe-sync-tool-window-v1\0").update(JSON.stringify([t.sessionId,t.sessionGenerationId,n.clientEventId])).digest().subarray(0,16);i[6]=i[6]&15|128,i[8]=i[8]&63|128;let o=i.toString("hex"),s=[o.slice(0,8),o.slice(8,12),o.slice(12,16),o.slice(16,20),o.slice(20)].join("-");return{envelope:n,operationId:s}}async function z1(t){let e={...t.sessionScope};return await t.outbox.withRetirementSources(e,async n=>{let i=n.windows.map(s=>V1(e,e.sessionId,s).operationId),o=await t.writer.removeRetiredToolOperations(i,t.expectedSessionKeyGen,t.confirm,n);return{windowsRemoved:i.length,operationsRemoved:o}})??{windowsRemoved:0,operationsRemoved:0}}function Xg(t){let{sessionId:e,sessionGenerationId:r}=t.sessionScope;(typeof e!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e)||typeof r!="string"||!j1.test(r))&&Yp();let n=Object.freeze({sessionId:e,sessionGenerationId:r.toLowerCase()}),i=t.writer,o=t.recoveryOnly===!0,s=t.getEncryptionContext.bind(t),a=(c,l)=>V1(n,c,l);return Object.freeze({protocol:"SYNC_V2",sessionGenerationId:n.sessionGenerationId,send:async(c,l)=>{let{envelope:d,operationId:u}=a(c,l);try{return await i.retry(u)}catch(m){if(!(m instanceof Ge)||m.code!=="SYNC_JOURNAL_MISSING"||o)throw m}let p=await s();(p.sessionId!==n.sessionId||p.sessionGenerationId?.toLowerCase()!==n.sessionGenerationId||typeof p.sessionKey!="string"||Buffer.from(p.sessionKey,"base64").length!==32||Buffer.from(p.sessionKey,"base64").toString("base64")!==p.sessionKey||p.sessionKeyGen!==null&&(typeof p.sessionKeyGen!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(p.sessionKeyGen)))&&Yp();let h=p.sessionKey;return await i.prepareCreate({...n,clientOperationId:u,type:"TOOL_ACTIVITY",timestamp:d.windowStart,expectedSessionKeyGen:p.sessionKeyGen??Di,isEncrypted:!0,encryptionVersion:1,content:Xe.encryptContent("Tool activity",h),metadata:{encrypted:Xe.encryptMetadata({manifest:d.manifest},h)}}),i.retry(u)},settled:async(c,l)=>{await i.acknowledge(a(c,l).operationId)}})}async function J1(t){let{sessionId:e,outbox:r,ledger:n}=t;(typeof e!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e))&&Yp(),await r.withSyncRecovery(e,async i=>{let s=(await r.listPending(e,{failClosed:!0})).valid.filter(a=>a.syncSessionGenerationId!==void 0);if(s.length!==0){for(let a of s)(a.backendSessionId!==e||!j1.test(a.syncSessionGenerationId)||a.syncSessionGenerationId!==a.syncSessionGenerationId.toLowerCase())&&Yp();await n.load({failClosed:!0});for(let a of s){await i();let c=t.transportForGeneration(a.syncSessionGenerationId),l=c.settled;if(c.protocol!=="SYNC_V2"||c.sessionGenerationId!==a.syncSessionGenerationId||!l)return Yp();if(!n.isTerminalWindow(a.clientEventId)){let d;try{d=await c.send(e,a)}catch(u){if(u instanceof Ge&&u.code==="SYNC_JOURNAL_MISSING")continue;throw u}if(d?.status==="ACCEPTED")Ps(d.receipt,{sessionId:e,type:"TOOL_ACTIVITY"});else if(d?.status!=="OMITTED"||d.reason!=="SYNC_QUOTA_EXHAUSTED")throw new Error("Invalid durable tool recovery result");await i(),await n.markSettled(a.clientEventId,a.invocationIds,d.status==="ACCEPTED"?"acked":"terminal")}await i(),await l.call(c,e,a),await i(),await r.prune(e,a.clientEventId)}}})}var K1,j1,Yp,Dk=D(()=>{"use strict";K1=require("node:crypto");_p();Tk();Ln();Qg();Ok();j1=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Yp=()=>{throw new ve("INVALID_SYNC_INPUT")}});async function Xp(t,e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Invalid tool file bound");let r=await zr.promises.open(t,zr.constants.O_RDONLY|zr.constants.O_NOFOLLOW|zr.constants.O_NONBLOCK);try{let n=await r.stat();if(!n.isFile()||n.nlink!==1||n.size>e||typeof process.getuid=="function"&&n.uid!==process.getuid())throw new Error("Tool sync recovery required");let i=Buffer.alloc(n.size+1),o=0;for(;o<i.length;){let a=await r.read(i,o,i.length-o,o);if(a.bytesRead===0)break;o+=a.bytesRead}let s=await r.stat();if(o!==n.size||s.size!==n.size||s.mtimeMs!==n.mtimeMs||s.ctimeMs!==n.ctimeMs)throw new Error("Tool sync source changed");return{bytes:i.subarray(0,o),dev:n.dev,ino:n.ino}}finally{await r.close()}}async function es(t){if(process.platform==="win32")return;let e=null;try{e=await zr.promises.open(t,zr.constants.O_RDONLY),await e.sync()}catch{}finally{e&&await e.close().catch(()=>{})}}async function Ni(t,e,r={}){let n=Q1.dirname(t);await zr.promises.mkdir(n,{recursive:!0,mode:wZ});let i=`${t}${Qp}${process.pid}.${X1.randomBytes(6).toString("hex")}`,o=null;try{if(o=await zr.promises.open(i,zr.constants.O_WRONLY|zr.constants.O_CREAT|zr.constants.O_EXCL,Y1),await o.writeFile(e,{encoding:"utf8"}),await o.sync(),await o.close(),o=null,process.platform!=="win32"&&await zr.promises.chmod(i,Y1).catch(()=>{}),await zr.promises.rename(i,t),r.requireDirectorySync){let s=await zr.promises.open(n,zr.constants.O_RDONLY|zr.constants.O_DIRECTORY|zr.constants.O_NOFOLLOW);try{await s.sync()}finally{await s.close()}}else await es(n)}catch(s){throw o&&await o.close().catch(()=>{}),await zr.promises.unlink(i).catch(()=>{}),s}}async function dd(t,e,r,n={}){let i=e.parse(r);await Ni(t,JSON.stringify(i),n)}async function ud(t,e,r,n){let i;try{i=n===void 0?await zr.promises.readFile(t,"utf8"):(await Xp(t,n)).bytes.toString("utf8")}catch(a){return a.code==="ENOENT"||r?.(`read failed: ${a.message}`),null}let o;try{o=JSON.parse(i)}catch{return r?.("malformed JSON"),null}let s=e.safeParse(o);return s.success?s.data:(r?.(`schema mismatch: ${s.error.message}`),null)}var zr,Q1,X1,wZ,Y1,Qp,pd=D(()=>{"use strict";zr=require("node:fs"),Q1=F(require("node:path")),X1=F(require("node:crypto")),wZ=448,Y1=384,Qp=".tmp."});function bZ(t){let e=UC.get(t);return e||(e={owned:new Set,inFlight:new Set,chain:Promise.resolve()},UC.set(t,e)),e}var Z1,Zg,eU,fi,HC,Nk,Mk,UC,Zp,WC=D(()=>{"use strict";Z1=require("node:fs"),Zg=F(require("node:path")),eU=F(require("node:os")),fi=require("zod");pd();HC=fi.z.object({clientEventId:fi.z.string().min(1),byteOffset:fi.z.number().int().nonnegative(),state:fi.z.enum(["durably-outboxed","acked","terminal"])}),Nk=fi.z.object({version:fi.z.literal(1),entries:fi.z.record(fi.z.string(),HC),terminalClientEventIds:fi.z.array(fi.z.string().min(1)).default([])}),Mk=fi.z.object({version:fi.z.literal(1),ids:fi.z.array(fi.z.string().min(1))}),UC=new Map;Zp=class{constructor(e){this.entries=new Map;this.terminalWindows=new Set;this.loaded=!1;this.mutationChain=Promise.resolve();this.agent=e.agent,this.sessionId=e.sessionId,this.logger=e.logger,this.rootDir=e.root??Zg.join(eU.homedir(),".codevibe",e.agent,"tool-activity-outbox")}filePath(){return Zg.join(this.rootDir,this.sessionId,"ledger.json")}legacyOwnedFilePath(){return Zg.join(this.rootDir,this.sessionId,"legacy-owned.json")}get coord(){return bZ(this.legacyOwnedFilePath())}async load(e={}){let r=await ud(this.filePath(),Nk,n=>{if(e.failClosed)throw new Error("Tool sync ledger recovery required");this.logger.error("[tool-activity-ledger] discarding invalid ledger; will rebuild from outbox",{agent:this.agent,sessionId:this.sessionId,reason:n})},e.failClosed?33554432:void 0);this.entries=new Map(r?Object.entries(r.entries):[]),this.terminalWindows=new Set(r?.terminalClientEventIds??[]);for(let n of this.entries.values())n.state==="terminal"&&this.terminalWindows.add(n.clientEventId);await this.reloadLegacyOwned(e),this.loaded=!0}rebuildFromOutbox(e){for(let r of e)if(!this.terminalWindows.has(r.clientEventId))for(let n of r.invocationIds){let i=this.entries.get(n);i&&(i.state==="acked"||i.state==="terminal")||this.entries.set(n,{clientEventId:r.clientEventId,byteOffset:i?.byteOffset??0,state:"durably-outboxed"})}}isKnown(e){let r=this.coord;return this.entries.has(e)||r.owned.has(e)||r.inFlight.has(e)}isKnownDurable(e){let r=this.coord;return this.entries.has(e)||r.owned.has(e)}isLegacyInFlight(e){return this.coord.inFlight.has(e)}getState(e){return this.entries.get(e)?.state}isTerminalWindow(e){return this.terminalWindows.has(e)}durablyOutboxedClientEventIds(){let e=new Set;for(let r of this.entries.values())r.state==="durably-outboxed"&&e.add(r.clientEventId);return[...e]}idsFor(e){let r=[];for(let[n,i]of this.entries)i.clientEventId===e&&r.push(n);return r}safeRewindOffsetFor(e){let r;for(let n of this.entries.values())n.clientEventId===e&&(r=r===void 0?n.byteOffset:Math.min(r,n.byteOffset));return r}async markDurablyOutboxed(e,r){await this.mutateAndPersist(n=>{let i=!1;for(let o of e){let s=n.get(o.id);s&&(s.state==="acked"||s.state==="terminal")||(n.set(o.id,{clientEventId:r,byteOffset:o.byteOffset,state:"durably-outboxed"}),i=!0)}return i})}async markAcked(e){await this.mutateAndPersist(r=>{let n=!1;for(let[i,o]of r)o.clientEventId===e&&o.state==="durably-outboxed"&&(r.set(i,{...o,state:"acked"}),n=!0);return n})}async markTerminal(e,r=[]){return this.markSettled(e,r,"terminal")}async markRetired(e,r){return this.markSettled(e,r,"terminal",!0)}async markSettled(e,r,n,i=!1){await this.mutateAndPersist((o,s)=>{let a=!s.has(e);s.add(e);for(let c of r)!c||o.has(c)||(o.set(c,{clientEventId:e,byteOffset:0,state:n}),a=!0);for(let[c,l]of o)l.clientEventId===e&&l.state==="durably-outboxed"&&(o.set(c,{...l,state:n}),a=!0);return a},i)}async invalidate(e){await this.mutateAndPersist(r=>{let n=!1;for(let[i,o]of r)o.clientEventId===e&&(r.delete(i),n=!0);return n})}async recordLegacyOwned(e){let r=this.coord,n=r.chain.then(async()=>{await this.reloadLegacyOwned();let i=!1;for(let o of e)o&&!r.owned.has(o)&&(r.owned.add(o),i=!0);i&&await dd(this.legacyOwnedFilePath(),Mk,{version:1,ids:[...r.owned]})});return r.chain=n.then(()=>{},()=>{}),n}markLegacyInFlight(e){e&&this.coord.inFlight.add(e)}clearLegacyInFlight(e){e&&this.coord.inFlight.delete(e)}async finalizeLegacyOwned(e){try{await this.recordLegacyOwned(e)}catch(r){this.logger.warn("[tool-activity-ledger] finalizeLegacyOwned durable record failed (best-effort)",{agent:this.agent,sessionId:this.sessionId,error:String(r)})}finally{let r=this.coord;for(let n of e)r.inFlight.delete(n)}}disposeLegacyCoordination(){UC.delete(this.legacyOwnedFilePath())}async reloadLegacyOwned(e={}){let r=await ud(this.legacyOwnedFilePath(),Mk,e.failClosed?()=>{throw new Error("Tool sync ledger recovery required")}:void 0,e.failClosed?33554432:void 0);if(r){let n=this.coord.owned;for(let i of r.ids)n.add(i)}}legacyOwnedSnapshot(){return[...this.coord.owned]}legacyInFlightSnapshot(){return[...this.coord.inFlight]}async prune(e){await this.mutateAndPersist(async(r,n)=>{let i=!1,o=new Map;for(let[s,a]of r)if(!(a.state!=="acked"&&a.state!=="terminal"||a.byteOffset>=e)){if(a.state==="terminal"){let c=o.get(a.clientEventId);if(c===void 0&&(c=await this.outboxEntryExists(a.clientEventId),o.set(a.clientEventId,c)),c)continue}r.delete(s),i=!0}for(let s of n){let a=o.get(s);a===void 0&&(a=await this.outboxEntryExists(s),o.set(s,a)),a||(n.delete(s),i=!0)}return i})}async mutateAndPersist(e,r=!1){let n=this.mutationChain.then(async()=>{let i=new Map(this.entries),o=new Set(this.terminalWindows);!await e(i,o)&&!r||(await this.persist(i,o,r),this.entries=i,this.terminalWindows=o)});return this.mutationChain=n.then(()=>{},()=>{}),n}async outboxEntryExists(e){try{return await Z1.promises.access(Zg.join(this.rootDir,this.sessionId,`${e}.json`)),!0}catch(r){if(r.code==="ENOENT")return!1;throw r}}async persist(e,r,n=!1){let i={version:1,entries:Object.fromEntries(e),terminalClientEventIds:[...r]};if(n&&Buffer.byteLength(JSON.stringify(i),"utf8")>32*1024*1024)throw new Error("Tool sync ledger capacity exceeded");await dd(this.filePath(),Nk,i,{requireDirectorySync:n})}}});function Lk(t){return t?.code==="ENOENT"}var Fn,qC,ts,rU,tU,eh,KC=D(()=>{"use strict";Fn=require("node:fs"),qC=require("node:crypto"),ts=F(require("node:path")),rU=F(require("node:os"));pd();kc();WC();Ok();tU=new Set(["ledger.json","legacy-owned.json","replay-cursor.json"]),eh=class{constructor(e){this.agent=e.agent,this.logger=e.logger,this.rootDir=e.root??ts.join(rU.homedir(),".codevibe",e.agent,"tool-activity-outbox")}sessionDir(e){return ts.join(this.rootDir,e)}retirementLocation(){if(this.agent!=="codex"&&this.agent!=="claude")throw new Error("Invalid tool sync provider");return Object.freeze({agent:this.agent,root:ts.resolve(this.rootDir)})}entryPath(e,r){return ts.join(this.sessionDir(e),`${r}.json`)}async persist(e,r){let n=Fc.parse(r);await Ni(this.entryPath(e,n.clientEventId),JSON.stringify(n))}async listPending(e,r={}){let n=this.sessionDir(e),i;try{i=await Fn.promises.readdir(n)}catch(a){if(Lk(a))return{valid:[],quarantined:[]};throw a}let o=[],s=[];for(let a of i){let c=ts.join(n,a);if(a.includes(Qp)){await Fn.promises.unlink(c).catch(()=>{});continue}if(a.endsWith(".corrupt")){if(r.failClosed)throw new Error("Tool sync outbox recovery required");continue}if(!a.endsWith(".json")||tU.has(a))continue;let l;try{l=JSON.parse(await Fn.promises.readFile(c,"utf8"))}catch{if(r.failClosed)throw new Error("Tool sync outbox recovery required");await this.quarantine(c),s.push(a);continue}let d=Fc.safeParse(l);if(!d.success){if(r.failClosed)throw new Error("Tool sync outbox recovery required");await this.quarantine(c),s.push(a);continue}if(`${d.data.clientEventId}.json`!==a){if(r.failClosed)throw new Error("Tool sync outbox recovery required");await this.quarantine(c),s.push(a);continue}o.push(d.data)}return{valid:o,quarantined:s}}async prune(e,r){try{await Fn.promises.unlink(this.entryPath(e,r))}catch(n){if(Lk(n))return;throw n}}async withSyncRecovery(e,r){if(!/^[A-Za-z0-9_-]{1,256}$/.test(e))throw new Error("Invalid tool sync session");let n=this.sessionDir(e),i;try{i=await Fn.promises.lstat(n)}catch(a){if(Lk(a))return null;throw a}if(!i.isDirectory()||i.isSymbolicLink()||typeof process.getuid=="function"&&i.uid!==process.getuid())throw new Error("Tool sync directory invalid");let o=await Ti({lockDir:ts.join(n,".sync-recovery.lockdir"),ownerlessGraceMs:1/0,maxWaitMs:2e3,requireRemovalOnRelease:!0}).acquire(),s=async()=>{let a=await Fn.promises.lstat(n);if(!a.isDirectory()||a.isSymbolicLink()||a.dev!==i.dev||a.ino!==i.ino||!await o.reassertOwnership())throw new Error("Tool sync ownership lost")};try{await s();let a=await r(s);return await s(),a}finally{await o.release()}}async withRetirementSources(e,r){if(typeof e.sessionGenerationId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e.sessionGenerationId))throw new Error("Invalid tool sync generation");let{sessionId:n,sessionGenerationId:i}=e;return this.withSyncRecovery(n,async o=>{let s=this.sessionDir(n),a=[],c=0,l=0,d=0,u=await Fn.promises.opendir(s);for await(let m of u){if(++c>1032)throw new Error("Tool sync outbox capacity exceeded");if(m.name.endsWith(".corrupt"))throw new Error("Tool sync outbox recovery required");if(m.name.includes(Qp)||tU.has(m.name)||!m.name.endsWith(".json"))continue;if(++d>256)throw new Error("Tool sync outbox capacity exceeded");let f=await Xp(ts.join(s,m.name),1024*1024);if(l+=f.bytes.length,l>32*1024*1024)throw new Error("Tool sync outbox capacity exceeded");let g=Fc.parse(JSON.parse(f.bytes.toString("utf8")));if(g.backendSessionId!==n||!/^[A-Za-z0-9_-]{1,128}$/.test(g.clientEventId)||m.name!==`${g.clientEventId}.json`)throw new Error("Tool sync outbox recovery required");g.syncSessionGenerationId===i&&a.push({name:m.name,dev:f.dev,ino:f.ino,sha256:(0,qC.createHash)("sha256").update(f.bytes).digest("hex"),envelope:g})}if(!a.length)return null;let p=new Zp({agent:this.agent,sessionId:n,root:this.rootDir,logger:this.logger});await p.load({failClosed:!0});let h=async()=>{await o();for(let m of a){let f=await Xp(ts.join(s,m.name),1048576);if(f.dev!==m.dev||f.ino!==m.ino||(0,qC.createHash)("sha256").update(f.bytes).digest("hex")!==m.sha256)throw new Error("Tool sync source changed")}};return r({windows:a.map(m=>m.envelope),markRetired:async()=>{await h();for(let{envelope:m}of a)await o(),await p.markRetired(m.clientEventId,m.invocationIds)},prune:async()=>{await h();for(let f of a)await o(),await Fn.promises.unlink(ts.join(s,f.name));let m=await Fn.promises.open(s,Fn.constants.O_RDONLY|Fn.constants.O_DIRECTORY|Fn.constants.O_NOFOLLOW);try{await m.sync()}finally{await m.close()}}})})}async enumerateSessions(){try{return(await Fn.promises.readdir(this.rootDir,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch(e){if(Lk(e))return[];throw e}}async quarantine(e){this.logger.error("[tool-activity-outbox] quarantining unreadable/invalid outbox entry; occurrences will be re-derived from the transcript",{agent:this.agent,file:e}),await Fn.promises.rename(e,`${e}.corrupt`).catch(async()=>{await Fn.promises.unlink(e).catch(()=>{})})}}});var nU=D(()=>{"use strict"});var iU=D(()=>{"use strict"});var jC,VC=D(()=>{"use strict";jC=(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))(jC||{})});var Ea=D(()=>{"use strict";Yl();Qg();nU();iU();VC()});var th,zC=D(()=>{"use strict";th=class{constructor(e){this.deps=e;this.state="idle";this.retryDelayMs=1e4}start(){this.state==="idle"&&(this.state="running",this.schedule())}stop(){if(this.stopPromise)return this.stopPromise;this.state="stopped",this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=this.active;return e?.controller.abort(new Error("SHELL_SYNC_STOPPED")),this.stopPromise=e?.done??Promise.resolve(),this.stopPromise}schedule(){this.state!=="running"||this.timer||this.active||(this.timer=setTimeout(()=>{this.timer=void 0,this.run()},this.retryDelayMs),this.timer.unref?.())}run(){if(this.state!=="running"||this.active)return;let e=new AbortController,r={controller:e,done:Promise.resolve()};this.active=r,r.done=Promise.resolve().then(async()=>{if(!e.signal.aborted)try{await this.deps.recover(e.signal),e.signal.aborted||(this.retryDelayMs=1e4)}catch(n){if(!e.signal.aborted){this.retryDelayMs=Math.min(6e4,this.retryDelayMs*2);try{this.deps.onFailure(n)}catch{}}}}).finally(()=>{this.active===r&&(this.active=void 0),this.schedule()})}}});function Cs(t,e){let r=t.toLowerCase();if(!JC.test(r)||r!==t.toLowerCase())throw new Error(`${e} must be a canonical UUID`);return r}function uU(t,e,r){if(!e.has(t))throw new Error(`${r} is not a supported decision`);return t}function AZ(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative safe integer`);return t}function TZ(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive safe integer`);return t}function PZ(t){if(!EZ.test(t)||t.length===0)throw new Error("notes.ciphertextB64 must be canonical padded Base64");let e=Buffer.from(t,"base64");if(e.length===0||e.toString("base64")!==t)throw new Error("notes.ciphertextB64 must be canonical padded Base64");return t}function pU(t,e){if(t!==void 0){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("notes must be an object or omitted");if(t.keyVersion!==1||t.sessionId!==e)throw new Error("notes must use keyVersion 1 and the outer sessionId");return{ciphertextB64:PZ(t.ciphertextB64),keyVersion:1,sessionId:e}}}function YC(t){let e=Cs(t.decisionAttemptId,"decisionAttemptId"),r=Cs(t.gateId,"gateId"),n=Cs(t.taskId,"taskId"),i=Cs(t.sessionId,"sessionId"),o=pU(t.notes,i);return{decision:uU(t.decision,RZ,"decision"),decisionAttemptId:e,gateId:r,promptKind:"GATE",currentRound:AZ(t.currentRound,"currentRound"),sessionId:i,taskId:n,...o?{notes:o}:{}}}function QC(t){let e=Cs(t.decisionAttemptId,"decisionAttemptId");if(!kZ.test(t.taskGroupId))throw new Error("taskGroupId must be a canonical 26-character Crockford ULID");let r=`group-escalation:${t.taskGroupId}`;if(t.promptId!==void 0&&t.promptId!==r)throw new Error("promptId does not match taskGroupId");let n=Cs(t.sessionId,"sessionId"),i=pU(t.notes,n);return{decision:uU(t.decision,IZ,"decision"),decisionAttemptId:e,groupGeneration:TZ(t.groupGeneration,"groupGeneration"),promptId:r,promptKind:"TASK_GROUP",sessionId:n,taskGroupId:t.taskGroupId,...i?{notes:i}:{}}}function XC(t){return Buffer.from(JSON.stringify(t),"utf8")}function hU(t){return ey.createHash("sha256").update(Buffer.from(SZ,"utf8")).update(XC(t)).digest("hex")}function ZC(t,e=new Date){let r=XC(t),n=e.toISOString();return{version:lU,request:t,canonicalRequestHash:hU(t),canonicalRequestBytesB64:r.toString("base64"),createdAt:n,updatedAt:n}}function fU(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e}: response is not an object`);return t}function rs(t,e){let r=t[e];return r??null}function fd(t,e,r){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`${r}: ${e} must be a non-empty string`);return n}function mU(t,e,r){for(let n of Object.keys(t))if(!e.has(n))throw new Error(`${r}: unknown field ${n}`)}function tx(t){let e="submitDecisionV2",r=fU(t,e);mU(r,CZ,e);let n=Cs(fd(r,"decisionAttemptId",e),"decisionAttemptId"),i=fd(r,"promptId",e),o=fd(r,"acceptanceStatus",e);if(typeof r.actionable!="boolean")throw new Error(`${e}: actionable is required`);let s={decisionAttemptId:n,promptId:i,actionable:r.actionable,decisionClaimId:rs(r,"decisionClaimId"),resolutionStatus:rs(r,"resolutionStatus"),workflowStatus:rs(r,"workflowStatus"),resolutionEventId:rs(r,"resolutionEventId"),resolutionTimestamp:rs(r,"resolutionTimestamp"),rejectionCode:rs(r,"rejectionCode")};if(o==="SUBMITTED_PENDING"){if(s.actionable!==!1||s.decisionClaimId!==null||s.resolutionStatus!==null||s.workflowStatus!==null||s.resolutionEventId!==null||s.resolutionTimestamp!==null||s.rejectionCode!==null)throw new Error(`${e}: contradictory SUBMITTED_PENDING result`);return{acceptanceStatus:o,...s}}if(o==="REJECTED"){if(s.decisionClaimId!==null||s.resolutionStatus!==null||s.workflowStatus!==null||s.resolutionEventId!==null||s.resolutionTimestamp!==null||s.rejectionCode===null||!ex.has(s.rejectionCode))throw new Error(`${e}: contradictory REJECTED result`);return{acceptanceStatus:o,...s}}if(o==="ACCEPTED_PENDING"){if(s.actionable!==!1||s.decisionClaimId===null||s.resolutionEventId===null||s.resolutionTimestamp!==null||s.rejectionCode!==null||!["PENDING","PENDING_ERROR"].includes(s.resolutionStatus??"")||s.workflowStatus!=="PENDING")throw new Error(`${e}: contradictory ACCEPTED_PENDING result`);return{acceptanceStatus:o,...s}}if(o==="ACCEPTED_RESOLVED"){if(s.actionable!==!1||s.decisionClaimId===null||s.resolutionEventId===null||s.resolutionTimestamp===null||s.rejectionCode!==null||s.resolutionStatus!=="COMPLETE"||s.workflowStatus===null||!_Z.has(s.workflowStatus))throw new Error(`${e}: contradictory ACCEPTED_RESOLVED result`);return{acceptanceStatus:o,...s}}throw new Error(`${e}: unknown acceptanceStatus`)}function gU(t){let e="getDecisionAttempt",r=fU(t,e);mU(r,xZ,e);let n={sessionId:Cs(fd(r,"sessionId",e),"sessionId"),promptId:fd(r,"promptId",e),decisionAttemptId:Cs(fd(r,"decisionAttemptId",e),"decisionAttemptId"),canonicalRequestHash:rs(r,"canonicalRequestHash"),decisionClaimId:rs(r,"decisionClaimId"),resolutionEventId:rs(r,"resolutionEventId"),resolutionTimestamp:rs(r,"resolutionTimestamp"),rejectionCode:rs(r,"rejectionCode"),actionable:r.actionable};if(typeof n.actionable!="boolean")throw new Error(`${e}: actionable is required`);if(n.canonicalRequestHash!==null&&!dU.test(n.canonicalRequestHash))throw new Error(`${e}: invalid canonicalRequestHash`);let i=fd(r,"state",e);if(i==="NOT_FOUND"){if(n.actionable!==!1||n.canonicalRequestHash!==null||n.decisionClaimId!==null||n.resolutionEventId!==null||n.resolutionTimestamp!==null||n.rejectionCode!==null)throw new Error(`${e}: contradictory NOT_FOUND result`)}else if(i==="SUBMITTED"){if(n.actionable!==!1||n.canonicalRequestHash===null||n.decisionClaimId!==null||n.resolutionEventId!==null||n.resolutionTimestamp!==null||n.rejectionCode!==null)throw new Error(`${e}: contradictory SUBMITTED result`)}else if(i==="CLAIMED"){if(n.actionable!==!1||n.canonicalRequestHash===null||n.decisionClaimId===null||n.resolutionEventId===null||n.resolutionTimestamp!==null||n.rejectionCode!==null)throw new Error(`${e}: contradictory CLAIMED result`)}else if(i==="RESOLVED"){if(n.actionable!==!1||n.canonicalRequestHash===null||n.decisionClaimId===null||n.resolutionEventId===null||n.resolutionTimestamp===null||n.rejectionCode!==null)throw new Error(`${e}: contradictory RESOLVED result`)}else if(i==="REJECTED"){if(n.decisionClaimId!==null||n.resolutionEventId!==null||n.resolutionTimestamp!==null||n.rejectionCode===null||!ex.has(n.rejectionCode)||n.canonicalRequestHash===null&&n.rejectionCode!=="ATTEMPT_LIMIT")throw new Error(`${e}: contradictory REJECTED result`)}else throw new Error(`${e}: unknown state`);return{state:i,...n}}function OZ(){return an.join(cU.homedir(),".codevibe","decision-attempts")}function Bk(t){return ey.createHash("sha256").update(t,"utf8").digest("hex")}function hd(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("DecisionAttemptReceiptStore: receipt is not an object");let e=t,r=new Set(["version","request","canonicalRequestHash","canonicalRequestBytesB64","createdAt","updatedAt","terminal"]);if(Object.keys(e).some(o=>!r.has(o))||Object.keys(e).length!==(e.terminal===void 0?6:7)||e.version!==lU||!dU.test(e.canonicalRequestHash)||typeof e.canonicalRequestBytesB64!="string"||typeof e.createdAt!="string"||!Number.isFinite(Date.parse(e.createdAt))||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt)))throw new Error("DecisionAttemptReceiptStore: receipt has an invalid envelope");let n=e.request?.promptKind==="GATE"?YC(e.request):e.request?.promptKind==="TASK_GROUP"?QC(e.request):null;if(!n)throw new Error("DecisionAttemptReceiptStore: unknown request kind");if(XC(n).toString("base64")!==e.canonicalRequestBytesB64||hU(n)!==e.canonicalRequestHash)throw new Error("DecisionAttemptReceiptStore: receipt identity mismatch");if(e.terminal!==void 0){if(!e.terminal||typeof e.terminal!="object"||Array.isArray(e.terminal))throw new Error("DecisionAttemptReceiptStore: terminal is malformed");let o=e.terminal;if(o.state==="RESOLVED"){let s=new Set(["state","decisionClaimId","resolutionEventId","resolutionTimestamp"]);if(Object.keys(o).length!==s.size||Object.keys(o).some(a=>!s.has(a))||typeof o.decisionClaimId!="string"||!JC.test(o.decisionClaimId)||typeof o.resolutionEventId!="string"||!JC.test(o.resolutionEventId)||typeof o.resolutionTimestamp!="string"||!Number.isFinite(Date.parse(o.resolutionTimestamp)))throw new Error("DecisionAttemptReceiptStore: resolved terminal is malformed")}else if(o.state==="REJECTED"){let s=new Set(["state","rejectionCode","actionable"]);if(Object.keys(o).length!==s.size||Object.keys(o).some(a=>!s.has(a))||typeof o.rejectionCode!="string"||!ex.has(o.rejectionCode)||typeof o.actionable!="boolean")throw new Error("DecisionAttemptReceiptStore: rejected terminal is malformed")}else throw new Error("DecisionAttemptReceiptStore: terminal state is unknown")}return{...e,request:n}}var ey,Mr,Ra,cU,an,SZ,lU,oU,sU,vZ,aU,JC,dU,kZ,EZ,RZ,IZ,ex,_Z,CZ,xZ,$c,ty=D(()=>{"use strict";ey=F(require("node:crypto")),Mr=F(require("node:fs/promises")),Ra=require("node:fs"),cU=F(require("node:os")),an=F(require("node:path")),SZ="codevibe.decision_attempt.v1\0",lU=1,oU=448,sU=384,vZ=64*1024,aU=16,JC=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,dU=/^[0-9a-f]{64}$/,kZ=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,EZ=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,RZ=new Set(["ACCEPT","ACCEPT_WITH_NOTES","REJECT_WITH_NOTES","REJECT_RESTART","ABORT_TASK","APPROVE","CANCEL","CONTINUE_WITH"]),IZ=new Set(["ACCEPT","ACCEPT_WITH_NOTES","REJECT_WITH_NOTES","REJECT_RESTART","ABORT_TASK"]);ex=new Set(["INVALID_PROMPT","STALE_GENERATION","DECISION_RACE_LOST","ATTEMPT_LIMIT","REQUEST_MISMATCH","ACCOUNT_DELETING","POLICY_REJECTED"]),_Z=new Set(["PENDING","PENDING_ERROR","COMPLETE"]);CZ=new Set(["decisionAttemptId","acceptanceStatus","decisionClaimId","promptId","actionable","resolutionStatus","workflowStatus","resolutionEventId","resolutionTimestamp","rejectionCode"]);xZ=new Set(["sessionId","promptId","decisionAttemptId","state","canonicalRequestHash","decisionClaimId","resolutionEventId","resolutionTimestamp","rejectionCode","actionable"]);$c=class t{static{this.sessionQueues=new Map}constructor(e={}){this.rootDir=e.rootDir??OZ(),this.syncDirectory=e.directorySync??(async r=>{let n;try{let i=Ra.constants.O_RDONLY|(typeof Ra.constants.O_NOFOLLOW=="number"?Ra.constants.O_NOFOLLOW:0)|(typeof Ra.constants.O_DIRECTORY=="number"?Ra.constants.O_DIRECTORY:0);n=await Mr.open(r,i)}catch(i){if(i.code==="ENOENT")return;throw i}try{await n.sync()}finally{await n.close()}})}receiptPath(e,r,n){return Cs(n,"decisionAttemptId"),an.join(this.rootDir,Bk(e),Bk(r),`${n.toLowerCase()}.json`)}sessionQueueKey(e){return an.join(an.resolve(this.rootDir),Bk(e))}async withSessionLock(e,r){let n=this.sessionQueueKey(e),i=t.sessionQueues.get(n)??Promise.resolve(),o,s=new Promise(c=>{o=c}),a=i.then(()=>s);t.sessionQueues.set(n,a),await i;try{return await r()}finally{o(),t.sessionQueues.get(n)===a&&t.sessionQueues.delete(n)}}async assertNoSymlinkComponents(e){let r=an.relative(this.rootDir,e);if(r.startsWith("..")||an.isAbsolute(r))throw new Error("DecisionAttemptReceiptStore: path escaped receipt root");let n=r?r.split(an.sep):[],i=this.rootDir;for(let o=-1;o<n.length;o+=1){o>=0&&(i=an.join(i,n[o]));try{if((await Mr.lstat(i)).isSymbolicLink())throw new Error("DecisionAttemptReceiptStore: symlinked path component")}catch(s){if(s.code==="ENOENT")return;throw s}}}async atomicWrite(e,r){await this.assertNoSymlinkComponents(e);let n=an.dirname(e);await Mr.mkdir(n,{recursive:!0,mode:oU}),process.platform!=="win32"&&await Mr.chmod(n,oU);let i=`${e}.tmp.${process.pid}.${ey.randomBytes(6).toString("hex")}`,o;try{o=await Mr.open(i,Ra.constants.O_WRONLY|Ra.constants.O_CREAT|Ra.constants.O_EXCL,sU),await o.writeFile(r,"utf8"),await o.sync(),await o.close(),o=void 0,process.platform!=="win32"&&await Mr.chmod(i,sU),await Mr.rename(i,e),await this.syncDirectory(n)}catch(s){throw await o?.close().catch(()=>{}),await Mr.unlink(i).catch(()=>{}),s}}async removeDirectoryEntryDurably(e){await this.assertNoSymlinkComponents(e);let r=an.dirname(e);try{await Mr.unlink(e)}catch(n){if(n.code!=="ENOENT")throw n}await this.assertNoSymlinkComponents(r),await this.syncDirectory(r)}async readUnlocked(e,r,n){let i=this.receiptPath(e,r,n);await this.assertNoSymlinkComponents(i);try{return hd(JSON.parse(await Mr.readFile(i,"utf8")))}catch(o){if(o.code==="ENOENT")return null;throw o}}sameImmutableIdentity(e,r){return e.canonicalRequestHash===r.canonicalRequestHash&&e.canonicalRequestBytesB64===r.canonicalRequestBytesB64&&e.createdAt===r.createdAt&&JSON.stringify(e.request)===JSON.stringify(r.request)}async write(e){let r=hd(e);if(r.terminal!==void 0)throw new Error("DecisionAttemptReceiptStore: initial write cannot carry a terminal");let n=r.request.promptKind==="GATE"?r.request.gateId:r.request.promptId,i=this.receiptPath(r.request.sessionId,n,r.request.decisionAttemptId);await this.withSessionLock(r.request.sessionId,async()=>{let o=await this.readUnlocked(r.request.sessionId,n,r.request.decisionAttemptId);if(o){if(!this.sameImmutableIdentity(o,r))throw new Error("DecisionAttemptReceiptStore: immutable receipt mismatch");return}if((await this.listForSessionUnlocked(r.request.sessionId)).length>=aU)throw new Error("DecisionAttemptReceiptStore: session receipt limit exceeded");await this.atomicWrite(i,`${JSON.stringify(r)}
768
768
  `)})}async read(e,r,n){return this.readUnlocked(e,r,n)}async listForSessionUnlocked(e){let r=an.join(this.rootDir,Bk(e));await this.assertNoSymlinkComponents(r);let n;try{n=await Mr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}let i=[];for(let o of n.sort((s,a)=>s.name.localeCompare(a.name))){if(!o.isDirectory()||o.isSymbolicLink())throw new Error("DecisionAttemptReceiptStore: unexpected session directory entry");let s=an.join(r,o.name);await this.assertNoSymlinkComponents(s);let a=await Mr.readdir(s,{withFileTypes:!0});for(let c of a.sort((l,d)=>l.name.localeCompare(d.name))){if(!c.isFile()||c.isSymbolicLink()||!c.name.endsWith(".json"))throw new Error("DecisionAttemptReceiptStore: unexpected prompt directory entry");if(i.length>=aU)throw new Error("DecisionAttemptReceiptStore: session receipt limit exceeded");let l=an.join(s,c.name);if(await this.assertNoSymlinkComponents(l),(await Mr.stat(l)).size>vZ)throw new Error("DecisionAttemptReceiptStore: receipt exceeds size limit");let u=hd(JSON.parse(await Mr.readFile(l,"utf8")));if(u.request.sessionId!==e)throw new Error("DecisionAttemptReceiptStore: receipt session mismatch");i.push(u)}}return i.sort((o,s)=>o.createdAt.localeCompare(s.createdAt))}async listForSession(e){return this.withSessionLock(e,()=>this.listForSessionUnlocked(e))}async markTerminal(e,r,n=new Date){let i=hd(e),o=i.request.promptKind==="GATE"?i.request.gateId:i.request.promptId,s=this.receiptPath(i.request.sessionId,o,i.request.decisionAttemptId);return this.withSessionLock(i.request.sessionId,async()=>{let a=await this.readUnlocked(i.request.sessionId,o,i.request.decisionAttemptId);if(!a)return null;if(!this.sameImmutableIdentity(a,i))throw new Error("DecisionAttemptReceiptStore: immutable receipt mismatch");if(a.terminal!==void 0){if(JSON.stringify(a.terminal)!==JSON.stringify(r))throw new Error("DecisionAttemptReceiptStore: conflicting terminal advancement");return a}let c=hd({...a,updatedAt:n.toISOString(),terminal:r});return await this.atomicWrite(s,`${JSON.stringify(c)}
769
769
  `),c})}async abandonUnsubmitted(e){let r=hd(e);if(r.terminal!==void 0)throw new Error("DecisionAttemptReceiptStore: cannot abandon a terminal receipt");let n=r.request.promptKind==="GATE"?r.request.gateId:r.request.promptId,i=this.receiptPath(r.request.sessionId,n,r.request.decisionAttemptId);await this.withSessionLock(r.request.sessionId,async()=>{let o=await this.readUnlocked(r.request.sessionId,n,r.request.decisionAttemptId);if(!o){await this.removeDirectoryEntryDurably(i);return}if(!this.sameImmutableIdentity(o,r))throw new Error("DecisionAttemptReceiptStore: immutable receipt mismatch");if(o.terminal!==void 0)throw new Error("DecisionAttemptReceiptStore: cannot abandon an advanced receipt");await this.removeDirectoryEntryDurably(i)})}async acknowledge(e){let r=hd(e);if(!r.terminal)throw new Error("DecisionAttemptReceiptStore: cannot acknowledge a non-terminal receipt");let n=r.request.promptKind==="GATE"?r.request.gateId:r.request.promptId,i=this.receiptPath(r.request.sessionId,n,r.request.decisionAttemptId);await this.withSessionLock(r.request.sessionId,async()=>{let o=await this.readUnlocked(r.request.sessionId,n,r.request.decisionAttemptId);if(!o){await this.removeDirectoryEntryDurably(i);return}if(!this.sameImmutableIdentity(o,r))throw new Error("DecisionAttemptReceiptStore: immutable receipt mismatch");if(o.terminal!==void 0&&JSON.stringify(o.terminal)!==JSON.stringify(r.terminal))throw new Error("DecisionAttemptReceiptStore: conflicting terminal acknowledgement");await this.removeDirectoryEntryDurably(i)})}}});function Co(t,e){try{e!==void 0&&t.readyState===Uc.default.OPEN&&t.send(JSON.stringify({id:e,type:"stop"}))}catch{}try{t.removeAllListeners()}catch{}try{t.on("error",()=>{})}catch{}try{t.close(1e3)}catch{}}function rh(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e}: malformed GroupOperationResult`);let r=t,n=["taskGroupId","groupGeneration","operationKind","callStatus","authorizationState","anchorId","anchorTimestamp","manifestHash","memberCount","operationHash","operationToken","decisionClaimId","operationReceiptHash","promotionCompletionKind","revertCompletionKind","committedAt","rejectionCode"];if(Object.keys(r).length!==n.length||!n.every(u=>Object.prototype.hasOwnProperty.call(r,u)))throw new Error(`${e}: malformed GroupOperationResult fields`);let i=new Set(["APPLIED","ALREADY_APPLIED","PENDING_RECOVERY","CANCELLED","REJECTED"]),o=new Set(["PROMOTE","KEEP","REVERT"]),s=new Set(["PROVISIONAL","AUTHORIZED","PROMOTING","REVERTING","READY_TO_COMMIT","COMMITTED","OUTCOME_RECORDED","CANCELLED"]);if(typeof r.taskGroupId!="string"||!/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(r.taskGroupId)||typeof r.groupGeneration!="number"||!Number.isSafeInteger(r.groupGeneration)||r.groupGeneration<1||typeof r.callStatus!="string"||!i.has(r.callStatus))throw new Error(`${e}: malformed GroupOperationResult identity`);let a=u=>{let p=r[u];if(p===null)return null;if(typeof p!="string"||p.length===0)throw new Error(`${e}: malformed ${u}`);return p},c=["operationKind","authorizationState","anchorId","anchorTimestamp","manifestHash","operationHash","operationToken","decisionClaimId","operationReceiptHash","promotionCompletionKind","revertCompletionKind","committedAt","rejectionCode"];for(let u of c)a(u);if(r.memberCount!==null&&(typeof r.memberCount!="number"||!Number.isSafeInteger(r.memberCount)||r.memberCount<1))throw new Error(`${e}: malformed memberCount`);let d={authorizeGroupTerminalOperation:new Set(["INVALID_GROUP","STALE_GENERATION","HALT_WON","OPERATION_CONFLICT","CLAIM_MISMATCH","ACCOUNT_DELETING"]),beginGroupPromotion:new Set(["INVALID_GROUP","STALE_GENERATION","HALT_WON","OPERATION_CONFLICT","TOKEN_MISMATCH","ACCOUNT_DELETING"]),completeGroupPromotion:new Set(["INVALID_GROUP","STALE_GENERATION","OPERATION_CONFLICT","TOKEN_MISMATCH","RECEIPT_MISMATCH","ACCOUNT_DELETING"]),beginGroupRevert:new Set(["INVALID_GROUP","STALE_GENERATION","OPERATION_CONFLICT","CLAIM_MISMATCH","TOKEN_MISMATCH","ACCOUNT_DELETING"]),completeGroupRevert:new Set(["INVALID_GROUP","STALE_GENERATION","OPERATION_CONFLICT","CLAIM_MISMATCH","TOKEN_MISMATCH","RECEIPT_MISMATCH","ACCOUNT_DELETING"]),prepareGroupKeep:new Set(["INVALID_GROUP","STALE_GENERATION","OPERATION_CONFLICT","CLAIM_MISMATCH","RECEIPT_MISMATCH","ACCOUNT_DELETING"])}[e];if(!d)throw new Error(`${e}: unknown group operation parser`);if(r.callStatus==="REJECTED"){if(typeof r.rejectionCode!="string"||!d.has(r.rejectionCode)||r.memberCount!==null||c.some(u=>u!=="rejectionCode"&&r[u]!==null))throw new Error(`${e}: contradictory rejected GroupOperationResult`)}else{if(typeof r.operationKind!="string"||!o.has(r.operationKind)||typeof r.authorizationState!="string"||!s.has(r.authorizationState)||typeof r.anchorId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r.anchorId)||typeof r.anchorTimestamp!="string"||!Number.isFinite(Date.parse(r.anchorTimestamp))||typeof r.manifestHash!="string"||!/^[0-9a-f]{64}$/.test(r.manifestHash)||typeof r.memberCount!="number"||!Number.isSafeInteger(r.memberCount)||r.memberCount<1||typeof r.operationHash!="string"||!/^[0-9a-f]{64}$/.test(r.operationHash)||r.rejectionCode!==null)throw new Error(`${e}: contradictory GroupOperationResult`);let u=r.operationKind,p=r.authorizationState,h=p==="COMMITTED"||p==="OUTCOME_RECORDED";if(!{PROMOTE:new Set(["PROVISIONAL","PROMOTING","COMMITTED","OUTCOME_RECORDED","CANCELLED"]),KEEP:new Set(["AUTHORIZED","READY_TO_COMMIT","COMMITTED","OUTCOME_RECORDED"]),REVERT:new Set(["AUTHORIZED","REVERTING","READY_TO_COMMIT","COMMITTED","OUTCOME_RECORDED"])}[u].has(p))throw new Error(`${e}: impossible operation/state pair`);let f=(b,v)=>{if(v!==(r[b]!==null))throw new Error(`${e}: contradictory ${b}`)};if(f("decisionClaimId",u!=="PROMOTE"),f("operationToken",u==="PROMOTE"&&(p==="PROMOTING"||h)||u==="REVERT"&&(p==="REVERTING"||p==="READY_TO_COMMIT"||h)),f("operationReceiptHash",p==="READY_TO_COMMIT"||h),f("promotionCompletionKind",u==="PROMOTE"&&h),f("revertCompletionKind",u==="REVERT"&&(p==="READY_TO_COMMIT"||h)),f("committedAt",h),r.operationToken!==null&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(String(r.operationToken))||r.decisionClaimId!==null&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(String(r.decisionClaimId))||r.operationReceiptHash!==null&&!/^[0-9a-f]{64}$/.test(String(r.operationReceiptHash))||r.promotionCompletionKind!==null&&!["FRESH_APPLIED","RECONCILED_APPLIED","ROLLED_BACK_NO_CHANGE"].includes(String(r.promotionCompletionKind))||r.revertCompletionKind!==null&&!["REVERTED","PARTIALLY_REVERTED","NO_CHANGE"].includes(String(r.revertCompletionKind))||r.committedAt!==null&&!Number.isFinite(Date.parse(String(r.committedAt))))throw new Error(`${e}: malformed authoritative fields`);let g=r.callStatus,y=(b,v)=>u===b&&v.includes(p),S=!1;switch(e){case"authorizeGroupTerminalOperation":S=g==="APPLIED"?y("PROMOTE",["PROVISIONAL"])||y("KEEP",["AUTHORIZED"])||y("REVERT",["AUTHORIZED"]):g==="ALREADY_APPLIED"?p!=="CANCELLED":g==="CANCELLED"&&y("PROMOTE",["CANCELLED"]);break;case"beginGroupPromotion":S=g==="APPLIED"?y("PROMOTE",["PROMOTING"]):g==="ALREADY_APPLIED"?y("PROMOTE",["PROMOTING","COMMITTED","OUTCOME_RECORDED"]):g==="CANCELLED"&&y("PROMOTE",["CANCELLED"]);break;case"completeGroupPromotion":S=g==="APPLIED"?y("PROMOTE",["COMMITTED"]):g==="ALREADY_APPLIED"?y("PROMOTE",["COMMITTED","OUTCOME_RECORDED"]):g==="PENDING_RECOVERY"&&y("PROMOTE",["PROMOTING"]);break;case"beginGroupRevert":S=g==="APPLIED"?y("REVERT",["REVERTING"]):g==="ALREADY_APPLIED"&&y("REVERT",["REVERTING","READY_TO_COMMIT","COMMITTED","OUTCOME_RECORDED"]);break;case"completeGroupRevert":S=g==="APPLIED"?y("REVERT",["READY_TO_COMMIT"]):g==="ALREADY_APPLIED"?y("REVERT",["READY_TO_COMMIT","COMMITTED","OUTCOME_RECORDED"]):g==="PENDING_RECOVERY"&&y("REVERT",["REVERTING"]);break;case"prepareGroupKeep":S=g==="APPLIED"?y("KEEP",["READY_TO_COMMIT"]):g==="ALREADY_APPLIED"?y("KEEP",["READY_TO_COMMIT","COMMITTED","OUTCOME_RECORDED"]):g==="PENDING_RECOVERY"&&y("KEEP",["AUTHORIZED"]);break}if(!S)throw new Error(`${e}: impossible call-status tuple`)}return{taskGroupId:r.taskGroupId,groupGeneration:r.groupGeneration,operationKind:r.operationKind,callStatus:r.callStatus,authorizationState:r.authorizationState,anchorId:a("anchorId"),anchorTimestamp:a("anchorTimestamp"),manifestHash:a("manifestHash"),memberCount:r.memberCount===null?null:r.memberCount,operationHash:a("operationHash"),operationToken:a("operationToken"),decisionClaimId:a("decisionClaimId"),operationReceiptHash:a("operationReceiptHash"),promotionCompletionKind:a("promotionCompletionKind"),revertCompletionKind:a("revertCompletionKind"),committedAt:a("committedAt"),rejectionCode:a("rejectionCode")}}function DZ(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("commitGroupDecisionV2: malformed result");let e=t;if(typeof e.taskGroupId!="string"||typeof e.decisionClaimId!="string"||!["COMMITTED","ALREADY_COMMITTED","PENDING_RECOVERY"].includes(String(e.commitStatus))||!["COMPLETE","PENDING_ERROR"].includes(String(e.workflowStatus)))throw new Error("commitGroupDecisionV2: malformed identity or status");let r=e.commitStatus==="PENDING_RECOVERY";if(r!==(e.workflowStatus==="PENDING_ERROR")||r&&(e.groupStatus!==null||e.committedAt!==null)||!r&&(!["COMPLETE","HALTED"].includes(String(e.groupStatus))||typeof e.committedAt!="string"||!Number.isFinite(Date.parse(e.committedAt))))throw new Error("commitGroupDecisionV2: contradictory result state");return e}function Gc(t,e){let r=t[e];return typeof r=="number"&&Number.isInteger(r)&&r>=0?{[e]:r}:{}}function rx(t,e){let r=typeof t.taskId=="string"&&t.taskId.length>0,n=typeof t.taskGroupId=="string"&&t.taskGroupId.length>0;if(r===n)throw new Error(`${e}: exactly one of taskId or taskGroupId is required`);return r?{taskId:t.taskId}:{taskGroupId:t.taskGroupId}}function nh(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t=="string"){let r;try{r=JSON.parse(t)}catch(n){throw new Error(`${e}: failed to parse AWSJSON payload: ${n.message}`)}if(typeof r=="string")try{r=JSON.parse(r)}catch(n){throw new Error(`${e}: failed to parse double-encoded AWSJSON payload: ${n.message}`)}if(r!==null&&typeof r=="object"&&!Array.isArray(r))return r;throw new Error(`${e}: parsed AWSJSON payload is not an object`)}throw new Error(`${e}: expected AWSJSON object or string, got ${t===null?"null":typeof t}`)}function NZ(t){return(t instanceof Error?t.message:String(t)).includes("RETIRED_SESSION_CANNOT_REACTIVATE")}function MZ(t){return t instanceof Ut?t.message.includes("field that is not defined for input object type 'SubmitImplementorOutputInput'"):!1}function yU(t,e){return!!(t.source==="MOBILE"||e&&t.source==="DESKTOP")}function ih(t,e){return t==="credential_storage_unavailable"?{exitCode:ny,message:["CodeVibe could not read its stored credentials. This is not a sign-in problem.",e??"The credential store is unavailable."].join(`
770
- `)}:t==="refresh_network"?{exitCode:1,message:"Could not reach the CodeVibe sign-in service to refresh your session. Check your network connection and try again; you are still signed in."}:{exitCode:1,message:'Not authenticated. Run "codevibe login" to sign in.'}}function ox(t=process.env){let e=jn(t);return e==="development"||e==="experiment"}function Fk(t,e=process.env){let r;if(t!==void 0?r=t:ox(e)&&e.CODEVIBE_HEARTBEAT_INTERVAL_MS!==void 0&&(r=e.CODEVIBE_HEARTBEAT_INTERVAL_MS),r==null||r==="")return ry;let n=typeof r=="number"?r:Number(r);return!Number.isFinite(n)||!Number.isInteger(n)||n<nx||n>ix?ry:n}var Uc,wU,bU,Qn,Ut,Mi,Kt,ny,ry,nx,ix,SU,xs,sx=D(()=>{"use strict";Uc=F(require("ws")),wU=require("node:crypto"),bU=require("json-freeze"),Qn=require("uuid");Rs();Ye();A_();Nn();Dn();T_();P_();Mp();q$();F_();Tk();Hp();q1();fC();wC();Qg();TC();CC();Dk();KC();Ln();Ea();zC();ty();Ut=class extends Error{constructor(e){super(`GraphQL error: ${e.message}`),this.name="AppSyncGraphQLError",this.responseMessage=e.message,this.errorType=e.errorType,this.extensions=e.extensions,this.path=e.path,this.data=e.data,this.requestId=typeof e.requestId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e.requestId)?e.requestId:void 0}},Mi=class extends Error{constructor(e){super(e==="refresh_network"?"Authentication refresh could not reach the authentication service":"Authentication refresh was rejected"),this.name="AppSyncAuthenticationError",this.kind=e}};Kt={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3};ny=78;ry=12e4,nx=1e3,ix=3e5,SU=new Set(["development","experiment"]);xs=class t{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.syncDisplayEpoch=0;this.syncDisplaySequence=0;this.syncDisplayAppliedSequence=0;this.syncDisplay=null;this.syncDisplayListeners=new Set;this.syncStateRead=null;this.syncStateRetry=null;this.syncProducerEpoch=0;this.syncProducerRetry=new Map;this.activeSubscriptions=new Map;this.lastAuthFailureKind=null;this.lastAuthFailureDetail=null;this.lastRefreshNetworkError=!1;this.pendingRefresh=null;this.pendingRefreshCredential=null;this.pendingReconnectReconciliation=null;this.reconnectReconciliationWaiters=new WeakMap;this.tokenStateGeneration=0;this.lastRefreshFailureAt=null;this.lastRefreshFailureCredential=null;this.deviceKeyWatcher=null;this.sessionUpdateWatchers=new Map;this.applyUserDecisionWatchers=new Map;this.promptActionWatchers=new Map;this.statusWriteChains=new Map;this.companionNoticeOwners=new Map;this.sessionRetirementRecoveryPasses=new Map;this.syncSubscriptionClosures=new Map;this.syncReadOwners=new Map;this.syncReadEpoch=0;this.syncRetiringSessions=new Set;this.syncRegistrations=new Map;this.heartbeatTimers=new Map;this.heartbeatTokens=new Map;this.heartbeatInitialPulses=new Map;this.heartbeatInitialOutcomes=new Map;this.heartbeatInFlight=new Map;this.classBWatcher=null;this.classBPacketHandlers=new Map;this.environment=jn(),w.info("[AppSyncClient] Initialized",{environment:this.environment})}static{this.REFRESH_BACKOFF_MS=3e4}static{this.COGNITO_REFRESH_TIMEOUT_MS=1e4}static{this.RECONNECT_RECONCILIATION_TIMEOUT_MS=1e4}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}getLastAuthFailureKind(){return this.lastAuthFailureKind}getLastAuthFailureDetail(){return this.lastAuthFailureDetail}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,this.lastAuthFailureDetail=null,this.resetSyncProducerAuthority(),this.resetCompanionSyncDisplay();try{let e;try{e=await _e.getTokens(this.environment)}catch(r){return w.error("[AppSyncClient] Could not read stored authentication tokens:",r),this.lastAuthFailureKind="credential_storage_unavailable",this.lastAuthFailureDetail=r instanceof Error?r.message:String(r),!1}if(!e)return w.debug("[AppSyncClient] No stored tokens found"),this.lastAuthFailureKind="no_tokens",!1;if(w.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:_e.isTokenExpired(e)}),_e.isTokenExpired(e)){if(w.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return w.warn("[AppSyncClient] Token refresh failed"),this.lastAuthFailureKind=this.lastRefreshNetworkError?"refresh_network":"refresh_auth_rejected",!1}else this.replaceTokens(e);return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,w.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){w.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}}static abortReason(e){if(e.reason instanceof Error)return e.reason;let r=new Error(e.reason===void 0?"operation aborted":String(e.reason));return r.name="AbortError",r}static throwIfAborted(e){if(e?.aborted)throw t.abortReason(e)}static async waitForSyncStateRetry(e,r){t.throwIfAborted(r),await new Promise((n,i)=>{let o=setTimeout(()=>{r?.removeEventListener("abort",s),n()},e),s=()=>{clearTimeout(o),r?.removeEventListener("abort",s),i(t.abortReason(r))};r?.addEventListener("abort",s,{once:!0}),r?.aborted&&s()})}static async awaitWithinAbsoluteDeadline(e,r,n,i){let o=e-Date.now(),s=new Error(`${r} timed out`);if(o<=0){try{i?.(s)}catch{}throw s}let a;try{let c=n();return await Promise.race([c,new Promise((l,d)=>{a=setTimeout(()=>{try{i?.(s)}catch{}d(s)},o),a.unref?.()})])}finally{a&&clearTimeout(a)}}static awaitSharedFlightForCaller(e,r){return r?(t.throwIfAborted(r),new Promise((n,i)=>{let o=!1,s=c=>{o||(o=!0,r.removeEventListener("abort",a),c())},a=()=>{s(()=>i(t.abortReason(r)))};if(r.addEventListener("abort",a,{once:!0}),r.aborted){a();return}e.then(c=>s(()=>n(c)),c=>s(()=>i(c)))})):e}replaceTokens(e){this.tokens=e,this.tokenStateGeneration+=1}async refreshTokens(e,r,n=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS,i=this.tokenStateGeneration){for(t.throwIfAborted(r);this.pendingRefresh;){if(this.pendingRefreshCredential===e.refreshToken)return t.awaitSharedFlightForCaller(this.pendingRefresh,r);if(await t.awaitSharedFlightForCaller(this.pendingRefresh,r),t.throwIfAborted(r),this.tokens?.refreshToken===e.refreshToken&&!_e.isTokenExpired(this.tokens))return!0;if(Date.now()>=n)return!1}if(this.lastRefreshFailureAt!==null&&this.lastRefreshFailureCredential===e.refreshToken&&Date.now()-this.lastRefreshFailureAt<t.REFRESH_BACKOFF_MS)return!1;let o=this.performRefresh(e,n,i);return this.pendingRefresh=o,this.pendingRefreshCredential=e.refreshToken,o.finally(()=>{this.pendingRefresh===o&&(this.pendingRefresh=null,this.pendingRefreshCredential=null)}).catch(()=>{}),t.awaitSharedFlightForCaller(o,r)}async performRefresh(e,r=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS,n=this.tokenStateGeneration){this.lastRefreshNetworkError=!1;let i=e.refreshToken,o=await this.callCognitoRefresh(e.refreshToken,r);if(o!==null)return this.applyRefreshedTokens(e,o,n,r);let s=null;try{s=await t.awaitWithinAbsoluteDeadline(r,"Cognito refresh storage recovery",()=>_e.getTokens(this.environment))}catch(a){w.warn("[AppSyncClient] Failed to re-read tokens from storage during refresh recovery",{error:a instanceof Error?a.message:String(a)})}if(s&&s.refreshToken&&s.refreshToken!==e.refreshToken){w.info("[AppSyncClient] In-memory refresh token rejected; retrying with storage-backed token (likely out-of-band re-auth)"),i=s.refreshToken,this.lastRefreshNetworkError=!1;let a=await this.callCognitoRefresh(s.refreshToken,r);if(a!==null)return this.applyRefreshedTokens(s,a,n,r)}return this.lastRefreshFailureAt=Date.now(),this.lastRefreshFailureCredential=i,!1}async callCognitoRefresh(e,r=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS){let n=new AbortController;try{let i=Bt(),o=`https://${i.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"refresh_token",client_id:i.aws.cognitoClientId,refresh_token:e}),a=await t.awaitWithinAbsoluteDeadline(r,"Cognito token refresh",async()=>{let c=await Op(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString(),signal:n.signal},"Token refresh");if(!c.ok)return{kind:"http-error",status:c.status};let l=await c.json(),d=l;if(typeof l!="object"||l===null||typeof d.access_token!="string"||d.access_token===""||typeof d.id_token!="string"||d.id_token===""||typeof d.expires_in!="number"||!Number.isFinite(d.expires_in)||d.expires_in<=0)throw new Error("Cognito token refresh returned an invalid payload");return{kind:"success",data:l}},c=>n.abort(c));return a.kind==="http-error"?(w.error("[AppSyncClient] Token refresh failed",{status:a.status}),(a.status>=500&&a.status<600||a.status===429)&&(this.lastRefreshNetworkError=!0),null):a.data}catch(i){return w.error("[AppSyncClient] Token refresh error:",i),this.lastRefreshNetworkError=!0,null}}async applyRefreshedTokens(e,r,n=this.tokenStateGeneration,i=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS){if(Date.now()>=i||this.tokenStateGeneration!==n)return w.warn("[AppSyncClient] Discarding stale token refresh result",{deadlineElapsed:Date.now()>=i,tokenGenerationChanged:this.tokenStateGeneration!==n}),!1;let o={...e,accessToken:r.access_token,idToken:r.id_token,expiresAt:Date.now()+r.expires_in*1e3};return this.replaceTokens(o),this.lastRefreshFailureAt=null,this.lastRefreshFailureCredential=null,w.info("[AppSyncClient] Tokens refreshed in memory",{expiresAt:new Date(o.expiresAt).toISOString(),durableRefreshTokenUnchanged:!0}),!0}reconcileTokensBeforeReconnect(e){t.throwIfAborted(e);let r=this.pendingReconnectReconciliation;if(!r){let n=Date.now()+t.RECONNECT_RECONCILIATION_TIMEOUT_MS,i=this.tokenStateGeneration;r=this.performReconnectTokenReconciliation(n,i),this.pendingReconnectReconciliation=r,r.finally(()=>{this.pendingReconnectReconciliation===r&&(this.pendingReconnectReconciliation=null)}).catch(()=>{})}return t.awaitSharedFlightForCaller(r,e)}async performReconnectTokenReconciliation(e,r){let n=await t.awaitWithinAbsoluteDeadline(e,"AppSync reconnect credential reconciliation",()=>_e.getTokens(this.environment));if(!n)return"missing";if(this.tokenStateGeneration!==r)return"memory_current";let i=this.tokens;if(i&&i.refreshToken===n.refreshToken&&i.expiresAt>=n.expiresAt&&!_e.isTokenExpired(i))return"memory_current";if(_e.isTokenExpired(n)){let o=r;if(!i||i.refreshToken!==n.refreshToken){if(Date.now()>=e||this.tokenStateGeneration!==r)return"memory_current";this.replaceTokens(n),o=this.tokenStateGeneration}return await this.refreshTokens(n,void 0,e,o)?"refreshed":"refresh_failed"}return Date.now()>=e||this.tokenStateGeneration!==r?"memory_current":(this.replaceTokens(n),"loaded")}beginReconnectReconciliationWait(e){this.reconnectReconciliationWaiters.get(e)?.abort(new Error("reconnect reconciliation superseded"));let n=new AbortController;return this.reconnectReconciliationWaiters.set(e,n),n.signal}finishReconnectReconciliationWait(e,r){this.reconnectReconciliationWaiters.get(e)?.signal===r&&this.reconnectReconciliationWaiters.delete(e)}cancelReconnectReconciliationWait(e){let r=this.reconnectReconciliationWaiters.get(e);r&&(this.reconnectReconciliationWaiters.delete(e),r.abort(new Error("WebSocket watcher stopped")))}isAuthenticated(){return this.authenticated}signOut(){this.resetSyncProducerAuthority(),this.authenticated=!1,this.replaceTokens(null),this.currentUserId=null,this.currentEmail=null,this.resetCompanionSyncDisplay(),this.cleanupSubscriptions(),w.info("[AppSyncClient] Signed out")}async graphqlRequest(e,r,n=!1,i,o,s,a){t.throwIfAborted(i),o!==void 0&&this.assertSyncAccount(o);let c=this.currentUserId,l=this.syncDisplayEpoch,d=Bt();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let u={"Content-Type":"application/json",Authorization:this.tokens.idToken};a?.();let p=await Op(d.aws.appsyncUrl,{method:"POST",headers:u,body:JSON.stringify({query:e,variables:r}),signal:i},"AppSync GraphQL request");if(o!==void 0&&this.assertSyncAccount(o),p.status===401){if(n)throw new Mi("refresh_auth_rejected");w.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),t.throwIfAborted(i);let m=await this.refreshTokens(this.tokens,i);if(t.throwIfAborted(i),m)return this.graphqlRequest(e,r,!0,i,o,s,a);throw new Mi(this.lastRefreshNetworkError?"refresh_network":"refresh_auth_rejected")}if(!p.ok)throw new Error(`GraphQL request failed: ${p.status}`);let h=s===void 0?await p.json():await this.boundedGraphQLJson(p,s,i);if(o!==void 0&&this.assertSyncAccount(o),h.errors?.length){let m=h.errors[0];throw[tt.createEvent,tt.updateEventStatus,tt.recordWorkspaceOutcomeV2,tt.reportSecurityPostureV2,qt.listEvents,qt.listSupervisionEvents,qt.getGateResolution,qt.getGateResolutionV2].includes(e)&&c===this.currentUserId&&l===this.syncDisplayEpoch&&["UPDATE_REQUIRED","AUTHORITY_UNAVAILABLE","SYNC_BLOCKED"].includes(m.errorType??"")&&this.resetCompanionSyncDisplay(),new Ut({message:m.message,errorType:m.errorType,extensions:m.extensions,path:m.path,data:m.data,requestId:p.headers?.get("x-amzn-requestid")})}return h}async boundedGraphQLJson(e,r,n){if(!Number.isSafeInteger(r)||r<1||r>8192||!e.body||!/^application\/json(?:\s*;|$)/i.test(e.headers.get("content-type")??""))throw new Tt("INVALID_SYNC_READ_RESPONSE");let i=e.headers.get("content-length");if(i!==null&&(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>r))throw await e.body.cancel(),new Tt("INVALID_SYNC_READ_RESPONSE");let o=e.body.getReader(),s=[],a=0;try{for(;;){t.throwIfAborted(n);let c=await o.read();if(t.throwIfAborted(n),c.done)break;if(a+=c.value.byteLength,a>r)throw new Tt("INVALID_SYNC_READ_RESPONSE");s.push(c.value)}try{return JSON.parse(new TextDecoder("utf8",{fatal:!0}).decode(Buffer.concat(s)))}catch{throw new Tt("INVALID_SYNC_READ_RESPONSE")}}finally{try{await o.cancel()}finally{o.releaseLock()}}}assertSyncAccount(e){if(!this.authenticated||this.currentUserId!==e||this.tokens?.userId!==e)throw new ve("SYNC_ACCOUNT_CHANGED")}async getCompanionSyncState(e){let r=this.getCurrentUserId(),n=this.syncDisplayEpoch,i=()=>{if(this.assertSyncAccount(r),t.throwIfAborted(e),n!==this.syncDisplayEpoch)throw new ve("INVALID_SYNC_STATE")};i();let o=this.syncStateRead;if(!o||o.userId!==r||o.epoch!==n||o.controller.signal.aborted){let a=new AbortController;o={userId:r,epoch:n,controller:a,promise:this.readCompanionSyncState(r,n,a.signal),waiters:0,settled:!1},this.syncStateRead=o;let c=o,l=()=>{c.settled=!0,this.syncStateRead===c&&(this.syncStateRead=null)};c.promise.then(l,l)}let s=o;return s.waiters++,new Promise((a,c)=>{let l=!1,d=p=>{if(!l){l=!0,e?.removeEventListener("abort",u),--s.waiters===0&&!s.settled&&(this.syncStateRead===s&&(this.syncStateRead=null),s.controller.abort(new Error("Sync state read has no callers")));try{if(i(),p!==void 0)throw p;let h=this.companionSyncStatusSnapshot(r);if(!h)throw new ve("INVALID_SYNC_STATE");a(h)}catch(h){c(h)}}},u=()=>d(t.abortReason(e));e?.addEventListener("abort",u,{once:!0}),s.promise.then(()=>d(),p=>d(p)),e?.aborted&&u()})}async readCompanionSyncState(e,r,n){this.assertSyncAccount(e);let i=++this.syncDisplaySequence;try{let o,s=0,a=0;for(;;){this.assertSyncAccount(e),t.throwIfAborted(n);let u=this.syncStateRetry;if(u?.userId===e&&u.epoch===r){let p=u.retryAtMs-Date.now();if(p>1e4-a)throw u.error;p>0&&(a+=p,await t.waitForSyncStateRetry(p,n),this.assertSyncAccount(e),t.throwIfAborted(n))}try{o=await this.graphqlRequest(qt.getCompanionSyncState,{},!1,n,e);break}catch(p){this.assertSyncAccount(e),t.throwIfAborted(n);let h=p instanceof Ut?p.data:void 0,m=h&&typeof h=="object"&&!Array.isArray(h)?h.retryAfterMs:void 0;if(!(p instanceof Ut)||p.errorType!=="HISTORY_RETRY_AFTER"||typeof m!="number"||!Number.isSafeInteger(m)||m<0)throw p;let f=Date.now()+Math.max(1,m);if(!Number.isSafeInteger(f)||(this.syncStateRetry={userId:e,epoch:r,retryAtMs:f,error:p},s>=2))throw p;s++}}this.assertSyncAccount(e),t.throwIfAborted(n),this.syncStateRetry?.userId===e&&this.syncStateRetry.epoch===r&&(this.syncStateRetry=null);let c=Gv(o?.data?.getCompanionSyncState,this.environment),l=this.publishCompanionSyncDisplay(e,c,r,i),d=Date.now();if(!l||!Number.isSafeInteger(d)||l.observedAtEpochMs>d+Ac||l.validUntilEpochMs<=d)throw new ve("INVALID_SYNC_STATE");return l}catch(o){throw this.publishCompanionSyncDisplay(e,null,r,i),o}}async getCompanionSyncRoute(e){let r=this.getCurrentUserId(),n=this.syncDisplayEpoch,i=()=>{if(this.assertSyncAccount(r),t.throwIfAborted(e),n!==this.syncDisplayEpoch)throw new ve("INVALID_SYNC_STATE")};i();let o=this.companionSyncStatusSnapshot(r);if(o)return{protocol:o.protocol};let s=await this.getCompanionSyncState(e);return i(),{protocol:s.protocol}}subscribeCompanionSyncState(e,r){this.assertSyncAccount(e);let n={userId:e,listener:r};return this.syncDisplayListeners.add(n),this.notifyCompanionSyncDisplay(n),()=>{this.syncDisplayListeners.delete(n)}}companionSyncStatusSnapshot(e){let r=this.syncDisplay,n=Date.now();return!this.authenticated||this.currentUserId!==e||this.tokens?.userId!==e||r?.userId!==e||r.state.environment!==this.environment||!Number.isSafeInteger(n)||r.state.observedAtEpochMs>n+Ac||n>=r.state.validUntilEpochMs?null:r.state}async refreshCompanionSyncDisplayOnMaintenance(e,r){this.assertSyncAccount(e),t.throwIfAborted(r),!this.companionSyncStatusSnapshot(e)&&(await this.getCompanionSyncState(r),this.assertSyncAccount(e),t.throwIfAborted(r))}notifyCompanionSyncDisplay(e){let r=this.syncDisplay;try{e.listener(this.authenticated&&this.currentUserId===e.userId&&this.tokens?.userId===e.userId&&r?.userId===e.userId?r.state:null)}catch{w.warn("[AppSyncClient] Companion status display listener failed")}}resetSyncProducerAuthority(){this.syncProducerEpoch++,this.syncProducerRetry.clear()}resetCompanionSyncDisplay(){this.syncDisplayEpoch+=1;let e=this.syncStateRead;this.syncStateRead=null,this.syncStateRetry=null,e?.controller.abort(new Error("Sync routing observation invalidated")),this.syncDisplay=null,this.syncDisplayAppliedSequence=this.syncDisplaySequence;for(let r of this.syncDisplayListeners)this.notifyCompanionSyncDisplay(r)}publishCompanionSyncDisplay(e,r,n,i){if(n!==this.syncDisplayEpoch||!this.authenticated||this.currentUserId!==e||this.tokens?.userId!==e)return null;if(i<this.syncDisplayAppliedSequence)return this.syncDisplay?.userId===e?this.syncDisplay.state:null;if(r&&this.syncDisplay?.userId===e){let o=B$(r,this.syncDisplay.state);if(o==="RETAIN")return this.syncDisplay.state;o==="CONFLICT"&&(r=null)}this.syncDisplayAppliedSequence=Math.max(i,this.syncDisplayAppliedSequence),this.syncDisplay=r?{userId:e,state:r}:null;for(let o of this.syncDisplayListeners)this.notifyCompanionSyncDisplay(o);return r}async reportSecurityPostureIfSelected(e,r,n){let i={sessionId:e.sessionId,sessionGenerationId:e.sessionGenerationId,expectedSessionKeyGen:e.sessionKeyGen??Di,posture:r},o=this.getCurrentUserId();this.assertSyncAccount(o),t.throwIfAborted(n);let s=await this.getCompanionSyncRoute(n);if(this.assertSyncAccount(o),t.throwIfAborted(n),s.protocol==="LEGACY")return null;if(s.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");if(!i.sessionGenerationId)throw new ve("SYNC_SESSION_GENERATION_CHANGED");let a=H$(o,{...i,sessionGenerationId:i.sessionGenerationId}),c=await _e.getDeviceIdentity();if(this.assertSyncAccount(o),t.throwIfAborted(n),!c)throw new ve("SYNC_IDENTITY_UNAVAILABLE");if(this.tokens&&this.tokens.expiresAt<=Date.now()&&await this.refreshTokens(this.tokens,n),this.assertSyncAccount(o),t.throwIfAborted(n),Bt().environment!==this.environment)throw new ve("SYNC_SESSION_UNAVAILABLE");let l=Np("REPORT_SECURITY_POSTURE",a,o,{privateKeyB64:c.privateKey,publicKeyB64:c.publicKey},Date.now()),d=await this.graphqlRequest(tt.reportSecurityPostureV2,{input:JSON.stringify(l)},!0,n,o,8192);return this.assertSyncAccount(o),t.throwIfAborted(n),W$(d?.data?.reportSecurityPostureV2,a)}async desktopSyncReadClient(e,r){let n={...e},i=this.getCurrentUserId();this.assertSyncAccount(i),t.throwIfAborted(r);let o=await this.getCompanionSyncRoute(r);if(this.assertSyncAccount(i),t.throwIfAborted(r),o.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");let s=Bt();if(s.environment!==this.environment||!s.aws.syncHttpUrl)throw new ve("SYNC_SESSION_UNAVAILABLE");return new Nc({endpoint:s.aws.syncHttpUrl,userId:i,sessionScope:n,assertAccount:()=>this.assertSyncAccount(i),getSigningKey:async()=>{let a=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),!a)throw new ve("SYNC_IDENTITY_UNAVAILABLE");return{privateKeyB64:a.privateKey,publicKeyB64:a.publicKey}},resolutionQuery:async(a,c)=>{this.assertSyncAccount(i),this.assertSyncReadAdmission(n.sessionId);try{let l=await this.graphqlRequest(qt.getGateResolutionV2,{input:a},!0,c,i,8192);return this.assertSyncAccount(i),this.assertSyncReadAdmission(n.sessionId),t.throwIfAborted(c),l?.data?.getGateResolutionV2}catch(l){throw this.assertSyncAccount(i),t.throwIfAborted(c),l instanceof Ut?Gg({ok:!1,errorCode:l.responseMessage}):l}},getToken:async a=>{if(this.assertSyncAccount(i),this.tokens&&this.tokens.expiresAt<=Date.now()&&await this.refreshTokens(this.tokens,a),this.assertSyncAccount(i),!this.tokens?.accessToken)throw new ve("SYNC_IDENTITY_UNAVAILABLE");return this.tokens.accessToken}})}async desktopSyncReadSession(e,r){let n={sessionId:e.sessionId,sessionGenerationId:e.sessionGenerationId},i=e.root,o=this.getCurrentUserId(),s=this.syncReadEpoch;this.assertSyncReadAdmission(n.sessionId);let a=await this.desktopSyncReadClient(n,r);if(this.assertSyncAccount(o),this.assertSyncReadAdmission(n.sessionId),t.throwIfAborted(r),s!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");let c=this.desktopSyncWriter({root:i,sessionScope:n}).desktopRegistration((l,d)=>a.register(l,d));return this.ownSyncReader({...n,...i!==void 0&&{root:i}},yC(a,c))}async desktopSyncLiveSession(e,r,n,i){let o={sessionId:e.sessionId,sessionGenerationId:e.sessionGenerationId},s=e.root;this.assertSyncReadAdmission(o.sessionId);let a=this.syncReadEpoch,c=this.getCurrentUserId(),l=await this.desktopSyncReadClient(o,i);if(this.assertSyncAccount(c),this.assertSyncReadAdmission(o.sessionId),t.throwIfAborted(i),a!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");let d=Bt();if(!d.aws.syncWebSocketUrl||d.environment!==this.environment||this.environment!=="development"&&this.environment!=="production")throw new ve("SYNC_SESSION_UNAVAILABLE");let u=this.desktopSyncWriter({root:s,sessionScope:o}),p=u.desktopRegistration((m,f)=>l.register(m,f)),h=this.ownSyncReader({...o,...s!==void 0&&{root:s}},yC(l,p));try{return new xk({endpoint:d.aws.syncWebSocketUrl,environment:this.environment,scope:o,wire:l,reader:h,inbound:u.inbound(),assertAccount:()=>this.assertSyncAccount(c),retryExecutionAcknowledgement:async(m,f)=>{this.assertSyncAccount(c),t.throwIfAborted(f);let g=await this.updateEventStatus({eventId:m.eventId,timestamp:m.timestamp,sessionId:o.sessionId,deliveryStatus:"EXECUTED"},{sessionGenerationId:o.sessionGenerationId},f);if(g.deliveryStatus!=="EXECUTED")throw new ve("INVALID_SYNC_RECEIPT");return{...g,deliveryStatus:"EXECUTED"}},onMaintenance:m=>this.refreshCompanionSyncDisplayOnMaintenance(c,m),onUncertain:m=>w.warn("[AppSyncClient] Mobile input outcome uncertain; not replaying terminal input",{sessionId:o.sessionId,count:m}),onEvent:m=>r(this.syncEventForConsumer(m)),onError:n})}catch(m){throw await h.close(),m}}syncEventForConsumer(e){let r;if(e.metadata!==void 0){if(typeof e.metadata!="string")throw new Tt("INVALID_SYNC_READ_RESPONSE");try{r=JSON.parse(e.metadata)}catch{throw new Tt("INVALID_SYNC_READ_RESPONSE")}}return{...e,...e.metadata!==void 0&&{metadata:r}}}async retireDesktopSyncRegistration(e,r){let n=this.getCurrentUserId();if(this.assertSyncAccount(n),!r||r.userId!==n||r.sessionId!==e.sessionId||r.status!=="INACTIVE"||r.sessionGenerationId!==e.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let i=this.desktopSyncWriter({root:e.root,sessionScope:e}),o=await i.removeDesktopRegistration();return await i.removeInbound(),await i.removeDeferredInputs(),await i.removeMobileEchoes(),await i.promptRetention().remove(),this.assertSyncAccount(n),o}desktopSyncWriter(e={}){let r=this.getCurrentUserId();if(this.assertSyncAccount(r),this.environment!=="development"&&this.environment!=="production")throw new ve("INVALID_SYNC_INPUT");return new Bc({userId:r,environment:this.environment,root:e.root,sessionScope:e.sessionScope,assertAccount:()=>this.assertSyncAccount(r),assertDeferredAdmission:()=>{if(this.assertSyncAccount(r),!e.sessionScope)throw new ve("INVALID_SYNC_INPUT");this.assertSyncReadAdmission(e.sessionScope.sessionId)},readPrivateKey:async()=>{let n=await _e.getDeviceIdentity();return this.assertSyncAccount(r),n?.privateKey??null},send:(n,i,o)=>(this.assertSyncAccount(r),this.mutateDesktopSyncEvent(n,i,o)),isQuotaDenial:n=>n instanceof Ut&&n.errorType==="SYNC_QUOTA_EXHAUSTED",omitNewPayload:async n=>{let i=await this.getCompanionSyncState(n);if(this.assertSyncAccount(r),t.throwIfAborted(n),i.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");return i.usage?.syncState==="PAUSED"}})}toolActivitySyncTransport(e){return Xg({sessionScope:e.sessionScope,writer:this.desktopSyncWriter(e),getEncryptionContext:e.getEncryptionContext})}companionNoticeOwner(e,r){let n=JSON.stringify([e,r??null]),i=this.companionNoticeOwners.get(n);if(!i){let o=this.getCurrentUserId();i={sessionId:e,closed:!1,recovery:new th({recover:s=>(this.assertSyncAccount(o),this.recoverPreparedCompanionEvents({sessionId:e,root:r},s)),onFailure:()=>w.warn("[sync-notice] prepared notice retained for retry",{sessionId:e})})},this.companionNoticeOwners.set(n,i)}return i}closeCompanionNoticeOwners(e){for(let[r,n]of this.companionNoticeOwners)e!==void 0&&n.sessionId!==e||(n.closed=!0,this.trackSyncClosure(n.sessionId,n.recovery.stop()),this.companionNoticeOwners.delete(r))}publishCompanionNotice(e,r,n={}){return!e||!["NOTIFICATION","ASSISTANT_RESPONSE"].includes(e.type)?Promise.reject(new ve("INVALID_SYNC_INPUT")):this.publishCompanionOccurrence(e,r,n).then(i=>i.protocol==="LEGACY"?i.value?"ACCEPTED":"DROPPED":i.result===null?"SETTLED":i.result==="PENDING"?"PENDING":i.result.status)}async publishCompanionEvent(e,r,n={}){let i=await this.publishCompanionOccurrence(e,r,n);if(i.protocol==="LEGACY"){if(i.value===null)return{status:"DROPPED"};let s=i.value?.eventId;if(typeof s!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(s)||s.startsWith("local-throttled"))throw new ve("INVALID_SYNC_RECEIPT");return{status:"ACCEPTED",eventId:s}}let o=i.result;return o===null?{status:"SETTLED"}:o==="PENDING"?{status:"PENDING"}:o.status==="ACCEPTED"?{status:"ACCEPTED",eventId:o.receipt.eventId,receipt:o.receipt}:{status:"OMITTED"}}publishCompanionOccurrence(e,r,n){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Object.keys(e).some(u=>!["sessionId","type","source","content","metadata","timestamp","isEncrypted"].includes(u))||!["USER_PROMPT","ASSISTANT_RESPONSE","REASONING","TOOL_USE"].includes(e.type)&&!(yg(e.type)&&e.type!=="TOOL_ACTIVITY")||e.source!=="DESKTOP"||e.isEncrypted===!0||typeof e.content!="string"||!e.content.length||typeof e.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e.sessionId)||typeof e.timestamp!="string"||!Number.isFinite(Date.parse(e.timestamp)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i=JSON.parse(JSON.stringify(e)),{sessionId:o}=i,{root:s}=n,a=this.getCurrentUserId(),c=this.companionNoticeOwner(o,s),l=()=>{if(n.assertOwner?.(),this.assertSyncAccount(a),this.assertSyncReadAdmission(o),c.closed)throw new ve("SYNC_SESSION_UNAVAILABLE")},d=(async()=>{l();let u=await this.selectCompanionSourceTransport({sessionId:o,root:s});if(l(),u.protocol==="LEGACY"){let f=await this.desktopSyncWriter({root:s}).shellSources();if(l(),f.some(y=>y.sessionId===o&&y.pendingCount>0))throw c.recovery.start(),new ve("SYNC_PRODUCER_FROZEN");let g=await r();return l(),{protocol:"LEGACY",value:g}}this.rememberSyncRegistration({...u.sessionScope,root:s});let p=await u.prepareEvent(i,(0,Qn.v4)());l();let h=u.writer.shellSource(),m=await h.append(p);l(),c.recovery.start();try{let f=await h.deliver(m);return l(),{protocol:"SYNC_V2",result:f}}catch{return l(),w.warn("[sync-notice] delivery pending; original encrypted source retained",{sessionId:o}),{protocol:"SYNC_V2",result:"PENDING"}}})();return this.trackSyncClosure(o,d.then(()=>{},()=>{})),d}async recoverCompanionSyncSources(e,r){let{sessionId:n,root:i}=e;if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n))throw new ve("INVALID_SYNC_INPUT");let o=this.getCurrentUserId();this.assertSyncAccount(o);let s=this.companionNoticeOwner(n,i);await this.recoverSessionRetirementsOnce({root:i},r);let a=await this.recoverPromptResolutions({sessionId:n,root:i},r),c=await this.desktopSyncWriter({root:i}).sourceStreams();this.assertSyncAccount(o);let l=a;for(let d of c){if(d.sessionId!==n||d.pendingCount===0)continue;t.throwIfAborted(r),this.assertSyncAccount(o);let u=this.desktopSyncWriter({root:i,sessionScope:{sessionId:n,sessionGenerationId:d.sessionGenerationId}}).sourceStream({provider:d.provider,streamSha256:d.streamSha256});await u.recover(),l<256&&(l+=await u.drain(256-l,r))}if(this.assertSyncAccount(o),!s.closed){let d=await this.desktopSyncWriter({root:i}).shellSources();this.assertSyncAccount(o),!s.closed&&d.some(u=>u.sessionId===n&&u.pendingCount>0)&&(s.recovery.start(),l+=await this.recoverPreparedCompanionEvents({sessionId:n,root:i},r,d))}return l}async recoverShellSyncSources(e,r){let{sessionId:n,root:i}=e;if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n))throw new ve("INVALID_SYNC_INPUT");let o=this.getCurrentUserId();this.assertSyncAccount(o),await this.recoverSessionRetirementsOnce({root:i},r);let s=await this.recoverPromptResolutions({sessionId:n,root:i},r),a=await this.desktopSyncWriter({root:i}).shellSources();return this.assertSyncAccount(o),s+await this.recoverPreparedCompanionEvents(e,r,a)}async recoverPreparedCompanionEvents(e,r,n){let{sessionId:i,root:o}=e,s=this.getCurrentUserId();this.assertSyncAccount(s),t.throwIfAborted(r);let a=n??await this.desktopSyncWriter({root:o}).shellSources();this.assertSyncAccount(s);let c=0;for(let l of a)l.sessionId!==i||l.pendingCount===0||(t.throwIfAborted(r),this.assertSyncAccount(s),c+=await this.desktopSyncWriter({root:o,sessionScope:{sessionId:i,sessionGenerationId:l.sessionGenerationId}}).shellSource().drain(64,r));return this.assertSyncAccount(s),c}async retireEmptyShellSyncSource(e,r){let n=this.getCurrentUserId();if(this.assertSyncAccount(n),!r||r.userId!==n||r.sessionId!==e.sessionId||r.status!=="INACTIVE"||r.sessionGenerationId!==e.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let i=this.desktopSyncWriter({root:e.root,sessionScope:e});await i.shellSource().recover();let o=await i.removeEmptyShellSource();return this.assertSyncAccount(n),o}async recoverToolActivityWindows(e){let{sessionId:r,root:n,outbox:i,ledger:o}=e,s=this.getCurrentUserId();this.assertSyncAccount(s),await J1({sessionId:r,outbox:i,ledger:o,transportForGeneration:a=>{this.assertSyncAccount(s);let c={sessionId:r,sessionGenerationId:a};return Xg({sessionScope:c,writer:this.desktopSyncWriter({root:n,sessionScope:c}),recoveryOnly:!0,getEncryptionContext:async()=>{throw new ve("SYNC_SESSION_UNAVAILABLE")}})}}),this.assertSyncAccount(s)}async selectToolActivityTransport(e){let{sessionId:r,root:n,legacyTransport:i}=e;if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(r)||i.protocol!==void 0&&i.protocol!=="LEGACY")throw new ve("INVALID_SYNC_INPUT");let o=await this.selectCompanionSourceTransport({sessionId:r,root:n});return o.protocol==="LEGACY"?i:this.toolActivitySyncTransport({root:n,sessionScope:o.sessionScope,getEncryptionContext:o.getEncryptionContext})}async selectCompanionSourceTransport(e){let{sessionId:r,root:n}=e;if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(r))throw new ve("INVALID_SYNC_INPUT");let i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await this.getCompanionSyncRoute();if(this.assertSyncAccount(i),o.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(o.protocol==="LEGACY")return Object.freeze({protocol:"LEGACY"});let s=async()=>{this.assertSyncAccount(i);let d=await this.getSession(r);if(this.assertSyncAccount(i),!d||d.sessionId!==r||d.userId!==i||d.status!=="ACTIVE"||d.isEncrypted!==!0||typeof d.sessionGenerationId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(d.sessionGenerationId))throw new ve("SYNC_SESSION_UNAVAILABLE");return d},a=await s(),c=Object.freeze({sessionId:r,sessionGenerationId:a.sessionGenerationId.toLowerCase()}),l=async()=>{let d=await s();if(d.sessionGenerationId.toLowerCase()!==c.sessionGenerationId)throw new ve("SYNC_SESSION_GENERATION_CHANGED");let u=d.sessionKeyGen??null,p=await _e.getSessionKey(r,d.encryptedKeys??[],u);if(this.assertSyncAccount(i),!p)throw new ve("SYNC_SESSION_KEY_UNAVAILABLE");return{...c,sessionKey:p,sessionKeyGen:u}};return Object.freeze({protocol:"SYNC_V2",sessionScope:c,writer:this.desktopSyncWriter({root:n,sessionScope:c}),getEncryptionContext:l,prepareEvent:async(d,u)=>{if(!d||typeof d!="object"||Array.isArray(d)||Object.keys(d).some(g=>!["sessionId","type","source","content","metadata","timestamp","isEncrypted",...ed].includes(g)))throw new ve("INVALID_SYNC_INPUT");let p=JSON.parse(JSON.stringify(d)),h=td(p);if(!p||p.sessionId!==c.sessionId||p.source!=="DESKTOP"||p.isEncrypted===!0||!["USER_PROMPT","ASSISTANT_RESPONSE","REASONING","TOOL_USE"].includes(p.type)&&!(yg(p.type)&&p.type!=="TOOL_ACTIVITY")&&!h||p.content!==void 0&&p.content!==null&&typeof p.content!="string")throw new ve("INVALID_SYNC_INPUT");let m=await l(),f={...c,clientOperationId:u,type:p.type,timestamp:p.timestamp,expectedSessionKeyGen:m.sessionKeyGen??Di,...h??{},isEncrypted:!0,encryptionVersion:1,content:Xe.encryptContent(p.content??"",m.sessionKey),...(p.metadata!=null||yg(p.type)||h)&&{metadata:{encrypted:Xe.encryptMetadata(p.metadata??{},m.sessionKey)}}};return Mn("CREATE_EVENT",f),f}})}publishCompanionPrompt(e,r,n={}){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Object.keys(e).some(p=>!["sessionId","type","source","content","metadata","timestamp","isEncrypted",...ed].includes(p)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i=JSON.parse(JSON.stringify(e)),o=td(i);if(!o||i.source!=="DESKTOP"||i.isEncrypted===!0||typeof i.content!="string"||!i.content.length||typeof i.timestamp!="string"||!Number.isFinite(Date.parse(i.timestamp)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let{root:s,reRaiseToken:a}=n,c=i.sessionId,l=this.getCurrentUserId(),d=()=>{this.assertSyncAccount(l),this.assertSyncReadAdmission(c)},u=(async()=>{d();let p=await this.selectCompanionSourceTransport({sessionId:c,root:s});if(d(),p.protocol==="LEGACY"){let S=await this.desktopSyncWriter({root:s}).promptPublications();if(d(),S.some(v=>v.sessionId===c&&v.promptId===o.promptId))throw new ve("SYNC_PRODUCER_FROZEN");let b=await r();return d(),b?"RERAISED":"RETRY"}this.rememberSyncRegistration({...p.sessionScope,root:s});let{timestamp:h,isEncrypted:m,...f}=i,g=(0,wU.createHash)("sha256").update((0,bU.canonicalize)(f)).digest("hex"),y=await p.writer.promptPublication(o.promptId).publish(g,S=>p.prepareEvent(i,S),{reRaiseToken:a});return d(),y.status==="OMITTED"?"OMITTED":"RERAISED"})();return this.trackSyncClosure(c,u.then(()=>{},()=>{})),u}resolveCompanionPrompt(e,r={}){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(a=>!["sessionId","promptId","ownerToken","resolutionAt"].includes(a)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let n={...e},{root:i}=r;if(typeof n.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n.sessionId)||n.resolutionAt!==void 0&&(typeof n.resolutionAt!="string"||!Number.isFinite(Date.parse(n.resolutionAt))))return Promise.reject(new ve("INVALID_SYNC_INPUT"));try{td({type:"NOTIFICATION",promptId:n.promptId,ownerToken:n.ownerToken,producerKind:"PLUGIN_APPROVAL",mobileActionable:!1})}catch(a){return Promise.reject(a)}let o=this.getCurrentUserId(),s=bk(o,{sessionId:n.sessionId,promptId:n.promptId,producerKind:"PLUGIN_APPROVAL",ownerToken:n.ownerToken});return this.resolvePromptByProtocol(s,()=>s,async()=>(await this.createEvent({sessionId:n.sessionId,type:"NOTIFICATION",source:"DESKTOP",resolvedPromptId:n.promptId,ownerToken:n.ownerToken,...n.resolutionAt!==void 0&&{resolutionAt:n.resolutionAt}}))?.promptId===n.promptId,{root:i})}resolveCoreOfferPrompt(e,r,n={}){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Reflect.ownKeys(e).some(s=>typeof s!="string"||!["sessionId","promptId","sessionGenerationId","sessionKeyGen"].includes(s))||Object.values(Object.getOwnPropertyDescriptors(e)).some(s=>!s.enumerable||!("value"in s)||s.value!==void 0&&s.value!==null&&typeof s.value!="string"))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i={...e},o=this.getCurrentUserId();return this.resolvePromptByProtocol({sessionId:i.sessionId,promptId:i.promptId},()=>bk(o,{sessionId:i.sessionId,promptId:i.promptId,producerKind:"CORE_OFFER",sessionGenerationId:i.sessionGenerationId,expectedSessionKeyGen:i.sessionKeyGen??Di}),r,n)}resolvePromptByProtocol(e,r,n,i){let o=this.getCurrentUserId(),s={sessionId:e.sessionId,promptId:e.promptId};if(typeof s.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(s.sessionId)||typeof s.promptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s.promptId))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let a=()=>this.assertSyncAccount(o),c=this.desktopSyncWriter(i),l=(async()=>{let d=await c.promptPublications();a();let u=await c.promptResolutions();a();let p=[...d,...u].some(f=>f.sessionId===s.sessionId&&f.promptId===s.promptId),h=(f,g)=>c.runPromptResolution(f,async(y,S)=>{let b=g??await this.getCompanionSyncRoute();if(await S(),b.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");return this.finishPromptResolution(y,i,S)});if(p)return h(r());let m=await this.getCompanionSyncRoute();if(a(),m.protocol==="LEGACY")return this.resolvePromptPublication(s,async f=>{if(f||(await c.promptResolutions()).some(g=>g.sessionId===s.sessionId&&g.promptId===s.promptId))throw new ve("SYNC_PRODUCER_FROZEN");return a(),n()},i);if(m.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");return h(r(),m)})();return this.trackSyncClosure(s.sessionId,l.then(()=>{},()=>{})),l}finishPromptResolution(e,r,n,i){return this.resolvePromptPublication({sessionId:e.sessionId,promptId:e.promptId},async()=>(await n(),t.throwIfAborted(i),await this.resolveDesktopSyncPrompt(e,i),await n(),!0),{...r,signal:i})}recoverPromptResolutions(e,r){let{sessionId:n,root:i}=e;if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let o=this.getCurrentUserId(),s=this.desktopSyncWriter({root:i}),a=()=>{this.assertSyncAccount(o),t.throwIfAborted(r)},c=(async()=>{a();let l=(await s.promptResolutions()).filter(h=>h.sessionId===n);if(a(),!l.length)return 0;let d=await this.getCompanionSyncRoute(r);if(a(),d.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");let u=0,p;for(let h of l){a();try{let m=await s.runPromptResolution(h,(f,g)=>this.finishPromptResolution(f,{root:i},g,r),{existingOnly:!0});a(),m&&u++}catch(m){a(),p??={error:m}}}if(p)throw p.error;return u})();return this.trackSyncClosure(n,c.then(()=>{},()=>{})),c}resolvePromptPublication(e,r,n={}){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Object.keys(e).some(d=>!["sessionId","promptId"].includes(d))||typeof e.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e.sessionId)||typeof e.promptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e.promptId))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i={...e},{root:o,signal:s}=n,a=this.getCurrentUserId(),c=()=>{this.assertSyncAccount(a),t.throwIfAborted(s)},l=(async()=>{c();let d=(await this.desktopSyncWriter({root:o}).promptPublications()).filter(h=>h.sessionId===i.sessionId&&h.promptId===i.promptId);c();let u=d.map(h=>this.desktopSyncWriter({root:o,sessionScope:h}).promptPublication(i.promptId));for(let h of u)await h.settle(s),c();let p=await r(d.length>0);if(c(),p!==!0)return!1;for(let h of u)await h.close(),c();return!0})();return this.trackSyncClosure(i.sessionId,l.then(()=>{},()=>{})),l}createDesktopSyncEvent(e,r){return this.mutateDesktopSyncEvent("CREATE_EVENT",e,r)}updateDesktopSyncEvent(e,r){return this.mutateDesktopSyncEvent("UPDATE_EVENT",e,r)}async confirmDesktopSyncRetirement(e,r){t.throwIfAborted(r);let n=Ek(e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),t.throwIfAborted(r),!o)throw new ve("SYNC_IDENTITY_UNAVAILABLE");let s=Np("CONFIRM_RETIREMENT",n,i,{privateKeyB64:o.privateKey,publicKeyB64:o.publicKey},Date.now()),a=await this.graphqlRequest(tt.confirmSessionRetirementV2,{input:s},!1,r,i);return this.assertSyncAccount(i),t.throwIfAborted(r),zg(a?.data?.confirmSessionRetirementV2,n)}async retireDesktopSyncSources(e,r,n){let{sessionId:i,sessionGenerationId:o,expectedSessionKeyGen:s,root:a}=e,c=this.getCurrentUserId(),l=ld(c,{sessionId:i,sessionGenerationId:o,expectedSessionKeyGen:s});return await this.quiesceDesktopSyncSession(i,r,n),this.desktopSyncWriter({root:a,sessionScope:l}).removeRetiredSources(s,d=>this.confirmDesktopSyncRetirement(d,n))}async quiesceDesktopSyncSession(e,r,n){let i=this.getCurrentUserId();if(typeof r!="function")throw new ve("INVALID_SYNC_INPUT");this.assertSyncAccount(i),t.throwIfAborted(n),this.syncRetiringSessions.add(e),this.cleanupSubscription(e),await r(),this.assertSyncAccount(i),t.throwIfAborted(n),await Promise.all([this.joinSyncSubscriptionClosures(e),...[...this.syncReadOwners.get(e)??[]].map(o=>o.close())]),this.assertSyncAccount(i),t.throwIfAborted(n)}async completeDesktopSyncRetirement(e,r,n,i){let{sessionId:o,root:s}=e,a=this.getCurrentUserId();if(this.assertSyncAccount(a),t.throwIfAborted(i),!r||r.userId!==a||r.sessionId!==o||r.status!=="INACTIVE"||!r.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let c=ld(a,{sessionId:o,sessionGenerationId:r.sessionGenerationId,expectedSessionKeyGen:r.sessionKeyGen??Di}),l=e.toolOutbox?.retirementLocation()??null;await this.quiesceDesktopSyncSession(o,n,i);let d=this.desktopSyncWriter({root:s,sessionScope:c}),u=await d.hasSessionRetirementWork(c.expectedSessionKeyGen)||e.toolOutbox&&await e.toolOutbox.withRetirementSources(c,async()=>!0);return this.assertSyncAccount(a),t.throwIfAborted(i),u?await d.runSessionRetirement(c,l,(p,h)=>this.finishRecordedSessionRetirement(p,{root:s},h,i))??{sourcesRemoved:0,operationsRemoved:0}:{sourcesRemoved:0,operationsRemoved:0}}async recoverSessionRetirements(e={},r){let{root:n}=e,i=this.getCurrentUserId();this.assertSyncAccount(i),t.throwIfAborted(r);let o=await this.desktopSyncWriter({root:n}).sessionRetirements(),s=0,a=0;for(let c of o){this.assertSyncAccount(i),t.throwIfAborted(r);try{let l=this.desktopSyncWriter({root:n,sessionScope:c.input});await this.quiesceDesktopSyncSession(c.input.sessionId,async()=>{},r),await l.runSessionRetirement(c.input,c.toolOutbox,(d,u)=>this.finishRecordedSessionRetirement(d,{root:n},u,r),{existingOnly:!0}),s++}catch(l){this.assertSyncAccount(i),t.throwIfAborted(r),a++,w.warn("[sync-retirement] prior-session cleanup retained for recovery",{code:l instanceof Ge?l.code:"CLEANUP_DEFERRED"})}}return this.assertSyncAccount(i),{completed:s,deferred:a}}async recoverSessionRetirementsOnce(e,r){let n=this.getCurrentUserId(),i=JSON.stringify([n,e.root??null]);this.assertSyncAccount(n),t.throwIfAborted(r);let o=this.sessionRetirementRecoveryPasses.get(i);if(!o){o=this.recoverSessionRetirements(e,r).then(()=>{},a=>{this.assertSyncAccount(n),t.throwIfAborted(r),w.warn("[sync-retirement] startup cleanup inventory unavailable; records retained")}),this.sessionRetirementRecoveryPasses.set(i,o);let s=o;s.catch(()=>{this.sessionRetirementRecoveryPasses.get(i)===s&&this.sessionRetirementRecoveryPasses.delete(i)})}await o,this.assertSyncAccount(n),t.throwIfAborted(r)}async finishRecordedSessionRetirement(e,r,n,i){let{input:o}=e,{root:s}=r,a=this.getCurrentUserId(),c=this.desktopSyncWriter({root:s,sessionScope:o});await n(),t.throwIfAborted(i);let l=await c.removeRetiredSources(o.expectedSessionKeyGen,d=>this.confirmDesktopSyncRetirement(d,i));if(e.toolOutbox){await n();let d=await z1({sessionScope:o,writer:c,outbox:new eh({...e.toolOutbox,logger:w}),expectedSessionKeyGen:o.expectedSessionKeyGen,confirm:u=>this.confirmDesktopSyncRetirement(u,i)});l.sourcesRemoved+=d.windowsRemoved,l.operationsRemoved+=d.operationsRemoved}for(let d of await c.promptResolutions())await n(),this.assertSyncAccount(a),t.throwIfAborted(i),await c.runPromptResolution(d,async(u,p)=>(await p(),await this.resolveDesktopSyncPrompt(u,i),await p(),!0),{existingOnly:!0});return await n(),this.assertSyncAccount(a),t.throwIfAborted(i),l}async resolveDesktopSyncPrompt(e,r){t.throwIfAborted(r);let n=Vp(e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=n;if(n.producerKind==="CORE_OFFER"){let a=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),t.throwIfAborted(r),!a)throw new ve("SYNC_IDENTITY_UNAVAILABLE");o=Np("RESOLVE_PROMPT",n,i,{privateKeyB64:a.privateKey,publicKeyB64:a.publicKey},Date.now())}let s=await this.graphqlRequest(tt.resolveOpenPromptV2,{input:o},!1,r,i);return this.assertSyncAccount(i),t.throwIfAborted(r),x1(s?.data?.resolveOpenPromptV2,n)}async updateDesktopSyncEventStatus(e,r){t.throwIfAborted(r);let n=Mn("UPDATE_EVENT_STATUS",e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),t.throwIfAborted(r),!o)throw new ve("SYNC_IDENTITY_UNAVAILABLE");let s=Np("UPDATE_EVENT_STATUS",n,i,{privateKeyB64:o.privateKey,publicKeyB64:o.publicKey},Date.now()),a=await this.graphqlRequest(tt.updateEventStatusV2,{input:s},!1,r,i);return this.assertSyncAccount(i),Mv(a?.data?.updateEventStatusV2,n)}async refreshDesktopSyncPrompt(e,r){if(t.throwIfAborted(r),typeof e!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e))throw new ve("INVALID_SYNC_INPUT");let n=this.getCurrentUserId();this.assertSyncAccount(n);let i=await this.graphqlRequest(tt.refreshOpenPromptTtlV2,{promptId:e},!1,r,n);return this.assertSyncAccount(n),t.throwIfAborted(r),Lv(i?.data?.refreshOpenPromptTtlV2,e)}async refreshSessionOpenPromptTtl(e,r){let{sessionId:n,root:i}=e,o=[...e.promptIds];if(!o.length)return;let s=this.getCurrentUserId();this.assertSyncAccount(s),this.assertSyncReadAdmission(n);let a=await this.selectCompanionSourceTransport({sessionId:n,root:i});if(this.assertSyncAccount(s),this.assertSyncReadAdmission(n),a.protocol==="LEGACY"){let d=await this.refreshOpenPromptTtl(o);this.assertSyncAccount(s);for(let u of d){if(this.assertSyncReadAdmission(n),await r(u)==="RETRY")throw new Error("SYNC_PROMPT_RERAISE_PENDING");this.assertSyncAccount(s)}return}this.rememberSyncRegistration({...a.sessionScope,root:i});let c=()=>{this.assertSyncAccount(s),this.assertSyncReadAdmission(n)},l=a.writer.promptRetention().run(o,async d=>{c();let u=await this.refreshDesktopSyncPrompt(d);return c(),u},async(d,u)=>{c();let p=await r(d,u);return c(),p});this.trackSyncClosure(n,l.then(()=>{},()=>{})),await l}async mutateDesktopSyncEvent(e,r,n){t.throwIfAborted(n);let i=Mn(e,r),o=this.getCurrentUserId(),s=this.syncProducerEpoch,a=!1,c=()=>{if(this.assertSyncAccount(o),t.throwIfAborted(n),s!==this.syncProducerEpoch)throw new ve("SYNC_ACCOUNT_CHANGED");for(let m of["PRODUCER","ENRICHMENT"]){if(m==="ENRICHMENT"&&e!=="UPDATE_EVENT")continue;let f=this.syncProducerRetry.get(m);if(f?.userId===o&&f.epoch===s&&f.retryAtMs>Date.now())throw a=!0,f.error}};c();let l=await _e.getDeviceIdentity();if(c(),!l)throw new ve("SYNC_IDENTITY_UNAVAILABLE");let d=Np(e,i,o,{privateKeyB64:l.privateKey,publicKeyB64:l.publicKey},Date.now()),u=e==="CREATE_EVENT"?"createEventV2":"updateEventV2",p;try{p=await this.graphqlRequest(tt[u],{input:d},!1,n,o,void 0,c)}catch(m){if(this.assertSyncAccount(o),!a&&s===this.syncProducerEpoch&&m instanceof Ut){let f=m.data&&typeof m.data=="object"&&!Array.isArray(m.data)?m.data.retryAfterMs:void 0,g=m.errorType==="PRODUCER_RETRY_AFTER"?"PRODUCER":e==="UPDATE_EVENT"&&m.errorType==="UPDATE_ENRICHMENT_RETRY_AFTER"?"ENRICHMENT":null,y=g??"PRODUCER",S=g!==null&&typeof f=="number"&&Number.isSafeInteger(f)&&f>=0?Math.max(1,f):m.errorType==="CONTROL_BREAKER_CONTENTION"?1e4:null;if(S!==null){let b=Date.now()+S,v=this.syncProducerRetry.get(y);Number.isSafeInteger(b)&&(!v||v.userId!==o||v.epoch!==s||v.retryAtMs<b)&&this.syncProducerRetry.set(y,{userId:o,epoch:s,retryAtMs:b,error:m})}}if(m instanceof Ut&&m.errorType==="SYNC_QUOTA_EXHAUSTED"){let f=this.syncDisplay?.userId===o?this.syncDisplay.state:null;if(f?.usage?.syncState!=="PAUSED"||f.validUntilEpochMs<=Date.now()){try{await this.getCompanionSyncState(n)}catch{}this.assertSyncAccount(o)}}throw m}this.assertSyncAccount(o);let h=N$(p?.data?.[u],i);if(h.refreshSyncState){try{await this.getCompanionSyncState(n)}catch{}this.assertSyncAccount(o)}return h.receipt}async createSession(e){let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},i=(await this.graphqlRequest(tt.createSession,{input:r})).data.createSession;return w.info("[AppSyncClient] Session created",{sessionId:i.sessionId,sessionGenerationId:i.sessionGenerationId??null,writerAttestationEligible:i.writerAttestationEligible===!0}),i}async putContextItem(e){if(e.trackId!==void 0&&e.taskId===void 0)throw new Error("putContextItem: trackId requires taskId");if((await this.graphqlRequest(tt.putContextItem,{input:e})).data?.putContextItem!==!0)throw new Error("putContextItem: backend did not accept the row")}async recordExecutionEvent(e,r,n={}){if(!e.taskId||!e.sessionId)throw new Error("recordExecutionEvent: taskId and sessionId are required");if(!/^[0-9a-f]{64}$/.test(e.dedupKeyHex))throw new Error("recordExecutionEvent: dedupKeyHex must be 64 lowercase hex chars");if(e.kind==="FLAG_BAD_APPROVAL"&&(!e.flaggedTaskId||!e.flaggedSeqNum||!e.flaggedEntryId))throw new Error("recordExecutionEvent: FLAG_BAD_APPROVAL requires the flaggedTaskId + flaggedSeqNum + flaggedEntryId target locator");let i;try{i=JSON.stringify(e.payload)}catch(c){throw new Error(`recordExecutionEvent: payload is not JSON-serializable: ${c.message}`)}if(i===void 0)throw new Error("recordExecutionEvent: payload must be a JSON value");let o=this.#r(i,e.sessionId,r),s=await this.graphqlRequest(tt.recordExecutionEvent,{input:{taskId:e.taskId,sessionId:e.sessionId,kind:e.kind,payload:o,dedupKeyHex:e.dedupKeyHex,...e.flaggedTaskId!==void 0?{flaggedTaskId:e.flaggedTaskId}:{},...e.flaggedSeqNum!==void 0?{flaggedSeqNum:e.flaggedSeqNum}:{},...e.flaggedEntryId!==void 0?{flaggedEntryId:e.flaggedEntryId}:{}}},!1,n.signal),a=nh(s.data?.recordExecutionEvent,"recordExecutionEvent");if(typeof a.errorType=="string"&&typeof a.errorMessage=="string")throw new Ut({message:a.errorMessage,errorType:a.errorType});if(typeof a.entryId!="string"||a.entryId.length===0)throw new Error("recordExecutionEvent: result missing entryId")}async updateSession(e){if(e.status===void 0)return this.doUpdateSession(e);let n=(this.statusWriteChains.get(e.sessionId)??Promise.resolve()).catch(()=>{}).then(()=>this.doUpdateSession(e));return this.statusWriteChains.set(e.sessionId,n.catch(()=>{})),n}async doUpdateSession(e){e.status==="INACTIVE"&&(this.syncRetiringSessions.add(e.sessionId),this.cleanupSubscription(e.sessionId),await Promise.all([this.joinSyncSubscriptionClosures(e.sessionId),...[...this.syncReadOwners.get(e.sessionId)??[]].map(o=>o.close())]));let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(tt.updateSession,{input:r});w.debug("[AppSyncClient] Session updated",{sessionId:n.data.updateSession.sessionId});let i=n.data.updateSession;if(e.status==="INACTIVE"&&i?.sessionGenerationId){let o=this.syncRegistrations.get(e.sessionId);for(let[s,a]of o??[])a.userId!==i.userId||a.scope.sessionGenerationId!==i.sessionGenerationId||(await this.retireDesktopSyncRegistration(a.scope,i),o.delete(s));o?.size||this.syncRegistrations.delete(e.sessionId)}return e.status==="ACTIVE"&&i.status==="ACTIVE"&&this.syncRetiringSessions.delete(e.sessionId),i}async getSession(e){return(await this.graphqlRequest(qt.getSession,{sessionId:e})).data.getSession}async submitWorkspaceOutcome(e,r={}){let n=K$(e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await this.getCompanionSyncRoute();if(this.assertSyncAccount(i),o.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(o.protocol==="LEGACY"){if(r.requiresV2)throw new ve("SYNC_PRODUCER_FROZEN");let a=await this.createEvent(n);return this.assertSyncAccount(i),j$(a,n)}await r.beforeV2?.(),this.assertSyncAccount(i);let s=await this.graphqlRequest(tt.recordWorkspaceOutcomeV2,{input:JSON.stringify(n)},!1,void 0,i);return this.assertSyncAccount(i),bg(s?.data?.recordWorkspaceOutcomeV2,n)}async createEvent(e){let r=Date.now();if(e.writerAttestation===void 0&&e.sessionId&&T$(e.sessionId,e.type,r)){let o=P$(e.sessionId);return o&&w.info("[AppSyncClient] client event throttle engaged",{sessionId:e.sessionId,type:e.type,windowCount:o.count,threshold:A$}),{eventId:`local-throttled-${r}-${Math.random().toString(36).slice(2,11)}`,sessionId:e.sessionId,type:e.type,source:e.source,content:e.content,timestamp:e.timestamp??new Date(r).toISOString(),...e.promptId!==void 0?{promptId:e.promptId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{},...e.isEncrypted!==void 0?{isEncrypted:e.isEncrypted}:{}}}let n={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0,...e.writerOutcomeSubject!==void 0&&{writerOutcomeSubject:JSON.stringify(e.writerOutcomeSubject)},...e.writerCausalPredecessor!==void 0&&{writerCausalPredecessor:JSON.stringify(e.writerCausalPredecessor)}};if(e.writerAttestation!==void 0){let o=Buffer.byteLength(JSON.stringify(n),"utf8"),s=180*1024;if(o>s)throw new Error(`WRITER_EVENT_INPUT_TOO_LARGE: ${o} bytes exceeds ${s}`)}let i=await this.graphqlRequest(tt.createEvent,{input:n});return w.debug("[AppSyncClient] Event created",{eventId:i.data.createEvent.eventId,type:i.data.createEvent.type}),i.data.createEvent}async refreshOpenPromptTtl(e){if(e.length===0)return[];let r=100;if(e.length<=r)return(await this.graphqlRequest(tt.refreshOpenPromptTtl,{promptIds:e})).data?.refreshOpenPromptTtl??[];let n=[];for(let i=0;i<e.length;i+=r){let o=e.slice(i,i+r),a=(await this.graphqlRequest(tt.refreshOpenPromptTtl,{promptIds:o})).data?.refreshOpenPromptTtl??[];a.length>0&&n.push(...a)}return n}async updateEventStatus(e,r,n){let i=r===void 0?void 0:{...r},o=i?.sessionGenerationId;if(o!==void 0&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(o))throw new ve("INVALID_SYNC_INPUT");if(i&&(typeof o!="string"||i.type!==void 0&&!["USER_PROMPT","PROMPT_RESPONSE"].includes(i.type)))throw new ve("INVALID_SYNC_INPUT");let s={...e},a=this.getCurrentUserId();if(this.assertSyncAccount(a),t.throwIfAborted(n),s.deliveryStatus==="EXECUTED"&&i?.type!==void 0)for(let{userId:h,scope:m}of this.syncRegistrations.get(s.sessionId)?.values()??[])h!==a||m.sessionGenerationId!==o||(await this.desktopSyncWriter({root:m.root,sessionScope:m}).inbound().markExecutedLocally({...s,sessionGenerationId:m.sessionGenerationId,source:"MOBILE",type:i.type}),this.assertSyncAccount(a),t.throwIfAborted(n));let c=await this.getCompanionSyncRoute(n);if(this.assertSyncAccount(a),t.throwIfAborted(n),c.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(o!==void 0&&c.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");if(c.protocol==="LEGACY"){let h=await this.graphqlRequest(tt.updateEventStatus,{input:s},!1,n,a);return this.assertSyncAccount(a),h.data.updateEventStatus}if(s.deliveryStatus!=="DELIVERED"&&s.deliveryStatus!=="EXECUTED")throw new ve("INVALID_SYNC_INPUT");let l=await this.getSession(s.sessionId);if(this.assertSyncAccount(a),t.throwIfAborted(n),!l||l.sessionId!==s.sessionId||l.userId!==a||l.status!=="ACTIVE"||typeof l.sessionGenerationId!="string")throw new ve("SYNC_SESSION_UNAVAILABLE");let d=[...this.syncRegistrations.get(s.sessionId)?.values()??[]].filter(h=>h.userId===a),u=l.sessionGenerationId.toLowerCase();if(o!==void 0&&u!==o)throw new ve("SYNC_SESSION_GENERATION_CHANGED");if(d.length&&!d.some(h=>h.scope.sessionGenerationId===u))throw new ve("SYNC_SESSION_GENERATION_CHANGED");let p=await this.updateDesktopSyncEventStatus({...s,clientOperationId:(0,Qn.v4)(),deliveryStatus:s.deliveryStatus==="DELIVERED"?"DELIVERED":"EXECUTED",sessionGenerationId:u,expectedSessionKeyGen:l.sessionKeyGen??Di},n);if(this.assertSyncAccount(a),t.throwIfAborted(n),i?.type!==void 0&&p.type!==i.type)throw new ve("INVALID_SYNC_RECEIPT");if(p.deliveryStatus==="EXECUTED")for(let{scope:h}of d)h.sessionGenerationId===p.sessionGenerationId&&await this.desktopSyncWriter({root:h.root,sessionScope:h}).inbound().acknowledgeExecuted(p);return p}async listEvents(e,r,n){let i=await this.getCompanionSyncRoute();if(i.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(i.protocol==="SYNC_V2"){if(n!==void 0&&(!Number.isSafeInteger(n)||n<1||n>100))throw new ve("INVALID_SYNC_INPUT");return(await this.syncHistoryForSession(e)).items.filter(a=>r===void 0||a.source===r).slice(0,n??100)}return(await this.graphqlRequest(qt.listEvents,{sessionId:e,source:r,limit:n})).data.listEvents.items}async listSupervisionEvents(e){let r=await this.getCompanionSyncRoute();if(r.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(r.protocol==="SYNC_V2"){if(e.limit!==void 0&&e.limit!==100)throw new ve("INVALID_SYNC_INPUT");return this.syncHistoryForSession(e.sessionId,e.sessionGenerationId,e.nextToken)}let i=(await this.graphqlRequest(qt.listSupervisionEvents,e)).data?.listSupervisionEvents;if(!i||!Array.isArray(i.items))throw new Error("listSupervisionEvents returned an invalid page");if(i.nextToken!==void 0&&i.nextToken!==null&&typeof i.nextToken!="string")throw new Error("listSupervisionEvents returned an invalid nextToken");return{items:i.items,nextToken:i.nextToken??null}}async listClaimedGatePrompts(e){let r=new Map,n=null,i=0;do{let s=(await this.graphqlRequest(qt.listOpenPrompts,{nextToken:n,limit:200})).data?.listOpenPrompts;if(!s||!Array.isArray(s.items))throw new Error("listOpenPrompts returned an invalid page");for(let a of s.items){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a;if(c.sessionId!==e||c.kind!=="GATE"||c.mobileActionable!==!1||typeof c.promptId!="string"||c.promptId.length===0)continue;let l=c.decisionClaimId;if(l!=null&&(typeof l!="string"||l.length===0))throw new Error("listOpenPrompts returned an invalid decisionClaimId");let d={sessionId:e,promptId:c.promptId,decisionClaimId:l??null},u=r.get(d.promptId);if(u&&u.decisionClaimId!==d.decisionClaimId)throw new Error("listOpenPrompts returned conflicting Gate claims");r.set(d.promptId,d)}if(s.nextToken!==void 0&&s.nextToken!==null&&typeof s.nextToken!="string")throw new Error("listOpenPrompts returned an invalid nextToken");if(n=s.nextToken??null,i++,i>=500&&n!==null)throw new Error("listOpenPrompts pagination exceeded the safety cap")}while(n!==null);return[...r.values()]}async listSessions(e=100){if(!this.currentUserId)throw new Error("Not authenticated");let r=[],n=null;do{let o=(await this.graphqlRequest(qt.listSessions,{userId:this.currentUserId,limit:e,nextToken:n})).data?.listSessions;o?.items&&r.push(...o.items),n=o?.nextToken??null}while(n);return r}async sweepOrphanSessions(e){let r=e.staleThresholdMs??9e5,n=new Set(e.excludeSessionIds??[]),i=Date.now(),o;try{o=await this.listSessions()}catch(a){return w.warn("[AppSyncClient] OrphanSweep: listSessions failed, skipping sweep",{agentType:e.agentType,error:a instanceof Error?a.message:String(a)}),0}let s=0;for(let a of o){if(a.agentType!==e.agentType||a.status!=="ACTIVE"||n.has(a.sessionId))continue;let l=[a.lastHeartbeatAt,a.createdAt,a.updatedAt].map(p=>p?Date.parse(p):Number.NaN).filter(p=>Number.isFinite(p));if(l.length===0)continue;let d=Math.max(...l),u=i-d;if(!(u<r)){w.warn("[AppSyncClient] OrphanSweep: marking stale session INACTIVE",{sessionId:a.sessionId,agentType:a.agentType,lastHeartbeatAt:a.lastHeartbeatAt,createdAt:a.createdAt,updatedAt:a.updatedAt,freshnessAgeMinutes:Math.round(u/6e4)});try{await this.updateSession({sessionId:a.sessionId,status:"INACTIVE"}),s++}catch(p){w.warn("[AppSyncClient] OrphanSweep: updateSession failed, leaving row as-is",{sessionId:a.sessionId,error:p instanceof Error?p.message:String(p)})}}}return s>0&&w.info("[AppSyncClient] OrphanSweep complete",{agentType:e.agentType,swept:s}),s}async listUserDeviceKeys(){return(await this.graphqlRequest(qt.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async listServiceDeviceKeys(){return(await this.graphqlRequest(qt.listServiceDeviceKeys,{})).data.listServiceDeviceKeys||[]}async registerDeviceKey(e,r,n,i){let o={deviceId:e,publicKey:r,platform:n,deviceName:i};await this.graphqlRequest(tt.registerDeviceKey,{input:o}),w.info("[AppSyncClient] Device key registered",{deviceId:e,platform:n})}async grantSessionKey(e){await this.graphqlRequest(tt.grantSessionKey,{input:e}),w.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(tt.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}async updateAvailableAgents(e,r=!1){let n=await this.graphqlRequest(tt.updateAvailableAgents,{agents:e,replace:r});return w.info("[AppSyncClient] Updated available agents",{agents:e,replace:r}),n.data.updateAvailableAgents}async updateAdapterCapabilities(e){let r=await this.graphqlRequest(tt.updateAdapterCapabilities,{capabilities:JSON.stringify(e)});return w.info("[AppSyncClient] Updated adapter capabilities",{recordCount:e.length}),r.data.updateAdapterCapabilities}async updateReviewerPolicy(e){let r=await this.graphqlRequest(tt.updateReviewerPolicy,{input:e});return w.info("[AppSyncClient] Updated reviewer policy",{orchestrationEnabledDefault:e.orchestrationEnabledDefault,reviewerSeatCount:e.reviewerSeats?.length}),r.data.updateReviewerPolicy}async getSubscriptionStatus(e){let r=this.getCurrentUserId();this.assertSyncAccount(r);let n=await this.graphqlRequest(qt.getSubscriptionStatus,{},!1,e,r);this.assertSyncAccount(r);let i=n?.data?.getSubscriptionStatus;if(i===null||typeof i!="object"||Array.isArray(i)||!["FREE","PRO","MAX"].includes(i.tier)||!["ACTIVE","EXPIRED","GRACE_PERIOD","BILLING_RETRY"].includes(i.status)||i.expiresAt!==null&&typeof i.expiresAt!="string")throw new Error("Subscription status response is malformed");return{tier:i.status==="EXPIRED"?"FREE":i.tier,status:i.status,expiresAt:i.expiresAt}}async classifyPlannerPrompt(e){return(await this.graphqlRequest(tt.classifyPlannerPrompt,{input:e})).data.classifyPlannerPrompt}async pingPlanner(e){return(await this.graphqlRequest(tt.pingPlanner,{input:e})).data.pingPlanner}async generatePlannerAdvisory(e){if(!e||typeof e!="object")throw new Error("generatePlannerAdvisory: input object is required");if(!e.sessionId||typeof e.sessionId!="string")throw new Error("generatePlannerAdvisory: sessionId is required");if(!e.prompt||typeof e.prompt!="string")throw new Error("generatePlannerAdvisory: prompt ciphertext is required");if(e.prompt.length>2e5)throw new Error(`generatePlannerAdvisory: prompt ciphertext exceeds 200,000 chars ceiling (${e.prompt.length})`);if(e.images!==void 0){if(!Array.isArray(e.images))throw new Error("generatePlannerAdvisory: images must be an array of string ciphertexts");if(e.images.length>5)throw new Error(`generatePlannerAdvisory: images count exceeds maximum of 5 (got ${e.images.length})`);let n=e.prompt.length;for(let i=0;i<e.images.length;i++){let o=e.images[i];if(typeof o!="string"||o.trim().length===0)throw new Error(`generatePlannerAdvisory: image at index ${i} must be a non-empty string ciphertext`);if(o.length>27e5)throw new Error(`generatePlannerAdvisory: image at index ${i} exceeds ciphertext limit of 2,700,000 chars (got ${o.length})`);n+=o.length}if(n>45e5)throw new Error(`generatePlannerAdvisory: total request ciphertext exceeds 4,500,000 chars ceiling (${n})`)}if(e.maxTokens!==void 0&&(e.maxTokens<1||e.maxTokens>1536))throw new Error(`generatePlannerAdvisory: maxTokens must be between 1 and 1536 (got ${e.maxTokens})`);if(e.temperature!==void 0&&(e.temperature<0||e.temperature>1))throw new Error(`generatePlannerAdvisory: temperature must be between 0 and 1 (got ${e.temperature})`);let r=await this.graphqlRequest(tt.generatePlannerAdvisory,{input:e});if(!r?.data?.generatePlannerAdvisory)throw new Error("generatePlannerAdvisory: empty response returned from AppSync");return r.data.generatePlannerAdvisory}async submitGateDecisionV2(e,r){let{promptKind:n,...i}=e,o=await this.graphqlRequest(tt.submitGateDecisionV2,{input:{...i,canonicalRequestHash:r}});return tx(o.data?.submitGateDecisionV2)}async submitGroupDecisionV2(e,r){let{promptKind:n,...i}=e,o=await this.graphqlRequest(tt.submitGroupDecisionV2,{input:{...i,canonicalRequestHash:r}});return tx(o.data?.submitGroupDecisionV2)}async authorizeGroupTerminalOperation(e){let r=await this.graphqlRequest(tt.authorizeGroupTerminalOperation,{input:e});return rh(r.data?.authorizeGroupTerminalOperation,"authorizeGroupTerminalOperation")}async beginGroupPromotion(e){let r=await this.graphqlRequest(tt.beginGroupPromotion,{input:e});return rh(r.data?.beginGroupPromotion,"beginGroupPromotion")}async completeGroupPromotion(e){let r=await this.graphqlRequest(tt.completeGroupPromotion,{input:e});return rh(r.data?.completeGroupPromotion,"completeGroupPromotion")}async beginGroupRevert(e){let r=await this.graphqlRequest(tt.beginGroupRevert,{input:e});return rh(r.data?.beginGroupRevert,"beginGroupRevert")}async completeGroupRevert(e){let r=await this.graphqlRequest(tt.completeGroupRevert,{input:e});return rh(r.data?.completeGroupRevert,"completeGroupRevert")}async prepareGroupKeep(e){let r=await this.graphqlRequest(tt.prepareGroupKeep,{input:e});return rh(r.data?.prepareGroupKeep,"prepareGroupKeep")}async commitGroupDecisionV2(e){let r=await this.graphqlRequest(tt.commitGroupDecisionV2,{input:e});return DZ(r.data?.commitGroupDecisionV2)}async getDecisionAttempt(e){let r=await this.graphqlRequest(qt.getDecisionAttempt,{input:e});return gU(r.data?.getDecisionAttempt)}async getGateResolution(e){let r={...e},n=this.getCurrentUserId(),i=this.syncReadEpoch;this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId);let o=await this.getCompanionSyncRoute();if(this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId),i!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");if(o.protocol==="LEGACY"){let a=await this.graphqlRequest(qt.getGateResolution,{input:{sessionId:r.sessionId,promptId:r.promptId}},!1,void 0,n);if(this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId),i!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");return a.data?.getGateResolution}if(o.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");if(!r.sessionGenerationId)throw new Tt("INVALID_SYNC_READ_INPUT");Fg({...r,sessionGenerationId:r.sessionGenerationId},()=>{throw new Tt("INVALID_SYNC_READ_INPUT")});let s=await this.desktopSyncReadSession({sessionId:r.sessionId,sessionGenerationId:r.sessionGenerationId});try{let a=await s.gateResolution(r.promptId);if(this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId),i!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");return a}finally{await s.close()}}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:Xe.encryptContent(e.notes,r),sessionId:e.sessionId,keyVersion:Pp}}let i=e.decision.toUpperCase(),s=(await this.graphqlRequest(tt.applyUserDecision,{input:{gateId:e.gateId,taskId:e.taskId,sessionId:e.sessionId,currentRound:e.currentRound,decision:i,notes:n}})).data?.applyUserDecision;if(!s||typeof s!="object")throw new Error("applyUserDecision: missing envelope on response");let a=nh(s.payload,"applyUserDecision");return{decision:typeof s.decision=="string"?s.decision.toLowerCase():e.decision,postAction:a}}async createTaskGroup(e){if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("createTaskGroup: sessionId is required");if(!Array.isArray(e.workItems)||e.workItems.length<2)throw new Error("createTaskGroup: requires at least 2 workItems (a team is \u22652 tracks)");if(typeof e.groupIdempotencyKey!="string"||e.groupIdempotencyKey.length===0)throw new Error("createTaskGroup: groupIdempotencyKey is required");let n=(await this.graphqlRequest(tt.createTaskGroup,{input:e})).data?.createTaskGroup;if(typeof n!="string")throw new Error(`createTaskGroup: expected AWSJSON string result, got ${typeof n}`);let i;try{i=JSON.parse(n)}catch(o){throw new Error(`createTaskGroup: failed to parse AWSJSON result: ${o.message}`)}if(!i||typeof i!="object")throw new Error("createTaskGroup: parsed result is not an object");if(typeof i.accepted!="boolean")throw new Error("createTaskGroup: result missing boolean `accepted`");return i}async submitMergeGateVerdict(e,r={}){if(typeof e.taskGroupId!="string"||e.taskGroupId.length===0)throw new Error("submitMergeGateVerdict: taskGroupId is required");if(typeof e.mergeGateId!="string"||e.mergeGateId.length===0)throw new Error("submitMergeGateVerdict: mergeGateId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitMergeGateVerdict: sessionId is required");if(typeof e.verdictIdempotencyKey!="string"||e.verdictIdempotencyKey.length===0)throw new Error("submitMergeGateVerdict: verdictIdempotencyKey is required");if(!e.classification||typeof e.classification!="object")throw new Error("submitMergeGateVerdict: classification is required");if(typeof e.classification.signatureB64!="string"||e.classification.signatureB64.length===0)throw new Error("submitMergeGateVerdict: classification.signatureB64 is required (sign via signMergeClassification)");if(typeof e.classification.leDeviceId!="string"||e.classification.leDeviceId.length===0)throw new Error("submitMergeGateVerdict: classification.leDeviceId is required");if(!e.detail||typeof e.detail!="object")throw new Error("submitMergeGateVerdict: detail is required");let i=(await this.graphqlRequest(tt.submitMergeGateVerdict,{input:e},!1,r.signal)).data?.submitMergeGateVerdict;if(typeof i!="string")throw new Error(`submitMergeGateVerdict: expected AWSJSON string result, got ${typeof i}`);let o;try{o=JSON.parse(i)}catch(s){throw new Error(`submitMergeGateVerdict: failed to parse AWSJSON result: ${s.message}`)}if(!o||typeof o!="object")throw new Error("submitMergeGateVerdict: parsed result is not an object");if(typeof o.outcome!="string")throw new Error("submitMergeGateVerdict: result missing string `outcome`");return o}async submitTrackVerificationOutcome(e){if(typeof e.taskGroupId!="string"||e.taskGroupId.length===0)throw new Error("submitTrackVerificationOutcome: taskGroupId is required");if(typeof e.trackIndex!="number"||!Number.isInteger(e.trackIndex))throw new Error("submitTrackVerificationOutcome: trackIndex must be an integer");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitTrackVerificationOutcome: sessionId is required");if(typeof e.verdictIdempotencyKey!="string"||e.verdictIdempotencyKey.length===0)throw new Error("submitTrackVerificationOutcome: verdictIdempotencyKey is required");let r=["verification_failure","out_of_scope_write","review_integrity_violation","promote_failure","no_change"];if(!r.includes(e.outcome))throw new Error(`submitTrackVerificationOutcome: outcome must be one of ${r.join(" | ")}, got ${String(e.outcome)}`);let i=(await this.graphqlRequest(tt.submitTrackVerificationOutcome,{input:e})).data?.submitTrackVerificationOutcome;if(typeof i!="string")throw new Error(`submitTrackVerificationOutcome: expected AWSJSON string result, got ${typeof i}`);let o;try{o=JSON.parse(i)}catch(s){throw new Error(`submitTrackVerificationOutcome: failed to parse AWSJSON result: ${s.message}`)}if(!o||typeof o!="object")throw new Error("submitTrackVerificationOutcome: parsed result is not an object");if(typeof o.trackState!="string")throw new Error("submitTrackVerificationOutcome: result missing string `trackState`");return o}async claimGroupDecision(e,r){if(typeof e.taskGroupId!="string"||e.taskGroupId.length===0)throw new Error("claimGroupDecision: taskGroupId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("claimGroupDecision: sessionId is required");if(e.phase!=="claim"&&e.phase!=="commit")throw new Error('claimGroupDecision: phase must be "claim" | "commit"');if(typeof e.verdictIdempotencyKey!="string"||e.verdictIdempotencyKey.length===0)throw new Error("claimGroupDecision: verdictIdempotencyKey is required");let n=["ACCEPT","ACCEPT_WITH_NOTES","REJECT_WITH_NOTES","REJECT_RESTART","ABORT_TASK"];if(!n.includes(e.decision))throw new Error(`claimGroupDecision: decision must be one of ${n.join(" | ")}, got ${String(e.decision)}`);if(e.phase==="commit"&&(typeof e.claimToken!="string"||e.claimToken.length===0))throw new Error("claimGroupDecision: commit requires the claimToken from the claim phase");let i;if(e.notes!==void 0){if(typeof r!="string"||r.length===0)throw new Error("claimGroupDecision: sessionKeyBase64 is required when notes are supplied");i=Xe.encryptContent(e.notes,r)}let s=(await this.graphqlRequest(tt.claimGroupDecision,{input:{...e,...i!==void 0?{notes:i}:{}}})).data?.claimGroupDecision;if(typeof s!="string")throw new Error(`claimGroupDecision: expected AWSJSON string result, got ${typeof s}`);let a;try{a=JSON.parse(s)}catch(c){throw new Error(`claimGroupDecision: failed to parse AWSJSON result: ${c.message}`)}if(!a||typeof a!="object")throw new Error("claimGroupDecision: parsed result is not an object");if(typeof a.phase!="string")throw new Error("claimGroupDecision: result missing string `phase`");if(typeof a.claimToken!="string")throw new Error("claimGroupDecision: result missing string `claimToken`");return a}async startTask(e){if(typeof e.taskId!="string"||e.taskId.length===0)throw new Error("startTask: taskId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("startTask: sessionId is required");if(!e.decision||typeof e.decision!="object")throw new Error("startTask: decision is required");let r={taskId:e.taskId,sessionId:e.sessionId,decision:e.decision};e.availableAgents!==void 0&&(r.availableAgents=e.availableAgents),e.implementorAgent!==void 0&&(r.implementorAgent=e.implementorAgent),e.slotLeaseProtocol!==void 0&&(r.slotLeaseProtocol=e.slotLeaseProtocol);let n=await this.graphqlRequest(tt.startTask,{input:r}),i=this.#t(n.data?.startTask,"startTask");if(typeof i.workflowState!="string"||i.workflowState.length===0)throw new Error("startTask: result missing string `workflowState`");return{workflowState:i.workflowState,...Gc(i,"queuePosition"),...Gc(i,"runningTracks"),...Gc(i,"trackBudget")}}async submitImplementorOutput(e,r){if(typeof e.taskId!="string"||e.taskId.length===0)throw new Error("submitImplementorOutput: taskId is required");if(typeof e.gateId!="string"||e.gateId.length===0)throw new Error("submitImplementorOutput: gateId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitImplementorOutput: sessionId is required");let n=this.#r(e.rawOutput,e.sessionId,r),i={input:{taskId:e.taskId,gateId:e.gateId,sessionId:e.sessionId,roundNumber:e.roundNumber,encProposal:n,...e.usage!==void 0?{usage:e.usage}:{},reviewScopeReset:e.reviewScopeReset??!1}},o;try{o=await this.graphqlRequest(tt.submitImplementorOutput,i)}catch(s){if(!MZ(s))throw s;if(e.reviewScopeReset===!0)throw w.warn("[AppSyncClient] explicit review-scope reset rejected by old backend schema; failing closed",{gateId:e.gateId,taskId:e.taskId}),s;w.warn("[AppSyncClient] submitImplementorOutput additive fields rejected by backend schema; retrying legacy input",{gateId:e.gateId,taskId:e.taskId,reason:s instanceof Error?s.message:String(s)});let a={input:{taskId:e.taskId,gateId:e.gateId,sessionId:e.sessionId,roundNumber:e.roundNumber,encProposal:n}};o=await this.graphqlRequest(tt.submitImplementorOutput,a)}return this.#e(o.data?.submitImplementorOutput,"submitImplementorOutput")}async submitReviewerVerdict(e,r){if(typeof e.gateId!="string"||e.gateId.length===0)throw new Error("submitReviewerVerdict: gateId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitReviewerVerdict: sessionId is required");if(!e.verdict||typeof e.verdict!="object")throw new Error("submitReviewerVerdict: verdict is required");let n=this.#r(JSON.stringify(e.verdict),e.sessionId,r),o=(await this.graphqlRequest(tt.submitReviewerVerdict,{input:{gateId:e.gateId,sessionId:e.sessionId,seatId:e.seatId,verdict:n}})).data?.submitReviewerVerdict;if(!o||typeof o!="object")throw new Error("submitReviewerVerdict: missing envelope on response");let s=o.payload;if(typeof s!="string")throw new Error(`submitReviewerVerdict: expected AWSJSON string payload, got ${typeof s}`);try{return JSON.parse(s)}catch(a){throw new Error(`submitReviewerVerdict: failed to parse AWSJSON payload: ${a.message}`)}}async getReviewerPrompt(e,r,n){if(typeof e!="string"||e.length===0)throw new Error("getReviewerPrompt: gateId is required");if(!Number.isInteger(r)||r<0)throw new Error("getReviewerPrompt: seatId must be a non-negative integer");let i=await this.graphqlRequest(qt.getReviewerPrompt,{gateId:e,seatId:r}),o=this.#e(i.data?.getReviewerPrompt,"getReviewerPrompt");if(!o.encPrompt||typeof o.encPrompt.ciphertextB64!="string")throw new Error("getReviewerPrompt: response missing encPrompt.ciphertextB64");let s=Xe.decryptContent(o.encPrompt.ciphertextB64,n);return{gateId:o.gateId,seatId:o.seatId,role:o.role,prompt:s,reviewScope:o.reviewScope}}async getTaskReviewSummary(e,r,n){if(typeof e!="string"||e.length===0)throw new Error("getTaskReviewSummary: taskId is required");if(typeof r!="string"||r.length===0)throw new Error("getTaskReviewSummary: gateId is required");if(typeof n!="string"||n.length===0)throw new Error("getTaskReviewSummary: sessionKeyBase64 is required");let i=await this.graphqlRequest(qt.getTaskReviewSummary,{taskId:e,gateId:r}),s=nh(i.data?.getTaskReviewSummary,"getTaskReviewSummary").summary;if(!s||typeof s!="object"||typeof s.ciphertextB64!="string"||s.ciphertextB64.length===0)throw new Error("getTaskReviewSummary: response missing summary.ciphertextB64");let a=Xe.decryptContent(s.ciphertextB64,n),c;try{c=JSON.parse(a)}catch(l){throw new Error(`getTaskReviewSummary: failed to parse decrypted summary: ${l.message}`)}if(!c||typeof c!="object"||Array.isArray(c))throw new Error("getTaskReviewSummary: decrypted summary is not an object");return c}async getClassBSigningPublicKey(){let e=await this.graphqlRequest(qt.getClassBSigningPublicKey,{}),r=this.#e(e.data?.getClassBSigningPublicKey,"getClassBSigningPublicKey");if(typeof r.publicKeyB64!="string"||typeof r.keyId!="string")throw new Error("getClassBSigningPublicKey: response missing publicKeyB64/keyId");return{publicKeyB64:r.publicKeyB64,keyId:r.keyId}}async getInReviewAssignments(e){if(typeof e!="string"||e.length===0)throw new Error("getInReviewAssignments: taskId is required");let r=await this.graphqlRequest(qt.getInReviewAssignments,{taskId:e}),n=this.#e(r.data?.getInReviewAssignments,"getInReviewAssignments");return Array.isArray(n.assignments)?n.assignments:[]}async getTaskGroupTracks(e){if(typeof e!="string"||e.length===0)throw new Error("getTaskGroupTracks: taskGroupId is required");let r=await this.graphqlRequest(qt.getTaskGroupTracks,{taskGroupId:e}),n=this.#e(r.data?.getTaskGroupTracks,"getTaskGroupTracks");return Array.isArray(n.tracks)?n.tracks:[]}async getInFlightTeamTracks(e){if(typeof e!="string"||e.length===0)throw new Error("getInFlightTeamTracks: sessionId is required");let r=await this.graphqlRequest(qt.getInFlightTeamTracks,{sessionId:e}),n=this.#e(r.data?.getInFlightTeamTracks,"getInFlightTeamTracks");return Array.isArray(n.tracks)?n.tracks:[]}async getTaskGroupStatus(e){if(typeof e!="string"||e.length===0)throw new Error("getTaskGroupStatus: taskGroupId is required");let r=await this.graphqlRequest(qt.getTaskGroupStatus,{taskGroupId:e}),n=this.#e(r.data?.getTaskGroupStatus,"getTaskGroupStatus");return{taskGroupId:typeof n.taskGroupId=="string"?n.taskGroupId:e,status:typeof n.status=="string"?n.status:"unknown",...typeof n.haltReason=="string"?{haltReason:n.haltReason}:{}}}async cancelQueuedWork(e){let r=rx(e,"cancelQueuedWork"),n=await this.graphqlRequest(tt.cancelQueuedWork,{input:r}),i=this.#t(n.data?.cancelQueuedWork,"cancelQueuedWork"),o=i.outcome;if(o!=="cancelled"&&o!=="not_queued"&&o!=="partly_running")throw new Error(`cancelQueuedWork: unexpected outcome ${String(o)}`);return{outcome:o,...typeof i.reason=="string"?{reason:i.reason}:{}}}async releaseSessionWork(e,r={}){if(typeof e!="string"||e.length===0)throw new Error("releaseSessionWork: sessionId is required");let n=await this.graphqlRequest(tt.releaseSessionWork,{input:{sessionId:e}},!1,r.signal),i=this.#t(n.data?.releaseSessionWork,"releaseSessionWork");return{haltedGroups:typeof i.haltedGroups=="number"?i.haltedGroups:0,endedTasks:typeof i.endedTasks=="number"?i.endedTasks:0}}async setTaskOrdinal(e){if(!Number.isInteger(e.ordinal)||e.ordinal<1||e.ordinal>9999)throw new Error("setTaskOrdinal: ordinal must be an integer 1-9999");let r=rx(e,"setTaskOrdinal"),n=await this.graphqlRequest(tt.setTaskOrdinal,{input:{...r,ordinal:e.ordinal}}),i=this.#t(n.data?.setTaskOrdinal,"setTaskOrdinal");if(typeof i.ordinal!="number")throw new Error("setTaskOrdinal: result missing number `ordinal`");return{ordinal:i.ordinal}}async getTrackBudgetStatus(e){if(typeof e!="string"||e.length===0)throw new Error("getTrackBudgetStatus: sessionId is required");let r=await this.graphqlRequest(qt.getTrackBudgetStatus,{sessionId:e}),n=this.#t(r.data?.getTrackBudgetStatus,"getTrackBudgetStatus"),i=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:0,o=Array.isArray(n.holders)?n.holders:[],s=Array.isArray(n.ended)?n.ended:[];return{running:i(n.running),queued:i(n.queued),budget:i(n.budget),holders:o.flatMap(a=>{if(!a||typeof a!="object")return[];let c=a;return c.kind!=="task"&&c.kind!=="track"||c.state!=="queued"&&c.state!=="running"?[]:[{kind:c.kind,state:c.state,sameSession:c.sameSession===!0,...typeof c.taskId=="string"?{taskId:c.taskId}:{},...typeof c.taskGroupId=="string"?{taskGroupId:c.taskGroupId}:{},...Gc(c,"trackIndex"),...Gc(c,"queuePosition"),...Gc(c,"ordinal")}]}),ended:s.flatMap(a=>{if(!a||typeof a!="object")return[];let c=a;return c.kind!=="task"&&c.kind!=="track"||c.state!=="done"&&c.state!=="cancelled"?[]:[{kind:c.kind,state:c.state,...typeof c.taskId=="string"?{taskId:c.taskId}:{},...typeof c.taskGroupId=="string"?{taskGroupId:c.taskGroupId}:{},...Gc(c,"trackIndex"),...typeof c.endReason=="string"?{endReason:c.endReason}:{},...typeof c.taskEnded=="string"?{taskEnded:c.taskEnded}:{},...Gc(c,"endedAt")}]})}}async openApplyRetryOffer(e){let r=rx(e,"openApplyRetryOffer");for(let o of["sessionTask","external","writeErrors"]){let s=e.counts?.[o];if(!Number.isInteger(s)||s<0)throw new Error(`openApplyRetryOffer: counts.${o} must be a non-negative integer`)}let n=await this.graphqlRequest(tt.openApplyRetryOffer,{input:{...r,counts:{sessionTask:e.counts.sessionTask,external:e.counts.external,writeErrors:e.counts.writeErrors}}}),i=this.#t(n.data?.openApplyRetryOffer,"openApplyRetryOffer");if(typeof i.gateId!="string"||typeof i.taskId!="string"||typeof i.sessionId!="string")throw new Error("openApplyRetryOffer: result missing gateId/taskId/sessionId");return{gateId:i.gateId,taskId:i.taskId,sessionId:i.sessionId}}async resolveApplyRetryOffer(e){if(typeof e.gateId!="string"||e.gateId.length===0)throw new Error("resolveApplyRetryOffer: gateId is required");if(e.choice!=="RETRY_AS_NEW_TASK"&&e.choice!=="DISCARD")throw new Error("resolveApplyRetryOffer: choice must be RETRY_AS_NEW_TASK | DISCARD");let r=await this.graphqlRequest(tt.resolveApplyRetryOffer,{input:{gateId:e.gateId,choice:e.choice}}),n=this.#t(r.data?.resolveApplyRetryOffer,"resolveApplyRetryOffer");if(typeof n.gateId!="string"||typeof n.taskId!="string"||typeof n.sessionId!="string"||n.choice!=="RETRY_AS_NEW_TASK"&&n.choice!=="DISCARD")throw new Error("resolveApplyRetryOffer: unexpected result shape");return{gateId:n.gateId,taskId:n.taskId,sessionId:n.sessionId,choice:n.choice}}#t(e,r){let n=this.#e(e,r);if(typeof n.errorType=="string"&&typeof n.errorMessage=="string")throw new Ut({message:n.errorMessage,errorType:n.errorType});return n}#r(e,r,n){if(typeof n!="string"||n.length===0)throw new Error("encryptForSession: sessionKeyBase64 is required");return{ciphertextB64:Xe.encryptContent(e,n),sessionId:r,keyVersion:Pp}}#e(e,r){if(typeof e!="string")throw new Error(`${r}: expected AWSJSON string result, got ${typeof e}`);let n;try{n=JSON.parse(e)}catch(i){throw new Error(`${r}: failed to parse AWSJSON result: ${i.message}`)}if(!n||typeof n!="object")throw new Error(`${r}: parsed result is not an object`);return n}async recordContinuationPacketWritten(e){try{let n=(await this.graphqlRequest(tt.recordContinuationPacketWritten,{input:e})).data?.recordContinuationPacketWritten;if(!n||typeof n!="object")return{kind:"error",reason:"missing envelope on recordContinuationPacketWritten response"};let i=n.auditEventId,o=n.alreadyExists;return typeof i!="string"||typeof o!="boolean"?{kind:"error",reason:"malformed recordContinuationPacketWritten response"}:{kind:"ok",auditEventId:i,alreadyExists:o}}catch(r){return r instanceof Ut?{kind:"error",reason:r.message}:{kind:"error",reason:r.message??String(r)}}}async verifyContinuationPacketWritten(e){try{let n=(await this.graphqlRequest(qt.verifyContinuationPacketWritten,{taskId:e.taskId,offerId:e.offerId,packetHash:e.packetHash})).data?.verifyContinuationPacketWritten;return typeof n!="boolean"?{kind:"error",reason:"malformed verifyContinuationPacketWritten response"}:{kind:"ok",exists:n}}catch(r){return r instanceof Ut?{kind:"error",reason:r.message}:{kind:"error",reason:r.message??String(r)}}}async queryAudit(e){let n=(await this.graphqlRequest(qt.queryAudit,{input:{taskId:e.taskId,sessionId:e.sessionId}})).data?.queryAudit,i=null;if(typeof n=="string")try{i=JSON.parse(n)}catch{i=null}else n&&typeof n=="object"&&(i=n);if(!i||typeof i!="object")return{rows:[]};let o=i.entries??i.rows;if(!Array.isArray(o))return{rows:[]};let s=o.filter(a=>!!a&&typeof a=="object");return e.kind!==void 0&&(s=s.filter(a=>a.kind===e.kind||a.kindWire===e.kind)),{rows:s}}assertSyncReadAdmission(e){if(this.syncRetiringSessions.has(e))throw new ve("SYNC_SESSION_UNAVAILABLE")}rememberSyncRegistration(e){let r=this.getCurrentUserId(),n=this.syncRegistrations.get(e.sessionId)??new Map;n.set(JSON.stringify([r,e.sessionGenerationId,e.root??null]),{userId:r,scope:{...e}}),this.syncRegistrations.set(e.sessionId,n)}ownSyncReader(e,r){this.rememberSyncRegistration(e);let n=this.syncReadOwners.get(e.sessionId)??new Set;this.syncReadOwners.set(e.sessionId,n);let i,o=Object.freeze({...r,close:()=>i||(i=r.close().finally(()=>{n.delete(o),!n.size&&this.syncReadOwners.get(e.sessionId)===n&&this.syncReadOwners.delete(e.sessionId)}),i)});return n.add(o),o}trackSyncClosure(e,r){let n=this.syncSubscriptionClosures.get(e)??new Set;this.syncSubscriptionClosures.set(e,n),n.add(r),r.finally(()=>{n.delete(r),!n.size&&this.syncSubscriptionClosures.get(e)===n&&this.syncSubscriptionClosures.delete(e)}).catch(()=>{})}async joinSyncSubscriptionClosures(e){let r=this.syncSubscriptionClosures.get(e);r&&await Promise.all([...r])}async syncHistoryForSession(e,r,n){this.assertSyncReadAdmission(e);let i=this.getCurrentUserId(),o=await this.getSession(e);if(this.assertSyncAccount(i),this.assertSyncReadAdmission(e),o?.sessionId!==e||!o.sessionGenerationId||o.userId!==i||r!==void 0&&r!==o.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let s={sessionId:e,sessionGenerationId:o.sessionGenerationId},a=this.activeSubscriptions.get(e),c=!a?.destroyed&&a?.syncSessionGenerationId===s.sessionGenerationId?a.syncConnection:void 0,l=c??await this.desktopSyncReadSession(s);try{let d=await l.history(n);if(this.assertSyncAccount(i),this.assertSyncReadAdmission(e),d.sessionId!==s.sessionId||d.sessionGenerationId!==s.sessionGenerationId)throw new Tt("INVALID_SYNC_READ_RESPONSE");return{items:d.items.map(u=>this.syncEventForConsumer(u)),nextToken:d.nextToken}}finally{c||await l.close()}}subscribeToEvents(e,r,n,i){w.info("[AppSyncClient] Subscribing to events",{sessionId:e});let o=this.activeSubscriptions.get(e);o&&(this.cleanupSubscriptionState(o),this.activeSubscriptions.delete(e));let s={ws:null,subscriptionId:(0,Qn.v4)(),...i?.onSupervisionEvent?{supervisionSubscriptionId:(0,Qn.v4)(),onSupervisionEvent:i.onSupervisionEvent}:{},sessionId:e,onEvent:r,onError:n,onSubscribed:i?.onSubscribed,onSessionRetired:i?.onSessionRetired,receiveDesktopEvents:i?.receiveDesktopEvents??!1,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,s),this.createSubscription(s),()=>{this.cleanupSubscriptionState(s),this.activeSubscriptions.get(e)===s&&this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=Bt(),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`,o={host:r.host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken);let s=Buffer.from(JSON.stringify(o)).toString("base64"),a=Buffer.from(JSON.stringify({})).toString("base64");return`${i}?header=${s}&payload=${a}`}createSubscription(e){let r=e.setupAbort=new AbortController,n=()=>!e.destroyed&&!r.signal.aborted&&this.activeSubscriptions.get(e.sessionId)===e,i=(async()=>{if(await this.joinSyncSubscriptionClosures(e.sessionId),!n())return;let o=this.getCurrentUserId(),s=await this.getCompanionSyncRoute(r.signal);if(!n())return;if(this.assertSyncAccount(o),s.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(s.protocol==="LEGACY"){this.createLegacySubscription(e);return}let a=await this.getSession(e.sessionId);if(!n())return;if(this.assertSyncAccount(o),!a?.sessionGenerationId||a.userId!==o||!["ACTIVE","PAUSED"].includes(a.status))throw new ve("SYNC_SESSION_UNAVAILABLE");let c=await this.desktopSyncLiveSession({sessionId:e.sessionId,sessionGenerationId:a.sessionGenerationId},l=>{if(n()&&yU(l,!!e.receiveDesktopEvents))return e.onEvent(l)},l=>{n()&&this.handleSubscriptionError(e,l)},r.signal);if(!n()){await c.close();return}e.syncConnection=c,e.syncSessionGenerationId=a.sessionGenerationId,this.rememberSyncRegistration({sessionId:e.sessionId,sessionGenerationId:a.sessionGenerationId}),await c.start(),n()&&this.handleSubscriptionStartAck(e)})().catch(o=>{n()&&this.handleSubscriptionError(e,o instanceof Error?o:new Error("Sync connection failed"))});e.setupPromise=i}createLegacySubscription(e){let{sessionId:r,subscriptionId:n,onEvent:i,onError:o,onSubscribed:s,receiveDesktopEvents:a}=e;try{let c=this.buildRealtimeUrl(),l=new Uc.default(c,["graphql-ws"]),d=new Set([n,...e.supervisionSubscriptionId?[e.supervisionSubscriptionId]:[]]);l.on("open",()=>{w.info("[AppSyncClient] WebSocket connected",{sessionId:r}),l.send(JSON.stringify({type:"connection_init"}))}),l.on("message",u=>{try{let p=JSON.parse(u.toString());switch(p.type){case"connection_ack":this.sendSubscriptionStart(l,e);break;case"start_ack":{d.delete(p.id)&&d.size===0&&this.handleSubscriptionStartAck(e);break}case"data":if(this.resetKeepAliveTimer(e),e.supervisionSubscriptionId&&p.id===e.supervisionSubscriptionId){let f=p.payload?.data?.onSupervisionEventCreated;f?.sessionId===r&&e.onSupervisionEvent?.(f);break}let h=p.payload?.data?.onEventCreated;h&&yU(h,!!a)&&i(h);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let m=p.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(m));break}}catch(p){w.error("[AppSyncClient] Failed to parse message",{error:p})}}),l.on("error",u=>{w.error("[AppSyncClient] WebSocket error",{sessionId:r,error:u.message}),this.handleSubscriptionError(e,u)}),l.on("close",(u,p)=>{w.info("[AppSyncClient] WebSocket closed",{sessionId:r,code:u}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(r)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${u}`))}),e.ws=l,this.resetKeepAliveTimer(e)}catch(c){this.handleSubscriptionError(e,c)}}handleSubscriptionStartAck(e){let{sessionId:r,onSubscribed:n}=e;if(e.destroyed)return;w.info("[AppSyncClient] Subscription started",{sessionId:r});let i=e.reconnectAttempts>0;e.isReconnecting=!1,this.startHeartbeatOutcome(r).then(o=>{if(!(e.destroyed||this.activeSubscriptions.get(r)!==e)){if(o==="retired"){this.notifyRetiredSession(r);return}if(o!=="confirmed"){this.handleSubscriptionError(e,new Error("Subscription established but initial heartbeat was not persisted"));return}e.reconnectAttempts=0,w.info("[AppSyncClient] Session liveness confirmed",{sessionId:r,wasReconnect:i});try{n?.(i)}catch(s){w.warn("[AppSyncClient] onSubscribed callback failed",{sessionId:r,error:s instanceof Error?s.message:String(s)})}}})}sendSubscriptionStart(e,r){let n=Bt(),{sessionId:i,subscriptionId:o}=r,s={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(s.Authorization=this.tokens.idToken);let a=[[o,Ao.onEventCreated]];r.supervisionSubscriptionId&&a.push([r.supervisionSubscriptionId,Ao.onSupervisionEventCreated]);for(let[c,l]of a)e.send(JSON.stringify({id:c,type:"start",payload:{data:JSON.stringify({query:l,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,r){let{sessionId:n,onError:i}=e;if(e.isReconnecting||e.destroyed||this.activeSubscriptions.get(n)!==e)return;e.isReconnecting=!0,e.reconnectAttempts++;try{i?.(r)}catch{}this.stopHeartbeat(n),e.setupAbort?.abort(r),e.syncConnection&&(this.trackSyncClosure(n,e.syncConnection.close()),e.syncConnection=void 0);let o=e.reconnectAttempts<=Kt.urgentMaxAttempts,s;o?s=Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):(s=Kt.persistentDelayMs,e.reconnectAttempts===Kt.urgentMaxAttempts+1&&w.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:n})),w.info("[AppSyncClient] Scheduling reconnect",{sessionId:n,attempt:e.reconnectAttempts,phase:o?"urgent":"persistent",delayMs:s}),e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(n)!==e){w.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:n});return}let a=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(a)==="refreshed"&&w.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:n})}catch{a.aborted||w.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:n})}finally{this.finishReconnectReconciliationWait(e,a)}if(e.destroyed||this.activeSubscriptions.get(n)!==e){w.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:n});return}e.subscriptionId=(0,Qn.v4)(),this.createSubscription(e)},s)}cleanupSubscriptionState(e){e.destroyed=!0,e.setupAbort?.abort(new Error("Subscription closed"));let r=Promise.allSettled([e.setupPromise,e.syncConnection?.close()]).then(()=>{});this.trackSyncClosure(e.sessionId,r),e.syncConnection=void 0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}subscribeToDeviceKeyRegistered(e,r,n,i){w.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let o={userId:e,subscriptionId:(0,Qn.v4)(),ws:null,onNewDevice:r,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;e&&(e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null),this.deviceKeyWatcher=null,w.info("[AppSyncClient] Device key watcher stopped"))}createDeviceKeyWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.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":w.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){w.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:l})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let a=o.payload?.data?.onDeviceKeyRegistered;if(a){w.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:a.deviceId,platform:a.platform});try{e.onNewDevice(a)}catch(l){w.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:l})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let c=o.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(c));break}}catch(o){w.error("[AppSyncClient] Failed to parse device key watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleDeviceKeyWatcherError(e,i)}),n.on("close",i=>{w.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=Bt(),{userId:i,subscriptionId:o}=r,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:Ao.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,r){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(r)}catch{}e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.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){w.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)==="refreshed"&&w.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId})}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,Qn.v4)(),this.createDeviceKeyWatcherConnection(e))},i)}watchForMobileEnd(e,r){w.info("[AppSyncClient] Starting mobile-end watcher",{sessionId:e});let n=this.sessionUpdateWatchers.get(e);n&&(w.info("[AppSyncClient] Replacing existing mobile-end watcher",{sessionId:e}),this.cleanupSessionUpdateWatcherState(n),this.sessionUpdateWatchers.delete(e));let i={sessionId:e,subscriptionId:(0,Qn.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),w.info("[AppSyncClient] Mobile-end watcher stopped",{sessionId:e}))}}}createSessionUpdateWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.info("[AppSyncClient] Mobile-end watcher WebSocket connected",{sessionId:e.sessionId}),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.sendSessionUpdateWatcherStart(n,e);break;case"start_ack":w.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,o.payload);break;case"ka":this.resetSessionUpdateWatcherKeepAlive(e);break;case"error":let s=o.payload?.errors?.[0]?.message||"Unknown error";this.handleSessionUpdateWatcherError(e,new Error(s));break}}catch(o){w.error("[AppSyncClient] Failed to parse mobile-end watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] Mobile-end watcher WebSocket error",{sessionId:e.sessionId,error:i.message}),this.handleSessionUpdateWatcherError(e,i)}),n.on("close",i=>{w.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){w.warn("[AppSyncClient] Mobile-end watcher received malformed payload",{sessionId:e.sessionId});return}if(e.firedOnce)return;let i=n.status;if(i==null){w.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",w.info("[AppSyncClient] Mobile end requested for session",{sessionId:e.sessionId}),Promise.resolve().then(()=>e.onMobileEndRequested()).catch(o=>{w.warn("[AppSyncClient] Mobile-end callback threw",{sessionId:e.sessionId,error:o})});return}e.priorStatus=i}sendSessionUpdateWatcherStart(e,r){let n=Bt(),{sessionId:i,subscriptionId:o}=r,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:Ao.onSessionUpdated,variables:{sessionId:i}}),extensions:{authorization:s}}}))}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;e.isReconnecting=!0,e.reconnectAttempts++,e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.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)return;let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before mobile-end watcher reconnect",{sessionId:e.sessionId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Qn.v4)(),this.createSessionUpdateWatcherConnection(e))},i)}cleanupSessionUpdateWatcherState(e){e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}subscribeToPromptActions(e,r,n,i){let o=this.getCurrentUserId(),s=this.promptActionWatchers.get(e);s&&(this.cleanupPromptActionWatcherState(s),this.promptActionWatchers.delete(e));let a={sessionId:e,userId:o,subscriptionId:(0,Qn.v4)(),ws:null,onActionFence:r,onSubscribed:n,onError:i,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.promptActionWatchers.set(e,a),this.createPromptActionWatcherConnection(a),{stop:()=>{this.promptActionWatchers.get(e)===a&&(this.cleanupPromptActionWatcherState(a),this.promptActionWatchers.delete(e))}}}createPromptActionWatcherConnection(e){try{let r=new Uc.default(this.buildRealtimeUrl(),["graphql-ws"]);r.on("open",()=>r.send(JSON.stringify({type:"connection_init"}))),r.on("message",n=>{try{let i=JSON.parse(n.toString());switch(i.type){case"connection_ack":this.sendPromptActionWatcherStart(r,e);break;case"start_ack":{let o=e.pendingReconnectSignal===!0;e.pendingReconnectSignal=!1,e.isReconnecting=!1,e.reconnectAttempts=0,e.onSubscribed&&Promise.resolve(e.onSubscribed(o)).catch(s=>{this.handlePromptActionWatcherError(e,s instanceof Error?s:new Error(String(s)))});break}case"data":this.resetPromptActionWatcherKeepAlive(e),this.handlePromptActionPayload(e,i.payload);break;case"ka":this.resetPromptActionWatcherKeepAlive(e);break;case"error":this.handlePromptActionWatcherError(e,new Error(i.payload?.errors?.[0]?.message||"Unknown promptAction error"));break}}catch(i){this.handlePromptActionWatcherError(e,i instanceof Error?i:new Error(String(i)))}}),r.on("error",n=>this.handlePromptActionWatcherError(e,n)),r.on("close",n=>{e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.promptActionWatchers.get(e.sessionId)===e&&this.handlePromptActionWatcherError(e,new Error(`WebSocket closed: ${n}`))}),e.ws=r,this.resetPromptActionWatcherKeepAlive(e)}catch(r){this.handlePromptActionWatcherError(e,r instanceof Error?r:new Error(String(r)))}}handlePromptActionPayload(e,r){let n=r?.data?.onPromptStateChanged;if(!n||typeof n!="object"||n.userId!==e.userId||n.sessionId!==e.sessionId||n.family!=="GATE"||n.mobileActionable!==!1||typeof n.promptId!="string"||n.promptId.length===0)return;let i=n.decisionClaimId;if(i!=null&&(typeof i!="string"||i.length===0)){this.handlePromptActionWatcherError(e,new Error("promptAction payload has an invalid decisionClaimId"));return}let o={sessionId:e.sessionId,promptId:n.promptId,decisionClaimId:i??null};Promise.resolve().then(()=>e.onActionFence(o)).catch(s=>{w.warn("[AppSyncClient] promptAction watcher callback threw",{sessionId:e.sessionId,error:s instanceof Error?s.message:String(s)})})}sendPromptActionWatcherStart(e,r){let n=Bt(),i={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(i.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:r.subscriptionId,type:"start",payload:{data:JSON.stringify({query:Ao.onPromptStateChanged,variables:{userId:r.userId}}),extensions:{authorization:i}}}))}resetPromptActionWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handlePromptActionWatcherError(e,new Error("promptAction watcher keep-alive timeout"))},300*1e3)}handlePromptActionWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.promptActionWatchers.get(e.sessionId)!==e)return;e.isReconnecting=!0,e.pendingReconnectSignal=!0,e.reconnectAttempts++,e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);try{e.onError?.(r)}catch{}let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.promptActionWatchers.get(e.sessionId)!==e)return;let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.promptActionWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Qn.v4)(),this.createPromptActionWatcherConnection(e))},i)}cleanupPromptActionWatcherState(e){e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}subscribeToApplyUserDecision(e,r,n){w.info("[AppSyncClient] Starting applyUserDecision watcher",{sessionId:e});let i=this.applyUserDecisionWatchers.get(e);i&&(w.info("[AppSyncClient] Replacing existing applyUserDecision watcher",{sessionId:e}),this.cleanupApplyUserDecisionWatcherState(i),this.applyUserDecisionWatchers.delete(e));let o={sessionId:e,subscriptionId:(0,Qn.v4)(),ws:null,onDecision:r,onError:n,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.applyUserDecisionWatchers.set(e,o),this.createApplyUserDecisionWatcherConnection(o),{stop:()=>{this.applyUserDecisionWatchers.get(e)===o&&(this.cleanupApplyUserDecisionWatcherState(o),this.applyUserDecisionWatchers.delete(e),w.info("[AppSyncClient] applyUserDecision watcher stopped",{sessionId:e}))}}}createApplyUserDecisionWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.info("[AppSyncClient] applyUserDecision watcher WebSocket connected",{sessionId:e.sessionId}),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.sendApplyUserDecisionWatcherStart(n,e);break;case"start_ack":w.info("[AppSyncClient] applyUserDecision watcher subscription started",{sessionId:e.sessionId}),e.isReconnecting=!1,e.reconnectAttempts=0;break;case"data":this.resetApplyUserDecisionWatcherKeepAlive(e),this.handleApplyUserDecisionPayload(e,o.payload);break;case"ka":this.resetApplyUserDecisionWatcherKeepAlive(e);break;case"error":{let s=o.payload?.errors?.[0]?.message||"Unknown error";this.handleApplyUserDecisionWatcherError(e,new Error(s));break}}}catch(o){w.error("[AppSyncClient] Failed to parse applyUserDecision watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] applyUserDecision watcher WebSocket error",{sessionId:e.sessionId,error:i.message}),this.handleApplyUserDecisionWatcherError(e,i)}),n.on("close",i=>{w.info("[AppSyncClient] applyUserDecision watcher WebSocket closed",{sessionId:e.sessionId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.applyUserDecisionWatchers.get(e.sessionId)===e&&this.handleApplyUserDecisionWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=n,this.resetApplyUserDecisionWatcherKeepAlive(e)}catch(r){this.handleApplyUserDecisionWatcherError(e,r)}}handleApplyUserDecisionPayload(e,r){let n=r?.data?.onApplyUserDecision;if(!n||typeof n!="object"){w.warn("[AppSyncClient] applyUserDecision watcher received malformed payload",{sessionId:e.sessionId});return}let i=n.taskId,o=n.gateId,s=n.decision;if(typeof i!="string"||typeof o!="string"){w.warn("[AppSyncClient] applyUserDecision watcher event missing taskId/gateId",{sessionId:e.sessionId});return}let a;try{a=nh(n.payload,"onApplyUserDecision")}catch(d){w.warn("[AppSyncClient] applyUserDecision watcher could not coerce payload",{sessionId:e.sessionId,error:d.message});return}let c=typeof s=="string"?s.toLowerCase():"",l={sessionId:e.sessionId,taskId:i,gateId:o,decision:c,action:a};Promise.resolve().then(()=>e.onDecision(l)).catch(d=>{w.warn("[AppSyncClient] applyUserDecision watcher callback threw",{sessionId:e.sessionId,error:d})})}sendApplyUserDecisionWatcherStart(e,r){let n=Bt(),{sessionId:i,subscriptionId:o}=r,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:Ao.onApplyUserDecision,variables:{sessionId:i}}),extensions:{authorization:s}}}))}resetApplyUserDecisionWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleApplyUserDecisionWatcherError(e,new Error("applyUserDecision watcher keep-alive timeout"))},300*1e3)}handleApplyUserDecisionWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.applyUserDecisionWatchers.get(e.sessionId)!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.onError)try{e.onError(r)}catch{}let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.warn("[AppSyncClient] applyUserDecision 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.applyUserDecisionWatchers.get(e.sessionId)!==e)return;let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before applyUserDecision watcher reconnect",{sessionId:e.sessionId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.applyUserDecisionWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Qn.v4)(),this.createApplyUserDecisionWatcherConnection(e))},i)}cleanupApplyUserDecisionWatcherState(e){e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}startHeartbeat(e,r){let n=Fk(r),i=this.heartbeatInitialPulses.get(e);if(i)return i;let s=this.startHeartbeatOutcome(e,n).then(a=>(a==="retired"&&this.notifyRetiredSession(e),a==="confirmed"));return this.heartbeatInitialPulses.set(e,s),s}startHeartbeatOutcome(e,r){let n=Fk(r),i=this.heartbeatTokens.get(e),o=this.heartbeatTimers.get(e);if(i&&o){let l=this.heartbeatInitialOutcomes.get(e);if(l)return l;let d=this.trackHeartbeatPulse(e,this.sendHeartbeat(e,i));return this.heartbeatInitialOutcomes.set(e,d),d}this.stopHeartbeat(e);let s=Symbol(e);this.heartbeatTokens.set(e,s);let a=this.trackHeartbeatPulse(e,this.sendHeartbeat(e,s));this.heartbeatInitialOutcomes.set(e,a);let c=setInterval(()=>{this.trackHeartbeatPulse(e,this.sendHeartbeat(e,s)).then(l=>{l==="retired"&&this.notifyRetiredSession(e)})},n);return this.heartbeatTimers.set(e,c),w.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:n}),a}stopHeartbeat(e){this.heartbeatTokens.delete(e),this.heartbeatInitialPulses.delete(e),this.heartbeatInitialOutcomes.delete(e);let r=this.heartbeatTimers.get(e);r&&(clearInterval(r),this.heartbeatTimers.delete(e),w.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async invalidateHeartbeat(e){this.stopHeartbeat(e);let r=Array.from(this.heartbeatInFlight.get(e)??[]);r.length>0&&await Promise.all(r);try{return await this.updateSession({sessionId:e,lastHeartbeatAt:new Date(0).toISOString()}),w.info("[AppSyncClient] Heartbeat liveness invalidated",{sessionId:e}),!0}catch(n){return w.warn("[AppSyncClient] Failed to invalidate heartbeat liveness",{sessionId:e,error:n}),!1}}trackHeartbeatPulse(e,r){let n=this.heartbeatInFlight.get(e);return n||(n=new Set,this.heartbeatInFlight.set(e,n)),n.add(r),r.finally(()=>{let i=this.heartbeatInFlight.get(e);i?.delete(r),i?.size===0&&this.heartbeatInFlight.delete(e)}),r}async sendHeartbeat(e,r){if(this.heartbeatTokens.get(e)!==r)return"stopped";try{let n=new Date().toISOString(),i=await this.updateSession({sessionId:e,lastHeartbeatAt:n});return this.heartbeatTokens.get(e)!==r||i.status!=="ACTIVE"&&(await this.updateSession({sessionId:e,lastHeartbeatAt:n,status:"ACTIVE"}),this.heartbeatTokens.get(e)!==r)?"stopped":(w.debug("[AppSyncClient] Heartbeat sent",{sessionId:e}),"confirmed")}catch(n){return w.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:n}),NZ(n)?"retired":"failed"}}notifyRetiredSession(e){let r=this.activeSubscriptions.get(e);!r||r.destroyed||r.retirementNotified||(r.retirementNotified=!0,this.stopHeartbeat(e),this.cleanupSubscriptionState(r),this.activeSubscriptions.get(e)===r&&this.activeSubscriptions.delete(e),Promise.resolve().then(()=>r.onSessionRetired?.()).catch(n=>{w.warn("[AppSyncClient] Retired-session recovery callback failed",{sessionId:e,error:n instanceof Error?n.message:String(n)})}))}cleanupSubscription(e){this.closeCompanionNoticeOwners(e);let r=this.activeSubscriptions.get(e);r&&(this.cleanupSubscriptionState(r),this.activeSubscriptions.get(e)===r&&this.activeSubscriptions.delete(e))}cleanupSubscriptions(){this.syncReadEpoch++,this.closeCompanionNoticeOwners(),this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear();for(let[e,r]of this.syncReadOwners)for(let n of r)this.trackSyncClosure(e,n.close());this.stopDeviceKeyWatcherInternal(),this.sessionUpdateWatchers.forEach(e=>{this.cleanupSessionUpdateWatcherState(e)}),this.sessionUpdateWatchers.clear(),this.applyUserDecisionWatchers.forEach(e=>{this.cleanupApplyUserDecisionWatcherState(e)}),this.applyUserDecisionWatchers.clear(),this.promptActionWatchers.forEach(e=>{this.cleanupPromptActionWatcherState(e)}),this.promptActionWatchers.clear(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear(),this.heartbeatTokens.clear(),this.heartbeatInitialPulses.clear(),this.heartbeatInitialOutcomes.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");w.info("[AppSyncClient] Subscribing to Class B packets",{userId:e});let n={userId:e,onPacket:r.onPacket,onError:r.onError,destroyed:!1};this.classBPacketHandlers.set(e,n),this.classBWatcher&&this.stopClassBWatcherInternal();let i=null;if(this.tokens?.idToken){i={userId:e,subscriptionId:(0,Qn.v4)(),ws:null,onPacket:r.onPacket,onError:r.onError,onReconnect:r.onReconnect,onSubscribed:r.onSubscribed,pendingReconnectSignal:!1,reconnectAttempts:0,isReconnecting:!1,destroyed:!1},this.classBWatcher=i;try{this.createClassBWatcherConnection(i)}catch(o){r.onError?.(o instanceof Error?o:new Error(String(o)))}}else w.info("[AppSyncClient] Class B watcher registered without socket (no idToken)",{userId:e});return{unsubscribe:async()=>{n.destroyed=!0,this.classBPacketHandlers.get(e)===n&&this.classBPacketHandlers.delete(e),i&&this.classBWatcher===i&&this.stopClassBWatcherInternal(),w.info("[AppSyncClient] Unsubscribed Class B packets",{userId:e})}}}stopClassBWatcher(){this.stopClassBWatcherInternal()}stopClassBWatcherInternal(){let e=this.classBWatcher;e&&(e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null),this.classBWatcher=null,w.info("[AppSyncClient] Class B watcher stopped"))}createClassBWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.info("[AppSyncClient] Class B 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.sendClassBWatcherStart(n,e);break;case"start_ack":{w.info("[AppSyncClient] Class B watcher subscription started",{userId:e.userId});let s=e.pendingReconnectSignal===!0;if(e.pendingReconnectSignal=!1,e.isReconnecting=!1,e.reconnectAttempts=0,s&&e.onReconnect)try{e.onReconnect()}catch(a){w.warn("[AppSyncClient] Class B watcher onReconnect handler threw",{error:a})}if(e.onSubscribed)try{e.onSubscribed(s)}catch(a){w.warn("[AppSyncClient] Class B watcher onSubscribed handler threw",{error:a})}break}case"data":{this.resetClassBWatcherKeepAlive(e);let s=o.payload?.data?.onClassBPacket;s&&this.dispatchClassBPacket(e.userId,s);break}case"ka":this.resetClassBWatcherKeepAlive(e);break;case"error":{let s=o.payload?.errors?.[0]?.message||"Unknown error";this.handleClassBWatcherError(e,new Error(s));break}}}catch(o){w.error("[AppSyncClient] Failed to parse Class B watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] Class B watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleClassBWatcherError(e,i)}),n.on("close",i=>{w.info("[AppSyncClient] Class B watcher WebSocket closed",{userId:e.userId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.classBWatcher===e&&this.handleClassBWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=n,this.resetClassBWatcherKeepAlive(e)}catch(r){this.handleClassBWatcherError(e,r)}}sendClassBWatcherStart(e,r){let n=Bt(),{userId:i,subscriptionId:o}=r,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:Ao.onClassBPacket,variables:{userId:i}}),extensions:{authorization:s}}}))}resetClassBWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleClassBWatcherError(e,new Error("Class B watcher keep-alive timeout"))},300*1e3)}handleClassBWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.classBWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.pendingReconnectSignal=!0,e.onError)try{e.onError(r)}catch{}e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.warn("[AppSyncClient] Class B 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.classBWatcher!==e){w.info("[AppSyncClient] Class B watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before Class B watcher reconnect, using existing tokens",{userId:e.userId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.classBWatcher!==e||(e.subscriptionId=(0,Qn.v4)(),this.createClassBWatcherConnection(e))},i)}dispatchClassBPacket(e,r){let n=this.classBPacketHandlers.get(e);if(!(!n||n.destroyed))try{let i=this.parseClassBPacketPayload(r.packetJson),o={sessionId:r.sessionId??"",userId:e,taskId:r.taskId??void 0,packetId:r.packetId??void 0,issuedAt:r.issuedAt??void 0};return Promise.resolve(n.onPacket(i,o))}catch(i){n.onError?.(i instanceof Error?i:new Error(String(i)))}}async _deliverClassBPacketForTests(e,r,n){await this.dispatchClassBPacket(e,{packetJson:r,sessionId:n?.sessionId??"",taskId:n?.taskId,packetId:n?.packetId,issuedAt:n?.issuedAt})}}});function Os(t){return t.source==="MOBILE"&&(t.type==="USER_PROMPT"||t.type==="PROMPT_RESPONSE")&&t.syncLifecycleVersion!==void 0}async function oh(t,e){return(await vU(t,e,"DELIVERED"))?.deliveryStatus!=="EXECUTED"}async function sh(t,e){await vU(t,e,"EXECUTED")}async function vU(t,e,r){let n=Os(e),i=e.sessionGenerationId;if(n&&(e.syncLifecycleVersion!==1||typeof i!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(i)))throw new ve("INVALID_SYNC_INPUT");let o={eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:r},s=e.type,a=n?await t(o,{sessionGenerationId:i,type:s}):await t(o);if(!n)return;let c=Mv(a,{...o,sessionGenerationId:i});if(c.type!==s)throw new ve("INVALID_SYNC_RECEIPT");return c}var kU=D(()=>{"use strict";Yl();Ln()});async function $k(t,e){let r=t.getCurrentUserId(),n=await t.getSubscriptionStatus(e);if(t.getCurrentUserId()!==r)throw new Error("Companion account changed during read; retry");let i=await t.getCompanionSyncState(e);if(t.getCurrentUserId()!==r)throw new Error("Companion account changed during read; retry");if(n.tier!==i.tier)throw new Error("Companion status changed during read; retry");let o=$v(i);if(o[0]==="Companion sync status unavailable")throw new Error("Companion status expired during read; retry");return[`Subscription: ${n.tier} (${n.status})`,...o]}var EU=D(()=>{"use strict";Mp()});async function Uk(t){let e=t.maxBacklogBytes??67108864,r=t.maxRecordBytes??16*1024*1024;if(![e,r].every(o=>Number.isSafeInteger(o)&&o>0))throw Error("SYNC_SOURCE_INVALID_LIMIT");let n=ns.openSync(t.filePath,ns.constants.O_RDONLY|ns.constants.O_NOFOLLOW),i=()=>{if(!t.isCurrent())throw Error("SYNC_SOURCE_STOPPED")};try{let o=ns.fstatSync(n);if(!o.isFile())throw Error("SYNC_SOURCE_NOT_REGULAR");let s=Object.freeze({filePath:t.filePath,fileIdentity:Object.freeze({dev:o.dev,ino:o.ino})}),a=(y,S)=>{let b=Buffer.alloc(S);if(ns.readSync(n,b,0,S,y)!==S)throw Error("SYNC_SOURCE_SHORT_READ");return b},c=(y,S=0)=>{if(y===0)return null;let b=Math.max(S,y-Zo);return{startOffset:b,endOffset:y,sha256:Gk(a(b,y-b))}},l=y=>y===0||a(y-1,1)[0]===10,d=Number.isSafeInteger(t.initialOffset)&&t.initialOffset>=0&&t.initialOffset<=o.size?t.initialOffset:0;i();let u=await t.admission.restore(s,{byteOffset:d,anchor:c(d),discardUntilNewline:!l(d)});if(i(),u===null)return null;if(!Number.isSafeInteger(u.byteOffset)||u.byteOffset<0||u.byteOffset>o.size||typeof u.discardUntilNewline!="boolean")throw Error("SYNC_SOURCE_INVALID_POSITION");if(u.byteOffset===0){if(u.anchor!==null||u.discardUntilNewline)throw Error("SYNC_SOURCE_INVALID_POSITION")}else{let y=u.anchor;if(!y||!Number.isSafeInteger(y.startOffset)||y.startOffset<0||y.endOffset!==u.byteOffset||y.endOffset<=y.startOffset||y.endOffset-y.startOffset>Zo||Gk(a(y.startOffset,y.endOffset-y.startOffset))!==y.sha256||!u.discardUntilNewline&&!l(u.byteOffset))throw Error("SYNC_SOURCE_ANCHOR_CHANGED")}let p={...u,anchor:u.anchor?{...u.anchor}:null},h=async(y,S,b)=>{i();let v=c(y,p.byteOffset);await t.admission.skip({startOffset:p.byteOffset,endOffset:y,anchor:v,reason:S,discardUntilNewline:b},s),i(),p={byteOffset:y,anchor:v,discardUntilNewline:b}};if(o.size-p.byteOffset>e){let y=o.size-e;await h(y,"BACKLOG_LIMIT",!l(y))}let m=p.byteOffset,f=[],g=0;for(;m<o.size;){i();let y=a(m,Math.min(LZ,o.size-m)),S=0;for(;S<y.length;){i();let b=y.indexOf(10,S),v=b<0?y.length:b+1,R=y.subarray(S,v),E=m+v;if(p.discardUntilNewline)await h(E,"PARTIAL_RECORD",b<0);else if(g+R.length>r)f=[],g=0,await h(E,"OVERSIZED_RECORD",b<0);else if(f.push(R),g+=R.length,b>=0){let I=Buffer.concat(f,g),k=I.subarray(0,I.length-1).toString("utf8").replace(/\r$/,""),P=null;if(k.trim())try{P=t.parse(k)}catch{}if(P){let A=p.byteOffset,C={startOffset:Math.max(A,E-Zo),endOffset:E,sha256:Gk(I.subarray(Math.max(0,I.length-Zo)))};await t.admission.admit(P,Object.freeze({...s,startOffset:A,endOffset:E,sha256:Gk(I),anchor:C})),i(),p={byteOffset:E,anchor:C,discardUntilNewline:!1}}else await h(E,k.trim()?"MALFORMED_RECORD":"EMPTY_RECORD",!1);f=[],g=0}S=v}m+=y.length}return{position:p,size:o.size,mtimeMs:o.mtimeMs}}finally{ns.closeSync(n)}}var ns,RU,LZ,Gk,IU=D(()=>{"use strict";ns=F(require("fs")),RU=require("crypto");ck();LZ=64*1024,Gk=t=>(0,RU.createHash)("sha256").update(t).digest("hex")});var AU={};jr(AU,{AppSyncAuthenticationError:()=>Mi,AppSyncClient:()=>xs,AppSyncGraphQLError:()=>Ut,CREDENTIAL_STORAGE_UNAVAILABLE_EXIT_CODE:()=>ny,DEFAULT_HEARTBEAT_INTERVAL_MS:()=>ry,DesktopSyncReadClient:()=>Nc,DurableDesktopSyncWriter:()=>Bc,MAX_HEARTBEAT_INTERVAL_MS:()=>ix,MAX_SYNC_SOURCE_ANCHOR_BYTES:()=>Zo,MIN_HEARTBEAT_INTERVAL_MS:()=>nx,PLAIN_DESKTOP_SYNC_TYPES:()=>Dp,RECOGNIZED_NON_PRODUCTION_ENVIRONMENTS:()=>SU,SyncEventClientError:()=>ve,SyncJournalError:()=>Ge,SyncReadClientError:()=>Tt,acknowledgeMobileInputDelivery:()=>oh,acknowledgeMobileInputExecution:()=>sh,coerceAwsJsonObject:()=>nh,describeStoredAuthFailure:()=>ih,desktopDeferredInputSha256:()=>ad,isPersistedEventResult:()=>Ov,isRecognizedNonProductionEnvironment:()=>ox,mutations:()=>tt,queries:()=>qt,readDesktopSyncFile:()=>Uk,readStandaloneCompanionStatus:()=>$k,requiresSyncInputDeliveryReceipt:()=>Os,resolveHeartbeatIntervalMs:()=>Fk,subscriptions:()=>Ao});var Sn=D(()=>{"use strict";sx();sx();P_();A_();Ln();kU();EU();Tk();mk();ck();IU();Hp()});async function iy(t){let e=null;for(let r=0;r<ch;r++){let n=ah+r;try{let i=await new Promise((o,s)=>{let a=_U.createServer(t),c=d=>{a.removeListener("listening",l),s(d)},l=()=>{a.removeListener("error",c),a.on("error",d=>{w.error("[AuthService] OAuth server post-bind error",{port:n,code:d?.code,message:d?.message})}),o(a)};a.once("error",c),a.once("listening",l),a.listen(n,"localhost")});return w.info(`[AuthService] OAuth server bound on port ${n} (attempt ${r+1}/${ch})`),{server:i,port:n}}catch(i){if(e=i,i?.code==="EADDRINUSE")continue;throw i}}throw Object.assign(new Error(`All ports ${ah}-${ah+ch-1} are in use. Free at least one for OAuth callback or quit a conflicting service (common collisions: Vite, Webpack, Spring Boot, Docker exposed ports). Underlying: ${e?.message??"EADDRINUSE"}`),{code:"EADDRINUSE_ALL"})}var TU,PU,_U,CU,ah,ch,ax,lh,xo,oy=D(()=>{"use strict";TU=F(require("crypto")),PU=F(require("fs")),_U=F(require("http")),CU=require("child_process");Or();Rs();Nn();Ye();T_();zl();ah=8080,ch=20,ax="/callback";lh=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=PU.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,r,n){if(n>=e.length){w.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],o=[...i.fixedArgs,r],s=!1,a=u=>{s||(s=!0,w.debug(`[AuthService] Browser command '${i.cmd}' ${u}; trying next fallback`),this.tryBrowserCommand(e,r,n+1))},c=u=>{s||(s=!0,w.debug(`[AuthService] Browser command '${i.cmd}' ${u}`))},l;try{l=(0,CU.spawn)(i.cmd,o,{detached:!0,stdio:"ignore",env:nt({...process.env})})}catch(u){a(`threw synchronously: ${u?.message||u}`);return}l.on("error",u=>{a(`failed to spawn: ${u?.message||u}`)}),l.on("exit",(u,p)=>{u===0?c("exited successfully"):a(p?`terminated by signal ${p}`:`exited with code ${u}`)}),setTimeout(()=>{c("still running after 3s, assuming success")},3e3).unref(),l.unref()}generateState(){return TU.randomBytes(32).toString("hex")}buildAuthUrl(e,r){let n=Bt(),i=new URLSearchParams({client_id:n.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:r,state:e});return`https://${n.aws.cognitoDomain}/oauth2/authorize?${i.toString()}`}async exchangeCodeForTokens(e,r){let n=Bt(),i=`https://${n.aws.cognitoDomain}/oauth2/token`,o=new URLSearchParams({grant_type:"authorization_code",client_id:n.aws.cognitoClientId,code:e,redirect_uri:r}),s;try{s=await Op(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},"Token exchange")}catch(c){throw await Ai("token_exchange_network_error"),Ro(c,"token_exchange_network_error"),c}if(!s.ok){let c=await s.text(),l=new Error(`Token exchange failed: ${s.status} ${c}`);throw await Ai("token_exchange_failed",{httpStatus:s.status}),Ro(l,"token_exchange_failed"),l}let a=await s.json();return{accessToken:a.access_token,idToken:a.id_token,refreshToken:a.refresh_token,expiresIn:a.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=Bt(),n=`https://${r.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:r.aws.cognitoClientId,refresh_token:e}),o=await Op(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 _e.getTokens(jn());if(e&&!_e.isTokenExpired(e))return e;let r=this.generateState();return new Promise((n,i)=>{let o={},s=null,a=!1,c=!1,l=p=>{p.closeAllConnections?.()},d=p=>{if(a)return;a=!0,s&&(clearTimeout(s),s=null);let h=o.server;h?(l(h),h.close(()=>n(p))):n(p)},u=p=>{if(a)return;a=!0,s&&(clearTimeout(s),s=null);let h=o.server;h?(l(h),h.close(()=>i(p))):i(p)};(async()=>{let p;try{p=await iy(async(f,g)=>{if(c||a){g.writeHead(200,{Connection:"close"}),g.end();return}let S=`http://localhost:${f.socket?.localPort??p.port}${ax}`,b=new URL(f.url||"",S);if(b.pathname!==ax){g.writeHead(404,{Connection:"close"}),g.end("Not found");return}try{let v=b.searchParams.get("code"),R=b.searchParams.get("state"),E=b.searchParams.get("error");if(E){let A=new Error(`OAuth error: ${E}`);throw await Ai("cognito_rejected"),Ro(A,"cognito_rejected"),A}if(R!==r){let A=new Error("State mismatch");throw await Ai("state_mismatch"),Ro(A,"state_mismatch"),A}if(!v){let A=new Error("No authorization code");throw await Ai("no_authorization_code"),Ro(A,"no_authorization_code"),A}c=!0;let I=await this.exchangeCodeForTokens(v,S),k=this.decodeJwt(I.idToken),P={accessToken:I.accessToken,idToken:I.idToken,refreshToken:I.refreshToken,expiresAt:Date.now()+I.expiresIn*1e3,userId:k.sub,email:k.email||"unknown"};try{await _e.setTokens(P,jn())}catch(A){throw await Ai("keychain_write_failed",{errorFragment:A?.message?String(A.message):String(A)}),Ro(A,"keychain_write_failed"),A}g.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),g.end(`
770
+ `)}:t==="refresh_network"?{exitCode:1,message:"Could not reach the CodeVibe sign-in service to refresh your session. Check your network connection and try again; you are still signed in."}:{exitCode:1,message:'Not authenticated. Run "codevibe login" to sign in.'}}function ox(t=process.env){let e=jn(t);return e==="development"||e==="experiment"}function Fk(t,e=process.env){let r;if(t!==void 0?r=t:ox(e)&&e.CODEVIBE_HEARTBEAT_INTERVAL_MS!==void 0&&(r=e.CODEVIBE_HEARTBEAT_INTERVAL_MS),r==null||r==="")return ry;let n=typeof r=="number"?r:Number(r);return!Number.isFinite(n)||!Number.isInteger(n)||n<nx||n>ix?ry:n}var Uc,wU,bU,Qn,Ut,Mi,Kt,ny,ry,nx,ix,SU,xs,sx=D(()=>{"use strict";Uc=F(require("ws")),wU=require("node:crypto"),bU=require("json-freeze"),Qn=require("uuid");Rs();Ye();A_();Nn();Dn();T_();P_();Mp();q$();F_();Tk();Hp();q1();fC();wC();Qg();TC();CC();Dk();KC();Ln();Ea();zC();ty();Ut=class extends Error{constructor(e){super(`GraphQL error: ${e.message}`),this.name="AppSyncGraphQLError",this.responseMessage=e.message,this.errorType=e.errorType,this.extensions=e.extensions,this.path=e.path,this.data=e.data,this.requestId=typeof e.requestId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e.requestId)?e.requestId:void 0}},Mi=class extends Error{constructor(e){super(e==="refresh_network"?"Authentication refresh could not reach the authentication service":"Authentication refresh was rejected"),this.name="AppSyncAuthenticationError",this.kind=e}};Kt={urgentMaxAttempts:10,baseDelayMs:1e3,maxDelayMs:6e4,backoffMultiplier:2,persistentDelayMs:300*1e3};ny=78;ry=12e4,nx=1e3,ix=3e5,SU=new Set(["development","experiment"]);xs=class t{constructor(){this.authenticated=!1;this.currentUserId=null;this.currentEmail=null;this.tokens=null;this.syncDisplayEpoch=0;this.syncDisplaySequence=0;this.syncDisplayAppliedSequence=0;this.syncDisplay=null;this.syncDisplayListeners=new Set;this.syncStateRead=null;this.syncStateRetry=null;this.syncProducerEpoch=0;this.syncProducerRetry=new Map;this.activeSubscriptions=new Map;this.lastAuthFailureKind=null;this.lastAuthFailureDetail=null;this.lastRefreshNetworkError=!1;this.pendingRefresh=null;this.pendingRefreshCredential=null;this.pendingReconnectReconciliation=null;this.reconnectReconciliationWaiters=new WeakMap;this.tokenStateGeneration=0;this.lastRefreshFailureAt=null;this.lastRefreshFailureCredential=null;this.deviceKeyWatcher=null;this.sessionUpdateWatchers=new Map;this.applyUserDecisionWatchers=new Map;this.promptActionWatchers=new Map;this.statusWriteChains=new Map;this.companionNoticeOwners=new Map;this.sessionRetirementRecoveryPasses=new Map;this.syncSubscriptionClosures=new Map;this.syncReadOwners=new Map;this.syncReadEpoch=0;this.syncRetiringSessions=new Set;this.syncRegistrations=new Map;this.heartbeatTimers=new Map;this.heartbeatTokens=new Map;this.heartbeatInitialPulses=new Map;this.heartbeatInitialOutcomes=new Map;this.heartbeatInFlight=new Map;this.classBWatcher=null;this.classBPacketHandlers=new Map;this.environment=jn(),w.info("[AppSyncClient] Initialized",{environment:this.environment})}static{this.REFRESH_BACKOFF_MS=3e4}static{this.COGNITO_REFRESH_TIMEOUT_MS=1e4}static{this.RECONNECT_RECONCILIATION_TIMEOUT_MS=1e4}getCurrentUserId(){if(!this.currentUserId)throw new Error("Not authenticated. Call authenticateWithStoredTokens() first.");return this.currentUserId}getCurrentUserEmail(){return this.currentEmail}getLastAuthFailureKind(){return this.lastAuthFailureKind}getLastAuthFailureDetail(){return this.lastAuthFailureDetail}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,this.lastAuthFailureDetail=null,this.resetSyncProducerAuthority(),this.resetCompanionSyncDisplay();try{let e;try{e=await _e.getTokens(this.environment)}catch(r){return w.error("[AppSyncClient] Could not read stored authentication tokens:",r),this.lastAuthFailureKind="credential_storage_unavailable",this.lastAuthFailureDetail=r instanceof Error?r.message:String(r),!1}if(!e)return w.debug("[AppSyncClient] No stored tokens found"),this.lastAuthFailureKind="no_tokens",!1;if(w.info("[AppSyncClient] Found stored OAuth tokens",{userId:e.userId,email:e.email,expired:_e.isTokenExpired(e)}),_e.isTokenExpired(e)){if(w.info("[AppSyncClient] Tokens expired, attempting refresh..."),!await this.refreshTokens(e))return w.warn("[AppSyncClient] Token refresh failed"),this.lastAuthFailureKind=this.lastRefreshNetworkError?"refresh_network":"refresh_auth_rejected",!1}else this.replaceTokens(e);return this.currentUserId=this.tokens.userId,this.currentEmail=this.tokens.email,this.authenticated=!0,w.info("[AppSyncClient] Authenticated successfully",{userId:this.currentUserId,email:this.currentEmail}),!0}catch(e){w.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}}static abortReason(e){if(e.reason instanceof Error)return e.reason;let r=new Error(e.reason===void 0?"operation aborted":String(e.reason));return r.name="AbortError",r}static throwIfAborted(e){if(e?.aborted)throw t.abortReason(e)}static async waitForSyncStateRetry(e,r){t.throwIfAborted(r),await new Promise((n,i)=>{let o=setTimeout(()=>{r?.removeEventListener("abort",s),n()},e),s=()=>{clearTimeout(o),r?.removeEventListener("abort",s),i(t.abortReason(r))};r?.addEventListener("abort",s,{once:!0}),r?.aborted&&s()})}static async awaitWithinAbsoluteDeadline(e,r,n,i){let o=e-Date.now(),s=new Error(`${r} timed out`);if(o<=0){try{i?.(s)}catch{}throw s}let a;try{let c=n();return await Promise.race([c,new Promise((l,d)=>{a=setTimeout(()=>{try{i?.(s)}catch{}d(s)},o),a.unref?.()})])}finally{a&&clearTimeout(a)}}static awaitSharedFlightForCaller(e,r){return r?(t.throwIfAborted(r),new Promise((n,i)=>{let o=!1,s=c=>{o||(o=!0,r.removeEventListener("abort",a),c())},a=()=>{s(()=>i(t.abortReason(r)))};if(r.addEventListener("abort",a,{once:!0}),r.aborted){a();return}e.then(c=>s(()=>n(c)),c=>s(()=>i(c)))})):e}replaceTokens(e){this.tokens=e,this.tokenStateGeneration+=1}async refreshTokens(e,r,n=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS,i=this.tokenStateGeneration){for(t.throwIfAborted(r);this.pendingRefresh;){if(this.pendingRefreshCredential===e.refreshToken)return t.awaitSharedFlightForCaller(this.pendingRefresh,r);if(await t.awaitSharedFlightForCaller(this.pendingRefresh,r),t.throwIfAborted(r),this.tokens?.refreshToken===e.refreshToken&&!_e.isTokenExpired(this.tokens))return!0;if(Date.now()>=n)return!1}if(this.lastRefreshFailureAt!==null&&this.lastRefreshFailureCredential===e.refreshToken&&Date.now()-this.lastRefreshFailureAt<t.REFRESH_BACKOFF_MS)return!1;let o=this.performRefresh(e,n,i);return this.pendingRefresh=o,this.pendingRefreshCredential=e.refreshToken,o.finally(()=>{this.pendingRefresh===o&&(this.pendingRefresh=null,this.pendingRefreshCredential=null)}).catch(()=>{}),t.awaitSharedFlightForCaller(o,r)}async performRefresh(e,r=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS,n=this.tokenStateGeneration){this.lastRefreshNetworkError=!1;let i=e.refreshToken,o=await this.callCognitoRefresh(e.refreshToken,r);if(o!==null)return this.applyRefreshedTokens(e,o,n,r);let s=null;try{s=await t.awaitWithinAbsoluteDeadline(r,"Cognito refresh storage recovery",()=>_e.getTokens(this.environment))}catch(a){w.warn("[AppSyncClient] Failed to re-read tokens from storage during refresh recovery",{error:a instanceof Error?a.message:String(a)})}if(s&&s.refreshToken&&s.refreshToken!==e.refreshToken){w.info("[AppSyncClient] In-memory refresh token rejected; retrying with storage-backed token (likely out-of-band re-auth)"),i=s.refreshToken,this.lastRefreshNetworkError=!1;let a=await this.callCognitoRefresh(s.refreshToken,r);if(a!==null)return this.applyRefreshedTokens(s,a,n,r)}return this.lastRefreshFailureAt=Date.now(),this.lastRefreshFailureCredential=i,!1}async callCognitoRefresh(e,r=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS){let n=new AbortController;try{let i=Bt(),o=`https://${i.aws.cognitoDomain}/oauth2/token`,s=new URLSearchParams({grant_type:"refresh_token",client_id:i.aws.cognitoClientId,refresh_token:e}),a=await t.awaitWithinAbsoluteDeadline(r,"Cognito token refresh",async()=>{let c=await Op(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString(),signal:n.signal},"Token refresh");if(!c.ok)return{kind:"http-error",status:c.status};let l=await c.json(),d=l;if(typeof l!="object"||l===null||typeof d.access_token!="string"||d.access_token===""||typeof d.id_token!="string"||d.id_token===""||typeof d.expires_in!="number"||!Number.isFinite(d.expires_in)||d.expires_in<=0)throw new Error("Cognito token refresh returned an invalid payload");return{kind:"success",data:l}},c=>n.abort(c));return a.kind==="http-error"?(w.error("[AppSyncClient] Token refresh failed",{status:a.status}),(a.status>=500&&a.status<600||a.status===429)&&(this.lastRefreshNetworkError=!0),null):a.data}catch(i){return w.error("[AppSyncClient] Token refresh error:",i),this.lastRefreshNetworkError=!0,null}}async applyRefreshedTokens(e,r,n=this.tokenStateGeneration,i=Date.now()+t.COGNITO_REFRESH_TIMEOUT_MS){if(Date.now()>=i||this.tokenStateGeneration!==n)return w.warn("[AppSyncClient] Discarding stale token refresh result",{deadlineElapsed:Date.now()>=i,tokenGenerationChanged:this.tokenStateGeneration!==n}),!1;let o={...e,accessToken:r.access_token,idToken:r.id_token,expiresAt:Date.now()+r.expires_in*1e3};return this.replaceTokens(o),this.lastRefreshFailureAt=null,this.lastRefreshFailureCredential=null,w.info("[AppSyncClient] Tokens refreshed in memory",{expiresAt:new Date(o.expiresAt).toISOString(),durableRefreshTokenUnchanged:!0}),!0}reconcileTokensBeforeReconnect(e){t.throwIfAborted(e);let r=this.pendingReconnectReconciliation;if(!r){let n=Date.now()+t.RECONNECT_RECONCILIATION_TIMEOUT_MS,i=this.tokenStateGeneration;r=this.performReconnectTokenReconciliation(n,i),this.pendingReconnectReconciliation=r,r.finally(()=>{this.pendingReconnectReconciliation===r&&(this.pendingReconnectReconciliation=null)}).catch(()=>{})}return t.awaitSharedFlightForCaller(r,e)}async performReconnectTokenReconciliation(e,r){let n=await t.awaitWithinAbsoluteDeadline(e,"AppSync reconnect credential reconciliation",()=>_e.getTokens(this.environment));if(!n)return"missing";if(this.tokenStateGeneration!==r)return"memory_current";let i=this.tokens;if(i&&i.refreshToken===n.refreshToken&&i.expiresAt>=n.expiresAt&&!_e.isTokenExpired(i))return"memory_current";if(_e.isTokenExpired(n)){let o=r;if(!i||i.refreshToken!==n.refreshToken){if(Date.now()>=e||this.tokenStateGeneration!==r)return"memory_current";this.replaceTokens(n),o=this.tokenStateGeneration}return await this.refreshTokens(n,void 0,e,o)?"refreshed":"refresh_failed"}return Date.now()>=e||this.tokenStateGeneration!==r?"memory_current":(this.replaceTokens(n),"loaded")}beginReconnectReconciliationWait(e){this.reconnectReconciliationWaiters.get(e)?.abort(new Error("reconnect reconciliation superseded"));let n=new AbortController;return this.reconnectReconciliationWaiters.set(e,n),n.signal}finishReconnectReconciliationWait(e,r){this.reconnectReconciliationWaiters.get(e)?.signal===r&&this.reconnectReconciliationWaiters.delete(e)}cancelReconnectReconciliationWait(e){let r=this.reconnectReconciliationWaiters.get(e);r&&(this.reconnectReconciliationWaiters.delete(e),r.abort(new Error("WebSocket watcher stopped")))}isAuthenticated(){return this.authenticated}signOut(){this.resetSyncProducerAuthority(),this.authenticated=!1,this.replaceTokens(null),this.currentUserId=null,this.currentEmail=null,this.resetCompanionSyncDisplay(),this.cleanupSubscriptions(),w.info("[AppSyncClient] Signed out")}async graphqlRequest(e,r,n=!1,i,o,s,a){t.throwIfAborted(i),o!==void 0&&this.assertSyncAccount(o);let c=this.currentUserId,l=this.syncDisplayEpoch,d=Bt();if(!this.tokens?.idToken)throw new Error('Not authenticated. Run "codevibe login" first.');let u={"Content-Type":"application/json",Authorization:this.tokens.idToken};a?.();let p=await Op(d.aws.appsyncUrl,{method:"POST",headers:u,body:JSON.stringify({query:e,variables:r}),signal:i},"AppSync GraphQL request");if(o!==void 0&&this.assertSyncAccount(o),p.status===401){if(n)throw new Mi("refresh_auth_rejected");w.info("[AppSyncClient] 401 Unauthorized, refreshing token..."),t.throwIfAborted(i);let m=await this.refreshTokens(this.tokens,i);if(t.throwIfAborted(i),m)return this.graphqlRequest(e,r,!0,i,o,s,a);throw new Mi(this.lastRefreshNetworkError?"refresh_network":"refresh_auth_rejected")}if(!p.ok)throw new Error(`GraphQL request failed: ${p.status}`);let h=s===void 0?await p.json():await this.boundedGraphQLJson(p,s,i);if(o!==void 0&&this.assertSyncAccount(o),h.errors?.length){let m=h.errors[0];throw[et.createEvent,et.updateEventStatus,et.createEventV2,et.updateEventV2,et.recordWorkspaceOutcomeV2,et.reportSecurityPostureV2,qt.listEvents,qt.listSupervisionEvents,qt.getGateResolution,qt.getGateResolutionV2].includes(e)&&c===this.currentUserId&&l===this.syncDisplayEpoch&&["UPDATE_REQUIRED","AUTHORITY_UNAVAILABLE","SYNC_BLOCKED"].includes(m.errorType??"")&&this.resetCompanionSyncDisplay(),new Ut({message:m.message,errorType:m.errorType,extensions:m.extensions,path:m.path,data:m.data,requestId:p.headers?.get("x-amzn-requestid")})}return h}async boundedGraphQLJson(e,r,n){if(!Number.isSafeInteger(r)||r<1||r>8192||!e.body||!/^application\/json(?:\s*;|$)/i.test(e.headers.get("content-type")??""))throw new Tt("INVALID_SYNC_READ_RESPONSE");let i=e.headers.get("content-length");if(i!==null&&(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>r))throw await e.body.cancel(),new Tt("INVALID_SYNC_READ_RESPONSE");let o=e.body.getReader(),s=[],a=0;try{for(;;){t.throwIfAborted(n);let c=await o.read();if(t.throwIfAborted(n),c.done)break;if(a+=c.value.byteLength,a>r)throw new Tt("INVALID_SYNC_READ_RESPONSE");s.push(c.value)}try{return JSON.parse(new TextDecoder("utf8",{fatal:!0}).decode(Buffer.concat(s)))}catch{throw new Tt("INVALID_SYNC_READ_RESPONSE")}}finally{try{await o.cancel()}finally{o.releaseLock()}}}assertSyncAccount(e){if(!this.authenticated||this.currentUserId!==e||this.tokens?.userId!==e)throw new ve("SYNC_ACCOUNT_CHANGED")}async getCompanionSyncState(e){let r=this.getCurrentUserId(),n=this.syncDisplayEpoch,i=()=>{if(this.assertSyncAccount(r),t.throwIfAborted(e),n!==this.syncDisplayEpoch)throw new ve("INVALID_SYNC_STATE")};i();let o=this.syncStateRead;if(!o||o.userId!==r||o.epoch!==n||o.controller.signal.aborted){let a=new AbortController;o={userId:r,epoch:n,controller:a,promise:this.readCompanionSyncState(r,n,a.signal),waiters:0,settled:!1},this.syncStateRead=o;let c=o,l=()=>{c.settled=!0,this.syncStateRead===c&&(this.syncStateRead=null)};c.promise.then(l,l)}let s=o;return s.waiters++,new Promise((a,c)=>{let l=!1,d=p=>{if(!l){l=!0,e?.removeEventListener("abort",u),--s.waiters===0&&!s.settled&&(this.syncStateRead===s&&(this.syncStateRead=null),s.controller.abort(new Error("Sync state read has no callers")));try{if(i(),p!==void 0)throw p;let h=this.companionSyncStatusSnapshot(r);if(!h)throw new ve("INVALID_SYNC_STATE");a(h)}catch(h){c(h)}}},u=()=>d(t.abortReason(e));e?.addEventListener("abort",u,{once:!0}),s.promise.then(()=>d(),p=>d(p)),e?.aborted&&u()})}async readCompanionSyncState(e,r,n){this.assertSyncAccount(e);let i=++this.syncDisplaySequence;try{let o,s=0,a=0;for(;;){this.assertSyncAccount(e),t.throwIfAborted(n);let u=this.syncStateRetry;if(u?.userId===e&&u.epoch===r){let p=u.retryAtMs-Date.now();if(p>1e4-a)throw u.error;p>0&&(a+=p,await t.waitForSyncStateRetry(p,n),this.assertSyncAccount(e),t.throwIfAborted(n))}try{o=await this.graphqlRequest(qt.getCompanionSyncState,{},!1,n,e);break}catch(p){this.assertSyncAccount(e),t.throwIfAborted(n);let h=p instanceof Ut?p.data:void 0,m=h&&typeof h=="object"&&!Array.isArray(h)?h.retryAfterMs:void 0;if(!(p instanceof Ut)||p.errorType!=="HISTORY_RETRY_AFTER"||typeof m!="number"||!Number.isSafeInteger(m)||m<0)throw p;let f=Date.now()+Math.max(1,m);if(!Number.isSafeInteger(f)||(this.syncStateRetry={userId:e,epoch:r,retryAtMs:f,error:p},s>=2))throw p;s++}}this.assertSyncAccount(e),t.throwIfAborted(n),this.syncStateRetry?.userId===e&&this.syncStateRetry.epoch===r&&(this.syncStateRetry=null);let c=Gv(o?.data?.getCompanionSyncState,this.environment),l=this.publishCompanionSyncDisplay(e,c,r,i),d=Date.now();if(!l||!Number.isSafeInteger(d)||l.observedAtEpochMs>d+Ac||l.validUntilEpochMs<=d)throw new ve("INVALID_SYNC_STATE");return l}catch(o){throw this.publishCompanionSyncDisplay(e,null,r,i),o}}async getCompanionSyncRoute(e){let r=this.getCurrentUserId(),n=this.syncDisplayEpoch,i=()=>{if(this.assertSyncAccount(r),t.throwIfAborted(e),n!==this.syncDisplayEpoch)throw new ve("INVALID_SYNC_STATE")};i();let o=this.companionSyncStatusSnapshot(r);if(o)return{protocol:o.protocol};let s=await this.getCompanionSyncState(e);return i(),{protocol:s.protocol}}subscribeCompanionSyncState(e,r){this.assertSyncAccount(e);let n={userId:e,listener:r};return this.syncDisplayListeners.add(n),this.notifyCompanionSyncDisplay(n),()=>{this.syncDisplayListeners.delete(n)}}companionSyncStatusSnapshot(e){let r=this.syncDisplay,n=Date.now();return!this.authenticated||this.currentUserId!==e||this.tokens?.userId!==e||r?.userId!==e||r.state.environment!==this.environment||!Number.isSafeInteger(n)||r.state.observedAtEpochMs>n+Ac||n>=r.state.validUntilEpochMs?null:r.state}async refreshCompanionSyncDisplayOnMaintenance(e,r){this.assertSyncAccount(e),t.throwIfAborted(r),!this.companionSyncStatusSnapshot(e)&&(await this.getCompanionSyncState(r),this.assertSyncAccount(e),t.throwIfAborted(r))}notifyCompanionSyncDisplay(e){let r=this.syncDisplay;try{e.listener(this.authenticated&&this.currentUserId===e.userId&&this.tokens?.userId===e.userId&&r?.userId===e.userId?r.state:null)}catch{w.warn("[AppSyncClient] Companion status display listener failed")}}resetSyncProducerAuthority(){this.syncProducerEpoch++,this.syncProducerRetry.clear()}resetCompanionSyncDisplay(){this.syncDisplayEpoch+=1;let e=this.syncStateRead;this.syncStateRead=null,this.syncStateRetry=null,e?.controller.abort(new Error("Sync routing observation invalidated")),this.syncDisplay=null,this.syncDisplayAppliedSequence=this.syncDisplaySequence;for(let r of this.syncDisplayListeners)this.notifyCompanionSyncDisplay(r)}publishCompanionSyncDisplay(e,r,n,i){if(n!==this.syncDisplayEpoch||!this.authenticated||this.currentUserId!==e||this.tokens?.userId!==e)return null;if(i<this.syncDisplayAppliedSequence)return this.syncDisplay?.userId===e?this.syncDisplay.state:null;if(r&&this.syncDisplay?.userId===e){let o=B$(r,this.syncDisplay.state);if(o==="RETAIN")return this.syncDisplay.state;o==="CONFLICT"&&(r=null)}this.syncDisplayAppliedSequence=Math.max(i,this.syncDisplayAppliedSequence),this.syncDisplay=r?{userId:e,state:r}:null;for(let o of this.syncDisplayListeners)this.notifyCompanionSyncDisplay(o);return r}async reportSecurityPostureIfSelected(e,r,n){let i={sessionId:e.sessionId,sessionGenerationId:e.sessionGenerationId,expectedSessionKeyGen:e.sessionKeyGen??Di,posture:r},o=this.getCurrentUserId();this.assertSyncAccount(o),t.throwIfAborted(n);let s=await this.getCompanionSyncRoute(n);if(this.assertSyncAccount(o),t.throwIfAborted(n),s.protocol==="LEGACY")return null;if(s.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");if(!i.sessionGenerationId)throw new ve("SYNC_SESSION_GENERATION_CHANGED");let a=H$(o,{...i,sessionGenerationId:i.sessionGenerationId}),c=await _e.getDeviceIdentity();if(this.assertSyncAccount(o),t.throwIfAborted(n),!c)throw new ve("SYNC_IDENTITY_UNAVAILABLE");if(this.tokens&&this.tokens.expiresAt<=Date.now()&&await this.refreshTokens(this.tokens,n),this.assertSyncAccount(o),t.throwIfAborted(n),Bt().environment!==this.environment)throw new ve("SYNC_SESSION_UNAVAILABLE");let l=Np("REPORT_SECURITY_POSTURE",a,o,{privateKeyB64:c.privateKey,publicKeyB64:c.publicKey},Date.now()),d=await this.graphqlRequest(et.reportSecurityPostureV2,{input:JSON.stringify(l)},!0,n,o,8192);return this.assertSyncAccount(o),t.throwIfAborted(n),W$(d?.data?.reportSecurityPostureV2,a)}async desktopSyncReadClient(e,r){let n={...e},i=this.getCurrentUserId();this.assertSyncAccount(i),t.throwIfAborted(r);let o=await this.getCompanionSyncRoute(r);if(this.assertSyncAccount(i),t.throwIfAborted(r),o.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");let s=Bt();if(s.environment!==this.environment||!s.aws.syncHttpUrl)throw new ve("SYNC_SESSION_UNAVAILABLE");return new Nc({endpoint:s.aws.syncHttpUrl,userId:i,sessionScope:n,assertAccount:()=>this.assertSyncAccount(i),getSigningKey:async()=>{let a=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),!a)throw new ve("SYNC_IDENTITY_UNAVAILABLE");return{privateKeyB64:a.privateKey,publicKeyB64:a.publicKey}},resolutionQuery:async(a,c)=>{this.assertSyncAccount(i),this.assertSyncReadAdmission(n.sessionId);try{let l=await this.graphqlRequest(qt.getGateResolutionV2,{input:a},!0,c,i,8192);return this.assertSyncAccount(i),this.assertSyncReadAdmission(n.sessionId),t.throwIfAborted(c),l?.data?.getGateResolutionV2}catch(l){throw this.assertSyncAccount(i),t.throwIfAborted(c),l instanceof Ut?Gg({ok:!1,errorCode:l.responseMessage}):l}},getToken:async a=>{if(this.assertSyncAccount(i),this.tokens&&this.tokens.expiresAt<=Date.now()&&await this.refreshTokens(this.tokens,a),this.assertSyncAccount(i),!this.tokens?.accessToken)throw new ve("SYNC_IDENTITY_UNAVAILABLE");return this.tokens.accessToken}})}async desktopSyncReadSession(e,r){let n={sessionId:e.sessionId,sessionGenerationId:e.sessionGenerationId},i=e.root,o=this.getCurrentUserId(),s=this.syncReadEpoch;this.assertSyncReadAdmission(n.sessionId);let a=await this.desktopSyncReadClient(n,r);if(this.assertSyncAccount(o),this.assertSyncReadAdmission(n.sessionId),t.throwIfAborted(r),s!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");let c=this.desktopSyncWriter({root:i,sessionScope:n}).desktopRegistration((l,d)=>a.register(l,d));return this.ownSyncReader({...n,...i!==void 0&&{root:i}},yC(a,c))}async desktopSyncLiveSession(e,r,n,i){let o={sessionId:e.sessionId,sessionGenerationId:e.sessionGenerationId},s=e.root;this.assertSyncReadAdmission(o.sessionId);let a=this.syncReadEpoch,c=this.getCurrentUserId(),l=await this.desktopSyncReadClient(o,i);if(this.assertSyncAccount(c),this.assertSyncReadAdmission(o.sessionId),t.throwIfAborted(i),a!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");let d=Bt();if(!d.aws.syncWebSocketUrl||d.environment!==this.environment||this.environment!=="development"&&this.environment!=="production")throw new ve("SYNC_SESSION_UNAVAILABLE");let u=this.desktopSyncWriter({root:s,sessionScope:o}),p=u.desktopRegistration((m,f)=>l.register(m,f)),h=this.ownSyncReader({...o,...s!==void 0&&{root:s}},yC(l,p));try{return new xk({endpoint:d.aws.syncWebSocketUrl,environment:this.environment,scope:o,wire:l,reader:h,inbound:u.inbound(),assertAccount:()=>this.assertSyncAccount(c),retryExecutionAcknowledgement:async(m,f)=>{this.assertSyncAccount(c),t.throwIfAborted(f);let g=await this.updateEventStatus({eventId:m.eventId,timestamp:m.timestamp,sessionId:o.sessionId,deliveryStatus:"EXECUTED"},{sessionGenerationId:o.sessionGenerationId},f);if(g.deliveryStatus!=="EXECUTED")throw new ve("INVALID_SYNC_RECEIPT");return{...g,deliveryStatus:"EXECUTED"}},onMaintenance:m=>this.refreshCompanionSyncDisplayOnMaintenance(c,m),onUncertain:m=>w.warn("[AppSyncClient] Mobile input outcome uncertain; not replaying terminal input",{sessionId:o.sessionId,count:m}),onEvent:m=>r(this.syncEventForConsumer(m)),onError:n})}catch(m){throw await h.close(),m}}syncEventForConsumer(e){let r;if(e.metadata!==void 0){if(typeof e.metadata!="string")throw new Tt("INVALID_SYNC_READ_RESPONSE");try{r=JSON.parse(e.metadata)}catch{throw new Tt("INVALID_SYNC_READ_RESPONSE")}}return{...e,...e.metadata!==void 0&&{metadata:r}}}async retireDesktopSyncRegistration(e,r){let n=this.getCurrentUserId();if(this.assertSyncAccount(n),!r||r.userId!==n||r.sessionId!==e.sessionId||r.status!=="INACTIVE"||r.sessionGenerationId!==e.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let i=this.desktopSyncWriter({root:e.root,sessionScope:e}),o=await i.removeDesktopRegistration();return await i.removeInbound(),await i.removeDeferredInputs(),await i.removeMobileEchoes(),await i.promptRetention().remove(),this.assertSyncAccount(n),o}desktopSyncWriter(e={}){let r=this.getCurrentUserId();if(this.assertSyncAccount(r),this.environment!=="development"&&this.environment!=="production")throw new ve("INVALID_SYNC_INPUT");return new Bc({userId:r,environment:this.environment,root:e.root,sessionScope:e.sessionScope,assertAccount:()=>this.assertSyncAccount(r),assertDeferredAdmission:()=>{if(this.assertSyncAccount(r),!e.sessionScope)throw new ve("INVALID_SYNC_INPUT");this.assertSyncReadAdmission(e.sessionScope.sessionId)},readPrivateKey:async()=>{let n=await _e.getDeviceIdentity();return this.assertSyncAccount(r),n?.privateKey??null},send:(n,i,o)=>(this.assertSyncAccount(r),this.mutateDesktopSyncEvent(n,i,o)),isQuotaDenial:n=>n instanceof Ut&&n.errorType==="SYNC_QUOTA_EXHAUSTED",omitNewPayload:async n=>{this.assertSyncAccount(r),t.throwIfAborted(n);let i=this.companionSyncStatusSnapshot(r),o=i?.mode==="SHADOW"?i:await this.getCompanionSyncState(n);if(this.assertSyncAccount(r),t.throwIfAborted(n),o.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");return o.usage?.syncState==="PAUSED"}})}toolActivitySyncTransport(e){return Xg({sessionScope:e.sessionScope,writer:this.desktopSyncWriter(e),getEncryptionContext:e.getEncryptionContext})}companionNoticeOwner(e,r){let n=JSON.stringify([e,r??null]),i=this.companionNoticeOwners.get(n);if(!i){let o=this.getCurrentUserId();i={sessionId:e,closed:!1,recovery:new th({recover:s=>(this.assertSyncAccount(o),this.recoverPreparedCompanionEvents({sessionId:e,root:r},s)),onFailure:()=>w.warn("[sync-notice] prepared notice retained for retry",{sessionId:e})})},this.companionNoticeOwners.set(n,i)}return i}closeCompanionNoticeOwners(e){for(let[r,n]of this.companionNoticeOwners)e!==void 0&&n.sessionId!==e||(n.closed=!0,this.trackSyncClosure(n.sessionId,n.recovery.stop()),this.companionNoticeOwners.delete(r))}publishCompanionNotice(e,r,n={}){return!e||!["NOTIFICATION","ASSISTANT_RESPONSE"].includes(e.type)?Promise.reject(new ve("INVALID_SYNC_INPUT")):this.publishCompanionOccurrence(e,r,n).then(i=>i.protocol==="LEGACY"?i.value?"ACCEPTED":"DROPPED":i.result===null?"SETTLED":i.result==="PENDING"?"PENDING":i.result.status)}async publishCompanionEvent(e,r,n={}){let i=await this.publishCompanionOccurrence(e,r,n);if(i.protocol==="LEGACY"){if(i.value===null)return{status:"DROPPED"};let s=i.value?.eventId;if(typeof s!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(s)||s.startsWith("local-throttled"))throw new ve("INVALID_SYNC_RECEIPT");return{status:"ACCEPTED",eventId:s}}let o=i.result;return o===null?{status:"SETTLED"}:o==="PENDING"?{status:"PENDING"}:o.status==="ACCEPTED"?{status:"ACCEPTED",eventId:o.receipt.eventId,receipt:o.receipt}:{status:"OMITTED"}}publishCompanionOccurrence(e,r,n){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Object.keys(e).some(u=>!["sessionId","type","source","content","metadata","timestamp","isEncrypted"].includes(u))||!["USER_PROMPT","ASSISTANT_RESPONSE","REASONING","TOOL_USE"].includes(e.type)&&!(yg(e.type)&&e.type!=="TOOL_ACTIVITY")||e.source!=="DESKTOP"||e.isEncrypted===!0||typeof e.content!="string"||!e.content.length||typeof e.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e.sessionId)||typeof e.timestamp!="string"||!Number.isFinite(Date.parse(e.timestamp)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i=JSON.parse(JSON.stringify(e)),{sessionId:o}=i,{root:s}=n,a=this.getCurrentUserId(),c=this.companionNoticeOwner(o,s),l=()=>{if(n.assertOwner?.(),this.assertSyncAccount(a),this.assertSyncReadAdmission(o),c.closed)throw new ve("SYNC_SESSION_UNAVAILABLE")},d=(async()=>{l();let u=await this.selectCompanionSourceTransport({sessionId:o,root:s});if(l(),u.protocol==="LEGACY"){let f=await this.desktopSyncWriter({root:s}).shellSources();if(l(),f.some(y=>y.sessionId===o&&y.pendingCount>0))throw c.recovery.start(),new ve("SYNC_PRODUCER_FROZEN");let g=await r();return l(),{protocol:"LEGACY",value:g}}this.rememberSyncRegistration({...u.sessionScope,root:s});let p=await u.prepareEvent(i,(0,Qn.v4)());l();let h=u.writer.shellSource(),m=await h.append(p);l(),c.recovery.start();try{let f=await h.deliver(m);return l(),{protocol:"SYNC_V2",result:f}}catch{return l(),w.warn("[sync-notice] delivery pending; original encrypted source retained",{sessionId:o}),{protocol:"SYNC_V2",result:"PENDING"}}})();return this.trackSyncClosure(o,d.then(()=>{},()=>{})),d}async recoverCompanionSyncSources(e,r){let{sessionId:n,root:i}=e;if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n))throw new ve("INVALID_SYNC_INPUT");let o=this.getCurrentUserId();this.assertSyncAccount(o);let s=this.companionNoticeOwner(n,i);await this.recoverSessionRetirementsOnce({root:i},r);let a=await this.recoverPromptResolutions({sessionId:n,root:i},r),c=await this.desktopSyncWriter({root:i}).sourceStreams();this.assertSyncAccount(o);let l=a;for(let d of c){if(d.sessionId!==n||d.pendingCount===0)continue;t.throwIfAborted(r),this.assertSyncAccount(o);let u=this.desktopSyncWriter({root:i,sessionScope:{sessionId:n,sessionGenerationId:d.sessionGenerationId}}).sourceStream({provider:d.provider,streamSha256:d.streamSha256});await u.recover(),l<256&&(l+=await u.drain(256-l,r))}if(this.assertSyncAccount(o),!s.closed){let d=await this.desktopSyncWriter({root:i}).shellSources();this.assertSyncAccount(o),!s.closed&&d.some(u=>u.sessionId===n&&u.pendingCount>0)&&(s.recovery.start(),l+=await this.recoverPreparedCompanionEvents({sessionId:n,root:i},r,d))}return l}async recoverShellSyncSources(e,r){let{sessionId:n,root:i}=e;if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n))throw new ve("INVALID_SYNC_INPUT");let o=this.getCurrentUserId();this.assertSyncAccount(o),await this.recoverSessionRetirementsOnce({root:i},r);let s=await this.recoverPromptResolutions({sessionId:n,root:i},r),a=await this.desktopSyncWriter({root:i}).shellSources();return this.assertSyncAccount(o),s+await this.recoverPreparedCompanionEvents(e,r,a)}async recoverPreparedCompanionEvents(e,r,n){let{sessionId:i,root:o}=e,s=this.getCurrentUserId();this.assertSyncAccount(s),t.throwIfAborted(r);let a=n??await this.desktopSyncWriter({root:o}).shellSources();this.assertSyncAccount(s);let c=0;for(let l of a)l.sessionId!==i||l.pendingCount===0||(t.throwIfAborted(r),this.assertSyncAccount(s),c+=await this.desktopSyncWriter({root:o,sessionScope:{sessionId:i,sessionGenerationId:l.sessionGenerationId}}).shellSource().drain(64,r));return this.assertSyncAccount(s),c}async retireEmptyShellSyncSource(e,r){let n=this.getCurrentUserId();if(this.assertSyncAccount(n),!r||r.userId!==n||r.sessionId!==e.sessionId||r.status!=="INACTIVE"||r.sessionGenerationId!==e.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let i=this.desktopSyncWriter({root:e.root,sessionScope:e});await i.shellSource().recover();let o=await i.removeEmptyShellSource();return this.assertSyncAccount(n),o}async recoverToolActivityWindows(e){let{sessionId:r,root:n,outbox:i,ledger:o}=e,s=this.getCurrentUserId();this.assertSyncAccount(s),await J1({sessionId:r,outbox:i,ledger:o,transportForGeneration:a=>{this.assertSyncAccount(s);let c={sessionId:r,sessionGenerationId:a};return Xg({sessionScope:c,writer:this.desktopSyncWriter({root:n,sessionScope:c}),recoveryOnly:!0,getEncryptionContext:async()=>{throw new ve("SYNC_SESSION_UNAVAILABLE")}})}}),this.assertSyncAccount(s)}async selectToolActivityTransport(e){let{sessionId:r,root:n,legacyTransport:i}=e;if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(r)||i.protocol!==void 0&&i.protocol!=="LEGACY")throw new ve("INVALID_SYNC_INPUT");let o=await this.selectCompanionSourceTransport({sessionId:r,root:n});return o.protocol==="LEGACY"?i:this.toolActivitySyncTransport({root:n,sessionScope:o.sessionScope,getEncryptionContext:o.getEncryptionContext})}async selectCompanionSourceTransport(e){let{sessionId:r,root:n}=e;if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(r))throw new ve("INVALID_SYNC_INPUT");let i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await this.getCompanionSyncRoute();if(this.assertSyncAccount(i),o.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(o.protocol==="LEGACY")return Object.freeze({protocol:"LEGACY"});let s=async()=>{this.assertSyncAccount(i);let d=await this.getSession(r);if(this.assertSyncAccount(i),!d||d.sessionId!==r||d.userId!==i||d.status!=="ACTIVE"||d.isEncrypted!==!0||typeof d.sessionGenerationId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(d.sessionGenerationId))throw new ve("SYNC_SESSION_UNAVAILABLE");return d},a=await s(),c=Object.freeze({sessionId:r,sessionGenerationId:a.sessionGenerationId.toLowerCase()}),l=async()=>{let d=await s();if(d.sessionGenerationId.toLowerCase()!==c.sessionGenerationId)throw new ve("SYNC_SESSION_GENERATION_CHANGED");let u=d.sessionKeyGen??null,p=await _e.getSessionKey(r,d.encryptedKeys??[],u);if(this.assertSyncAccount(i),!p)throw new ve("SYNC_SESSION_KEY_UNAVAILABLE");return{...c,sessionKey:p,sessionKeyGen:u}};return Object.freeze({protocol:"SYNC_V2",sessionScope:c,writer:this.desktopSyncWriter({root:n,sessionScope:c}),getEncryptionContext:l,prepareEvent:async(d,u)=>{if(!d||typeof d!="object"||Array.isArray(d)||Object.keys(d).some(g=>!["sessionId","type","source","content","metadata","timestamp","isEncrypted",...ed].includes(g)))throw new ve("INVALID_SYNC_INPUT");let p=JSON.parse(JSON.stringify(d)),h=td(p);if(!p||p.sessionId!==c.sessionId||p.source!=="DESKTOP"||p.isEncrypted===!0||!["USER_PROMPT","ASSISTANT_RESPONSE","REASONING","TOOL_USE"].includes(p.type)&&!(yg(p.type)&&p.type!=="TOOL_ACTIVITY")&&!h||p.content!==void 0&&p.content!==null&&typeof p.content!="string")throw new ve("INVALID_SYNC_INPUT");let m=await l(),f={...c,clientOperationId:u,type:p.type,timestamp:p.timestamp,expectedSessionKeyGen:m.sessionKeyGen??Di,...h??{},isEncrypted:!0,encryptionVersion:1,content:Xe.encryptContent(p.content??"",m.sessionKey),...(p.metadata!=null||yg(p.type)||h)&&{metadata:{encrypted:Xe.encryptMetadata(p.metadata??{},m.sessionKey)}}};return Mn("CREATE_EVENT",f),f}})}publishCompanionPrompt(e,r,n={}){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Object.keys(e).some(p=>!["sessionId","type","source","content","metadata","timestamp","isEncrypted",...ed].includes(p)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i=JSON.parse(JSON.stringify(e)),o=td(i);if(!o||i.source!=="DESKTOP"||i.isEncrypted===!0||typeof i.content!="string"||!i.content.length||typeof i.timestamp!="string"||!Number.isFinite(Date.parse(i.timestamp)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let{root:s,reRaiseToken:a}=n,c=i.sessionId,l=this.getCurrentUserId(),d=()=>{this.assertSyncAccount(l),this.assertSyncReadAdmission(c)},u=(async()=>{d();let p=await this.selectCompanionSourceTransport({sessionId:c,root:s});if(d(),p.protocol==="LEGACY"){let S=await this.desktopSyncWriter({root:s}).promptPublications();if(d(),S.some(v=>v.sessionId===c&&v.promptId===o.promptId))throw new ve("SYNC_PRODUCER_FROZEN");let b=await r();return d(),b?"RERAISED":"RETRY"}this.rememberSyncRegistration({...p.sessionScope,root:s});let{timestamp:h,isEncrypted:m,...f}=i,g=(0,wU.createHash)("sha256").update((0,bU.canonicalize)(f)).digest("hex"),y=await p.writer.promptPublication(o.promptId).publish(g,S=>p.prepareEvent(i,S),{reRaiseToken:a});return d(),y.status==="OMITTED"?"OMITTED":"RERAISED"})();return this.trackSyncClosure(c,u.then(()=>{},()=>{})),u}resolveCompanionPrompt(e,r={}){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(a=>!["sessionId","promptId","ownerToken","resolutionAt"].includes(a)))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let n={...e},{root:i}=r;if(typeof n.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n.sessionId)||n.resolutionAt!==void 0&&(typeof n.resolutionAt!="string"||!Number.isFinite(Date.parse(n.resolutionAt))))return Promise.reject(new ve("INVALID_SYNC_INPUT"));try{td({type:"NOTIFICATION",promptId:n.promptId,ownerToken:n.ownerToken,producerKind:"PLUGIN_APPROVAL",mobileActionable:!1})}catch(a){return Promise.reject(a)}let o=this.getCurrentUserId(),s=bk(o,{sessionId:n.sessionId,promptId:n.promptId,producerKind:"PLUGIN_APPROVAL",ownerToken:n.ownerToken});return this.resolvePromptByProtocol(s,()=>s,async()=>(await this.createEvent({sessionId:n.sessionId,type:"NOTIFICATION",source:"DESKTOP",resolvedPromptId:n.promptId,ownerToken:n.ownerToken,...n.resolutionAt!==void 0&&{resolutionAt:n.resolutionAt}}))?.promptId===n.promptId,{root:i})}resolveCoreOfferPrompt(e,r,n={}){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Reflect.ownKeys(e).some(s=>typeof s!="string"||!["sessionId","promptId","sessionGenerationId","sessionKeyGen"].includes(s))||Object.values(Object.getOwnPropertyDescriptors(e)).some(s=>!s.enumerable||!("value"in s)||s.value!==void 0&&s.value!==null&&typeof s.value!="string"))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i={...e},o=this.getCurrentUserId();return this.resolvePromptByProtocol({sessionId:i.sessionId,promptId:i.promptId},()=>bk(o,{sessionId:i.sessionId,promptId:i.promptId,producerKind:"CORE_OFFER",sessionGenerationId:i.sessionGenerationId,expectedSessionKeyGen:i.sessionKeyGen??Di}),r,n)}resolvePromptByProtocol(e,r,n,i){let o=this.getCurrentUserId(),s={sessionId:e.sessionId,promptId:e.promptId};if(typeof s.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(s.sessionId)||typeof s.promptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s.promptId))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let a=()=>this.assertSyncAccount(o),c=this.desktopSyncWriter(i),l=(async()=>{let d=await c.promptPublications();a();let u=await c.promptResolutions();a();let p=[...d,...u].some(f=>f.sessionId===s.sessionId&&f.promptId===s.promptId),h=(f,g)=>c.runPromptResolution(f,async(y,S)=>{let b=g??await this.getCompanionSyncRoute();if(await S(),b.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");return this.finishPromptResolution(y,i,S)});if(p)return h(r());let m=await this.getCompanionSyncRoute();if(a(),m.protocol==="LEGACY")return this.resolvePromptPublication(s,async f=>{if(f||(await c.promptResolutions()).some(g=>g.sessionId===s.sessionId&&g.promptId===s.promptId))throw new ve("SYNC_PRODUCER_FROZEN");return a(),n()},i);if(m.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");return h(r(),m)})();return this.trackSyncClosure(s.sessionId,l.then(()=>{},()=>{})),l}finishPromptResolution(e,r,n,i){return this.resolvePromptPublication({sessionId:e.sessionId,promptId:e.promptId},async()=>(await n(),t.throwIfAborted(i),await this.resolveDesktopSyncPrompt(e,i),await n(),!0),{...r,signal:i})}recoverPromptResolutions(e,r){let{sessionId:n,root:i}=e;if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(n))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let o=this.getCurrentUserId(),s=this.desktopSyncWriter({root:i}),a=()=>{this.assertSyncAccount(o),t.throwIfAborted(r)},c=(async()=>{a();let l=(await s.promptResolutions()).filter(h=>h.sessionId===n);if(a(),!l.length)return 0;let d=await this.getCompanionSyncRoute(r);if(a(),d.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");let u=0,p;for(let h of l){a();try{let m=await s.runPromptResolution(h,(f,g)=>this.finishPromptResolution(f,{root:i},g,r),{existingOnly:!0});a(),m&&u++}catch(m){a(),p??={error:m}}}if(p)throw p.error;return u})();return this.trackSyncClosure(n,c.then(()=>{},()=>{})),c}resolvePromptPublication(e,r,n={}){if(!e||typeof e!="object"||Array.isArray(e)||typeof r!="function"||Object.keys(e).some(d=>!["sessionId","promptId"].includes(d))||typeof e.sessionId!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e.sessionId)||typeof e.promptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e.promptId))return Promise.reject(new ve("INVALID_SYNC_INPUT"));let i={...e},{root:o,signal:s}=n,a=this.getCurrentUserId(),c=()=>{this.assertSyncAccount(a),t.throwIfAborted(s)},l=(async()=>{c();let d=(await this.desktopSyncWriter({root:o}).promptPublications()).filter(h=>h.sessionId===i.sessionId&&h.promptId===i.promptId);c();let u=d.map(h=>this.desktopSyncWriter({root:o,sessionScope:h}).promptPublication(i.promptId));for(let h of u)await h.settle(s),c();let p=await r(d.length>0);if(c(),p!==!0)return!1;for(let h of u)await h.close(),c();return!0})();return this.trackSyncClosure(i.sessionId,l.then(()=>{},()=>{})),l}createDesktopSyncEvent(e,r){return this.mutateDesktopSyncEvent("CREATE_EVENT",e,r)}updateDesktopSyncEvent(e,r){return this.mutateDesktopSyncEvent("UPDATE_EVENT",e,r)}async confirmDesktopSyncRetirement(e,r){t.throwIfAborted(r);let n=Ek(e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),t.throwIfAborted(r),!o)throw new ve("SYNC_IDENTITY_UNAVAILABLE");let s=Np("CONFIRM_RETIREMENT",n,i,{privateKeyB64:o.privateKey,publicKeyB64:o.publicKey},Date.now()),a=await this.graphqlRequest(et.confirmSessionRetirementV2,{input:s},!1,r,i);return this.assertSyncAccount(i),t.throwIfAborted(r),zg(a?.data?.confirmSessionRetirementV2,n)}async retireDesktopSyncSources(e,r,n){let{sessionId:i,sessionGenerationId:o,expectedSessionKeyGen:s,root:a}=e,c=this.getCurrentUserId(),l=ld(c,{sessionId:i,sessionGenerationId:o,expectedSessionKeyGen:s});return await this.quiesceDesktopSyncSession(i,r,n),this.desktopSyncWriter({root:a,sessionScope:l}).removeRetiredSources(s,d=>this.confirmDesktopSyncRetirement(d,n))}async quiesceDesktopSyncSession(e,r,n){let i=this.getCurrentUserId();if(typeof r!="function")throw new ve("INVALID_SYNC_INPUT");this.assertSyncAccount(i),t.throwIfAborted(n),this.syncRetiringSessions.add(e),this.cleanupSubscription(e),await r(),this.assertSyncAccount(i),t.throwIfAborted(n),await Promise.all([this.joinSyncSubscriptionClosures(e),...[...this.syncReadOwners.get(e)??[]].map(o=>o.close())]),this.assertSyncAccount(i),t.throwIfAborted(n)}async completeDesktopSyncRetirement(e,r,n,i){let{sessionId:o,root:s}=e,a=this.getCurrentUserId();if(this.assertSyncAccount(a),t.throwIfAborted(i),!r||r.userId!==a||r.sessionId!==o||r.status!=="INACTIVE"||!r.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let c=ld(a,{sessionId:o,sessionGenerationId:r.sessionGenerationId,expectedSessionKeyGen:r.sessionKeyGen??Di}),l=e.toolOutbox?.retirementLocation()??null;await this.quiesceDesktopSyncSession(o,n,i);let d=this.desktopSyncWriter({root:s,sessionScope:c}),u=await d.hasSessionRetirementWork(c.expectedSessionKeyGen)||e.toolOutbox&&await e.toolOutbox.withRetirementSources(c,async()=>!0);return this.assertSyncAccount(a),t.throwIfAborted(i),u?await d.runSessionRetirement(c,l,(p,h)=>this.finishRecordedSessionRetirement(p,{root:s},h,i))??{sourcesRemoved:0,operationsRemoved:0}:{sourcesRemoved:0,operationsRemoved:0}}async recoverSessionRetirements(e={},r){let{root:n}=e,i=this.getCurrentUserId();this.assertSyncAccount(i),t.throwIfAborted(r);let o=await this.desktopSyncWriter({root:n}).sessionRetirements(),s=0,a=0;for(let c of o){this.assertSyncAccount(i),t.throwIfAborted(r);try{let l=this.desktopSyncWriter({root:n,sessionScope:c.input});await this.quiesceDesktopSyncSession(c.input.sessionId,async()=>{},r),await l.runSessionRetirement(c.input,c.toolOutbox,(d,u)=>this.finishRecordedSessionRetirement(d,{root:n},u,r),{existingOnly:!0}),s++}catch(l){this.assertSyncAccount(i),t.throwIfAborted(r),a++,w.warn("[sync-retirement] prior-session cleanup retained for recovery",{code:l instanceof Ge?l.code:"CLEANUP_DEFERRED"})}}return this.assertSyncAccount(i),{completed:s,deferred:a}}async recoverSessionRetirementsOnce(e,r){let n=this.getCurrentUserId(),i=JSON.stringify([n,e.root??null]);this.assertSyncAccount(n),t.throwIfAborted(r);let o=this.sessionRetirementRecoveryPasses.get(i);if(!o){o=this.recoverSessionRetirements(e,r).then(()=>{},a=>{this.assertSyncAccount(n),t.throwIfAborted(r),w.warn("[sync-retirement] startup cleanup inventory unavailable; records retained")}),this.sessionRetirementRecoveryPasses.set(i,o);let s=o;s.catch(()=>{this.sessionRetirementRecoveryPasses.get(i)===s&&this.sessionRetirementRecoveryPasses.delete(i)})}await o,this.assertSyncAccount(n),t.throwIfAborted(r)}async finishRecordedSessionRetirement(e,r,n,i){let{input:o}=e,{root:s}=r,a=this.getCurrentUserId(),c=this.desktopSyncWriter({root:s,sessionScope:o});await n(),t.throwIfAborted(i);let l=await c.removeRetiredSources(o.expectedSessionKeyGen,d=>this.confirmDesktopSyncRetirement(d,i));if(e.toolOutbox){await n();let d=await z1({sessionScope:o,writer:c,outbox:new eh({...e.toolOutbox,logger:w}),expectedSessionKeyGen:o.expectedSessionKeyGen,confirm:u=>this.confirmDesktopSyncRetirement(u,i)});l.sourcesRemoved+=d.windowsRemoved,l.operationsRemoved+=d.operationsRemoved}for(let d of await c.promptResolutions())await n(),this.assertSyncAccount(a),t.throwIfAborted(i),await c.runPromptResolution(d,async(u,p)=>(await p(),await this.resolveDesktopSyncPrompt(u,i),await p(),!0),{existingOnly:!0});return await n(),this.assertSyncAccount(a),t.throwIfAborted(i),l}async resolveDesktopSyncPrompt(e,r){t.throwIfAborted(r);let n=Vp(e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=n;if(n.producerKind==="CORE_OFFER"){let a=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),t.throwIfAborted(r),!a)throw new ve("SYNC_IDENTITY_UNAVAILABLE");o=Np("RESOLVE_PROMPT",n,i,{privateKeyB64:a.privateKey,publicKeyB64:a.publicKey},Date.now())}let s=await this.graphqlRequest(et.resolveOpenPromptV2,{input:o},!1,r,i);return this.assertSyncAccount(i),t.throwIfAborted(r),x1(s?.data?.resolveOpenPromptV2,n)}async updateDesktopSyncEventStatus(e,r){t.throwIfAborted(r);let n=Mn("UPDATE_EVENT_STATUS",e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await _e.getDeviceIdentity();if(this.assertSyncAccount(i),t.throwIfAborted(r),!o)throw new ve("SYNC_IDENTITY_UNAVAILABLE");let s=Np("UPDATE_EVENT_STATUS",n,i,{privateKeyB64:o.privateKey,publicKeyB64:o.publicKey},Date.now()),a=await this.graphqlRequest(et.updateEventStatusV2,{input:s},!1,r,i);return this.assertSyncAccount(i),Mv(a?.data?.updateEventStatusV2,n)}async refreshDesktopSyncPrompt(e,r){if(t.throwIfAborted(r),typeof e!="string"||!/^[A-Za-z0-9_-]{1,256}$/.test(e))throw new ve("INVALID_SYNC_INPUT");let n=this.getCurrentUserId();this.assertSyncAccount(n);let i=await this.graphqlRequest(et.refreshOpenPromptTtlV2,{promptId:e},!1,r,n);return this.assertSyncAccount(n),t.throwIfAborted(r),Lv(i?.data?.refreshOpenPromptTtlV2,e)}async refreshSessionOpenPromptTtl(e,r){let{sessionId:n,root:i}=e,o=[...e.promptIds];if(!o.length)return;let s=this.getCurrentUserId();this.assertSyncAccount(s),this.assertSyncReadAdmission(n);let a=await this.selectCompanionSourceTransport({sessionId:n,root:i});if(this.assertSyncAccount(s),this.assertSyncReadAdmission(n),a.protocol==="LEGACY"){let d=await this.refreshOpenPromptTtl(o);this.assertSyncAccount(s);for(let u of d){if(this.assertSyncReadAdmission(n),await r(u)==="RETRY")throw new Error("SYNC_PROMPT_RERAISE_PENDING");this.assertSyncAccount(s)}return}this.rememberSyncRegistration({...a.sessionScope,root:i});let c=()=>{this.assertSyncAccount(s),this.assertSyncReadAdmission(n)},l=a.writer.promptRetention().run(o,async d=>{c();let u=await this.refreshDesktopSyncPrompt(d);return c(),u},async(d,u)=>{c();let p=await r(d,u);return c(),p});this.trackSyncClosure(n,l.then(()=>{},()=>{})),await l}async mutateDesktopSyncEvent(e,r,n){t.throwIfAborted(n);let i=Mn(e,r),o=this.getCurrentUserId(),s=this.syncProducerEpoch,a=!1,c=()=>{if(this.assertSyncAccount(o),t.throwIfAborted(n),s!==this.syncProducerEpoch)throw new ve("SYNC_ACCOUNT_CHANGED");for(let m of["PRODUCER","ENRICHMENT"]){if(m==="ENRICHMENT"&&e!=="UPDATE_EVENT")continue;let f=this.syncProducerRetry.get(m);if(f?.userId===o&&f.epoch===s&&f.retryAtMs>Date.now())throw a=!0,f.error}};c();let l=await _e.getDeviceIdentity();if(c(),!l)throw new ve("SYNC_IDENTITY_UNAVAILABLE");let d=Np(e,i,o,{privateKeyB64:l.privateKey,publicKeyB64:l.publicKey},Date.now()),u=e==="CREATE_EVENT"?"createEventV2":"updateEventV2",p;try{p=await this.graphqlRequest(et[u],{input:d},!1,n,o,void 0,c)}catch(m){if(this.assertSyncAccount(o),!a&&s===this.syncProducerEpoch&&m instanceof Ut){let f=m.data&&typeof m.data=="object"&&!Array.isArray(m.data)?m.data.retryAfterMs:void 0,g=m.errorType==="PRODUCER_RETRY_AFTER"?"PRODUCER":e==="UPDATE_EVENT"&&m.errorType==="UPDATE_ENRICHMENT_RETRY_AFTER"?"ENRICHMENT":null,y=g??"PRODUCER",S=g!==null&&typeof f=="number"&&Number.isSafeInteger(f)&&f>=0?Math.max(1,f):m.errorType==="CONTROL_BREAKER_CONTENTION"?1e4:null;if(S!==null){let b=Date.now()+S,v=this.syncProducerRetry.get(y);Number.isSafeInteger(b)&&(!v||v.userId!==o||v.epoch!==s||v.retryAtMs<b)&&this.syncProducerRetry.set(y,{userId:o,epoch:s,retryAtMs:b,error:m})}}if(m instanceof Ut&&m.errorType==="SYNC_QUOTA_EXHAUSTED"){let f=this.syncDisplay?.userId===o?this.syncDisplay.state:null;if(f?.usage?.syncState!=="PAUSED"||f.validUntilEpochMs<=Date.now()){try{await this.getCompanionSyncState(n)}catch{}this.assertSyncAccount(o)}}throw m}this.assertSyncAccount(o);let h=N$(p?.data?.[u],i);if(h.refreshSyncState){try{await this.getCompanionSyncState(n)}catch{}this.assertSyncAccount(o)}return h.receipt}async createSession(e){let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},i=(await this.graphqlRequest(et.createSession,{input:r})).data.createSession;return w.info("[AppSyncClient] Session created",{sessionId:i.sessionId,sessionGenerationId:i.sessionGenerationId??null,writerAttestationEligible:i.writerAttestationEligible===!0}),i}async putContextItem(e){if(e.trackId!==void 0&&e.taskId===void 0)throw new Error("putContextItem: trackId requires taskId");if((await this.graphqlRequest(et.putContextItem,{input:e})).data?.putContextItem!==!0)throw new Error("putContextItem: backend did not accept the row")}async recordExecutionEvent(e,r,n={}){if(!e.taskId||!e.sessionId)throw new Error("recordExecutionEvent: taskId and sessionId are required");if(!/^[0-9a-f]{64}$/.test(e.dedupKeyHex))throw new Error("recordExecutionEvent: dedupKeyHex must be 64 lowercase hex chars");if(e.kind==="FLAG_BAD_APPROVAL"&&(!e.flaggedTaskId||!e.flaggedSeqNum||!e.flaggedEntryId))throw new Error("recordExecutionEvent: FLAG_BAD_APPROVAL requires the flaggedTaskId + flaggedSeqNum + flaggedEntryId target locator");let i;try{i=JSON.stringify(e.payload)}catch(c){throw new Error(`recordExecutionEvent: payload is not JSON-serializable: ${c.message}`)}if(i===void 0)throw new Error("recordExecutionEvent: payload must be a JSON value");let o=this.#r(i,e.sessionId,r),s=await this.graphqlRequest(et.recordExecutionEvent,{input:{taskId:e.taskId,sessionId:e.sessionId,kind:e.kind,payload:o,dedupKeyHex:e.dedupKeyHex,...e.flaggedTaskId!==void 0?{flaggedTaskId:e.flaggedTaskId}:{},...e.flaggedSeqNum!==void 0?{flaggedSeqNum:e.flaggedSeqNum}:{},...e.flaggedEntryId!==void 0?{flaggedEntryId:e.flaggedEntryId}:{}}},!1,n.signal),a=nh(s.data?.recordExecutionEvent,"recordExecutionEvent");if(typeof a.errorType=="string"&&typeof a.errorMessage=="string")throw new Ut({message:a.errorMessage,errorType:a.errorType});if(typeof a.entryId!="string"||a.entryId.length===0)throw new Error("recordExecutionEvent: result missing entryId")}async updateSession(e){if(e.status===void 0)return this.doUpdateSession(e);let n=(this.statusWriteChains.get(e.sessionId)??Promise.resolve()).catch(()=>{}).then(()=>this.doUpdateSession(e));return this.statusWriteChains.set(e.sessionId,n.catch(()=>{})),n}async doUpdateSession(e){e.status==="INACTIVE"&&(this.syncRetiringSessions.add(e.sessionId),this.cleanupSubscription(e.sessionId),await Promise.all([this.joinSyncSubscriptionClosures(e.sessionId),...[...this.syncReadOwners.get(e.sessionId)??[]].map(o=>o.close())]));let r={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n=await this.graphqlRequest(et.updateSession,{input:r});w.debug("[AppSyncClient] Session updated",{sessionId:n.data.updateSession.sessionId});let i=n.data.updateSession;if(e.status==="INACTIVE"&&i?.sessionGenerationId){let o=this.syncRegistrations.get(e.sessionId);for(let[s,a]of o??[])a.userId!==i.userId||a.scope.sessionGenerationId!==i.sessionGenerationId||(await this.retireDesktopSyncRegistration(a.scope,i),o.delete(s));o?.size||this.syncRegistrations.delete(e.sessionId)}return e.status==="ACTIVE"&&i.status==="ACTIVE"&&this.syncRetiringSessions.delete(e.sessionId),i}async getSession(e){return(await this.graphqlRequest(qt.getSession,{sessionId:e})).data.getSession}async submitWorkspaceOutcome(e,r={}){let n=K$(e),i=this.getCurrentUserId();this.assertSyncAccount(i);let o=await this.getCompanionSyncRoute();if(this.assertSyncAccount(i),o.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(o.protocol==="LEGACY"){if(r.requiresV2)throw new ve("SYNC_PRODUCER_FROZEN");let a=await this.createEvent(n);return this.assertSyncAccount(i),j$(a,n)}await r.beforeV2?.(),this.assertSyncAccount(i);let s=await this.graphqlRequest(et.recordWorkspaceOutcomeV2,{input:JSON.stringify(n)},!1,void 0,i);return this.assertSyncAccount(i),bg(s?.data?.recordWorkspaceOutcomeV2,n)}async createEvent(e){let r=Date.now();if(e.writerAttestation===void 0&&e.sessionId&&T$(e.sessionId,e.type,r)){let o=P$(e.sessionId);return o&&w.info("[AppSyncClient] client event throttle engaged",{sessionId:e.sessionId,type:e.type,windowCount:o.count,threshold:A$}),{eventId:`local-throttled-${r}-${Math.random().toString(36).slice(2,11)}`,sessionId:e.sessionId,type:e.type,source:e.source,content:e.content,timestamp:e.timestamp??new Date(r).toISOString(),...e.promptId!==void 0?{promptId:e.promptId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{},...e.isEncrypted!==void 0?{isEncrypted:e.isEncrypted}:{}}}let n={...e,metadata:e.metadata?JSON.stringify(e.metadata):void 0,...e.writerOutcomeSubject!==void 0&&{writerOutcomeSubject:JSON.stringify(e.writerOutcomeSubject)},...e.writerCausalPredecessor!==void 0&&{writerCausalPredecessor:JSON.stringify(e.writerCausalPredecessor)}};if(e.writerAttestation!==void 0){let o=Buffer.byteLength(JSON.stringify(n),"utf8"),s=180*1024;if(o>s)throw new Error(`WRITER_EVENT_INPUT_TOO_LARGE: ${o} bytes exceeds ${s}`)}let i=await this.graphqlRequest(et.createEvent,{input:n});return w.debug("[AppSyncClient] Event created",{eventId:i.data.createEvent.eventId,type:i.data.createEvent.type}),i.data.createEvent}async refreshOpenPromptTtl(e){if(e.length===0)return[];let r=100;if(e.length<=r)return(await this.graphqlRequest(et.refreshOpenPromptTtl,{promptIds:e})).data?.refreshOpenPromptTtl??[];let n=[];for(let i=0;i<e.length;i+=r){let o=e.slice(i,i+r),a=(await this.graphqlRequest(et.refreshOpenPromptTtl,{promptIds:o})).data?.refreshOpenPromptTtl??[];a.length>0&&n.push(...a)}return n}async updateEventStatus(e,r,n){let i=r===void 0?void 0:{...r},o=i?.sessionGenerationId;if(o!==void 0&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(o))throw new ve("INVALID_SYNC_INPUT");if(i&&(typeof o!="string"||i.type!==void 0&&!["USER_PROMPT","PROMPT_RESPONSE"].includes(i.type)))throw new ve("INVALID_SYNC_INPUT");let s={...e},a=this.getCurrentUserId();if(this.assertSyncAccount(a),t.throwIfAborted(n),s.deliveryStatus==="EXECUTED"&&i?.type!==void 0)for(let{userId:h,scope:m}of this.syncRegistrations.get(s.sessionId)?.values()??[])h!==a||m.sessionGenerationId!==o||(await this.desktopSyncWriter({root:m.root,sessionScope:m}).inbound().markExecutedLocally({...s,sessionGenerationId:m.sessionGenerationId,source:"MOBILE",type:i.type}),this.assertSyncAccount(a),t.throwIfAborted(n));let c=await this.getCompanionSyncRoute(n);if(this.assertSyncAccount(a),t.throwIfAborted(n),c.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(o!==void 0&&c.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");if(c.protocol==="LEGACY"){let h=await this.graphqlRequest(et.updateEventStatus,{input:s},!1,n,a);return this.assertSyncAccount(a),h.data.updateEventStatus}if(s.deliveryStatus!=="DELIVERED"&&s.deliveryStatus!=="EXECUTED")throw new ve("INVALID_SYNC_INPUT");let l=await this.getSession(s.sessionId);if(this.assertSyncAccount(a),t.throwIfAborted(n),!l||l.sessionId!==s.sessionId||l.userId!==a||l.status!=="ACTIVE"||typeof l.sessionGenerationId!="string")throw new ve("SYNC_SESSION_UNAVAILABLE");let d=[...this.syncRegistrations.get(s.sessionId)?.values()??[]].filter(h=>h.userId===a),u=l.sessionGenerationId.toLowerCase();if(o!==void 0&&u!==o)throw new ve("SYNC_SESSION_GENERATION_CHANGED");if(d.length&&!d.some(h=>h.scope.sessionGenerationId===u))throw new ve("SYNC_SESSION_GENERATION_CHANGED");let p=await this.updateDesktopSyncEventStatus({...s,clientOperationId:(0,Qn.v4)(),deliveryStatus:s.deliveryStatus==="DELIVERED"?"DELIVERED":"EXECUTED",sessionGenerationId:u,expectedSessionKeyGen:l.sessionKeyGen??Di},n);if(this.assertSyncAccount(a),t.throwIfAborted(n),i?.type!==void 0&&p.type!==i.type)throw new ve("INVALID_SYNC_RECEIPT");if(p.deliveryStatus==="EXECUTED")for(let{scope:h}of d)h.sessionGenerationId===p.sessionGenerationId&&await this.desktopSyncWriter({root:h.root,sessionScope:h}).inbound().acknowledgeExecuted(p);return p}async listEvents(e,r,n){let i=await this.getCompanionSyncRoute();if(i.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(i.protocol==="SYNC_V2"){if(n!==void 0&&(!Number.isSafeInteger(n)||n<1||n>100))throw new ve("INVALID_SYNC_INPUT");return(await this.syncHistoryForSession(e)).items.filter(a=>r===void 0||a.source===r).slice(0,n??100)}return(await this.graphqlRequest(qt.listEvents,{sessionId:e,source:r,limit:n})).data.listEvents.items}async listSupervisionEvents(e){let r=await this.getCompanionSyncRoute();if(r.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(r.protocol==="SYNC_V2"){if(e.limit!==void 0&&e.limit!==100)throw new ve("INVALID_SYNC_INPUT");return this.syncHistoryForSession(e.sessionId,e.sessionGenerationId,e.nextToken)}let i=(await this.graphqlRequest(qt.listSupervisionEvents,e)).data?.listSupervisionEvents;if(!i||!Array.isArray(i.items))throw new Error("listSupervisionEvents returned an invalid page");if(i.nextToken!==void 0&&i.nextToken!==null&&typeof i.nextToken!="string")throw new Error("listSupervisionEvents returned an invalid nextToken");return{items:i.items,nextToken:i.nextToken??null}}async listClaimedGatePrompts(e){let r=new Map,n=null,i=0;do{let s=(await this.graphqlRequest(qt.listOpenPrompts,{nextToken:n,limit:200})).data?.listOpenPrompts;if(!s||!Array.isArray(s.items))throw new Error("listOpenPrompts returned an invalid page");for(let a of s.items){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a;if(c.sessionId!==e||c.kind!=="GATE"||c.mobileActionable!==!1||typeof c.promptId!="string"||c.promptId.length===0)continue;let l=c.decisionClaimId;if(l!=null&&(typeof l!="string"||l.length===0))throw new Error("listOpenPrompts returned an invalid decisionClaimId");let d={sessionId:e,promptId:c.promptId,decisionClaimId:l??null},u=r.get(d.promptId);if(u&&u.decisionClaimId!==d.decisionClaimId)throw new Error("listOpenPrompts returned conflicting Gate claims");r.set(d.promptId,d)}if(s.nextToken!==void 0&&s.nextToken!==null&&typeof s.nextToken!="string")throw new Error("listOpenPrompts returned an invalid nextToken");if(n=s.nextToken??null,i++,i>=500&&n!==null)throw new Error("listOpenPrompts pagination exceeded the safety cap")}while(n!==null);return[...r.values()]}async listSessions(e=100){if(!this.currentUserId)throw new Error("Not authenticated");let r=[],n=null;do{let o=(await this.graphqlRequest(qt.listSessions,{userId:this.currentUserId,limit:e,nextToken:n})).data?.listSessions;o?.items&&r.push(...o.items),n=o?.nextToken??null}while(n);return r}async sweepOrphanSessions(e){let r=e.staleThresholdMs??9e5,n=new Set(e.excludeSessionIds??[]),i=Date.now(),o;try{o=await this.listSessions()}catch(a){return w.warn("[AppSyncClient] OrphanSweep: listSessions failed, skipping sweep",{agentType:e.agentType,error:a instanceof Error?a.message:String(a)}),0}let s=0;for(let a of o){if(a.agentType!==e.agentType||a.status!=="ACTIVE"||n.has(a.sessionId))continue;let l=[a.lastHeartbeatAt,a.createdAt,a.updatedAt].map(p=>p?Date.parse(p):Number.NaN).filter(p=>Number.isFinite(p));if(l.length===0)continue;let d=Math.max(...l),u=i-d;if(!(u<r)){w.warn("[AppSyncClient] OrphanSweep: marking stale session INACTIVE",{sessionId:a.sessionId,agentType:a.agentType,lastHeartbeatAt:a.lastHeartbeatAt,createdAt:a.createdAt,updatedAt:a.updatedAt,freshnessAgeMinutes:Math.round(u/6e4)});try{await this.updateSession({sessionId:a.sessionId,status:"INACTIVE"}),s++}catch(p){w.warn("[AppSyncClient] OrphanSweep: updateSession failed, leaving row as-is",{sessionId:a.sessionId,error:p instanceof Error?p.message:String(p)})}}}return s>0&&w.info("[AppSyncClient] OrphanSweep complete",{agentType:e.agentType,swept:s}),s}async listUserDeviceKeys(){return(await this.graphqlRequest(qt.listUserDeviceKeys,{})).data.listUserDeviceKeys||[]}async listServiceDeviceKeys(){return(await this.graphqlRequest(qt.listServiceDeviceKeys,{})).data.listServiceDeviceKeys||[]}async registerDeviceKey(e,r,n,i){let o={deviceId:e,publicKey:r,platform:n,deviceName:i};await this.graphqlRequest(et.registerDeviceKey,{input:o}),w.info("[AppSyncClient] Device key registered",{deviceId:e,platform:n})}async grantSessionKey(e){await this.graphqlRequest(et.grantSessionKey,{input:e}),w.info("[AppSyncClient] Session key granted",{sessionId:e.sessionId,deviceId:e.deviceId})}async getAttachmentDownloadUrl(e){return(await this.graphqlRequest(et.getAttachmentDownloadUrl,{s3Key:e})).data.getAttachmentDownloadUrl}async updateAvailableAgents(e,r=!1){let n=await this.graphqlRequest(et.updateAvailableAgents,{agents:e,replace:r});return w.info("[AppSyncClient] Updated available agents",{agents:e,replace:r}),n.data.updateAvailableAgents}async updateAdapterCapabilities(e){let r=await this.graphqlRequest(et.updateAdapterCapabilities,{capabilities:JSON.stringify(e)});return w.info("[AppSyncClient] Updated adapter capabilities",{recordCount:e.length}),r.data.updateAdapterCapabilities}async updateReviewerPolicy(e){let r=await this.graphqlRequest(et.updateReviewerPolicy,{input:e});return w.info("[AppSyncClient] Updated reviewer policy",{orchestrationEnabledDefault:e.orchestrationEnabledDefault,reviewerSeatCount:e.reviewerSeats?.length}),r.data.updateReviewerPolicy}async getSubscriptionStatus(e){let r=this.getCurrentUserId();this.assertSyncAccount(r);let n=await this.graphqlRequest(qt.getSubscriptionStatus,{},!1,e,r);this.assertSyncAccount(r);let i=n?.data?.getSubscriptionStatus;if(i===null||typeof i!="object"||Array.isArray(i)||!["FREE","PRO","MAX"].includes(i.tier)||!["ACTIVE","EXPIRED","GRACE_PERIOD","BILLING_RETRY"].includes(i.status)||i.expiresAt!==null&&typeof i.expiresAt!="string")throw new Error("Subscription status response is malformed");return{tier:i.status==="EXPIRED"?"FREE":i.tier,status:i.status,expiresAt:i.expiresAt}}async classifyPlannerPrompt(e){return(await this.graphqlRequest(et.classifyPlannerPrompt,{input:e})).data.classifyPlannerPrompt}async pingPlanner(e){return(await this.graphqlRequest(et.pingPlanner,{input:e})).data.pingPlanner}async generatePlannerAdvisory(e){if(!e||typeof e!="object")throw new Error("generatePlannerAdvisory: input object is required");if(!e.sessionId||typeof e.sessionId!="string")throw new Error("generatePlannerAdvisory: sessionId is required");if(!e.prompt||typeof e.prompt!="string")throw new Error("generatePlannerAdvisory: prompt ciphertext is required");if(e.prompt.length>2e5)throw new Error(`generatePlannerAdvisory: prompt ciphertext exceeds 200,000 chars ceiling (${e.prompt.length})`);if(e.images!==void 0){if(!Array.isArray(e.images))throw new Error("generatePlannerAdvisory: images must be an array of string ciphertexts");if(e.images.length>5)throw new Error(`generatePlannerAdvisory: images count exceeds maximum of 5 (got ${e.images.length})`);let n=e.prompt.length;for(let i=0;i<e.images.length;i++){let o=e.images[i];if(typeof o!="string"||o.trim().length===0)throw new Error(`generatePlannerAdvisory: image at index ${i} must be a non-empty string ciphertext`);if(o.length>27e5)throw new Error(`generatePlannerAdvisory: image at index ${i} exceeds ciphertext limit of 2,700,000 chars (got ${o.length})`);n+=o.length}if(n>45e5)throw new Error(`generatePlannerAdvisory: total request ciphertext exceeds 4,500,000 chars ceiling (${n})`)}if(e.maxTokens!==void 0&&(e.maxTokens<1||e.maxTokens>1536))throw new Error(`generatePlannerAdvisory: maxTokens must be between 1 and 1536 (got ${e.maxTokens})`);if(e.temperature!==void 0&&(e.temperature<0||e.temperature>1))throw new Error(`generatePlannerAdvisory: temperature must be between 0 and 1 (got ${e.temperature})`);let r=await this.graphqlRequest(et.generatePlannerAdvisory,{input:e});if(!r?.data?.generatePlannerAdvisory)throw new Error("generatePlannerAdvisory: empty response returned from AppSync");return r.data.generatePlannerAdvisory}async submitGateDecisionV2(e,r){let{promptKind:n,...i}=e,o=await this.graphqlRequest(et.submitGateDecisionV2,{input:{...i,canonicalRequestHash:r}});return tx(o.data?.submitGateDecisionV2)}async submitGroupDecisionV2(e,r){let{promptKind:n,...i}=e,o=await this.graphqlRequest(et.submitGroupDecisionV2,{input:{...i,canonicalRequestHash:r}});return tx(o.data?.submitGroupDecisionV2)}async authorizeGroupTerminalOperation(e){let r=await this.graphqlRequest(et.authorizeGroupTerminalOperation,{input:e});return rh(r.data?.authorizeGroupTerminalOperation,"authorizeGroupTerminalOperation")}async beginGroupPromotion(e){let r=await this.graphqlRequest(et.beginGroupPromotion,{input:e});return rh(r.data?.beginGroupPromotion,"beginGroupPromotion")}async completeGroupPromotion(e){let r=await this.graphqlRequest(et.completeGroupPromotion,{input:e});return rh(r.data?.completeGroupPromotion,"completeGroupPromotion")}async beginGroupRevert(e){let r=await this.graphqlRequest(et.beginGroupRevert,{input:e});return rh(r.data?.beginGroupRevert,"beginGroupRevert")}async completeGroupRevert(e){let r=await this.graphqlRequest(et.completeGroupRevert,{input:e});return rh(r.data?.completeGroupRevert,"completeGroupRevert")}async prepareGroupKeep(e){let r=await this.graphqlRequest(et.prepareGroupKeep,{input:e});return rh(r.data?.prepareGroupKeep,"prepareGroupKeep")}async commitGroupDecisionV2(e){let r=await this.graphqlRequest(et.commitGroupDecisionV2,{input:e});return DZ(r.data?.commitGroupDecisionV2)}async getDecisionAttempt(e){let r=await this.graphqlRequest(qt.getDecisionAttempt,{input:e});return gU(r.data?.getDecisionAttempt)}async getGateResolution(e){let r={...e},n=this.getCurrentUserId(),i=this.syncReadEpoch;this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId);let o=await this.getCompanionSyncRoute();if(this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId),i!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");if(o.protocol==="LEGACY"){let a=await this.graphqlRequest(qt.getGateResolution,{input:{sessionId:r.sessionId,promptId:r.promptId}},!1,void 0,n);if(this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId),i!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");return a.data?.getGateResolution}if(o.protocol!=="SYNC_V2")throw new ve("SYNC_PRODUCER_FROZEN");if(!r.sessionGenerationId)throw new Tt("INVALID_SYNC_READ_INPUT");Fg({...r,sessionGenerationId:r.sessionGenerationId},()=>{throw new Tt("INVALID_SYNC_READ_INPUT")});let s=await this.desktopSyncReadSession({sessionId:r.sessionId,sessionGenerationId:r.sessionGenerationId});try{let a=await s.gateResolution(r.promptId);if(this.assertSyncAccount(n),this.assertSyncReadAdmission(r.sessionId),i!==this.syncReadEpoch)throw new ve("SYNC_SESSION_UNAVAILABLE");return a}finally{await s.close()}}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:Xe.encryptContent(e.notes,r),sessionId:e.sessionId,keyVersion:Pp}}let i=e.decision.toUpperCase(),s=(await this.graphqlRequest(et.applyUserDecision,{input:{gateId:e.gateId,taskId:e.taskId,sessionId:e.sessionId,currentRound:e.currentRound,decision:i,notes:n}})).data?.applyUserDecision;if(!s||typeof s!="object")throw new Error("applyUserDecision: missing envelope on response");let a=nh(s.payload,"applyUserDecision");return{decision:typeof s.decision=="string"?s.decision.toLowerCase():e.decision,postAction:a}}async createTaskGroup(e){if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("createTaskGroup: sessionId is required");if(!Array.isArray(e.workItems)||e.workItems.length<2)throw new Error("createTaskGroup: requires at least 2 workItems (a team is \u22652 tracks)");if(typeof e.groupIdempotencyKey!="string"||e.groupIdempotencyKey.length===0)throw new Error("createTaskGroup: groupIdempotencyKey is required");let n=(await this.graphqlRequest(et.createTaskGroup,{input:e})).data?.createTaskGroup;if(typeof n!="string")throw new Error(`createTaskGroup: expected AWSJSON string result, got ${typeof n}`);let i;try{i=JSON.parse(n)}catch(o){throw new Error(`createTaskGroup: failed to parse AWSJSON result: ${o.message}`)}if(!i||typeof i!="object")throw new Error("createTaskGroup: parsed result is not an object");if(typeof i.accepted!="boolean")throw new Error("createTaskGroup: result missing boolean `accepted`");return i}async submitMergeGateVerdict(e,r={}){if(typeof e.taskGroupId!="string"||e.taskGroupId.length===0)throw new Error("submitMergeGateVerdict: taskGroupId is required");if(typeof e.mergeGateId!="string"||e.mergeGateId.length===0)throw new Error("submitMergeGateVerdict: mergeGateId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitMergeGateVerdict: sessionId is required");if(typeof e.verdictIdempotencyKey!="string"||e.verdictIdempotencyKey.length===0)throw new Error("submitMergeGateVerdict: verdictIdempotencyKey is required");if(!e.classification||typeof e.classification!="object")throw new Error("submitMergeGateVerdict: classification is required");if(typeof e.classification.signatureB64!="string"||e.classification.signatureB64.length===0)throw new Error("submitMergeGateVerdict: classification.signatureB64 is required (sign via signMergeClassification)");if(typeof e.classification.leDeviceId!="string"||e.classification.leDeviceId.length===0)throw new Error("submitMergeGateVerdict: classification.leDeviceId is required");if(!e.detail||typeof e.detail!="object")throw new Error("submitMergeGateVerdict: detail is required");let i=(await this.graphqlRequest(et.submitMergeGateVerdict,{input:e},!1,r.signal)).data?.submitMergeGateVerdict;if(typeof i!="string")throw new Error(`submitMergeGateVerdict: expected AWSJSON string result, got ${typeof i}`);let o;try{o=JSON.parse(i)}catch(s){throw new Error(`submitMergeGateVerdict: failed to parse AWSJSON result: ${s.message}`)}if(!o||typeof o!="object")throw new Error("submitMergeGateVerdict: parsed result is not an object");if(typeof o.outcome!="string")throw new Error("submitMergeGateVerdict: result missing string `outcome`");return o}async submitTrackVerificationOutcome(e){if(typeof e.taskGroupId!="string"||e.taskGroupId.length===0)throw new Error("submitTrackVerificationOutcome: taskGroupId is required");if(typeof e.trackIndex!="number"||!Number.isInteger(e.trackIndex))throw new Error("submitTrackVerificationOutcome: trackIndex must be an integer");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitTrackVerificationOutcome: sessionId is required");if(typeof e.verdictIdempotencyKey!="string"||e.verdictIdempotencyKey.length===0)throw new Error("submitTrackVerificationOutcome: verdictIdempotencyKey is required");let r=["verification_failure","out_of_scope_write","review_integrity_violation","promote_failure","no_change"];if(!r.includes(e.outcome))throw new Error(`submitTrackVerificationOutcome: outcome must be one of ${r.join(" | ")}, got ${String(e.outcome)}`);let i=(await this.graphqlRequest(et.submitTrackVerificationOutcome,{input:e})).data?.submitTrackVerificationOutcome;if(typeof i!="string")throw new Error(`submitTrackVerificationOutcome: expected AWSJSON string result, got ${typeof i}`);let o;try{o=JSON.parse(i)}catch(s){throw new Error(`submitTrackVerificationOutcome: failed to parse AWSJSON result: ${s.message}`)}if(!o||typeof o!="object")throw new Error("submitTrackVerificationOutcome: parsed result is not an object");if(typeof o.trackState!="string")throw new Error("submitTrackVerificationOutcome: result missing string `trackState`");return o}async claimGroupDecision(e,r){if(typeof e.taskGroupId!="string"||e.taskGroupId.length===0)throw new Error("claimGroupDecision: taskGroupId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("claimGroupDecision: sessionId is required");if(e.phase!=="claim"&&e.phase!=="commit")throw new Error('claimGroupDecision: phase must be "claim" | "commit"');if(typeof e.verdictIdempotencyKey!="string"||e.verdictIdempotencyKey.length===0)throw new Error("claimGroupDecision: verdictIdempotencyKey is required");let n=["ACCEPT","ACCEPT_WITH_NOTES","REJECT_WITH_NOTES","REJECT_RESTART","ABORT_TASK"];if(!n.includes(e.decision))throw new Error(`claimGroupDecision: decision must be one of ${n.join(" | ")}, got ${String(e.decision)}`);if(e.phase==="commit"&&(typeof e.claimToken!="string"||e.claimToken.length===0))throw new Error("claimGroupDecision: commit requires the claimToken from the claim phase");let i;if(e.notes!==void 0){if(typeof r!="string"||r.length===0)throw new Error("claimGroupDecision: sessionKeyBase64 is required when notes are supplied");i=Xe.encryptContent(e.notes,r)}let s=(await this.graphqlRequest(et.claimGroupDecision,{input:{...e,...i!==void 0?{notes:i}:{}}})).data?.claimGroupDecision;if(typeof s!="string")throw new Error(`claimGroupDecision: expected AWSJSON string result, got ${typeof s}`);let a;try{a=JSON.parse(s)}catch(c){throw new Error(`claimGroupDecision: failed to parse AWSJSON result: ${c.message}`)}if(!a||typeof a!="object")throw new Error("claimGroupDecision: parsed result is not an object");if(typeof a.phase!="string")throw new Error("claimGroupDecision: result missing string `phase`");if(typeof a.claimToken!="string")throw new Error("claimGroupDecision: result missing string `claimToken`");return a}async startTask(e){if(typeof e.taskId!="string"||e.taskId.length===0)throw new Error("startTask: taskId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("startTask: sessionId is required");if(!e.decision||typeof e.decision!="object")throw new Error("startTask: decision is required");let r={taskId:e.taskId,sessionId:e.sessionId,decision:e.decision};e.availableAgents!==void 0&&(r.availableAgents=e.availableAgents),e.implementorAgent!==void 0&&(r.implementorAgent=e.implementorAgent),e.slotLeaseProtocol!==void 0&&(r.slotLeaseProtocol=e.slotLeaseProtocol);let n=await this.graphqlRequest(et.startTask,{input:r}),i=this.#t(n.data?.startTask,"startTask");if(typeof i.workflowState!="string"||i.workflowState.length===0)throw new Error("startTask: result missing string `workflowState`");return{workflowState:i.workflowState,...Gc(i,"queuePosition"),...Gc(i,"runningTracks"),...Gc(i,"trackBudget")}}async submitImplementorOutput(e,r){if(typeof e.taskId!="string"||e.taskId.length===0)throw new Error("submitImplementorOutput: taskId is required");if(typeof e.gateId!="string"||e.gateId.length===0)throw new Error("submitImplementorOutput: gateId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitImplementorOutput: sessionId is required");let n=this.#r(e.rawOutput,e.sessionId,r),i={input:{taskId:e.taskId,gateId:e.gateId,sessionId:e.sessionId,roundNumber:e.roundNumber,encProposal:n,...e.usage!==void 0?{usage:e.usage}:{},reviewScopeReset:e.reviewScopeReset??!1}},o;try{o=await this.graphqlRequest(et.submitImplementorOutput,i)}catch(s){if(!MZ(s))throw s;if(e.reviewScopeReset===!0)throw w.warn("[AppSyncClient] explicit review-scope reset rejected by old backend schema; failing closed",{gateId:e.gateId,taskId:e.taskId}),s;w.warn("[AppSyncClient] submitImplementorOutput additive fields rejected by backend schema; retrying legacy input",{gateId:e.gateId,taskId:e.taskId,reason:s instanceof Error?s.message:String(s)});let a={input:{taskId:e.taskId,gateId:e.gateId,sessionId:e.sessionId,roundNumber:e.roundNumber,encProposal:n}};o=await this.graphqlRequest(et.submitImplementorOutput,a)}return this.#e(o.data?.submitImplementorOutput,"submitImplementorOutput")}async submitReviewerVerdict(e,r){if(typeof e.gateId!="string"||e.gateId.length===0)throw new Error("submitReviewerVerdict: gateId is required");if(typeof e.sessionId!="string"||e.sessionId.length===0)throw new Error("submitReviewerVerdict: sessionId is required");if(!e.verdict||typeof e.verdict!="object")throw new Error("submitReviewerVerdict: verdict is required");let n=this.#r(JSON.stringify(e.verdict),e.sessionId,r),o=(await this.graphqlRequest(et.submitReviewerVerdict,{input:{gateId:e.gateId,sessionId:e.sessionId,seatId:e.seatId,verdict:n}})).data?.submitReviewerVerdict;if(!o||typeof o!="object")throw new Error("submitReviewerVerdict: missing envelope on response");let s=o.payload;if(typeof s!="string")throw new Error(`submitReviewerVerdict: expected AWSJSON string payload, got ${typeof s}`);try{return JSON.parse(s)}catch(a){throw new Error(`submitReviewerVerdict: failed to parse AWSJSON payload: ${a.message}`)}}async getReviewerPrompt(e,r,n){if(typeof e!="string"||e.length===0)throw new Error("getReviewerPrompt: gateId is required");if(!Number.isInteger(r)||r<0)throw new Error("getReviewerPrompt: seatId must be a non-negative integer");let i=await this.graphqlRequest(qt.getReviewerPrompt,{gateId:e,seatId:r}),o=this.#e(i.data?.getReviewerPrompt,"getReviewerPrompt");if(!o.encPrompt||typeof o.encPrompt.ciphertextB64!="string")throw new Error("getReviewerPrompt: response missing encPrompt.ciphertextB64");let s=Xe.decryptContent(o.encPrompt.ciphertextB64,n);return{gateId:o.gateId,seatId:o.seatId,role:o.role,prompt:s,reviewScope:o.reviewScope}}async getTaskReviewSummary(e,r,n){if(typeof e!="string"||e.length===0)throw new Error("getTaskReviewSummary: taskId is required");if(typeof r!="string"||r.length===0)throw new Error("getTaskReviewSummary: gateId is required");if(typeof n!="string"||n.length===0)throw new Error("getTaskReviewSummary: sessionKeyBase64 is required");let i=await this.graphqlRequest(qt.getTaskReviewSummary,{taskId:e,gateId:r}),s=nh(i.data?.getTaskReviewSummary,"getTaskReviewSummary").summary;if(!s||typeof s!="object"||typeof s.ciphertextB64!="string"||s.ciphertextB64.length===0)throw new Error("getTaskReviewSummary: response missing summary.ciphertextB64");let a=Xe.decryptContent(s.ciphertextB64,n),c;try{c=JSON.parse(a)}catch(l){throw new Error(`getTaskReviewSummary: failed to parse decrypted summary: ${l.message}`)}if(!c||typeof c!="object"||Array.isArray(c))throw new Error("getTaskReviewSummary: decrypted summary is not an object");return c}async getClassBSigningPublicKey(){let e=await this.graphqlRequest(qt.getClassBSigningPublicKey,{}),r=this.#e(e.data?.getClassBSigningPublicKey,"getClassBSigningPublicKey");if(typeof r.publicKeyB64!="string"||typeof r.keyId!="string")throw new Error("getClassBSigningPublicKey: response missing publicKeyB64/keyId");return{publicKeyB64:r.publicKeyB64,keyId:r.keyId}}async getInReviewAssignments(e){if(typeof e!="string"||e.length===0)throw new Error("getInReviewAssignments: taskId is required");let r=await this.graphqlRequest(qt.getInReviewAssignments,{taskId:e}),n=this.#e(r.data?.getInReviewAssignments,"getInReviewAssignments");return Array.isArray(n.assignments)?n.assignments:[]}async getTaskGroupTracks(e){if(typeof e!="string"||e.length===0)throw new Error("getTaskGroupTracks: taskGroupId is required");let r=await this.graphqlRequest(qt.getTaskGroupTracks,{taskGroupId:e}),n=this.#e(r.data?.getTaskGroupTracks,"getTaskGroupTracks");return Array.isArray(n.tracks)?n.tracks:[]}async getInFlightTeamTracks(e){if(typeof e!="string"||e.length===0)throw new Error("getInFlightTeamTracks: sessionId is required");let r=await this.graphqlRequest(qt.getInFlightTeamTracks,{sessionId:e}),n=this.#e(r.data?.getInFlightTeamTracks,"getInFlightTeamTracks");return Array.isArray(n.tracks)?n.tracks:[]}async getTaskGroupStatus(e){if(typeof e!="string"||e.length===0)throw new Error("getTaskGroupStatus: taskGroupId is required");let r=await this.graphqlRequest(qt.getTaskGroupStatus,{taskGroupId:e}),n=this.#e(r.data?.getTaskGroupStatus,"getTaskGroupStatus");return{taskGroupId:typeof n.taskGroupId=="string"?n.taskGroupId:e,status:typeof n.status=="string"?n.status:"unknown",...typeof n.haltReason=="string"?{haltReason:n.haltReason}:{}}}async cancelQueuedWork(e){let r=rx(e,"cancelQueuedWork"),n=await this.graphqlRequest(et.cancelQueuedWork,{input:r}),i=this.#t(n.data?.cancelQueuedWork,"cancelQueuedWork"),o=i.outcome;if(o!=="cancelled"&&o!=="not_queued"&&o!=="partly_running")throw new Error(`cancelQueuedWork: unexpected outcome ${String(o)}`);return{outcome:o,...typeof i.reason=="string"?{reason:i.reason}:{}}}async releaseSessionWork(e,r={}){if(typeof e!="string"||e.length===0)throw new Error("releaseSessionWork: sessionId is required");let n=await this.graphqlRequest(et.releaseSessionWork,{input:{sessionId:e}},!1,r.signal),i=this.#t(n.data?.releaseSessionWork,"releaseSessionWork");return{haltedGroups:typeof i.haltedGroups=="number"?i.haltedGroups:0,endedTasks:typeof i.endedTasks=="number"?i.endedTasks:0}}async setTaskOrdinal(e){if(!Number.isInteger(e.ordinal)||e.ordinal<1||e.ordinal>9999)throw new Error("setTaskOrdinal: ordinal must be an integer 1-9999");let r=rx(e,"setTaskOrdinal"),n=await this.graphqlRequest(et.setTaskOrdinal,{input:{...r,ordinal:e.ordinal}}),i=this.#t(n.data?.setTaskOrdinal,"setTaskOrdinal");if(typeof i.ordinal!="number")throw new Error("setTaskOrdinal: result missing number `ordinal`");return{ordinal:i.ordinal}}async getTrackBudgetStatus(e){if(typeof e!="string"||e.length===0)throw new Error("getTrackBudgetStatus: sessionId is required");let r=await this.graphqlRequest(qt.getTrackBudgetStatus,{sessionId:e}),n=this.#t(r.data?.getTrackBudgetStatus,"getTrackBudgetStatus"),i=a=>typeof a=="number"&&Number.isFinite(a)&&a>=0?a:0,o=Array.isArray(n.holders)?n.holders:[],s=Array.isArray(n.ended)?n.ended:[];return{running:i(n.running),queued:i(n.queued),budget:i(n.budget),holders:o.flatMap(a=>{if(!a||typeof a!="object")return[];let c=a;return c.kind!=="task"&&c.kind!=="track"||c.state!=="queued"&&c.state!=="running"?[]:[{kind:c.kind,state:c.state,sameSession:c.sameSession===!0,...typeof c.taskId=="string"?{taskId:c.taskId}:{},...typeof c.taskGroupId=="string"?{taskGroupId:c.taskGroupId}:{},...Gc(c,"trackIndex"),...Gc(c,"queuePosition"),...Gc(c,"ordinal")}]}),ended:s.flatMap(a=>{if(!a||typeof a!="object")return[];let c=a;return c.kind!=="task"&&c.kind!=="track"||c.state!=="done"&&c.state!=="cancelled"?[]:[{kind:c.kind,state:c.state,...typeof c.taskId=="string"?{taskId:c.taskId}:{},...typeof c.taskGroupId=="string"?{taskGroupId:c.taskGroupId}:{},...Gc(c,"trackIndex"),...typeof c.endReason=="string"?{endReason:c.endReason}:{},...typeof c.taskEnded=="string"?{taskEnded:c.taskEnded}:{},...Gc(c,"endedAt")}]})}}async openApplyRetryOffer(e){let r=rx(e,"openApplyRetryOffer");for(let o of["sessionTask","external","writeErrors"]){let s=e.counts?.[o];if(!Number.isInteger(s)||s<0)throw new Error(`openApplyRetryOffer: counts.${o} must be a non-negative integer`)}let n=await this.graphqlRequest(et.openApplyRetryOffer,{input:{...r,counts:{sessionTask:e.counts.sessionTask,external:e.counts.external,writeErrors:e.counts.writeErrors}}}),i=this.#t(n.data?.openApplyRetryOffer,"openApplyRetryOffer");if(typeof i.gateId!="string"||typeof i.taskId!="string"||typeof i.sessionId!="string")throw new Error("openApplyRetryOffer: result missing gateId/taskId/sessionId");return{gateId:i.gateId,taskId:i.taskId,sessionId:i.sessionId}}async resolveApplyRetryOffer(e){if(typeof e.gateId!="string"||e.gateId.length===0)throw new Error("resolveApplyRetryOffer: gateId is required");if(e.choice!=="RETRY_AS_NEW_TASK"&&e.choice!=="DISCARD")throw new Error("resolveApplyRetryOffer: choice must be RETRY_AS_NEW_TASK | DISCARD");let r=await this.graphqlRequest(et.resolveApplyRetryOffer,{input:{gateId:e.gateId,choice:e.choice}}),n=this.#t(r.data?.resolveApplyRetryOffer,"resolveApplyRetryOffer");if(typeof n.gateId!="string"||typeof n.taskId!="string"||typeof n.sessionId!="string"||n.choice!=="RETRY_AS_NEW_TASK"&&n.choice!=="DISCARD")throw new Error("resolveApplyRetryOffer: unexpected result shape");return{gateId:n.gateId,taskId:n.taskId,sessionId:n.sessionId,choice:n.choice}}#t(e,r){let n=this.#e(e,r);if(typeof n.errorType=="string"&&typeof n.errorMessage=="string")throw new Ut({message:n.errorMessage,errorType:n.errorType});return n}#r(e,r,n){if(typeof n!="string"||n.length===0)throw new Error("encryptForSession: sessionKeyBase64 is required");return{ciphertextB64:Xe.encryptContent(e,n),sessionId:r,keyVersion:Pp}}#e(e,r){if(typeof e!="string")throw new Error(`${r}: expected AWSJSON string result, got ${typeof e}`);let n;try{n=JSON.parse(e)}catch(i){throw new Error(`${r}: failed to parse AWSJSON result: ${i.message}`)}if(!n||typeof n!="object")throw new Error(`${r}: parsed result is not an object`);return n}async recordContinuationPacketWritten(e){try{let n=(await this.graphqlRequest(et.recordContinuationPacketWritten,{input:e})).data?.recordContinuationPacketWritten;if(!n||typeof n!="object")return{kind:"error",reason:"missing envelope on recordContinuationPacketWritten response"};let i=n.auditEventId,o=n.alreadyExists;return typeof i!="string"||typeof o!="boolean"?{kind:"error",reason:"malformed recordContinuationPacketWritten response"}:{kind:"ok",auditEventId:i,alreadyExists:o}}catch(r){return r instanceof Ut?{kind:"error",reason:r.message}:{kind:"error",reason:r.message??String(r)}}}async verifyContinuationPacketWritten(e){try{let n=(await this.graphqlRequest(qt.verifyContinuationPacketWritten,{taskId:e.taskId,offerId:e.offerId,packetHash:e.packetHash})).data?.verifyContinuationPacketWritten;return typeof n!="boolean"?{kind:"error",reason:"malformed verifyContinuationPacketWritten response"}:{kind:"ok",exists:n}}catch(r){return r instanceof Ut?{kind:"error",reason:r.message}:{kind:"error",reason:r.message??String(r)}}}async queryAudit(e){let n=(await this.graphqlRequest(qt.queryAudit,{input:{taskId:e.taskId,sessionId:e.sessionId}})).data?.queryAudit,i=null;if(typeof n=="string")try{i=JSON.parse(n)}catch{i=null}else n&&typeof n=="object"&&(i=n);if(!i||typeof i!="object")return{rows:[]};let o=i.entries??i.rows;if(!Array.isArray(o))return{rows:[]};let s=o.filter(a=>!!a&&typeof a=="object");return e.kind!==void 0&&(s=s.filter(a=>a.kind===e.kind||a.kindWire===e.kind)),{rows:s}}assertSyncReadAdmission(e){if(this.syncRetiringSessions.has(e))throw new ve("SYNC_SESSION_UNAVAILABLE")}rememberSyncRegistration(e){let r=this.getCurrentUserId(),n=this.syncRegistrations.get(e.sessionId)??new Map;n.set(JSON.stringify([r,e.sessionGenerationId,e.root??null]),{userId:r,scope:{...e}}),this.syncRegistrations.set(e.sessionId,n)}ownSyncReader(e,r){this.rememberSyncRegistration(e);let n=this.syncReadOwners.get(e.sessionId)??new Set;this.syncReadOwners.set(e.sessionId,n);let i,o=Object.freeze({...r,close:()=>i||(i=r.close().finally(()=>{n.delete(o),!n.size&&this.syncReadOwners.get(e.sessionId)===n&&this.syncReadOwners.delete(e.sessionId)}),i)});return n.add(o),o}trackSyncClosure(e,r){let n=this.syncSubscriptionClosures.get(e)??new Set;this.syncSubscriptionClosures.set(e,n),n.add(r),r.finally(()=>{n.delete(r),!n.size&&this.syncSubscriptionClosures.get(e)===n&&this.syncSubscriptionClosures.delete(e)}).catch(()=>{})}async joinSyncSubscriptionClosures(e){let r=this.syncSubscriptionClosures.get(e);r&&await Promise.all([...r])}async syncHistoryForSession(e,r,n){this.assertSyncReadAdmission(e);let i=this.getCurrentUserId(),o=await this.getSession(e);if(this.assertSyncAccount(i),this.assertSyncReadAdmission(e),o?.sessionId!==e||!o.sessionGenerationId||o.userId!==i||r!==void 0&&r!==o.sessionGenerationId)throw new ve("SYNC_SESSION_UNAVAILABLE");let s={sessionId:e,sessionGenerationId:o.sessionGenerationId},a=this.activeSubscriptions.get(e),c=!a?.destroyed&&a?.syncSessionGenerationId===s.sessionGenerationId?a.syncConnection:void 0,l=c??await this.desktopSyncReadSession(s);try{let d=await l.history(n);if(this.assertSyncAccount(i),this.assertSyncReadAdmission(e),d.sessionId!==s.sessionId||d.sessionGenerationId!==s.sessionGenerationId)throw new Tt("INVALID_SYNC_READ_RESPONSE");return{items:d.items.map(u=>this.syncEventForConsumer(u)),nextToken:d.nextToken}}finally{c||await l.close()}}subscribeToEvents(e,r,n,i){w.info("[AppSyncClient] Subscribing to events",{sessionId:e});let o=this.activeSubscriptions.get(e);o&&(this.cleanupSubscriptionState(o),this.activeSubscriptions.delete(e));let s={ws:null,subscriptionId:(0,Qn.v4)(),...i?.onSupervisionEvent?{supervisionSubscriptionId:(0,Qn.v4)(),onSupervisionEvent:i.onSupervisionEvent}:{},sessionId:e,onEvent:r,onError:n,onSubscribed:i?.onSubscribed,onSessionRetired:i?.onSessionRetired,receiveDesktopEvents:i?.receiveDesktopEvents??!1,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.activeSubscriptions.set(e,s),this.createSubscription(s),()=>{this.cleanupSubscriptionState(s),this.activeSubscriptions.get(e)===s&&this.activeSubscriptions.delete(e)}}buildRealtimeUrl(){let e=Bt(),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`,o={host:r.host};this.tokens?.idToken&&(o.Authorization=this.tokens.idToken);let s=Buffer.from(JSON.stringify(o)).toString("base64"),a=Buffer.from(JSON.stringify({})).toString("base64");return`${i}?header=${s}&payload=${a}`}createSubscription(e){let r=e.setupAbort=new AbortController,n=()=>!e.destroyed&&!r.signal.aborted&&this.activeSubscriptions.get(e.sessionId)===e,i=(async()=>{if(await this.joinSyncSubscriptionClosures(e.sessionId),!n())return;let o=this.getCurrentUserId(),s=await this.getCompanionSyncRoute(r.signal);if(!n())return;if(this.assertSyncAccount(o),s.protocol==="FROZEN")throw new ve("SYNC_PRODUCER_FROZEN");if(s.protocol==="LEGACY"){this.createLegacySubscription(e);return}let a=await this.getSession(e.sessionId);if(!n())return;if(this.assertSyncAccount(o),!a?.sessionGenerationId||a.userId!==o||!["ACTIVE","PAUSED"].includes(a.status))throw new ve("SYNC_SESSION_UNAVAILABLE");let c=await this.desktopSyncLiveSession({sessionId:e.sessionId,sessionGenerationId:a.sessionGenerationId},l=>{if(n()&&yU(l,!!e.receiveDesktopEvents))return e.onEvent(l)},l=>{n()&&this.handleSubscriptionError(e,l)},r.signal);if(!n()){await c.close();return}e.syncConnection=c,e.syncSessionGenerationId=a.sessionGenerationId,this.rememberSyncRegistration({sessionId:e.sessionId,sessionGenerationId:a.sessionGenerationId}),await c.start(),n()&&this.handleSubscriptionStartAck(e)})().catch(o=>{n()&&this.handleSubscriptionError(e,o instanceof Error?o:new Error("Sync connection failed"))});e.setupPromise=i}createLegacySubscription(e){let{sessionId:r,subscriptionId:n,onEvent:i,onError:o,onSubscribed:s,receiveDesktopEvents:a}=e;try{let c=this.buildRealtimeUrl(),l=new Uc.default(c,["graphql-ws"]),d=new Set([n,...e.supervisionSubscriptionId?[e.supervisionSubscriptionId]:[]]);l.on("open",()=>{w.info("[AppSyncClient] WebSocket connected",{sessionId:r}),l.send(JSON.stringify({type:"connection_init"}))}),l.on("message",u=>{try{let p=JSON.parse(u.toString());switch(p.type){case"connection_ack":this.sendSubscriptionStart(l,e);break;case"start_ack":{d.delete(p.id)&&d.size===0&&this.handleSubscriptionStartAck(e);break}case"data":if(this.resetKeepAliveTimer(e),e.supervisionSubscriptionId&&p.id===e.supervisionSubscriptionId){let f=p.payload?.data?.onSupervisionEventCreated;f?.sessionId===r&&e.onSupervisionEvent?.(f);break}let h=p.payload?.data?.onEventCreated;h&&yU(h,!!a)&&i(h);break;case"ka":this.resetKeepAliveTimer(e);break;case"error":let m=p.payload?.errors?.[0]?.message||"Unknown error";this.handleSubscriptionError(e,new Error(m));break}}catch(p){w.error("[AppSyncClient] Failed to parse message",{error:p})}}),l.on("error",u=>{w.error("[AppSyncClient] WebSocket error",{sessionId:r,error:u.message}),this.handleSubscriptionError(e,u)}),l.on("close",(u,p)=>{w.info("[AppSyncClient] WebSocket closed",{sessionId:r,code:u}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.activeSubscriptions.get(r)===e&&this.handleSubscriptionError(e,new Error(`WebSocket closed: ${u}`))}),e.ws=l,this.resetKeepAliveTimer(e)}catch(c){this.handleSubscriptionError(e,c)}}handleSubscriptionStartAck(e){let{sessionId:r,onSubscribed:n}=e;if(e.destroyed)return;w.info("[AppSyncClient] Subscription started",{sessionId:r});let i=e.reconnectAttempts>0;e.isReconnecting=!1,this.startHeartbeatOutcome(r).then(o=>{if(!(e.destroyed||this.activeSubscriptions.get(r)!==e)){if(o==="retired"){this.notifyRetiredSession(r);return}if(o!=="confirmed"){this.handleSubscriptionError(e,new Error("Subscription established but initial heartbeat was not persisted"));return}e.reconnectAttempts=0,w.info("[AppSyncClient] Session liveness confirmed",{sessionId:r,wasReconnect:i});try{n?.(i)}catch(s){w.warn("[AppSyncClient] onSubscribed callback failed",{sessionId:r,error:s instanceof Error?s.message:String(s)})}}})}sendSubscriptionStart(e,r){let n=Bt(),{sessionId:i,subscriptionId:o}=r,s={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(s.Authorization=this.tokens.idToken);let a=[[o,Ao.onEventCreated]];r.supervisionSubscriptionId&&a.push([r.supervisionSubscriptionId,Ao.onSupervisionEventCreated]);for(let[c,l]of a)e.send(JSON.stringify({id:c,type:"start",payload:{data:JSON.stringify({query:l,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,r){let{sessionId:n,onError:i}=e;if(e.isReconnecting||e.destroyed||this.activeSubscriptions.get(n)!==e)return;e.isReconnecting=!0,e.reconnectAttempts++;try{i?.(r)}catch{}this.stopHeartbeat(n),e.setupAbort?.abort(r),e.syncConnection&&(this.trackSyncClosure(n,e.syncConnection.close()),e.syncConnection=void 0);let o=e.reconnectAttempts<=Kt.urgentMaxAttempts,s;o?s=Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):(s=Kt.persistentDelayMs,e.reconnectAttempts===Kt.urgentMaxAttempts+1&&w.info("[AppSyncClient] Switching to persistent reconnect (every 5min)",{sessionId:n})),w.info("[AppSyncClient] Scheduling reconnect",{sessionId:n,attempt:e.reconnectAttempts,phase:o?"urgent":"persistent",delayMs:s}),e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.activeSubscriptions.get(n)!==e){w.info("[AppSyncClient] Reconnect skipped \u2014 state is no longer canonical",{sessionId:n});return}let a=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(a)==="refreshed"&&w.info("[AppSyncClient] Tokens refreshed before reconnect",{sessionId:n})}catch{a.aborted||w.warn("[AppSyncClient] Token refresh failed before reconnect, using existing tokens",{sessionId:n})}finally{this.finishReconnectReconciliationWait(e,a)}if(e.destroyed||this.activeSubscriptions.get(n)!==e){w.info("[AppSyncClient] Reconnect skipped after token refresh \u2014 state no longer canonical",{sessionId:n});return}e.subscriptionId=(0,Qn.v4)(),this.createSubscription(e)},s)}cleanupSubscriptionState(e){e.destroyed=!0,e.setupAbort?.abort(new Error("Subscription closed"));let r=Promise.allSettled([e.setupPromise,e.syncConnection?.close()]).then(()=>{});this.trackSyncClosure(e.sessionId,r),e.syncConnection=void 0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}subscribeToDeviceKeyRegistered(e,r,n,i){w.info("[AppSyncClient] Subscribing to device key registrations",{userId:e}),this.deviceKeyWatcher&&this.stopDeviceKeyWatcherInternal();let o={userId:e,subscriptionId:(0,Qn.v4)(),ws:null,onNewDevice:r,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;e&&(e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null),this.deviceKeyWatcher=null,w.info("[AppSyncClient] Device key watcher stopped"))}createDeviceKeyWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.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":w.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){w.warn("[AppSyncClient] Device key watcher onReconnect handler threw",{error:l})}break;case"data":this.resetDeviceKeyWatcherKeepAlive(e);let a=o.payload?.data?.onDeviceKeyRegistered;if(a){w.info("[AppSyncClient] Device key registration observed",{userId:e.userId,newDeviceId:a.deviceId,platform:a.platform});try{e.onNewDevice(a)}catch(l){w.warn("[AppSyncClient] Device key watcher onNewDevice handler threw",{error:l})}}break;case"ka":this.resetDeviceKeyWatcherKeepAlive(e);break;case"error":let c=o.payload?.errors?.[0]?.message||"Unknown error";this.handleDeviceKeyWatcherError(e,new Error(c));break}}catch(o){w.error("[AppSyncClient] Failed to parse device key watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] Device key watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleDeviceKeyWatcherError(e,i)}),n.on("close",i=>{w.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=Bt(),{userId:i,subscriptionId:o}=r,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:Ao.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,r){if(e.isReconnecting||e.destroyed||this.deviceKeyWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.onError)try{e.onError(r)}catch{}e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.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){w.info("[AppSyncClient] Device key watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)==="refreshed"&&w.info("[AppSyncClient] Tokens refreshed before device key watcher reconnect",{userId:e.userId})}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before device key watcher reconnect, using existing tokens",{userId:e.userId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.deviceKeyWatcher!==e||(e.subscriptionId=(0,Qn.v4)(),this.createDeviceKeyWatcherConnection(e))},i)}watchForMobileEnd(e,r){w.info("[AppSyncClient] Starting mobile-end watcher",{sessionId:e});let n=this.sessionUpdateWatchers.get(e);n&&(w.info("[AppSyncClient] Replacing existing mobile-end watcher",{sessionId:e}),this.cleanupSessionUpdateWatcherState(n),this.sessionUpdateWatchers.delete(e));let i={sessionId:e,subscriptionId:(0,Qn.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),w.info("[AppSyncClient] Mobile-end watcher stopped",{sessionId:e}))}}}createSessionUpdateWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.info("[AppSyncClient] Mobile-end watcher WebSocket connected",{sessionId:e.sessionId}),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.sendSessionUpdateWatcherStart(n,e);break;case"start_ack":w.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,o.payload);break;case"ka":this.resetSessionUpdateWatcherKeepAlive(e);break;case"error":let s=o.payload?.errors?.[0]?.message||"Unknown error";this.handleSessionUpdateWatcherError(e,new Error(s));break}}catch(o){w.error("[AppSyncClient] Failed to parse mobile-end watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] Mobile-end watcher WebSocket error",{sessionId:e.sessionId,error:i.message}),this.handleSessionUpdateWatcherError(e,i)}),n.on("close",i=>{w.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){w.warn("[AppSyncClient] Mobile-end watcher received malformed payload",{sessionId:e.sessionId});return}if(e.firedOnce)return;let i=n.status;if(i==null){w.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",w.info("[AppSyncClient] Mobile end requested for session",{sessionId:e.sessionId}),Promise.resolve().then(()=>e.onMobileEndRequested()).catch(o=>{w.warn("[AppSyncClient] Mobile-end callback threw",{sessionId:e.sessionId,error:o})});return}e.priorStatus=i}sendSessionUpdateWatcherStart(e,r){let n=Bt(),{sessionId:i,subscriptionId:o}=r,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:Ao.onSessionUpdated,variables:{sessionId:i}}),extensions:{authorization:s}}}))}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;e.isReconnecting=!0,e.reconnectAttempts++,e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.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)return;let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before mobile-end watcher reconnect",{sessionId:e.sessionId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.sessionUpdateWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Qn.v4)(),this.createSessionUpdateWatcherConnection(e))},i)}cleanupSessionUpdateWatcherState(e){e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}subscribeToPromptActions(e,r,n,i){let o=this.getCurrentUserId(),s=this.promptActionWatchers.get(e);s&&(this.cleanupPromptActionWatcherState(s),this.promptActionWatchers.delete(e));let a={sessionId:e,userId:o,subscriptionId:(0,Qn.v4)(),ws:null,onActionFence:r,onSubscribed:n,onError:i,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.promptActionWatchers.set(e,a),this.createPromptActionWatcherConnection(a),{stop:()=>{this.promptActionWatchers.get(e)===a&&(this.cleanupPromptActionWatcherState(a),this.promptActionWatchers.delete(e))}}}createPromptActionWatcherConnection(e){try{let r=new Uc.default(this.buildRealtimeUrl(),["graphql-ws"]);r.on("open",()=>r.send(JSON.stringify({type:"connection_init"}))),r.on("message",n=>{try{let i=JSON.parse(n.toString());switch(i.type){case"connection_ack":this.sendPromptActionWatcherStart(r,e);break;case"start_ack":{let o=e.pendingReconnectSignal===!0;e.pendingReconnectSignal=!1,e.isReconnecting=!1,e.reconnectAttempts=0,e.onSubscribed&&Promise.resolve(e.onSubscribed(o)).catch(s=>{this.handlePromptActionWatcherError(e,s instanceof Error?s:new Error(String(s)))});break}case"data":this.resetPromptActionWatcherKeepAlive(e),this.handlePromptActionPayload(e,i.payload);break;case"ka":this.resetPromptActionWatcherKeepAlive(e);break;case"error":this.handlePromptActionWatcherError(e,new Error(i.payload?.errors?.[0]?.message||"Unknown promptAction error"));break}}catch(i){this.handlePromptActionWatcherError(e,i instanceof Error?i:new Error(String(i)))}}),r.on("error",n=>this.handlePromptActionWatcherError(e,n)),r.on("close",n=>{e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.promptActionWatchers.get(e.sessionId)===e&&this.handlePromptActionWatcherError(e,new Error(`WebSocket closed: ${n}`))}),e.ws=r,this.resetPromptActionWatcherKeepAlive(e)}catch(r){this.handlePromptActionWatcherError(e,r instanceof Error?r:new Error(String(r)))}}handlePromptActionPayload(e,r){let n=r?.data?.onPromptStateChanged;if(!n||typeof n!="object"||n.userId!==e.userId||n.sessionId!==e.sessionId||n.family!=="GATE"||n.mobileActionable!==!1||typeof n.promptId!="string"||n.promptId.length===0)return;let i=n.decisionClaimId;if(i!=null&&(typeof i!="string"||i.length===0)){this.handlePromptActionWatcherError(e,new Error("promptAction payload has an invalid decisionClaimId"));return}let o={sessionId:e.sessionId,promptId:n.promptId,decisionClaimId:i??null};Promise.resolve().then(()=>e.onActionFence(o)).catch(s=>{w.warn("[AppSyncClient] promptAction watcher callback threw",{sessionId:e.sessionId,error:s instanceof Error?s.message:String(s)})})}sendPromptActionWatcherStart(e,r){let n=Bt(),i={host:new URL(n.aws.appsyncUrl).host};this.tokens?.idToken&&(i.Authorization=this.tokens.idToken),e.send(JSON.stringify({id:r.subscriptionId,type:"start",payload:{data:JSON.stringify({query:Ao.onPromptStateChanged,variables:{userId:r.userId}}),extensions:{authorization:i}}}))}resetPromptActionWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handlePromptActionWatcherError(e,new Error("promptAction watcher keep-alive timeout"))},300*1e3)}handlePromptActionWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.promptActionWatchers.get(e.sessionId)!==e)return;e.isReconnecting=!0,e.pendingReconnectSignal=!0,e.reconnectAttempts++,e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);try{e.onError?.(r)}catch{}let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;e.reconnectTimer=setTimeout(async()=>{if(e.isReconnecting=!1,e.destroyed||this.promptActionWatchers.get(e.sessionId)!==e)return;let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.promptActionWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Qn.v4)(),this.createPromptActionWatcherConnection(e))},i)}cleanupPromptActionWatcherState(e){e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}subscribeToApplyUserDecision(e,r,n){w.info("[AppSyncClient] Starting applyUserDecision watcher",{sessionId:e});let i=this.applyUserDecisionWatchers.get(e);i&&(w.info("[AppSyncClient] Replacing existing applyUserDecision watcher",{sessionId:e}),this.cleanupApplyUserDecisionWatcherState(i),this.applyUserDecisionWatchers.delete(e));let o={sessionId:e,subscriptionId:(0,Qn.v4)(),ws:null,onDecision:r,onError:n,reconnectAttempts:0,isReconnecting:!1,destroyed:!1};return this.applyUserDecisionWatchers.set(e,o),this.createApplyUserDecisionWatcherConnection(o),{stop:()=>{this.applyUserDecisionWatchers.get(e)===o&&(this.cleanupApplyUserDecisionWatcherState(o),this.applyUserDecisionWatchers.delete(e),w.info("[AppSyncClient] applyUserDecision watcher stopped",{sessionId:e}))}}}createApplyUserDecisionWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.info("[AppSyncClient] applyUserDecision watcher WebSocket connected",{sessionId:e.sessionId}),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.sendApplyUserDecisionWatcherStart(n,e);break;case"start_ack":w.info("[AppSyncClient] applyUserDecision watcher subscription started",{sessionId:e.sessionId}),e.isReconnecting=!1,e.reconnectAttempts=0;break;case"data":this.resetApplyUserDecisionWatcherKeepAlive(e),this.handleApplyUserDecisionPayload(e,o.payload);break;case"ka":this.resetApplyUserDecisionWatcherKeepAlive(e);break;case"error":{let s=o.payload?.errors?.[0]?.message||"Unknown error";this.handleApplyUserDecisionWatcherError(e,new Error(s));break}}}catch(o){w.error("[AppSyncClient] Failed to parse applyUserDecision watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] applyUserDecision watcher WebSocket error",{sessionId:e.sessionId,error:i.message}),this.handleApplyUserDecisionWatcherError(e,i)}),n.on("close",i=>{w.info("[AppSyncClient] applyUserDecision watcher WebSocket closed",{sessionId:e.sessionId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.applyUserDecisionWatchers.get(e.sessionId)===e&&this.handleApplyUserDecisionWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=n,this.resetApplyUserDecisionWatcherKeepAlive(e)}catch(r){this.handleApplyUserDecisionWatcherError(e,r)}}handleApplyUserDecisionPayload(e,r){let n=r?.data?.onApplyUserDecision;if(!n||typeof n!="object"){w.warn("[AppSyncClient] applyUserDecision watcher received malformed payload",{sessionId:e.sessionId});return}let i=n.taskId,o=n.gateId,s=n.decision;if(typeof i!="string"||typeof o!="string"){w.warn("[AppSyncClient] applyUserDecision watcher event missing taskId/gateId",{sessionId:e.sessionId});return}let a;try{a=nh(n.payload,"onApplyUserDecision")}catch(d){w.warn("[AppSyncClient] applyUserDecision watcher could not coerce payload",{sessionId:e.sessionId,error:d.message});return}let c=typeof s=="string"?s.toLowerCase():"",l={sessionId:e.sessionId,taskId:i,gateId:o,decision:c,action:a};Promise.resolve().then(()=>e.onDecision(l)).catch(d=>{w.warn("[AppSyncClient] applyUserDecision watcher callback threw",{sessionId:e.sessionId,error:d})})}sendApplyUserDecisionWatcherStart(e,r){let n=Bt(),{sessionId:i,subscriptionId:o}=r,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:Ao.onApplyUserDecision,variables:{sessionId:i}}),extensions:{authorization:s}}}))}resetApplyUserDecisionWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleApplyUserDecisionWatcherError(e,new Error("applyUserDecision watcher keep-alive timeout"))},300*1e3)}handleApplyUserDecisionWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.applyUserDecisionWatchers.get(e.sessionId)!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.onError)try{e.onError(r)}catch{}let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.warn("[AppSyncClient] applyUserDecision 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.applyUserDecisionWatchers.get(e.sessionId)!==e)return;let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before applyUserDecision watcher reconnect",{sessionId:e.sessionId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.applyUserDecisionWatchers.get(e.sessionId)!==e||(e.subscriptionId=(0,Qn.v4)(),this.createApplyUserDecisionWatcherConnection(e))},i)}cleanupApplyUserDecisionWatcherState(e){e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null)}startHeartbeat(e,r){let n=Fk(r),i=this.heartbeatInitialPulses.get(e);if(i)return i;let s=this.startHeartbeatOutcome(e,n).then(a=>(a==="retired"&&this.notifyRetiredSession(e),a==="confirmed"));return this.heartbeatInitialPulses.set(e,s),s}startHeartbeatOutcome(e,r){let n=Fk(r),i=this.heartbeatTokens.get(e),o=this.heartbeatTimers.get(e);if(i&&o){let l=this.heartbeatInitialOutcomes.get(e);if(l)return l;let d=this.trackHeartbeatPulse(e,this.sendHeartbeat(e,i));return this.heartbeatInitialOutcomes.set(e,d),d}this.stopHeartbeat(e);let s=Symbol(e);this.heartbeatTokens.set(e,s);let a=this.trackHeartbeatPulse(e,this.sendHeartbeat(e,s));this.heartbeatInitialOutcomes.set(e,a);let c=setInterval(()=>{this.trackHeartbeatPulse(e,this.sendHeartbeat(e,s)).then(l=>{l==="retired"&&this.notifyRetiredSession(e)})},n);return this.heartbeatTimers.set(e,c),w.info("[AppSyncClient] Heartbeat started",{sessionId:e,intervalMs:n}),a}stopHeartbeat(e){this.heartbeatTokens.delete(e),this.heartbeatInitialPulses.delete(e),this.heartbeatInitialOutcomes.delete(e);let r=this.heartbeatTimers.get(e);r&&(clearInterval(r),this.heartbeatTimers.delete(e),w.info("[AppSyncClient] Heartbeat stopped",{sessionId:e}))}async invalidateHeartbeat(e){this.stopHeartbeat(e);let r=Array.from(this.heartbeatInFlight.get(e)??[]);r.length>0&&await Promise.all(r);try{return await this.updateSession({sessionId:e,lastHeartbeatAt:new Date(0).toISOString()}),w.info("[AppSyncClient] Heartbeat liveness invalidated",{sessionId:e}),!0}catch(n){return w.warn("[AppSyncClient] Failed to invalidate heartbeat liveness",{sessionId:e,error:n}),!1}}trackHeartbeatPulse(e,r){let n=this.heartbeatInFlight.get(e);return n||(n=new Set,this.heartbeatInFlight.set(e,n)),n.add(r),r.finally(()=>{let i=this.heartbeatInFlight.get(e);i?.delete(r),i?.size===0&&this.heartbeatInFlight.delete(e)}),r}async sendHeartbeat(e,r){if(this.heartbeatTokens.get(e)!==r)return"stopped";try{let n=new Date().toISOString(),i=await this.updateSession({sessionId:e,lastHeartbeatAt:n});return this.heartbeatTokens.get(e)!==r||i.status!=="ACTIVE"&&(await this.updateSession({sessionId:e,lastHeartbeatAt:n,status:"ACTIVE"}),this.heartbeatTokens.get(e)!==r)?"stopped":(w.debug("[AppSyncClient] Heartbeat sent",{sessionId:e}),"confirmed")}catch(n){return w.warn("[AppSyncClient] Heartbeat failed",{sessionId:e,error:n}),NZ(n)?"retired":"failed"}}notifyRetiredSession(e){let r=this.activeSubscriptions.get(e);!r||r.destroyed||r.retirementNotified||(r.retirementNotified=!0,this.stopHeartbeat(e),this.cleanupSubscriptionState(r),this.activeSubscriptions.get(e)===r&&this.activeSubscriptions.delete(e),Promise.resolve().then(()=>r.onSessionRetired?.()).catch(n=>{w.warn("[AppSyncClient] Retired-session recovery callback failed",{sessionId:e,error:n instanceof Error?n.message:String(n)})}))}cleanupSubscription(e){this.closeCompanionNoticeOwners(e);let r=this.activeSubscriptions.get(e);r&&(this.cleanupSubscriptionState(r),this.activeSubscriptions.get(e)===r&&this.activeSubscriptions.delete(e))}cleanupSubscriptions(){this.syncReadEpoch++,this.closeCompanionNoticeOwners(),this.activeSubscriptions.forEach(e=>{this.cleanupSubscriptionState(e)}),this.activeSubscriptions.clear();for(let[e,r]of this.syncReadOwners)for(let n of r)this.trackSyncClosure(e,n.close());this.stopDeviceKeyWatcherInternal(),this.sessionUpdateWatchers.forEach(e=>{this.cleanupSessionUpdateWatcherState(e)}),this.sessionUpdateWatchers.clear(),this.applyUserDecisionWatchers.forEach(e=>{this.cleanupApplyUserDecisionWatcherState(e)}),this.applyUserDecisionWatchers.clear(),this.promptActionWatchers.forEach(e=>{this.cleanupPromptActionWatcherState(e)}),this.promptActionWatchers.clear(),this.heartbeatTimers.forEach(e=>clearInterval(e)),this.heartbeatTimers.clear(),this.heartbeatTokens.clear(),this.heartbeatInitialPulses.clear(),this.heartbeatInitialOutcomes.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");w.info("[AppSyncClient] Subscribing to Class B packets",{userId:e});let n={userId:e,onPacket:r.onPacket,onError:r.onError,destroyed:!1};this.classBPacketHandlers.set(e,n),this.classBWatcher&&this.stopClassBWatcherInternal();let i=null;if(this.tokens?.idToken){i={userId:e,subscriptionId:(0,Qn.v4)(),ws:null,onPacket:r.onPacket,onError:r.onError,onReconnect:r.onReconnect,onSubscribed:r.onSubscribed,pendingReconnectSignal:!1,reconnectAttempts:0,isReconnecting:!1,destroyed:!1},this.classBWatcher=i;try{this.createClassBWatcherConnection(i)}catch(o){r.onError?.(o instanceof Error?o:new Error(String(o)))}}else w.info("[AppSyncClient] Class B watcher registered without socket (no idToken)",{userId:e});return{unsubscribe:async()=>{n.destroyed=!0,this.classBPacketHandlers.get(e)===n&&this.classBPacketHandlers.delete(e),i&&this.classBWatcher===i&&this.stopClassBWatcherInternal(),w.info("[AppSyncClient] Unsubscribed Class B packets",{userId:e})}}}stopClassBWatcher(){this.stopClassBWatcherInternal()}stopClassBWatcherInternal(){let e=this.classBWatcher;e&&(e.destroyed=!0,this.cancelReconnectReconciliationWait(e),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0),e.ws&&(Co(e.ws,e.subscriptionId),e.ws=null),this.classBWatcher=null,w.info("[AppSyncClient] Class B watcher stopped"))}createClassBWatcherConnection(e){try{let r=this.buildRealtimeUrl(),n=new Uc.default(r,["graphql-ws"]);n.on("open",()=>{w.info("[AppSyncClient] Class B 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.sendClassBWatcherStart(n,e);break;case"start_ack":{w.info("[AppSyncClient] Class B watcher subscription started",{userId:e.userId});let s=e.pendingReconnectSignal===!0;if(e.pendingReconnectSignal=!1,e.isReconnecting=!1,e.reconnectAttempts=0,s&&e.onReconnect)try{e.onReconnect()}catch(a){w.warn("[AppSyncClient] Class B watcher onReconnect handler threw",{error:a})}if(e.onSubscribed)try{e.onSubscribed(s)}catch(a){w.warn("[AppSyncClient] Class B watcher onSubscribed handler threw",{error:a})}break}case"data":{this.resetClassBWatcherKeepAlive(e);let s=o.payload?.data?.onClassBPacket;s&&this.dispatchClassBPacket(e.userId,s);break}case"ka":this.resetClassBWatcherKeepAlive(e);break;case"error":{let s=o.payload?.errors?.[0]?.message||"Unknown error";this.handleClassBWatcherError(e,new Error(s));break}}}catch(o){w.error("[AppSyncClient] Failed to parse Class B watcher message",{error:o})}}),n.on("error",i=>{w.error("[AppSyncClient] Class B watcher WebSocket error",{userId:e.userId,error:i.message}),this.handleClassBWatcherError(e,i)}),n.on("close",i=>{w.info("[AppSyncClient] Class B watcher WebSocket closed",{userId:e.userId,code:i}),e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),!e.destroyed&&this.classBWatcher===e&&this.handleClassBWatcherError(e,new Error(`WebSocket closed: ${i}`))}),e.ws=n,this.resetClassBWatcherKeepAlive(e)}catch(r){this.handleClassBWatcherError(e,r)}}sendClassBWatcherStart(e,r){let n=Bt(),{userId:i,subscriptionId:o}=r,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:Ao.onClassBPacket,variables:{userId:i}}),extensions:{authorization:s}}}))}resetClassBWatcherKeepAlive(e){e.keepAliveTimer&&clearTimeout(e.keepAliveTimer),e.keepAliveTimer=setTimeout(()=>{this.handleClassBWatcherError(e,new Error("Class B watcher keep-alive timeout"))},300*1e3)}handleClassBWatcherError(e,r){if(e.isReconnecting||e.destroyed||this.classBWatcher!==e)return;if(e.isReconnecting=!0,e.reconnectAttempts++,e.pendingReconnectSignal=!0,e.onError)try{e.onError(r)}catch{}e.ws&&(Co(e.ws),e.ws=null),e.keepAliveTimer&&(clearTimeout(e.keepAliveTimer),e.keepAliveTimer=void 0);let i=e.reconnectAttempts<=Kt.urgentMaxAttempts?Math.min(Kt.baseDelayMs*Math.pow(Kt.backoffMultiplier,e.reconnectAttempts-1),Kt.maxDelayMs):Kt.persistentDelayMs;w.warn("[AppSyncClient] Class B 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.classBWatcher!==e){w.info("[AppSyncClient] Class B watcher reconnect skipped \u2014 state no longer canonical",{userId:e.userId});return}let o=this.beginReconnectReconciliationWait(e);try{await this.reconcileTokensBeforeReconnect(o)}catch{o.aborted||w.warn("[AppSyncClient] Token refresh failed before Class B watcher reconnect, using existing tokens",{userId:e.userId})}finally{this.finishReconnectReconciliationWait(e,o)}e.destroyed||this.classBWatcher!==e||(e.subscriptionId=(0,Qn.v4)(),this.createClassBWatcherConnection(e))},i)}dispatchClassBPacket(e,r){let n=this.classBPacketHandlers.get(e);if(!(!n||n.destroyed))try{let i=this.parseClassBPacketPayload(r.packetJson),o={sessionId:r.sessionId??"",userId:e,taskId:r.taskId??void 0,packetId:r.packetId??void 0,issuedAt:r.issuedAt??void 0};return Promise.resolve(n.onPacket(i,o))}catch(i){n.onError?.(i instanceof Error?i:new Error(String(i)))}}async _deliverClassBPacketForTests(e,r,n){await this.dispatchClassBPacket(e,{packetJson:r,sessionId:n?.sessionId??"",taskId:n?.taskId,packetId:n?.packetId,issuedAt:n?.issuedAt})}}});function Os(t){return t.source==="MOBILE"&&(t.type==="USER_PROMPT"||t.type==="PROMPT_RESPONSE")&&t.syncLifecycleVersion!==void 0}async function oh(t,e){return(await vU(t,e,"DELIVERED"))?.deliveryStatus!=="EXECUTED"}async function sh(t,e){await vU(t,e,"EXECUTED")}async function vU(t,e,r){let n=Os(e),i=e.sessionGenerationId;if(n&&(e.syncLifecycleVersion!==1||typeof i!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(i)))throw new ve("INVALID_SYNC_INPUT");let o={eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:r},s=e.type,a=n?await t(o,{sessionGenerationId:i,type:s}):await t(o);if(!n)return;let c=Mv(a,{...o,sessionGenerationId:i});if(c.type!==s)throw new ve("INVALID_SYNC_RECEIPT");return c}var kU=D(()=>{"use strict";Yl();Ln()});async function $k(t,e){let r=t.getCurrentUserId(),n=await t.getSubscriptionStatus(e);if(t.getCurrentUserId()!==r)throw new Error("Companion account changed during read; retry");let i=await t.getCompanionSyncState(e);if(t.getCurrentUserId()!==r)throw new Error("Companion account changed during read; retry");if(n.tier!==i.tier)throw new Error("Companion status changed during read; retry");let o=$v(i);if(o[0]==="Companion sync status unavailable")throw new Error("Companion status expired during read; retry");return[`Subscription: ${n.tier} (${n.status})`,...o]}var EU=D(()=>{"use strict";Mp()});async function Uk(t){let e=t.maxBacklogBytes??67108864,r=t.maxRecordBytes??16*1024*1024;if(![e,r].every(o=>Number.isSafeInteger(o)&&o>0))throw Error("SYNC_SOURCE_INVALID_LIMIT");let n=ns.openSync(t.filePath,ns.constants.O_RDONLY|ns.constants.O_NOFOLLOW),i=()=>{if(!t.isCurrent())throw Error("SYNC_SOURCE_STOPPED")};try{let o=ns.fstatSync(n);if(!o.isFile())throw Error("SYNC_SOURCE_NOT_REGULAR");let s=Object.freeze({filePath:t.filePath,fileIdentity:Object.freeze({dev:o.dev,ino:o.ino})}),a=(y,S)=>{let b=Buffer.alloc(S);if(ns.readSync(n,b,0,S,y)!==S)throw Error("SYNC_SOURCE_SHORT_READ");return b},c=(y,S=0)=>{if(y===0)return null;let b=Math.max(S,y-Zo);return{startOffset:b,endOffset:y,sha256:Gk(a(b,y-b))}},l=y=>y===0||a(y-1,1)[0]===10,d=Number.isSafeInteger(t.initialOffset)&&t.initialOffset>=0&&t.initialOffset<=o.size?t.initialOffset:0;i();let u=await t.admission.restore(s,{byteOffset:d,anchor:c(d),discardUntilNewline:!l(d)});if(i(),u===null)return null;if(!Number.isSafeInteger(u.byteOffset)||u.byteOffset<0||u.byteOffset>o.size||typeof u.discardUntilNewline!="boolean")throw Error("SYNC_SOURCE_INVALID_POSITION");if(u.byteOffset===0){if(u.anchor!==null||u.discardUntilNewline)throw Error("SYNC_SOURCE_INVALID_POSITION")}else{let y=u.anchor;if(!y||!Number.isSafeInteger(y.startOffset)||y.startOffset<0||y.endOffset!==u.byteOffset||y.endOffset<=y.startOffset||y.endOffset-y.startOffset>Zo||Gk(a(y.startOffset,y.endOffset-y.startOffset))!==y.sha256||!u.discardUntilNewline&&!l(u.byteOffset))throw Error("SYNC_SOURCE_ANCHOR_CHANGED")}let p={...u,anchor:u.anchor?{...u.anchor}:null},h=async(y,S,b)=>{i();let v=c(y,p.byteOffset);await t.admission.skip({startOffset:p.byteOffset,endOffset:y,anchor:v,reason:S,discardUntilNewline:b},s),i(),p={byteOffset:y,anchor:v,discardUntilNewline:b}};if(o.size-p.byteOffset>e){let y=o.size-e;await h(y,"BACKLOG_LIMIT",!l(y))}let m=p.byteOffset,f=[],g=0;for(;m<o.size;){i();let y=a(m,Math.min(LZ,o.size-m)),S=0;for(;S<y.length;){i();let b=y.indexOf(10,S),v=b<0?y.length:b+1,R=y.subarray(S,v),E=m+v;if(p.discardUntilNewline)await h(E,"PARTIAL_RECORD",b<0);else if(g+R.length>r)f=[],g=0,await h(E,"OVERSIZED_RECORD",b<0);else if(f.push(R),g+=R.length,b>=0){let I=Buffer.concat(f,g),k=I.subarray(0,I.length-1).toString("utf8").replace(/\r$/,""),P=null;if(k.trim())try{P=t.parse(k)}catch{}if(P){let A=p.byteOffset,C={startOffset:Math.max(A,E-Zo),endOffset:E,sha256:Gk(I.subarray(Math.max(0,I.length-Zo)))};await t.admission.admit(P,Object.freeze({...s,startOffset:A,endOffset:E,sha256:Gk(I),anchor:C})),i(),p={byteOffset:E,anchor:C,discardUntilNewline:!1}}else await h(E,k.trim()?"MALFORMED_RECORD":"EMPTY_RECORD",!1);f=[],g=0}S=v}m+=y.length}return{position:p,size:o.size,mtimeMs:o.mtimeMs}}finally{ns.closeSync(n)}}var ns,RU,LZ,Gk,IU=D(()=>{"use strict";ns=F(require("fs")),RU=require("crypto");ck();LZ=64*1024,Gk=t=>(0,RU.createHash)("sha256").update(t).digest("hex")});var AU={};jr(AU,{AppSyncAuthenticationError:()=>Mi,AppSyncClient:()=>xs,AppSyncGraphQLError:()=>Ut,CREDENTIAL_STORAGE_UNAVAILABLE_EXIT_CODE:()=>ny,DEFAULT_HEARTBEAT_INTERVAL_MS:()=>ry,DesktopSyncReadClient:()=>Nc,DurableDesktopSyncWriter:()=>Bc,MAX_HEARTBEAT_INTERVAL_MS:()=>ix,MAX_SYNC_SOURCE_ANCHOR_BYTES:()=>Zo,MIN_HEARTBEAT_INTERVAL_MS:()=>nx,PLAIN_DESKTOP_SYNC_TYPES:()=>Dp,RECOGNIZED_NON_PRODUCTION_ENVIRONMENTS:()=>SU,SyncEventClientError:()=>ve,SyncJournalError:()=>Ge,SyncReadClientError:()=>Tt,acknowledgeMobileInputDelivery:()=>oh,acknowledgeMobileInputExecution:()=>sh,coerceAwsJsonObject:()=>nh,describeStoredAuthFailure:()=>ih,desktopDeferredInputSha256:()=>ad,isPersistedEventResult:()=>Ov,isRecognizedNonProductionEnvironment:()=>ox,mutations:()=>et,queries:()=>qt,readDesktopSyncFile:()=>Uk,readStandaloneCompanionStatus:()=>$k,requiresSyncInputDeliveryReceipt:()=>Os,resolveHeartbeatIntervalMs:()=>Fk,subscriptions:()=>Ao});var Sn=D(()=>{"use strict";sx();sx();P_();A_();Ln();kU();EU();Tk();mk();ck();IU();Hp()});async function iy(t){let e=null;for(let r=0;r<ch;r++){let n=ah+r;try{let i=await new Promise((o,s)=>{let a=_U.createServer(t),c=d=>{a.removeListener("listening",l),s(d)},l=()=>{a.removeListener("error",c),a.on("error",d=>{w.error("[AuthService] OAuth server post-bind error",{port:n,code:d?.code,message:d?.message})}),o(a)};a.once("error",c),a.once("listening",l),a.listen(n,"localhost")});return w.info(`[AuthService] OAuth server bound on port ${n} (attempt ${r+1}/${ch})`),{server:i,port:n}}catch(i){if(e=i,i?.code==="EADDRINUSE")continue;throw i}}throw Object.assign(new Error(`All ports ${ah}-${ah+ch-1} are in use. Free at least one for OAuth callback or quit a conflicting service (common collisions: Vite, Webpack, Spring Boot, Docker exposed ports). Underlying: ${e?.message??"EADDRINUSE"}`),{code:"EADDRINUSE_ALL"})}var TU,PU,_U,CU,ah,ch,ax,lh,xo,oy=D(()=>{"use strict";TU=F(require("crypto")),PU=F(require("fs")),_U=F(require("http")),CU=require("child_process");Or();Rs();Nn();Ye();T_();zl();ah=8080,ch=20,ax="/callback";lh=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=PU.readFileSync("/proc/sys/kernel/osrelease","utf8");return/microsoft|wsl/i.test(e)}catch{return!1}}tryBrowserCommand(e,r,n){if(n>=e.length){w.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],o=[...i.fixedArgs,r],s=!1,a=u=>{s||(s=!0,w.debug(`[AuthService] Browser command '${i.cmd}' ${u}; trying next fallback`),this.tryBrowserCommand(e,r,n+1))},c=u=>{s||(s=!0,w.debug(`[AuthService] Browser command '${i.cmd}' ${u}`))},l;try{l=(0,CU.spawn)(i.cmd,o,{detached:!0,stdio:"ignore",env:nt({...process.env})})}catch(u){a(`threw synchronously: ${u?.message||u}`);return}l.on("error",u=>{a(`failed to spawn: ${u?.message||u}`)}),l.on("exit",(u,p)=>{u===0?c("exited successfully"):a(p?`terminated by signal ${p}`:`exited with code ${u}`)}),setTimeout(()=>{c("still running after 3s, assuming success")},3e3).unref(),l.unref()}generateState(){return TU.randomBytes(32).toString("hex")}buildAuthUrl(e,r){let n=Bt(),i=new URLSearchParams({client_id:n.aws.cognitoClientId,response_type:"code",scope:"email openid profile",redirect_uri:r,state:e});return`https://${n.aws.cognitoDomain}/oauth2/authorize?${i.toString()}`}async exchangeCodeForTokens(e,r){let n=Bt(),i=`https://${n.aws.cognitoDomain}/oauth2/token`,o=new URLSearchParams({grant_type:"authorization_code",client_id:n.aws.cognitoClientId,code:e,redirect_uri:r}),s;try{s=await Op(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},"Token exchange")}catch(c){throw await Ai("token_exchange_network_error"),Ro(c,"token_exchange_network_error"),c}if(!s.ok){let c=await s.text(),l=new Error(`Token exchange failed: ${s.status} ${c}`);throw await Ai("token_exchange_failed",{httpStatus:s.status}),Ro(l,"token_exchange_failed"),l}let a=await s.json();return{accessToken:a.access_token,idToken:a.id_token,refreshToken:a.refresh_token,expiresIn:a.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=Bt(),n=`https://${r.aws.cognitoDomain}/oauth2/token`,i=new URLSearchParams({grant_type:"refresh_token",client_id:r.aws.cognitoClientId,refresh_token:e}),o=await Op(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 _e.getTokens(jn());if(e&&!_e.isTokenExpired(e))return e;let r=this.generateState();return new Promise((n,i)=>{let o={},s=null,a=!1,c=!1,l=p=>{p.closeAllConnections?.()},d=p=>{if(a)return;a=!0,s&&(clearTimeout(s),s=null);let h=o.server;h?(l(h),h.close(()=>n(p))):n(p)},u=p=>{if(a)return;a=!0,s&&(clearTimeout(s),s=null);let h=o.server;h?(l(h),h.close(()=>i(p))):i(p)};(async()=>{let p;try{p=await iy(async(f,g)=>{if(c||a){g.writeHead(200,{Connection:"close"}),g.end();return}let S=`http://localhost:${f.socket?.localPort??p.port}${ax}`,b=new URL(f.url||"",S);if(b.pathname!==ax){g.writeHead(404,{Connection:"close"}),g.end("Not found");return}try{let v=b.searchParams.get("code"),R=b.searchParams.get("state"),E=b.searchParams.get("error");if(E){let A=new Error(`OAuth error: ${E}`);throw await Ai("cognito_rejected"),Ro(A,"cognito_rejected"),A}if(R!==r){let A=new Error("State mismatch");throw await Ai("state_mismatch"),Ro(A,"state_mismatch"),A}if(!v){let A=new Error("No authorization code");throw await Ai("no_authorization_code"),Ro(A,"no_authorization_code"),A}c=!0;let I=await this.exchangeCodeForTokens(v,S),k=this.decodeJwt(I.idToken),P={accessToken:I.accessToken,idToken:I.idToken,refreshToken:I.refreshToken,expiresAt:Date.now()+I.expiresIn*1e3,userId:k.sub,email:k.email||"unknown"};try{await _e.setTokens(P,jn())}catch(A){throw await Ai("keychain_write_failed",{errorFragment:A?.message?String(A.message):String(A)}),Ro(A,"keychain_write_failed"),A}g.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),g.end(`
771
771
  <!DOCTYPE html>
772
772
  <html>
773
773
  <head><title>Success</title></head>
@@ -5880,7 +5880,7 @@ ${X.bold}left alone${X.reset} ${X.dim}(needs --force)${X.reset}:`);for(let _ of
5880
5880
  ${X.red}\u2717${X.reset} ${g.length} entr${g.length===1?"y":"ies"} may still hold real data and ${g.length===1?"was":"were"} NOT included above. Re-run with ${X.bold}--force${X.reset} as well if you mean to give those bytes up.`)}if(!f.length){if(i&&!a){let _=await zS(e,s,u,l);if(fP(_))return 1}return 1}if(!i)return console.log(`
5881
5881
  Nothing was written. Re-run with ${X.bold}--yes${X.reset} to apply${g.length?" the entries listed first":""}.`),0;let y=_r.join(s,Ka),S=[];try{S=yt.readdirSync(y)}catch{S=[]}if(S.length)return console.error(`${X.red}\u2717${X.reset} A CodeVibe session is registering a root right now. Try again once it is idle.`),1;let b=_r.join(s,al),v=yt.readFileSync(b,"utf8");if(RB.createHash("sha256").update(v).digest("hex")!==RB.createHash("sha256").update(p.raw).digest("hex"))return console.error(`${X.red}\u2717${X.reset} The registry changed while this ran. Nothing was written; re-run.`),1;let R=new Date().toISOString().replace(/[:.]/g,"-"),E=_r.join(_r.dirname(s),"shadow-root-backups",R),I=_r.join(E,"shadow-roots.json");try{yt.mkdirSync(E,{recursive:!0,mode:448}),yt.copyFileSync(b,I)}catch(_){return console.error(`${X.red}\u2717${X.reset} Could not write the backup at ${E} (${_.code??"unknown error"}). Nothing was changed \u2014 this command will not clear an entry it cannot restore.`),1}let k=new Set(f.map(_=>_.root.path)),P=p.roots.filter(_=>!k.has(_.path)),A=_r.join(E,`.registry.next.${process.pid}`);try{yt.writeFileSync(A,JSON.stringify({version:2,roots:P}),{mode:384}),yt.renameSync(A,b)}catch(_){return console.error(`${X.red}\u2717${X.reset} Could not replace the registry (${_.code??"unknown error"}). Nothing was changed; a copy of it is at ${I}.`),1}finally{try{yt.unlinkSync(A)}catch{}}let C=[],T=[];for(let _ of f)for(let O of _.markers){let V=_r.join(E,`marker-${C.length}-${_r.basename(O)}`);try{yt.copyFileSync(O,V),C.push({copy:_r.basename(V),original:O})}catch(z){if(z.code!=="ENOENT"){T.push(O);continue}}try{yt.unlinkSync(O)}catch{}try{yt.rmdirSync(_r.dirname(O))}catch{}}try{yt.writeFileSync(_r.join(E,"manifest.json"),`${JSON.stringify({clearedAtUtc:new Date().toISOString(),registry:b,registryBackup:_r.basename(I),clearedRoots:f.map(_=>_.root.path),markers:C,unbackedMarkers:T},null,2)}
5882
5882
  `,{mode:384})}catch{}if(console.log(`
5883
- ${X.green}\u2713${X.reset} Cleared ${f.length} entr${f.length===1?"y":"ies"}${C.length?` and ${C.length} task record(s)`:""}. Backup: ${E}`),T.length&&console.error(`${X.red}!${X.reset} ${T.length} task record(s) could not be backed up and were left in place. They name a cleared root and do nothing, but nothing was destroyed either \u2014 remove them by hand once you know why the copy failed.`),g.length&&console.log(`${X.dim} ${g.length} entr${g.length===1?"y was":"ies were"} left alone; re-run with --force if you mean to give those bytes up.${X.reset}`),!a){let _=await zS(e,s,u,l);if(fP(_))return 1}return console.log(" Tasks should start again in any CodeVibe session."),0}var yt,_r,RB,gP,X,Ume,vP=D(()=>{"use strict";yt=F(require("fs")),_r=F(require("path")),RB=F(require("crypto")),gP=require("child_process");Rs();oy();Nn();Ap();VS();Uo();Ua();Bs();$w();dl();X={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m"},Ume=[{agent:"CLAUDE",command:"claude",name:"Claude Code"},{agent:"CODEX",command:"codex",name:"Codex CLI"},{agent:"ANTIGRAVITY",command:"agy",name:"Antigravity CLI"}]});var QS,IB=D(()=>{"use strict";QS=[{method:"POST",path:"/v1/messages",auth:"broker_token"},{method:"POST",path:"/v1/responses",auth:"broker_token"},{method:"GET",path:"/healthz",auth:"none"},{method:"GET",path:"/models",auth:"none"},{method:"GET",path:"/v1/models",auth:"none"}]});var Um,AB=D(()=>{"use strict";Um=class{constructor(e={}){this.opts=e;this.emitted=[];this.counter=0}async emit(e,r){if(this.emitted.push({kind:e,payload:r}),this.opts.failKinds?.includes(e))throw new Error(`StubStrictAuditSink: simulated IPC failure for ${e}`);return this.opts.nackKinds?.includes(e)?{nack:`StubStrictAuditSink: simulated nack for ${e}`}:(this.counter+=1,{ack:`stub-ack-${this.counter}`})}ofKind(e){return this.emitted.filter(r=>r.kind===e)}}});function Hm(t){return jme[t]}function kP(t){return t==="/v1/messages"?"anthropic":t==="/v1/responses"?"openai":null}var qme,Kme,jme,EP=D(()=>{"use strict";qme="2023-06-01",Kme=new Set(["oauth-2025-04-20","claude-code-20250219","context-1m-2025-08-07","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","mid-conversation-system-2026-04-07","effort-2025-11-24","thinking-token-count-2026-05-13","per-turn-control-2026-07-01","mid-conversation-tool-changes-2026-07-01","dangerous-tool-use-2026-09-03"]),jme={anthropic:{upstreamBaseUrl:"https://api.anthropic.com",upstreamPath:"/v1/messages",synthesizedHeaders:{"anthropic-version":qme,"content-type":"application/json"},betaTokenAllowlist:Kme,betaHeaderName:"anthropic-beta"},openai:{upstreamBaseUrl:"https://api.openai.com",upstreamPath:"/v1/responses",synthesizedHeaders:{"content-type":"application/json"},betaTokenAllowlist:new Set,betaHeaderName:null}}});var TB,Vme,v9,Wm,PB=D(()=>{"use strict";TB=require("node:crypto"),Vme=1800*1e3,v9=32,Wm=class{constructor(e=Vme){this.ttlMs=e;this.current=null;this.graceToken=null;this.generation=0}mint(e=Date.now()){let r=(0,TB.randomBytes)(v9).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.graceToken=null,this.generation+=1,this.current}rotateWithGrace(e=Date.now()){if(this.current===null||this.graceToken!==null)return null;this.graceToken=this.current;let r=(0,TB.randomBytes)(v9).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.generation+=1,{token:this.current,generation:this.generation}}commitRotation(e){e!==void 0&&e.generation!==this.generation||(this.graceToken=null)}rollbackRotation(e){e!==void 0&&e.generation!==this.generation||this.graceToken!==null&&(this.current=this.graceToken,this.graceToken=null)}hasPendingGrace(){return this.graceToken!==null}get(){return this.current}acceptedValues(){let e=[];return this.current&&e.push(this.current.value),this.graceToken&&e.push(this.graceToken.value),e}authenticate(e,r=Date.now()){return e?!!(this.current&&r<this.current.expiresAtMs&&e===this.current.value||this.graceToken&&r<this.graceToken.expiresAtMs&&e===this.graceToken.value):!1}clear(){this.current=null,this.graceToken=null}}});function ke(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function CB(t){return(0,RP.createHash)("sha256").update(JSON.stringify(t)).digest("hex")}function It(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dp(t){return typeof t=="number"&&Number.isFinite(t)}function Wl(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function k9(t){if(!It(t))return!1;for(let e of Object.keys(t))if(typeof t[e]!="string")return!1;return!0}function E9(t){if(!It(t))return!1;let e=Object.keys(t);for(let r of e)if(!tge.has(r))return!1;return!(!ke(t,"path")||typeof t.path!="string"||!ke(t,"resolved")||!Wl(t.resolved)||ke(t,"source")&&t.source!==void 0&&typeof t.source!="string")}function R9(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!uge.has(e))return!1;return!(!ke(t,"host")||typeof t.host!="string"||!ke(t,"remote")||typeof t.remote!="string"||!ke(t,"visibility")||typeof t.visibility!="string"||!_9.has(t.visibility))}function xge(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!pge.has(e))return!1;return!(!ke(t,"name")||typeof t.name!="string"||!ke(t,"host")||typeof t.host!="string"||!ke(t,"remote")||typeof t.remote!="string"||!ke(t,"visibility")||typeof t.visibility!="string"||!_9.has(t.visibility))}function I9(t){if(!It(t))return!1;for(let e of Object.keys(t)){if(!sge.has(e))return!1;let r=t[e];if(e==="cwd"||e==="root"||e==="branch"||e==="default_branch"){if(r!=null&&typeof r!="string")return!1}else if(e==="error"){if(r!=null&&(typeof r!="string"||!age.has(r)))return!1}else if(e==="truncated"){if(r!==void 0&&typeof r!="boolean")return!1}else if(e==="status"){if(r!=null){if(!It(r))return!1;for(let n of Object.keys(r))if(!cge.has(n))return!1;if(!ke(r,"clean")||typeof r.clean!="boolean"||!ke(r,"truncated")||typeof r.truncated!="boolean"||!ke(r,"porcelain")||r.porcelain!==null&&typeof r.porcelain!="string"||!ke(r,"counts"))return!1;if(r.counts!==null){if(!It(r.counts))return!1;for(let n of Object.keys(r.counts))if(!lge.has(n))return!1;if(!ke(r.counts,"staged")||!dp(r.counts.staged)||!ke(r.counts,"modified")||!dp(r.counts.modified)||!ke(r.counts,"untracked")||r.counts.untracked!==null&&!dp(r.counts.untracked)||!ke(r.counts,"untracked_normal")||r.counts.untracked_normal!==null&&!dp(r.counts.untracked_normal))return!1}}}else if(e==="visibility"&&r!=null){if(!It(r))return!1;for(let n of Object.keys(r))if(!dge.has(n))return!1;if(!ke(r,"origin")||r.origin!==null&&!R9(r.origin)||!ke(r,"push_remote")||r.push_remote!==null&&typeof r.push_remote!="string"||!ke(r,"remotes")||!Array.isArray(r.remotes)||!r.remotes.every(xge)||!ke(r,"visibility_cache")||!Array.isArray(r.visibility_cache)||!r.visibility_cache.every(R9))return!1}}return!0}function A9(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!hge.has(e))return!1;if(!ke(t,"enabled")||typeof t.enabled!="boolean"||!ke(t,"baselines")||!k9(t.baselines))return!1;if(ke(t,"tabs")&&t.tabs!==void 0){if(!It(t.tabs))return!1;for(let e of Object.keys(t.tabs))if(!k9(t.tabs[e]))return!1}return!0}function Hge(t){if(!Array.isArray(t))return!1;for(let e of t){if(!It(e))return!1;for(let r of Object.keys(e))if(!Gge.has(r))return!1;if(!ke(e,"path")||typeof e.path!="string"||e.path!==""&&!x9.test(e.path)||ke(e,"read")&&e.read!==void 0&&(typeof e.read!="string"||!T9.has(e.read))||ke(e,"write")&&e.write!==void 0&&(typeof e.write!="string"||!T9.has(e.write)))return!1}return!0}function Wge(t,e){if(!Oge.has(t)||!It(e))return!1;if(t==="mcp"){for(let r of Object.keys(e))if(!Bge.has(r))return!1;if(ke(e,"dynamic")&&e.dynamic!==void 0&&typeof e.dynamic!="boolean")return!1;if(ke(e,"servers")&&e.servers!==void 0){if(!Array.isArray(e.servers)||e.servers.length>Nge||e.servers.length===0&&e.dynamic!==!0)return!1;for(let r of e.servers){if(!It(r))return!1;for(let n of Object.keys(r))if(!Fge.has(n))return!1;if(!ke(r,"server")||typeof r.server!="string"||r.server.length===0||r.server.length>128||!ke(r,"tools")||!Array.isArray(r.tools)||r.tools.length===0||r.tools.length>Mge||!r.tools.every(n=>typeof n=="string"&&Lge.test(n)))return!1}}return!0}if(t==="user"){for(let r of Object.keys(e))if(!Uge.has(r))return!1;return!(ke(e,"scopes")&&e.scopes!==void 0&&(!Array.isArray(e.scopes)||!e.scopes.every(r=>typeof r=="string"&&P9.test(r))))}if(C9.has(t)){for(let r of Object.keys(e))if(!$ge.has(r))return!1;return!(ke(e,"rules")&&e.rules!==void 0&&!Hge(e.rules)||ke(e,"wake")&&e.wake!==void 0&&(!Array.isArray(e.wake)||!e.wake.every(r=>typeof r=="string"&&x9.test(r))))}for(let r of Object.keys(e)){if(!P9.test(r))return!1;let n=e[r];if(n!==null&&typeof n!="string"&&typeof n!="boolean"&&!dp(n))return!1}return!0}function qge(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!vge.has(e))return!1;if(!ke(t,"mode")||typeof t.mode!="string"||!ke(t,"is_shared_live")||typeof t.is_shared_live!="boolean"||!ke(t,"probed")||typeof t.probed!="boolean"||!ke(t,"probe_current_account")||typeof t.probe_current_account!="boolean"||!ke(t,"grant_observed")||typeof t.grant_observed!="boolean"||ke(t,"role")&&t.role!==void 0&&typeof t.role!="string"||ke(t,"artifact_kind")&&t.artifact_kind!==void 0&&typeof t.artifact_kind!="string"||ke(t,"type_lock")&&t.type_lock!==void 0&&typeof t.type_lock!="boolean")return!1;for(let e of kge)if(ke(t,e)&&t[e]!==void 0&&t[e]!==!0)return!1;if(ke(t,"live_paths")&&t.live_paths!==void 0&&!Wl(t.live_paths))return!1;if(ke(t,"capabilities")&&t.capabilities!==void 0){if(!It(t.capabilities)||Buffer.byteLength(JSON.stringify(t.capabilities),"utf8")>Dge)return!1;for(let e of Object.keys(t.capabilities))if(!Wge(e,t.capabilities[e]))return!1}return!0}function Kge(t){if(!It(t))return!1;for(let r of Object.keys(t))if(!yge.has(r))return!1;if(!ke(t,"by_slug")||!It(t.by_slug))return!1;for(let r of Object.keys(t.by_slug)){let n=t.by_slug[r];if(!It(n))return!1;for(let i of Object.keys(n))if(!bge.has(i))return!1;if(ke(n,"share")&&n.share!==void 0&&!qge(n.share)||ke(n,"attested")&&n.attested!==void 0&&typeof n.attested!="string"||ke(n,"notice_pending")&&n.notice_pending!==void 0&&n.notice_pending!==!0||ke(n,"published_env")&&n.published_env!==void 0&&(typeof n.published_env!="string"||!_B.has(n.published_env)))return!1;if(ke(n,"watch")&&n.watch!==void 0){if(!It(n.watch))return!1;for(let i of Object.keys(n.watch))if(!Sge.has(i)||n.watch[i]!==void 0&&n.watch[i]!==!0)return!1}}if(!ke(t,"by_path")||!It(t.by_path))return!1;for(let r of Object.keys(t.by_path)){let n=t.by_path[r];if(!It(n))return!1;for(let i of Object.keys(n))if(!Ege.has(i))return!1;if(ke(n,"slug")&&n.slug!==void 0&&typeof n.slug!="string"||ke(n,"thumbnail_named")&&n.thumbnail_named!==void 0&&!Wl(n.thumbnail_named))return!1}if(!ke(t,"live_docs")||!Array.isArray(t.live_docs))return!1;for(let r of t.live_docs){if(!It(r))return!1;for(let n of Object.keys(r))if(!Rge.has(n))return!1;if(!ke(r,"slug")||typeof r.slug!="string"||!ke(r,"live_path")||typeof r.live_path!="string"||!ke(r,"working_copy")||typeof r.working_copy!="string")return!1}if(!ke(t,"room_armed")||!Wl(t.room_armed)||!ke(t,"type_reads")||!It(t.type_reads))return!1;for(let r of Object.keys(t.type_reads)){let n=t.type_reads[r];if(!It(n))return!1;for(let i of Object.keys(n))if(!Ige.has(i))return!1;if(!ke(n,"declares_room")||typeof n.declares_room!="boolean")return!1}if(ke(t,"last_publish")&&t.last_publish!==void 0){let r=t.last_publish;if(!It(r))return!1;for(let n of Object.keys(r))if(!Age.has(n))return!1;if(!ke(r,"slug")||typeof r.slug!="string"||!ke(r,"env")||typeof r.env!="string"||!_B.has(r.env))return!1}if(!ke(t,"session")||!It(t.session))return!1;let e=t.session;for(let r of Object.keys(e))if(!Tge.has(r))return!1;if(!ke(e,"frame_env")||typeof e.frame_env!="string"||!_B.has(e.frame_env)||!ke(e,"viewer_origin")||typeof e.viewer_origin!="string"||ke(e,"dev_viewer_origin")&&e.dev_viewer_origin!==void 0&&typeof e.dev_viewer_origin!="string")return!1;for(let r of Pge)if(!ke(e,r)||typeof e[r]!="boolean")return!1;for(let r of _ge)if(ke(e,r)&&e[r]!==void 0&&typeof e[r]!="boolean")return!1;return!(ke(e,"inherited_type_grant")&&e.inherited_type_grant!==void 0&&e.inherited_type_grant!==!0||ke(e,"watch_rail")&&e.watch_rail!==void 0&&(typeof e.watch_rail!="string"||!wge.has(e.watch_rail))||!ke(e,"scratchpad_dir")||e.scratchpad_dir!==null&&typeof e.scratchpad_dir!="string"||ke(e,"tool_results_dir")&&e.tool_results_dir!==void 0&&typeof e.tool_results_dir!="string"||ke(t,"truncated")&&t.truncated!==void 0&&typeof t.truncated!="boolean")}function jge(t){if(!Array.isArray(t)||t.length>Cge)throw new et("safeguards is not a canonical dangerous_tool_use array");for(let e of t){if(!It(e))throw new et("safeguards entry is not a plain object");for(let r of Object.keys(e))if(!Jme.has(r))throw new et("safeguards entry contains unsupported key");if(!ke(e,"type")||e.type!=="dangerous_tool_use")throw new et("safeguards entry type is not dangerous_tool_use");if(ke(e,"classifier_context")&&e.classifier_context!==void 0){let r=e.classifier_context;if(!It(r))throw new et("safeguards classifier_context is not a plain object");for(let n of Object.keys(r))if(!Yme.has(n))throw new et("safeguards classifier_context contains unsupported key");if(ke(r,"v")&&r.v!==void 0&&!dp(r.v))throw new et("safeguards classifier_context.v is not a finite number");for(let n of Qme)if(ke(r,n)&&r[n]!==void 0&&typeof r[n]!="string")throw new et("safeguards classifier_context string field is invalid");for(let n of Xme)if(ke(r,n)&&r[n]!==void 0&&typeof r[n]!="boolean")throw new et("safeguards classifier_context boolean field is invalid");if(ke(r,"user_identity")&&r.user_identity!==void 0&&r.user_identity!==null&&typeof r.user_identity!="string")throw new et("safeguards classifier_context.user_identity is invalid");if(ke(r,"rule_roots")&&r.rule_roots!==void 0){if(!It(r.rule_roots))throw new et("safeguards classifier_context.rule_roots is invalid");for(let n of Object.keys(r.rule_roots)){let i=r.rule_roots[n];if(!Zme.has(n)||i!==null&&typeof i!="string")throw new et("safeguards classifier_context.rule_roots is invalid")}}if(ke(r,"trusted_directories")&&r.trusted_directories!==void 0){if(!It(r.trusted_directories))throw new et("safeguards classifier_context.trusted_directories is invalid");let n=r.trusted_directories;for(let i of Object.keys(n))if(!ege.has(i))throw new et("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"primary")&&n.primary!==void 0&&n.primary!==null&&!E9(n.primary))throw new et("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"additional")&&n.additional!==void 0&&(!Array.isArray(n.additional)||!n.additional.every(i=>typeof i=="string"||E9(i))))throw new et("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"network")&&n.network!==void 0&&!Wl(n.network))throw new et("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"block_reads_outside_working_directories")&&n.block_reads_outside_working_directories!==void 0&&typeof n.block_reads_outside_working_directories!="boolean")throw new et("safeguards classifier_context.trusted_directories is invalid")}if(ke(r,"rules")&&r.rules!==void 0){if(!It(r.rules))throw new et("safeguards classifier_context.rules is invalid");for(let n of Object.keys(r.rules)){let i=r.rules[n];if(!rge.has(n)||!Array.isArray(i))throw new et("safeguards classifier_context.rules is invalid");for(let o of i){if(!It(o))throw new et("safeguards classifier_context.rules is invalid");for(let s of Object.keys(o))if(!ige.has(s))throw new et("safeguards classifier_context.rules is invalid");if(!ke(o,"rule")||typeof o.rule!="string"||!ke(o,"source")||typeof o.source!="string")throw new et("safeguards classifier_context.rules is invalid");if(ke(o,"canonical")&&o.canonical!==void 0&&typeof o.canonical!="string")throw new et("safeguards classifier_context.rules is invalid");if(ke(o,"root")&&o.root!==void 0&&o.root!==null&&typeof o.root!="string")throw new et("safeguards classifier_context.rules is invalid");if(ke(o,"pattern")&&o.pattern!==void 0&&typeof o.pattern!="string")throw new et("safeguards classifier_context.rules is invalid")}}}if(ke(r,"dropped")&&r.dropped!==void 0){if(!It(r.dropped))throw new et("safeguards classifier_context.dropped is invalid");for(let n of Object.keys(r.dropped)){let i=r.dropped[n];if(!nge.has(n)||!dp(i))throw new et("safeguards classifier_context.dropped is invalid")}}if(ke(r,"auto_mode")&&r.auto_mode!==void 0){if(!It(r.auto_mode))throw new et("safeguards classifier_context.auto_mode is invalid");for(let n of Object.keys(r.auto_mode))if(!oge.has(n)||!Wl(r.auto_mode[n]))throw new et("safeguards classifier_context.auto_mode is invalid")}if(ke(r,"git_state")&&r.git_state!==void 0&&r.git_state!==null&&!I9(r.git_state))throw new et("safeguards classifier_context.git_state is invalid");if(ke(r,"chrome_navigation")&&r.chrome_navigation!==void 0&&!A9(r.chrome_navigation))throw new et("safeguards classifier_context.chrome_navigation is invalid");if(ke(r,"prior_turn_context")&&r.prior_turn_context!==void 0){if(!Array.isArray(r.prior_turn_context))throw new et("safeguards classifier_context.prior_turn_context is invalid");for(let n of r.prior_turn_context){if(!It(n))throw new et("safeguards classifier_context.prior_turn_context is invalid");for(let i of Object.keys(n))if(!fge.has(i))throw new et("safeguards classifier_context.prior_turn_context is invalid");if(!ke(n,"tool_use_ids")||!Wl(n.tool_use_ids))throw new et("safeguards classifier_context.prior_turn_context is invalid");if(!ke(n,"context")||!It(n.context))throw new et("safeguards classifier_context.prior_turn_context is invalid");for(let i of Object.keys(n.context))if(!mge.has(i))throw new et("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"git_state")&&n.context.git_state!==void 0&&n.context.git_state!==null&&!I9(n.context.git_state))throw new et("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"chrome_navigation")&&n.context.chrome_navigation!==void 0&&!A9(n.context.chrome_navigation))throw new et("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"live_cwd")&&n.context.live_cwd!==void 0&&typeof n.context.live_cwd!="string")throw new et("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"platform")&&n.context.platform!==void 0&&typeof n.context.platform!="string")throw new et("safeguards classifier_context.prior_turn_context is invalid")}}if(ke(r,"system_reminders")&&r.system_reminders!==void 0){if(!Array.isArray(r.system_reminders))throw new et("safeguards classifier_context.system_reminders is invalid");for(let n of r.system_reminders){if(!It(n))throw new et("safeguards classifier_context.system_reminders is invalid");for(let i of Object.keys(n))if(!gge.has(i))throw new et("safeguards classifier_context.system_reminders is invalid");if(!ke(n,"id")||typeof n.id!="string"||!ke(n,"provenance")||typeof n.provenance!="string")throw new et("safeguards classifier_context.system_reminders is invalid");if(ke(n,"author")&&n.author!==void 0&&typeof n.author!="string")throw new et("safeguards classifier_context.system_reminders is invalid");if(ke(n,"written")&&n.written!==void 0&&typeof n.written!="string")throw new et("safeguards classifier_context.system_reminders is invalid")}}if(ke(r,"artifacts")&&r.artifacts!==void 0&&!Kge(r.artifacts))throw new et("safeguards classifier_context.artifacts is invalid");if(ke(r,"shed")&&r.shed!==void 0&&!Wl(r.shed))throw new et("safeguards classifier_context.shed is invalid")}}}function Vge(t,e){let r=Hm(t);if(!r.betaHeaderName)return{};let n=e?.[r.betaHeaderName];if(n===void 0||n==="")return{};let i=n.split(",").map(a=>a.trim()).filter(a=>a.length>0),o=i.filter(a=>r.betaTokenAllowlist.has(a)),s=i.filter(a=>!r.betaTokenAllowlist.has(a));return s.length>0&&w.warn("[canonical] dropped non-allowlisted beta tokens",{dropped:s}),o.length===0?{}:{[r.betaHeaderName]:o.join(",")}}function IP(t){let{provider:e,request:r}=t,n=Hm(e);if(t.agentContentType!==void 0&&t.agentContentType.split(";")[0].trim().toLowerCase()!=="application/json")throw new et("non-JSON content type");let i=r.body;if(i==null||typeof i!="object"||Array.isArray(i))throw new et("body is not a JSON object");if(ke(i,"model")){let c=i.model;if(typeof c!="string"||!zme.test(c))throw new et("model is not a canonical model id")}e==="anthropic"&&ke(i,"safeguards")&&jge(i.safeguards);let o=(0,RP.randomUUID)(),s=CB(i),a={...n.synthesizedHeaders,...Vge(e,t.agentHeaders)};return{provider:e,upstreamUrl:n.upstreamBaseUrl+n.upstreamPath,headers:a,body:i,modelCallId:o,requestSha256:s}}function AP(t,e){let r=e.filter(p=>p.length>0),n=[],i=[],o="[REDACTED-SELF-CRED]",s="[REDACTED-SELF-CRED-KEY]",a="[REDACTED-CP7-KEY]",c=p=>r.some(h=>p.includes(h)),l=(p,h)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)?`${p}.${h}`:`${p}['${h.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}']`,d=(p,h)=>{if(typeof p=="string"){if(r.length===0)return p;let m=p,f=!1;for(let g of r)m.includes(g)&&(m=m.split(g).join(o),f=!0);return f&&n.push(h),m}if(Array.isArray(p))return p.map((m,f)=>d(m,`${h}[${f}]`));if(p!==null&&typeof p=="object"){let m=Object.create(null),f=0,g=0;for(let[y,S]of Object.entries(p))if(r.length>0&&c(y)){f+=1;let b=`${s}-${f}`,v=l(h,b);n.push(v),m[b]=d(S,v)}else if($0(y)){g+=1;let b=`${a}-${g}`,v=l(h,b);i.push({field:v,patternClass:"secret_object_key"}),m[b]=d(S,v)}else m[y]=d(S,l(h,y));return m}return p};return{body:d(t,"$"),leakedPaths:n,keyScrubs:i}}var RP,et,zme,Jme,Yme,Qme,Xme,Zme,ege,tge,rge,nge,ige,oge,sge,age,cge,lge,dge,_9,uge,pge,hge,fge,mge,gge,yge,_B,wge,bge,Sge,vge,kge,Ege,Rge,Ige,Age,Tge,Pge,_ge,Cge,C9,Oge,Dge,Nge,Mge,Lge,Bge,Fge,$ge,Gge,x9,T9,Uge,P9,xB=D(()=>{"use strict";RP=require("node:crypto");EP();Ye();Du();et=class extends Error{constructor(r){super(r);this.reason=r;this.name="CanonicalRejectError"}},zme=/^[A-Za-z0-9._:/-]{1,200}$/;Jme=new Set(["type","classifier_context"]),Yme=new Set(["v","permission_mode","platform","live_cwd","home_dir","rule_roots","trusted_directories","rules","auto_mode","artifact_consent_holdback","case_insensitive_paths","restricted","is_remote_mode","classify_all_shell","user_identity","git_state","dropped","truncated","chrome_navigation","prior_turn_context","system_reminders","artifacts","shed","tool_host_attached"]),Qme=["permission_mode","platform","live_cwd","home_dir"],Xme=["artifact_consent_holdback","case_insensitive_paths","restricted","is_remote_mode","classify_all_shell","truncated","tool_host_attached"],Zme=new Set(["userSettings","projectSettings","localSettings","flagSettings","policySettings","cliArg","command","session","toolsNarrowing","mcpServerPolicy","hostCredential"]),ege=new Set(["primary","additional","network","block_reads_outside_working_directories"]),tge=new Set(["path","resolved","source"]),rge=new Set(["allow","deny","ask"]),nge=new Set(["allow","deny","ask","auto_mode_allow","auto_mode_soft_deny","auto_mode_hard_deny","auto_mode_environment"]),ige=new Set(["rule","canonical","source","root","pattern"]),oge=new Set(["allow","soft_deny","hard_deny","environment"]),sge=new Set(["cwd","root","branch","default_branch","status","visibility","error","truncated"]),age=new Set(["timeout","not_a_repo","error","pending"]),cge=new Set(["clean","counts","porcelain","truncated"]),lge=new Set(["staged","modified","untracked","untracked_normal"]),dge=new Set(["origin","push_remote","remotes","visibility_cache"]),_9=new Set(["public","private","unknown"]),uge=new Set(["host","remote","visibility"]),pge=new Set(["name","host","remote","visibility"]),hge=new Set(["enabled","baselines","tabs"]),fge=new Set(["tool_use_ids","context"]),mge=new Set(["git_state","chrome_navigation","live_cwd","platform"]),gge=new Set(["id","provenance","author","written"]),yge=new Set(["by_slug","by_path","live_docs","room_armed","type_reads","last_publish","session","truncated"]),_B=new Set(["prod","staging"]),wge=new Set(["live","durable","none"]),bge=new Set(["share","attested","notice_pending","published_env","watch"]),Sge=new Set(["stopped","auto_reply_stopped","auto_reply_swept","replies_declined"]),vge=new Set(["mode","is_shared_live","role","probe_failed","probed","probe_current_account","cowritten","outside_writer","artifact_kind","type_locked","type_lock","type_first_party","caps_read_not_found","live_paths","capabilities","capabilities_unknown","capabilities_cut","grant_observed"]),kge=["probe_failed","cowritten","outside_writer","type_locked","type_first_party","caps_read_not_found","capabilities_unknown","capabilities_cut"],Ege=new Set(["slug","thumbnail_named"]),Rge=new Set(["slug","live_path","working_copy"]),Ige=new Set(["declares_room"]),Age=new Set(["slug","env"]),Tge=new Set(["frame_env","viewer_origin","dev_viewer_origin","toolset","short_links","ant_build","live_edit","live_doc_stream","live_paths_schema","copy_from","types_on","five_class_asks","inherited_type_grant","watch_rail","auto_react","comments_in_schema","db_str_replace","handlers","room_client","eval_stub","scratchpad_dir","tool_results_dir"]),Pge=["ant_build","comments_in_schema","handlers","room_client","eval_stub"],_ge=["toolset","short_links","live_edit","live_doc_stream","live_paths_schema","copy_from","types_on","five_class_asks","auto_react","db_str_replace"],Cge=16;C9=new Set(["artifact","self","downloads","comments","room","db","assets"]),Oge=new Set([...C9,"user","mcp","flags"]),Dge=4e3,Nge=32,Mge=128,Lge=/^[A-Za-z0-9_.-]{1,128}$/,Bge=new Set(["servers","dynamic"]),Fge=new Set(["server","tools"]),$ge=new Set(["rules","wake"]),Gge=new Set(["path","read","write"]),x9=/^(?:[A-Za-z0-9_.~:@+-]+|\{self\})(?:\/(?:[A-Za-z0-9_.~:@+-]+|\{self\}))*$/,T9=new Set(["view","interact","admin","owner"]),Uge=new Set(["scopes"]),P9=/^[a-z][a-z0-9_-]{0,31}$/});function TP(){return up.upstreamBaseUrl+up.upstreamPath}var zge,up,PP,_P,CP,xP=D(()=>{"use strict";zge="0.144.4",up={upstreamBaseUrl:"https://chatgpt.com/backend-api/codex",upstreamPath:"/responses",synthesizedHeaders:{"content-type":"application/json",originator:"codex_cli_rs","user-agent":`codex_cli_rs/${zge}`},assumeSseOn200:!0};PP="https://auth.openai.com/oauth/token",_P="app_EMoamEEZ73f0CkXaXp7hrann",CP="application/x-www-form-urlencoded"});function O9(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}async function Qge(t,e){let r=t.body;if(!r||typeof r.getReader!="function"){let s=await t.text();return Buffer.byteLength(s,"utf8")>e?{rawBody:"",oversized:!0}:{rawBody:s,oversized:!1}}let n=r.getReader(),i=[],o=0;try{for(;;){let{done:s,value:a}=await n.read();if(s)break;if(!(!a||a.byteLength===0)){if(o+a.byteLength>e)return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0};o+=a.byteLength,i.push(a)}}}catch{return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0}}return{rawBody:Buffer.concat(i.map(s=>Buffer.from(s)),o).toString("utf8"),oversized:!1}}function OB(t){let e=new URLSearchParams;return e.set("grant_type","refresh_token"),e.set("refresh_token",t),e.set("client_id",_P),e.toString()}async function OP(t,e,r={}){let n=(r.now?.()??new Date).toISOString(),i;try{i=await e.post({url:PP,body:OB(t.refresh_token),contentType:CP,signal:r.signal})}catch{return{kind:"transient",reason:"transport_error"}}if(i.status===200){let a=D9(i,!1);if(a&&typeof a.access_token=="string"&&a.access_token.length>0){let c={access_token:a.access_token,refresh_token:typeof a.refresh_token=="string"&&a.refresh_token.length>0?a.refresh_token:t.refresh_token,account_id:t.account_id,last_refresh:n},l=typeof a.id_token=="string"&&a.id_token.length>0?a.id_token:t.id_token;return l!==void 0&&(c.id_token=l),{kind:"rotated",bundle:c}}return{kind:"transient",reason:"malformed_success"}}let o=D9(i,!0),s=typeof o?.error=="string"?o.error:void 0;return s==="invalid_grant"?(w.warn("[oauth-refresh] permanent refresh failure (invalid_grant)"),{kind:"permanent",reason:"invalid_grant"}):(w.warn(`[oauth-refresh] transient refresh failure (status=${i.status})`),{kind:"transient",reason:s??`status_${i.status}`})}function D9(t,e){if(t.oversized||e&&(!t.contentType||!t.contentType.includes("application/json"))||!t.rawBody||t.rawBody.length===0)return null;try{let r=JSON.parse(t.rawBody);return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}var Jge,Yge,qm,DB=D(()=>{"use strict";Ye();xP();Jge=64*1024,Yge=3e4,qm=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??Yge,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=()=>i.abort();e.signal&&(e.signal.aborted?i.abort():e.signal.addEventListener("abort",s,{once:!0}));try{let a=await r(e.url,{method:"POST",headers:{"content-type":e.contentType},body:e.body,redirect:"error",signal:i.signal}),{rawBody:c,oversized:l}=await Qge(a,Jge);return w.debug(`[oauth-refresh] POST ${O9(e.url)} -> ${a.status}`),{status:a.status,rawBody:c,contentType:(a.headers.get("content-type")??void 0)?.toLowerCase(),oversized:l}}catch(a){throw w.warn(`[oauth-refresh] transport error POSTing ${O9(e.url)}`,{code:a?.code}),new Error("oauth refresh transport error")}finally{clearTimeout(o),e.signal&&e.signal.removeEventListener("abort",s)}}}});function nye(){return{status:200,body:{models:rye.map(t=>({slug:t.slug,display_name:t.displayName,description:"CodeVibe broker compatibility model metadata.",default_reasoning_level:"medium",supported_reasoning_levels:tye,shell_type:"shell_command",visibility:t.slug==="codex-auto-review"?"hide":"list",supported_in_api:t.supportedInApi,priority:t.priority,additional_speed_tiers:[],service_tiers:[],availability_nux:null,upgrade:null,base_instructions:"You are Codex, a coding agent.",model_messages:null,supports_reasoning_summaries:!1,default_reasoning_summary:"none",reasoning_summary_format:null,support_verbosity:!0,default_verbosity:"low",apply_patch_tool_type:"freeform",web_search_tool_type:"text",truncation_policy:{mode:"tokens",limit:1e4},supports_parallel_tool_calls:!0,supports_image_detail_original:!1,context_window:128e3,max_context_window:128e3,auto_compact_token_limit:null,comp_hash:null,effective_context_window_percent:95,experimental_supported_tools:[],input_modalities:["text"],supports_search_tool:!0,use_responses_lite:!1}))}}}function N9(t,e){return e.class==="oauth_bundle"?{authorization:`Bearer ${e.material.access_token}`,"ChatGPT-Account-Id":e.material.account_id}:t==="anthropic"?e.class==="subscription_token"?{authorization:`Bearer ${e.material}`}:{"x-api-key":e.material,authorization:`Bearer ${e.material}`}:{authorization:`Bearer ${e.material}`}}function iye(t,e){return t==="anthropic"&&e.startsWith("sk-ant-oat")?{class:"subscription_token",material:e}:{class:"api_key",material:e}}function oye(t){return t.class==="oauth_bundle"?[t.material.access_token,t.material.refresh_token]:[t.material]}function sye(t){return t.class==="oauth_bundle"?t.material.refresh_token:t.material}function aye(t,e,r){return`${t}-${e}-${r}`}function cye(t){let e=(o,s)=>Object.prototype.hasOwnProperty.call(o,s)?o[s]:void 0;if(t===void 0)return;if(typeof t=="string")return{kind:"string",bytes:t.length};if(t===null)return{kind:"null"};if(Array.isArray(t))return{kind:"array"};if(typeof t!="object")return{kind:typeof t};let r=e(t,"error");if(typeof r=="string")return{kind:"string-error",bytes:r.length};let n=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:t,i={};for(let o of["message","type","code"]){let s=e(n,o);typeof s=="string"&&(i[o]=s.length)}return{kind:"object",nestedError:n!==t,fields:i}}var M9,L9,B9,F9,Xge,Zge,eye,NB,tye,rye,Km,$9=D(()=>{"use strict";M9=require("node:crypto"),L9=F(require("node:http")),B9=require("node:stream"),F9=require("node:stream/promises");Ye();AB();EP();PB();xB();Du();VS();xP();DB();kc();IB();Xge=1500*1e3,Zge=5e3,eye=12e4,NB=class extends B9.PassThrough{constructor(r,n){super({autoDestroy:!0});this.idleMs=r;this.onIdle=n;this.disarmed=!1}_construct(r){this.arm(),r()}_transform(r,n,i){this.arm(),i(null,r)}_destroy(r,n){this.disarm(),n(r)}arm(){this.disarmed||(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(this.onIdle,this.idleMs),this.idleTimer.unref?.())}disarm(){this.disarmed=!0,this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0)}},tye=[{effort:"low",description:"Fast responses with lighter reasoning"},{effort:"medium",description:"Balances speed and reasoning depth for everyday tasks"},{effort:"high",description:"Greater reasoning depth for complex problems"},{effort:"xhigh",description:"Extra high reasoning depth for complex problems"}],rye=[{slug:"gpt-5.5",displayName:"GPT-5.5",priority:7,supportedInApi:!0},{slug:"gpt-5.4",displayName:"GPT-5.4",priority:16,supportedInApi:!0},{slug:"gpt-5.4-mini",displayName:"GPT-5.4-Mini",priority:23,supportedInApi:!0},{slug:"gpt-5.3-codex",displayName:"GPT-5.3-Codex",priority:26,supportedInApi:!0},{slug:"gpt-5.2",displayName:"GPT-5.2",priority:35,supportedInApi:!0},{slug:"codex-auto-review",displayName:"Codex Auto Review",priority:43,supportedInApi:!0}];Km=class{constructor(e){this.tokenMinter=new Wm;this.server=null;this.boundAddr=null;this.upstreamKeys=new Map;this.issuanceIds=new Map;this.issuanceCounter=0;this.credentialGeneration=new Map;this.inflightRefresh=new Map;this.stopping=!1;this.lifecycleGeneration=0;this.ops=new Set;this.taskId=e.taskId,this.upstreamClient=e.upstreamClient,this.vendorKeyStore=e.vendorKeyStore??new Ii,this.auditSink=e.auditSink??new Um,this.brokerId=`broker-${process.pid}-${Date.now()}`,this.refreshTransport=e.refreshTransport??new qm,this.oauthLock=e.oauthLock,this.proactiveThresholdMs=e.proactiveRefreshThresholdMs??Xge,this.stopDrainTimeoutMs=e.stopDrainTimeoutMs??Zge,this.nowFn=e.now??Date.now,this.delayFn=e.delay??(r=>new Promise(n=>setTimeout(n,r)))}getOAuthLock(e){return this.oauthLock||(this.oauthLock=Ti({lockDir:vc(`vendor-oauth-${e}`)})),this.oauthLock}async start(){this.tokenMinter.mint();let e=L9.createServer((n,i)=>{this.handleHttp(n,i)});await new Promise((n,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>{e.removeListener("error",i),n()})});let r=e.address();return this.server=e,this.boundAddr=`127.0.0.1:${r.port}`,w.info(`[Broker] Started model gateway on ${this.boundAddr}`,{taskId:this.taskId}),{hostBrokerAddr:this.boundAddr}}async healthz(){return this.server!==null}async stop(){let e=!this.stopping;this.stopping=!0,e&&(this.lifecycleGeneration+=1);let r=[...this.ops];r.length>0&&await Promise.race([Promise.allSettled(r.map(i=>i.done)),this.delayFn(this.stopDrainTimeoutMs)]);let n=[...this.ops];for(let i of n)try{i.controller.abort()}catch{}if(await Promise.allSettled(n.map(i=>i.done)),this.upstreamKeys.clear(),this.credentialGeneration.clear(),this.inflightRefresh.clear(),this.tokenMinter.clear(),this.server){let i=this.server;this.server=null,this.boundAddr=null,await new Promise(o=>i.close(()=>o()))}w.info("[Broker] Stopped + zeroized upstream credentials",{taskId:this.taskId})}registerOp(){let e,r=new Promise(i=>{e=i}),n={controller:new AbortController,done:r,resolveDone:e,lifecycleGen:this.lifecycleGeneration};return this.ops.add(n),n}deregisterOp(e){this.ops.delete(e),e.resolveDone()}isStale(e){return this.lifecycleGeneration!==e.lifecycleGen}currentBrokerToken(){return this.tokenMinter.get()}rotateBrokerToken(){return this.server===null?null:this.tokenMinter.rotateWithGrace()}commitBrokerTokenRotation(e){this.tokenMinter.commitRotation(e)}rollbackBrokerTokenRotation(e){this.tokenMinter.rollbackRotation(e)}getVendorKey(e){return this.vendorKeyStore.getVendorKey(e)}setVendorKey(e,r){return this.vendorKeyStore.setVendorKey(e,r)}clearVendorKey(e){return this.vendorKeyStore.clearVendorKey(e)}getVendorOAuthBundle(e){return this.vendorKeyStore.getVendorOAuthBundle(e)}setVendorOAuthBundle(e,r){return this.vendorKeyStore.setVendorOAuthBundle(e,r)}clearVendorOAuthBundle(e){return this.vendorKeyStore.clearVendorOAuthBundle(e)}async handle(e,r){let n=QS.find(o=>o.method===e.method&&o.path===e.path);if(!n)return{status:403,body:{error:"forbidden"}};if(n.path==="/healthz")return{status:200,body:{ok:!0}};if(n.path==="/models"||n.path==="/v1/models")return nye();if(!this.tokenMinter.authenticate(e.brokerToken))return{status:401,body:{error:"invalid broker token"}};let i=kP(e.path);return i?this.gateway(i,e,r):{status:403,body:{error:"forbidden"}}}async gateway(e,r,n){let i=this.registerOp(),o={signal:i.controller.signal,lifecycleGen:i.lifecycleGen};try{return this.stopping?{status:503,body:{error:"broker stopping"}}:await this.gatewayInner(e,r,o,i,n)}finally{this.deregisterOp(i)}}async gatewayInner(e,r,n,i,o){let s=await this.loadVendorCredential(e,n);if(s===null)return{status:503,body:{error:"no upstream credential"}};if(s.class==="oauth_bundle"&&this.isProactiveDue(s.material)){let S=await this.refreshOAuth(e,n,"proactive");if(S.kind==="rotated"||S.kind==="adopted")s={class:"oauth_bundle",material:S.bundle};else{if(S.kind==="revoked")return{status:503,body:{error:"no upstream credential"}};if(S.kind==="permanent")return this.permanentRefreshResponse()}}let a;try{a=IP({provider:e,request:r,agentHeaders:r.agentHeaders,agentQuery:r.agentQuery,agentContentType:r.agentContentType})}catch(S){if(S instanceof et)return w.warn("[broker] rejected non-canonical model request",{provider:e,reason:S.reason}),{status:400,body:{error:S.reason}};throw S}let{modelCallId:c,requestSha256:l}=a,d=[...oye(s),...this.tokenMinter.acceptedValues()],u=AP(a.body,d),p=KI(u.body);for(let S of u.leakedPaths)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:S,pattern_class:"self_credential"}))return{status:503,body:{error:"audit unavailable"}};for(let S of u.keyScrubs)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:S.field,pattern_class:S.patternClass}))return{status:503,body:{error:"audit unavailable"}};for(let S of p.findings)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:S.field,pattern_class:S.patternClass}))return{status:503,body:{error:"audit unavailable"}};if(!await this.emitGated("model_call",{agent:e,model:this.extractModel(p.scrubbed),model_call_id:c,request_sha256:l,credential_issuance_id:this.lastIssuanceId(e)}))return{status:503,body:{error:"audit unavailable"}};let m=this.genOf(e),f=s,g=this.buildUpstreamTarget(e,f,a.headers,a.upstreamUrl),y=!1;try{for(;;){let S=await this.upstreamClient.post({url:g.url,headers:g.headers,body:p.scrubbed,signal:n.signal}),b=(S.headers["content-type"]??"").toLowerCase().trim(),v=b.length===0,R=b.startsWith("text/event-stream"),E=g.assumeSseOn200,I=S.status===200&&!!o&&(R||v&&E);if(w.info("[Broker] forward decision",{taskId:this.taskId,modelCallId:c,status:S.status,ctAbsent:v,isSse:R,assumeSse:E,decision:I?"streamed":"buffered"}),I&&o)return await this.streamForward(S,o,n,i,c);let k=await S.readText(),P;try{P=k.length?JSON.parse(k):void 0}catch{P=void 0}if(!y&&f.class==="oauth_bundle"&&S.status===401){y=!0;let C=await this.refreshOAuth(e,n,"reactive",m);if(C.kind==="rotated"||C.kind==="adopted"){f={class:"oauth_bundle",material:C.bundle},g=this.buildUpstreamTarget(e,f,a.headers,a.upstreamUrl);continue}if(C.kind==="permanent"){let T=this.permanentRefreshResponse();return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"refresh_permanent"}),T}if(C.kind==="revoked"){let T={status:503,body:{error:"no upstream credential"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"revoked"}),T}}let A=this.mapUpstream({status:S.status,body:P});return await this.emitBestEffort("model_call_result",{model_call_id:c,result:A.status===200?"ok":`upstream_${S.status}`,...this.extractUsage(P)}),A}}catch{let S={status:502,body:{error:"upstream forward failed"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"forward_error"}),S}}async streamForward(e,r,n,i,o){let s,a;try{s=e.bodyStream();let c=(e.headers["content-type"]??"").trim();return r.writeHead(200,{"content-type":c.length?e.headers["content-type"]:"text/event-stream"}),a=new NB(eye,()=>i.controller.abort()),await(0,F9.pipeline)(s,a,r,{signal:n.signal}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"ok_streamed",usageSource:"unavailable_streamed"}),{kind:"handled"}}catch(c){return a?.destroy(),s&&(s.on("error",()=>{}),s.destroy()),i.controller.abort(),r.headersSent?(r.destroy(),w.warn("[Broker] streaming forward failed after headers sent",{errorShape:c instanceof Error?{name:c.name}:{kind:typeof c}}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"stream_error",usageSource:"unavailable_streamed"}),{kind:"handled"}):(await this.emitBestEffort("model_call_result",{model_call_id:o,result:"forward_error",usageSource:"unavailable_streamed"}),{status:502,body:{error:"upstream forward failed"}})}}buildUpstreamTarget(e,r,n,i){if(r.class==="oauth_bundle"){let s={...n,...up.synthesizedHeaders,...N9(e,r)};return{url:TP(),headers:s,assumeSseOn200:up.assumeSseOn200}}let o={...n,...N9(e,r)};if(e==="anthropic"&&r.class==="subscription_token"){let s=o["anthropic-beta"];o["anthropic-beta"]=s?s.includes("oauth-2025-04-20")?s:`${s},oauth-2025-04-20`:"oauth-2025-04-20"}return{url:i,headers:o,assumeSseOn200:!1}}async loadVendorCredential(e,r){let n=this.upstreamKeys.get(e);if(n!==void 0)return n;let i=await this.vendorKeyStore.getVendorKey(e),o=null;if(i!==null)o=iye(e,i);else if(e==="openai"){let a=await this.vendorKeyStore.getVendorOAuthBundle(e);a&&(o={class:"oauth_bundle",material:a})}if(o===null)return null;if(this.isStale(r)||this.stopping)return o;this.upstreamKeys.set(e,o),o.class==="oauth_bundle"&&!this.credentialGeneration.has(e)&&this.credentialGeneration.set(e,0),this.issuanceCounter+=1;let s=aye(this.brokerId,e,this.issuanceCounter);return this.issuanceIds.set(e,s),await this.emitBestEffort("broker_credential_loaded",{provider:e,key_fingerprint:(0,M9.createHash)("sha256").update(sye(o)).digest("hex").slice(0,16),credential_issuance_id:s}),o}genOf(e){return this.credentialGeneration.get(e)??0}currentBundle(e){let r=this.upstreamKeys.get(e);return r&&r.class==="oauth_bundle"?r.material:null}isProactiveDue(e){let r=Date.parse(e.last_refresh);return Number.isNaN(r)?!1:this.nowFn()-r>=this.proactiveThresholdMs}adoptBundle(e,r,n){this.isStale(n)||this.stopping||(this.upstreamKeys.set(e,{class:"oauth_bundle",material:r}),this.credentialGeneration.set(e,this.genOf(e)+1))}async refreshOAuth(e,r,n,i){if(n==="reactive"&&i!==void 0&&i<this.genOf(e)){let s=this.currentBundle(e);return s?{kind:"adopted",bundle:s}:{kind:"transient",reason:"gen_advanced_but_absent"}}let o=this.inflightRefresh.get(e);return o||(o=this.doRefreshUnderLock(e,r).finally(()=>{this.inflightRefresh.delete(e)}),this.inflightRefresh.set(e,o)),o}async doRefreshUnderLock(e,r){let n=this.getOAuthLock(e),i;try{i=await n.acquire()}catch{return{kind:"transient",reason:"lock_unavailable"}}try{let o=await this.vendorKeyStore.getVendorOAuthBundle(e);if(!o)return{kind:"revoked",reason:"cleared"};let s=this.currentBundle(e);if(s&&o.access_token!==s.access_token)return this.adoptBundle(e,o,r),{kind:"adopted",bundle:o};let a=await OP(o,this.refreshTransport,{signal:r.signal});return a.kind==="permanent"?{kind:"permanent",reason:a.reason}:a.kind==="transient"?{kind:"transient",reason:a.reason}:this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:await i.reassertOwnership()?this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:(await this.vendorKeyStore.setVendorOAuthBundle(e,a.bundle),this.adoptBundle(e,a.bundle,r),{kind:"rotated",bundle:a.bundle}):{kind:"transient",reason:"ownership_lost"}}finally{await i.release()}}lastIssuanceId(e){return this.issuanceIds.get(e)??""}permanentRefreshResponse(){return{status:502,body:{error:"upstream auth failed",remediation:"re-run: codevibe vendor-key import-codex"}}}mapUpstream(e){return e.status!==200&&w.warn("[Broker] upstream non-200",{status:e.status,errorShape:cye(e.body)}),e.status===401||e.status===403?{status:502,body:{error:"upstream auth failed"}}:e.status===200?{status:200,body:e.body}:{status:502,body:{error:`upstream_${e.status}`}}}extractModel(e){if(e!==null&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"model")){let r=e.model;if(typeof r=="string")return r}return"unknown"}extractUsage(e){if(e===null||typeof e!="object")return{};let r=e.usage;if(r===null||typeof r!="object")return{};let n=r,i={};return typeof n.input_tokens=="number"&&(i.prompt_tokens=n.input_tokens),typeof n.output_tokens=="number"&&(i.completion_tokens=n.output_tokens),typeof n.prompt_tokens=="number"&&(i.prompt_tokens=n.prompt_tokens),typeof n.completion_tokens=="number"&&(i.completion_tokens=n.completion_tokens),i}async emitGated(e,r){try{return"ack"in await this.auditSink.emit(e,r)}catch{return!1}}async emitBestEffort(e,r){try{await this.auditSink.emit(e,r)}catch{}}async handleHttp(e,r){try{let n=e.method??"GET",i=new URL(e.url??"/","http://127.0.0.1"),o=i.pathname,s={};for(let[p,h]of Object.entries(e.headers))typeof h=="string"?s[p.toLowerCase()]=h:Array.isArray(h)&&(s[p.toLowerCase()]=h.join(","));let a={};for(let[p,h]of i.searchParams.entries())a[p]=h;let c=this.extractBrokerToken(s),l,d=!1;if(n==="POST"){let p=await this.readBody(e);if(p.length>0)try{l=JSON.parse(p)}catch{d=!0}}if(d&&QS.some(p=>p.method===n&&p.path===o)){this.writeJson(r,400,{error:"malformed JSON body"});return}let u=await this.handle({method:n,path:o,brokerToken:c,body:l,agentHeaders:s,agentQuery:a,agentContentType:s["content-type"]},r);if("kind"in u)return;this.writeJson(r,u.status,u.body)}catch(n){w.error("[Broker] HTTP handler error",{error:n instanceof Error?n.message:String(n)}),r.headersSent?r.destroy():this.writeJson(r,502,{error:"broker internal error"})}}extractBrokerToken(e){if(e["x-api-key"])return e["x-api-key"];let r=e.authorization;if(r&&r.toLowerCase().startsWith("bearer "))return r.slice(7).trim()}readBody(e){return new Promise((r,n)=>{let i=[];e.on("data",o=>i.push(o)),e.on("end",()=>r(Buffer.concat(i).toString("utf8"))),e.on("error",n)})}writeJson(e,r,n){let i=JSON.stringify(n??{});e.writeHead(r,{"content-type":"application/json"}),e.end(i)}}});function G9(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}var MB,lye,jm,U9=D(()=>{"use strict";MB=require("node:stream");Ye();lye=12e4;jm=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??lye,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=e.signal,a=()=>i.abort();s&&(s.aborted?i.abort():s.addEventListener("abort",a,{once:!0}));let c=!1,l=()=>{c||(c=!0,s&&s.removeEventListener("abort",a))},d;try{d=await r(e.url,{method:"POST",headers:{...e.headers},body:JSON.stringify(e.body),redirect:"error",signal:i.signal})}catch(f){throw clearTimeout(o),l(),w.warn(`[UpstreamClient] transport error POSTing ${G9(e.url)}`,{code:f?.code}),new Error("upstream transport error")}clearTimeout(o),w.debug(`[UpstreamClient] POST ${G9(e.url)} -> ${d.status}`);let u={};d.headers.forEach((f,g)=>{u[g.toLowerCase()]=f});let p=d,h=!1,m=()=>{if(h)throw new Error("UpstreamResult body already consumed (bodyStream/readText are one-shot; LOCK #643-1)");h=!0};return{status:p.status,headers:u,bodyStream(){if(m(),p.body===null)return l(),MB.Readable.from([]);let f=MB.Readable.fromWeb(p.body);return f.once("close",l),f},async readText(){m();let f=setTimeout(()=>i.abort(),n);s?.aborted&&i.abort();try{return await p.text()}catch{throw new Error("upstream transport error")}finally{clearTimeout(f),l()}}}}}});var LB={};jr(LB,{BROKER_ROUTES:()=>QS,BrokerTokenMinter:()=>Wm,CHATGPT_OAUTH_CLIENT_ID:()=>_P,CHATGPT_REFRESH_CONTENT_TYPE:()=>CP,CHATGPT_TOKEN_ENDPOINT:()=>PP,CHATGPT_UPSTREAM_CONFIG:()=>up,CanonicalRejectError:()=>et,FetchRefreshTransport:()=>qm,FetchUpstreamClient:()=>jm,KeychainVendorKeyStore:()=>Ii,LocalModelGatewayBroker:()=>Km,OAuthAccountLock:()=>sg,StubStrictAuditSink:()=>Um,buildCanonicalRequest:()=>IP,buildRefreshBody:()=>OB,chatGptUpstreamUrl:()=>TP,createOAuthAccountLock:()=>Ti,defaultOAuthLockDir:()=>vc,getProviderConfig:()=>Hm,providerForPath:()=>kP,refreshOAuthToken:()=>OP,requestSha256:()=>CB,scrubRequestBody:()=>KI,selfCredentialGuard:()=>AP});var DP=D(()=>{"use strict";IB();$9();U9();AB();VS();PB();xP();DB();kc();xB();Du();EP()});function NP(t){let e={},r=process.execPath.slice(0,process.execPath.lastIndexOf("/"));e.PATH=`${t.path??ZS}:${r}`,e.HOME=t.sandboxHome;let n=t.safeSource??{};for(let i of XS){let o=n[i];typeof o=="string"&&o.length>0&&(e[i]=o)}return t.provider==="anthropic"?e.ANTHROPIC_BASE_URL=t.sandboxBrokerUrl:e.OPENAI_BASE_URL=`${t.sandboxBrokerUrl.replace(/\/+$/,"")}/v1`,t.provider==="anthropic"?(e.CLAUDE_CONFIG_DIR=t.sandboxBootstrapDir,e.CLAUDE_CODE_TMPDIR=t.claudeScratchDir??t.sandboxBootstrapDir):e.CODEX_HOME=t.sandboxBootstrapDir,e}function ev(t){let e=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL"]);for(let r of Object.keys(t))if(!e.has(r)){for(let n of dye)if(n.test(r))throw new Error(`sanitizedEnv I1 violation: credential-shaped key "${r}" present in the agent env \u2014 refusing to launch (allow-list bug)`)}}var XS,ZS,dye,BB=D(()=>{"use strict";XS=["LANG","LC_ALL","LC_CTYPE","TERM","TZ"],ZS="/usr/local/bin:/usr/bin:/bin";dye=[/^ANTHROPIC_API_KEY$/i,/^ANTHROPIC_AUTH_TOKEN$/i,/^OPENAI_API_KEY$/i,/_API_KEY$/i,/_SECRET$/i,/_SECRET_ACCESS_KEY$/i,/^AWS_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/^GOOGLE_/i,/_TOKEN$/i,/^SSH_/i]});function $B(t){return t==="CLAUDE"?"anthropic":t==="CODEX"?"openai":null}function FB(t,e){if(t===e)return!0;let r=gn.relative(e,t);return r.length>0&&!r.startsWith("..")&&!gn.isAbsolute(r)}function fye(t){let e=t.split(gn.sep);for(let i=e.length-2;i>=0;i--)if(e[i]===hye&&e[i+1]===pye){let o=[...e];return o[i+1]=uye,gn.join(o.join(gn.sep),H9)}let r=gn.dirname(t),n=gn.basename(t);return gn.join(r,".codevibe-audit",n,H9)}async function mye(t,e){let r;try{r=await pp.promises.realpath(e)}catch{throw new Error(`CP-7 W3: cannot realpath workdir "${e}" \u2014 refusing to launch (audit containment fail-closed)`)}let n=gn.dirname(t);await pp.promises.mkdir(n,{recursive:!0});let i;try{i=await pp.promises.realpath(n)}catch{throw new Error(`CP-7 W3: cannot realpath audit dir "${n}" \u2014 refusing to launch (fail-closed)`)}let o=gn.join(i,gn.basename(t)),s;try{s=await pp.promises.lstat(o)}catch{s=void 0}let a=o;if(s?.isSymbolicLink())try{a=await pp.promises.realpath(o)}catch{throw new Error(`CP-7 W3: audit leaf "${o}" is a symlink that does not resolve (dangling) \u2014 refusing to launch (fail-closed). The audit file must be a regular file in the sibling .codevibe/audit/ tree.`)}if(FB(i,r)||FB(o,r)||FB(a,r))throw new Error(`CP-7 W3: audit path "${o}" (resolved target "${a}") is inside the agent workdir "${r}" \u2014 the agent could truncate/forge the forensic record (Stage-1 r1 HIGH fail-closed). The audit MUST live in the sibling .codevibe/audit/ tree, never under .codevibe/state/<group>/<track>/.`);return o}async function Vm(t){if(t.webBrowsingActive)return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`Agent web browsing active for ${t.agentKind} \u2014 running in reduced-trust mode with shadow-diff capture and guarded web tools`,teardown:async()=>{}};let e=$B(t.agentKind);if(e===null)return t.requireConfined?yye(t):{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${t.agentKind} is a reduced-trust agent (\xA76 Q4) \u2014 no vendor broker; runs on the legacy spawn path with shadow-diff capture`,teardown:async()=>{}};let r=await Wu(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:r.reducedTrustReason,teardown:async()=>{}};let n,i=null;if(t.brokerDeps?.auditSink)n=t.brokerDeps.auditSink;else{let y=t.auditPath??fye(t.workdir),S=await mye(y,t.workdir);i=gn.dirname(S),n=new Tu(t.taskId,S)}let o=t.upstreamClient??new jm,s=(t.makeBroker??(y=>new Km(y)))({taskId:t.taskId,upstreamClient:o,...t.brokerDeps?.vendorKeyStore?{vendorKeyStore:t.brokerDeps.vendorKeyStore}:{},auditSink:n}),a;try{({hostBrokerAddr:a}=await s.start())}catch(y){let S=Object.assign(new Error("CP-7: broker failed to start \u2014 refusing to launch the implementor (fail-closed)"),{cause:y});try{await s.stop()}catch(b){throw Object.assign(new Error("CP-7: broker start failed and cleanup also failed"),{causes:[S,b]})}throw S}let c=s.currentBrokerToken();if(!c){let y=new Error("CP-7: broker minted no token \u2014 refusing to launch (fail-closed)");try{await s.stop()}catch(S){throw Object.assign(new Error("CP-7: broker minted no token and cleanup also failed"),{causes:[y,S]})}throw y}let l=c.value,d=r.tier==="docker"?`http://127.0.0.1:${cm}`:`http://${a}`,u=r.tier==="docker"?Qb:t.workdir,p=r.tier==="docker"?NR:null,h=r.tier==="docker"?GD:null,m,f,g;try{m=await pf.create({provider:e,sandboxBrokerUrl:d,initialToken:l,...p!==null?{sandboxDir:p,sandboxConfigDir:h??GD}:{sandboxDirEqualsHostDir:!0,configDirEqualsHostDir:!0},hostRoot:t.bootstrapHostRoot,...r.tier==="sandbox_exec"&&e==="anthropic"?{claudeScratchHostRoot:t.claudeScratchHostRoot??"/tmp"}:{},workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{}});let y=p!==null?{hostDir:m.hostDir,sandboxDir:p}:{hostDir:m.hostDir,sandboxDir:m.hostDir},S=h!==null?{hostDir:m.configHostDir,sandboxDir:h}:{hostDir:m.configHostDir,sandboxDir:m.configHostDir},b=m.claudeScratchSpec,v=NP({provider:e,sandboxBrokerUrl:d,sandboxHome:u,sandboxBootstrapDir:S.sandboxDir,...b!==null?{claudeScratchDir:b.sandboxDir}:{},safeSource:t.localeSource});ev(v);let R=AD(t.role,v,t.processTreeId),E={isolationTech:r.tier==="docker"?"docker":"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:a,sandboxBrokerUrl:d,taskId:t.taskId,sanitizedEnv:R,agentBootstrap:y,agentConfig:S,...b!==null?{agentScratch:b}:{},...i!==null?{auditDir:i}:{}};f=await r.substrate.launch(E),w.info(`[CP-7] Substrate engaged (tier=${r.tier}, egress=${f.egressFidelity}) \u2014 agent is creditless, broker holds the key`,{taskId:t.taskId,agent:t.agentKind});let I=m,k=f,P=s,A=null,C,T=()=>C||(C=(async()=>{A&&(clearInterval(A),A=null);let N=[];for(let $ of[()=>k.teardown(),()=>P.stop(),()=>I.destroy()])try{await $()}catch(L){N.push(L)}if(N.length>0)throw w.warn("[CP-7] substrate cleanup failed \u2014 task cannot pass",{taskId:t.taskId,failureCount:N.length,...Rn(N[0])}),N.length===1?N[0]:Object.assign(new Error("CP-7 substrate cleanup failed"),{causes:N})})(),C);g=T;let _=`launch-${t.taskId}-${Date.now()}`,O=k.egressFidelity==="strict"?"structural_deny_network_none":"coarse_loopback_only",V;try{V=await n.emit("egress_denied",{destination:"*",protocol:"all",denial_reason:O,caller_event_id:_})}catch(N){throw Object.assign(new Error("CP-7 W3: egress-posture audit emit failed \u2014 refusing to launch the creditless agent (audit-before-effect fail-closed)"),{cause:N})}if(!("ack"in V))throw new Error("CP-7 W3: egress-posture audit was rejected \u2014 refusing to launch the creditless agent (no durable egress posture \u2192 no agent)");let z=t.tokenRefreshIntervalMs??600*1e3,H=null,W=async()=>{if(!(typeof P.rotateBrokerToken=="function"&&typeof P.commitBrokerTokenRotation=="function"&&typeof P.rollbackBrokerTokenRotation=="function")){let L=P.currentBrokerToken();L&&await I.refresh(L.value);return}let $=P.rotateBrokerToken();if($)try{await I.refresh($.token.value),P.commitBrokerTokenRotation($)}catch(L){P.rollbackBrokerTokenRotation($),w.warn("[CP-7] broker-token refresh write FAILED \u2014 rolled back to the prior token and tearing down (fail-closed)",{taskId:t.taskId,...Rn(L)});let K=Object.assign(new Error("CP-7 broker-token refresh failed"),{cause:L});try{await T()}catch(re){throw Object.assign(new Error("CP-7 broker-token refresh failed and cleanup also failed"),{causes:[K,re]})}throw K}},Z=async()=>{let $=(H??Promise.resolve()).catch(()=>{}).then(()=>W());H=$;try{await $}finally{H===$&&(H=null)}};return z>0&&(A=setInterval(()=>{Z().catch(()=>{})},z),A.unref?.()),{mode:"substrate",tier:r.tier,reducedTrust:r.reducedTrust,reducedTrustReason:r.tier==="sandbox_exec"?r.reducedTrustReason:void 0,substrateHandle:k,agentConfigDir:S.sandboxDir,finalEnv:R,refreshBrokerToken:Z,teardown:T}}catch(y){let S=y instanceof Error?y:new Error("CP-7 substrate launch failed"),b=[];if(g)try{await g()}catch(v){b.push(v)}else for(let v of[...f?[()=>f.teardown()]:[],...m?[()=>m.destroy()]:[],()=>s.stop()])try{await v()}catch(R){b.push(R)}throw b.length>0?(w.warn("[CP-7] failed launch also failed cleanup",{taskId:t.taskId,failureCount:b.length,...Rn(b[0])}),Object.assign(new Error("CP-7 substrate launch failed and cleanup also failed"),{causes:[S,...b]})):S}}async function yye(t){let e=t.agentKind;if(e!=="GEMINI"&&e!=="ANTIGRAVITY")throw new Error(`engageWriteConfinedResolverSandbox: unmapped broker-less agent ${e}`);let r=await Wu(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable \u2014 no sandbox substrate on this host (${r.reducedTrustReason}); the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};if(r.tier==="docker")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable on the docker tier \u2014 the A1 image cannot carry the host-installed ${e} binary + its file-based auth; the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};let n=W9.homedir(),i=gn.join(n,...gye[e]);await pp.promises.mkdir(i,{recursive:!0}).catch(()=>{});let o={},s=process.execPath.slice(0,process.execPath.lastIndexOf("/"));o.PATH=`${ZS}:${s}`,o.HOME=n;let a=t.localeSource??{};for(let u of XS){let p=a[u];typeof p=="string"&&p.length>0&&(o[u]=p)}ev(o);let c=AD(t.role,o,t.processTreeId),l={isolationTech:"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:"",sandboxBrokerUrl:"",taskId:t.taskId,sanitizedEnv:c,agentConfig:{hostDir:i,sandboxDir:i},networkPosture:"open"},d=await r.substrate.launch(l);return w.info(`[A1d] Resolver-confinement row engaged (tier=sandbox_exec, egress=open) \u2014 writes fenced to the disposable workspace; ${e} runs on its own file-based auth (no broker)`,{taskId:t.taskId,agent:e}),{mode:"substrate",tier:"sandbox_exec",reducedTrust:!0,reducedTrustReason:`${e} class-2 resolver: write-confined to the disposable merge workspace (A5 Seatbelt); egress OPEN (broker-less \u2014 the agent dials its vendor directly with its own file-based auth)`,substrateHandle:d,agentConfigDir:i,finalEnv:c,refreshBrokerToken:async()=>{},teardown:async()=>{await d.teardown().catch(()=>{})}}}var pp,W9,gn,uye,pye,hye,H9,gye,q9=D(()=>{"use strict";pp=require("node:fs"),W9=F(require("node:os")),gn=F(require("node:path"));DP();qO();MI();Ye();RR();SA();wA();MR();vA();BB();uye="audit",pye="state",hye=".codevibe",H9="audit.jsonl";gye={GEMINI:[".gemini"],ANTIGRAVITY:[".gemini","antigravity-cli"]}});function MP(t){return bye.has(t.toUpperCase())||Sye.test(t)?!1:wye.some(e=>e.test(t))}function GB(t){return Object.keys(t).filter(MP)}function UB(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(MP(r)||(e[r]=n));return e[tv]="1",e}function LP(t={}){let e=t.platform??process.platform,r=t.env??process.env,n=t.exit??(u=>process.exit(u));if(e!=="darwin")return!1;let i=GB(r);if(i.length===0)return!1;if(r[tv])throw new Error(`[le-env-scrub] Refusing to launch the Local Executor: the scrub marker (${tv}) is set but credential-shaped env vars are still present (${i.join(", ")}). A genuine re-exec'd child has NO credential-shaped vars; this indicates a spoofed marker or a broken scrub. Fail closed (CP-7 I1, A5 parent-procargs vector) \u2014 never launch the LE with a vendor credential in its exec-time procargs.`);let o=t.spawnSyncFn??K9.spawnSync,s=t.execPath??process.execPath,a=t.argv??process.argv.slice(1),c=t.cwd??process.cwd(),l=UB(r);try{t.onScrub?.(i)}catch{}let d=o(s,a,{env:l,stdio:"inherit",cwd:c});return d.signal?n(1):n(d.status??1),!0}var K9,tv,wye,bye,Sye,j9=D(()=>{"use strict";K9=require("node:child_process"),tv="CODEVIBE_LE_ENV_SCRUBBED",wye=[/^ANTHROPIC_/i,/^OPENAI_/i,/^GOOGLE_/i,/^GEMINI_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/_API_KEY$/i,/_ACCESS_KEY_ID$/i,/_SECRET_ACCESS_KEY$/i,/_SECRET$/i,/_TOKEN$/i],bye=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL","GOOGLE_BASE_URL"]),Sye=/_BASE_URL$/i});var HB={};jr(HB,{ApiKeyBootstrap:()=>pf,CODEX_PROVIDER_ID:()=>Iw,CP7_CANONICAL_FORM_VERSION:()=>T0,Cp7AuditWriter:()=>Tu,GENESIS_PREV_HASH:()=>NI,HELPER_SCRIPT_NAME:()=>OR,IMPLEMENTOR_CREDENTIAL_MISSING:()=>hM,ImplementorCredentialMissingError:()=>Gu,LE_ENV_SCRUBBED_MARKER:()=>tv,REVIEWER_CREDENTIAL_MISSING:()=>Gb,ReviewerCredentialMissingError:()=>$u,SAFE_ENV_ALLOWLIST:()=>XS,SANDBOX_BOOTSTRAP_DIR:()=>NR,SANDBOX_DEFAULT_PATH:()=>ZS,TOKEN_FILE_NAME:()=>DR,assertImplementorVendorCredential:()=>qb,assertNoAmbientCreds:()=>ev,assertReviewerVendorCredential:()=>Wb,buildSanitizedBaseEnv:()=>NP,buildScrubbedLeEnv:()=>UB,canonicalEntryBytes:()=>fb,canonicalJson:()=>qf,computeEntryHash:()=>Kf,engageSubstrate:()=>Vm,findCredShapedKeys:()=>GB,implementorProviderFor:()=>Hb,isCredShapedEnvKey:()=>MP,providerForAgent:()=>$B,reviewerProviderFor:()=>Ub,scrubLeEnvOrReexec:()=>LP,selectSubstrate:()=>Wu,verifyChain:()=>P0,withImplementorCredentialPreflight:()=>Uu,withReviewerCredentialPreflight:()=>sm});var BP=D(()=>{"use strict";q9();vA();BB();MR();fM();j9();MI()});function rv(t,e,r){let n=zd(e.prompt_template,"AntigravityReviewerProvider"),i=[];e.model_hint!==null&&i.push("--model",e.model_hint);let o=Math.max(1,Math.floor(e.timeout_ms/1e3)-5);i.push("--print-timeout",`${o}s`),i.push("--add-dir",r),i.push("--print",n);let s=nt({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:i,env:s}}async function vye(t,e,r,n){if(!r.exit_success){let a=qu(r.stderr)??"spawn_failed";throw new Ft({kind:"spawn_failed",agent:t.agent,reason:`agy exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:a})}let i=r.stdout,o={verdict_id:(0,V9.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:null,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:kr("provider_unsupported",r.elapsed_ms)};if(n!==void 0){let a=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),c=gm(a,i);return{...o,...c}}let s=Pl(i);if(!s.ok)throw new Ft({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...o,verdict:s.verdict.kind,reasoning:s.verdict.reasoning,suggested_changes:s.verdict.suggested_changes,residual_observations:s.verdict.residual_observations}}var V9,zm,WB=D(()=>{"use strict";V9=require("uuid");af();fm();Tl();hm();tS();Xc();_A();mm();Or();zm=class{constructor(e={}){this.executable=e.executable??"agy"}async evaluate(e,r,n){if(e.agent!=="antigravity")throw new Error(`AntigravityReviewerProvider called with non-Antigravity spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);if(n?.substrate!==void 0)throw new Ft({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider received a substrate handle \u2014 agy is reduced-trust (never substrate-contained, \xA76 Q4); the loop must pre-route antigravity seats to the legacy path",failureReason:"spawn_failed"});let i=n?.workdir;if(i===void 0||i.length===0)throw new Ft({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider requires opts.workdir (agy is workspace-centric \u2014 without --add-dir it cannot read the repo); the evaluate site must thread the loop workingDir",failureReason:"spawn_failed"});let o;try{o=rv(this.executable,e,i)}catch(a){throw new Ft({kind:"spawn_failed",agent:e.agent,reason:a instanceof Error?a.message:String(a),failureReason:"spawn_failed"})}let s;try{s=await oa({command:o.command,args:o.args,env:o.env,prompt:"",timeout_ms:e.timeout_ms})}catch(a){throw a instanceof Pn?new Ft(ym(e.agent,a.detail)):a}return vye(e,r,s,n?.classifyVerdict)}}});function nv(t,e,r=!1){let n=[];n.push("--print"),n.push("--output-format","json"),n.push("--allowed-tools",e.tool_allowlist.join(",")),n.push("--tools",e.tool_allowlist.join(",")),n.push("--disallowed-tools","WebFetch,WebSearch,Agent,Task,Workflow,SendMessage,ListAgents"),n.push("--strict-mcp-config"),e.model_hint!==null&&n.push("--model",e.model_hint);let i=r?{}:nt({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:n,env:i}}async function kye(t,e,r,n){if(!r.exit_success){let c=pc(r.stdout)??qu(r.stderr)??"spawn_failed";throw new Ft({kind:"spawn_failed",agent:t.agent,reason:`claude exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:c})}let{text:i}=Oa(r.stdout),o=Pd(r.stdout,r.elapsed_ms),s={verdict_id:(0,z9.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:o.totalTokens,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:o};if(n!==void 0){let c=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),l=gm(c,i);return{...s,...l}}let a=Pl(i);if(!a.ok)throw new Ft({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...s,verdict:a.verdict.kind,reasoning:a.verdict.reasoning,suggested_changes:a.verdict.suggested_changes,residual_observations:a.verdict.residual_observations}}var z9,Jm,qB=D(()=>{"use strict";z9=require("uuid");fm();Tl();hm();tS();_A();mm();Xc();Or();Jm=class{constructor(e={}){this.executable=e.executable??"claude"}async evaluate(e,r,n){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 i=n?.substrate!==void 0,o=nv(this.executable,e,i),s;try{s=await oa({command:o.command,args:o.args,env:o.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms,...n?.substrate!==void 0?{substrate:n.substrate}:{}})}catch(a){throw a instanceof Pn?new Ft(ym(e.agent,a.detail)):a}return kye(e,r,s,n?.classifyVerdict)}}});function FP(){return new iv().with("claude",new Jm).with("codex",new wm).with("antigravity",new zm)}var iv,KB=D(()=>{"use strict";Tl();WB();qB();nS();iv=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,n){let i=this.providers.get(e.agent);if(i===void 0)throw new Ft({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 i.evaluate(e,r,n)}}});function Q9(){return{schemaVersion:1,choice:"not_configured",artifactId:null,ollamaModel:null,updatedAt:new Date(0).toISOString()}}function Eye(t=process.env){return t.NODE_ENV==="test"&&t.CODEVIBE_HOME_OVERRIDE?t.CODEVIBE_HOME_OVERRIDE:$P.default.join(Y9.default.homedir(),".codevibe")}function Rye(t=process.env){return $P.default.join(Eye(t),"local-model-state.json")}function J9(t){if(!t||typeof t!="object")return Q9();let e=t;return{schemaVersion:1,choice:e.choice==="skipped"||e.choice==="enabled"?e.choice:"not_configured",artifactId:typeof e.artifactId=="string"&&e.artifactId.trim()?e.artifactId:null,ollamaModel:typeof e.ollamaModel=="string"&&e.ollamaModel.trim()?e.ollamaModel:null,updatedAt:typeof e.updatedAt=="string"&&e.updatedAt?e.updatedAt:new Date(0).toISOString()}}async function VB(t=GP){return t.read()}async function zB(t,e=null,r=GP){await r.write({schemaVersion:1,choice:"enabled",artifactId:t,ollamaModel:e,updatedAt:new Date().toISOString()})}var ov,Y9,$P,jB,GP,JB=D(()=>{"use strict";ov=require("fs"),Y9=F(require("os")),$P=F(require("path"));jB=class{constructor(e=Rye()){this.filePath=e}async read(){try{let e=await ov.promises.readFile(this.filePath,"utf8");return J9(JSON.parse(e))}catch{return Q9()}}async write(e){await ov.promises.mkdir($P.default.dirname(this.filePath),{recursive:!0,mode:448}),await ov.promises.writeFile(this.filePath,`${JSON.stringify(J9(e),null,2)}
5883
+ ${X.green}\u2713${X.reset} Cleared ${f.length} entr${f.length===1?"y":"ies"}${C.length?` and ${C.length} task record(s)`:""}. Backup: ${E}`),T.length&&console.error(`${X.red}!${X.reset} ${T.length} task record(s) could not be backed up and were left in place. They name a cleared root and do nothing, but nothing was destroyed either \u2014 remove them by hand once you know why the copy failed.`),g.length&&console.log(`${X.dim} ${g.length} entr${g.length===1?"y was":"ies were"} left alone; re-run with --force if you mean to give those bytes up.${X.reset}`),!a){let _=await zS(e,s,u,l);if(fP(_))return 1}return console.log(" Tasks should start again in any CodeVibe session."),0}var yt,_r,RB,gP,X,Ume,vP=D(()=>{"use strict";yt=F(require("fs")),_r=F(require("path")),RB=F(require("crypto")),gP=require("child_process");Rs();oy();Nn();Ap();VS();Uo();Ua();Bs();$w();dl();X={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m"},Ume=[{agent:"CLAUDE",command:"claude",name:"Claude Code"},{agent:"CODEX",command:"codex",name:"Codex CLI"},{agent:"ANTIGRAVITY",command:"agy",name:"Antigravity CLI"}]});var QS,IB=D(()=>{"use strict";QS=[{method:"POST",path:"/v1/messages",auth:"broker_token"},{method:"POST",path:"/v1/responses",auth:"broker_token"},{method:"GET",path:"/healthz",auth:"none"},{method:"GET",path:"/models",auth:"none"},{method:"GET",path:"/v1/models",auth:"none"}]});var Um,AB=D(()=>{"use strict";Um=class{constructor(e={}){this.opts=e;this.emitted=[];this.counter=0}async emit(e,r){if(this.emitted.push({kind:e,payload:r}),this.opts.failKinds?.includes(e))throw new Error(`StubStrictAuditSink: simulated IPC failure for ${e}`);return this.opts.nackKinds?.includes(e)?{nack:`StubStrictAuditSink: simulated nack for ${e}`}:(this.counter+=1,{ack:`stub-ack-${this.counter}`})}ofKind(e){return this.emitted.filter(r=>r.kind===e)}}});function Hm(t){return jme[t]}function kP(t){return t==="/v1/messages"?"anthropic":t==="/v1/responses"?"openai":null}var qme,Kme,jme,EP=D(()=>{"use strict";qme="2023-06-01",Kme=new Set(["oauth-2025-04-20","claude-code-20250219","context-1m-2025-08-07","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","mid-conversation-system-2026-04-07","effort-2025-11-24","thinking-token-count-2026-05-13","per-turn-control-2026-07-01","mid-conversation-tool-changes-2026-07-01","dangerous-tool-use-2026-09-03"]),jme={anthropic:{upstreamBaseUrl:"https://api.anthropic.com",upstreamPath:"/v1/messages",synthesizedHeaders:{"anthropic-version":qme,"content-type":"application/json"},betaTokenAllowlist:Kme,betaHeaderName:"anthropic-beta"},openai:{upstreamBaseUrl:"https://api.openai.com",upstreamPath:"/v1/responses",synthesizedHeaders:{"content-type":"application/json"},betaTokenAllowlist:new Set,betaHeaderName:null}}});var TB,Vme,v9,Wm,PB=D(()=>{"use strict";TB=require("node:crypto"),Vme=1800*1e3,v9=32,Wm=class{constructor(e=Vme){this.ttlMs=e;this.current=null;this.graceToken=null;this.generation=0}mint(e=Date.now()){let r=(0,TB.randomBytes)(v9).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.graceToken=null,this.generation+=1,this.current}rotateWithGrace(e=Date.now()){if(this.current===null||this.graceToken!==null)return null;this.graceToken=this.current;let r=(0,TB.randomBytes)(v9).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.generation+=1,{token:this.current,generation:this.generation}}commitRotation(e){e!==void 0&&e.generation!==this.generation||(this.graceToken=null)}rollbackRotation(e){e!==void 0&&e.generation!==this.generation||this.graceToken!==null&&(this.current=this.graceToken,this.graceToken=null)}hasPendingGrace(){return this.graceToken!==null}get(){return this.current}acceptedValues(){let e=[];return this.current&&e.push(this.current.value),this.graceToken&&e.push(this.graceToken.value),e}authenticate(e,r=Date.now()){return e?!!(this.current&&r<this.current.expiresAtMs&&e===this.current.value||this.graceToken&&r<this.graceToken.expiresAtMs&&e===this.graceToken.value):!1}clear(){this.current=null,this.graceToken=null}}});function ke(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function CB(t){return(0,RP.createHash)("sha256").update(JSON.stringify(t)).digest("hex")}function It(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dp(t){return typeof t=="number"&&Number.isFinite(t)}function Wl(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function k9(t){if(!It(t))return!1;for(let e of Object.keys(t))if(typeof t[e]!="string")return!1;return!0}function E9(t){if(!It(t))return!1;let e=Object.keys(t);for(let r of e)if(!tge.has(r))return!1;return!(!ke(t,"path")||typeof t.path!="string"||!ke(t,"resolved")||!Wl(t.resolved)||ke(t,"source")&&t.source!==void 0&&typeof t.source!="string")}function R9(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!uge.has(e))return!1;return!(!ke(t,"host")||typeof t.host!="string"||!ke(t,"remote")||typeof t.remote!="string"||!ke(t,"visibility")||typeof t.visibility!="string"||!_9.has(t.visibility))}function xge(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!pge.has(e))return!1;return!(!ke(t,"name")||typeof t.name!="string"||!ke(t,"host")||typeof t.host!="string"||!ke(t,"remote")||typeof t.remote!="string"||!ke(t,"visibility")||typeof t.visibility!="string"||!_9.has(t.visibility))}function I9(t){if(!It(t))return!1;for(let e of Object.keys(t)){if(!sge.has(e))return!1;let r=t[e];if(e==="cwd"||e==="root"||e==="branch"||e==="default_branch"){if(r!=null&&typeof r!="string")return!1}else if(e==="error"){if(r!=null&&(typeof r!="string"||!age.has(r)))return!1}else if(e==="truncated"){if(r!==void 0&&typeof r!="boolean")return!1}else if(e==="status"){if(r!=null){if(!It(r))return!1;for(let n of Object.keys(r))if(!cge.has(n))return!1;if(!ke(r,"clean")||typeof r.clean!="boolean"||!ke(r,"truncated")||typeof r.truncated!="boolean"||!ke(r,"porcelain")||r.porcelain!==null&&typeof r.porcelain!="string"||!ke(r,"counts"))return!1;if(r.counts!==null){if(!It(r.counts))return!1;for(let n of Object.keys(r.counts))if(!lge.has(n))return!1;if(!ke(r.counts,"staged")||!dp(r.counts.staged)||!ke(r.counts,"modified")||!dp(r.counts.modified)||!ke(r.counts,"untracked")||r.counts.untracked!==null&&!dp(r.counts.untracked)||!ke(r.counts,"untracked_normal")||r.counts.untracked_normal!==null&&!dp(r.counts.untracked_normal))return!1}}}else if(e==="visibility"&&r!=null){if(!It(r))return!1;for(let n of Object.keys(r))if(!dge.has(n))return!1;if(!ke(r,"origin")||r.origin!==null&&!R9(r.origin)||!ke(r,"push_remote")||r.push_remote!==null&&typeof r.push_remote!="string"||!ke(r,"remotes")||!Array.isArray(r.remotes)||!r.remotes.every(xge)||!ke(r,"visibility_cache")||!Array.isArray(r.visibility_cache)||!r.visibility_cache.every(R9))return!1}}return!0}function A9(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!hge.has(e))return!1;if(!ke(t,"enabled")||typeof t.enabled!="boolean"||!ke(t,"baselines")||!k9(t.baselines))return!1;if(ke(t,"tabs")&&t.tabs!==void 0){if(!It(t.tabs))return!1;for(let e of Object.keys(t.tabs))if(!k9(t.tabs[e]))return!1}return!0}function Hge(t){if(!Array.isArray(t))return!1;for(let e of t){if(!It(e))return!1;for(let r of Object.keys(e))if(!Gge.has(r))return!1;if(!ke(e,"path")||typeof e.path!="string"||e.path!==""&&!x9.test(e.path)||ke(e,"read")&&e.read!==void 0&&(typeof e.read!="string"||!T9.has(e.read))||ke(e,"write")&&e.write!==void 0&&(typeof e.write!="string"||!T9.has(e.write)))return!1}return!0}function Wge(t,e){if(!Oge.has(t)||!It(e))return!1;if(t==="mcp"){for(let r of Object.keys(e))if(!Bge.has(r))return!1;if(ke(e,"dynamic")&&e.dynamic!==void 0&&typeof e.dynamic!="boolean")return!1;if(ke(e,"servers")&&e.servers!==void 0){if(!Array.isArray(e.servers)||e.servers.length>Nge||e.servers.length===0&&e.dynamic!==!0)return!1;for(let r of e.servers){if(!It(r))return!1;for(let n of Object.keys(r))if(!Fge.has(n))return!1;if(!ke(r,"server")||typeof r.server!="string"||r.server.length===0||r.server.length>128||!ke(r,"tools")||!Array.isArray(r.tools)||r.tools.length===0||r.tools.length>Mge||!r.tools.every(n=>typeof n=="string"&&Lge.test(n)))return!1}}return!0}if(t==="user"){for(let r of Object.keys(e))if(!Uge.has(r))return!1;return!(ke(e,"scopes")&&e.scopes!==void 0&&(!Array.isArray(e.scopes)||!e.scopes.every(r=>typeof r=="string"&&P9.test(r))))}if(C9.has(t)){for(let r of Object.keys(e))if(!$ge.has(r))return!1;return!(ke(e,"rules")&&e.rules!==void 0&&!Hge(e.rules)||ke(e,"wake")&&e.wake!==void 0&&(!Array.isArray(e.wake)||!e.wake.every(r=>typeof r=="string"&&x9.test(r))))}for(let r of Object.keys(e)){if(!P9.test(r))return!1;let n=e[r];if(n!==null&&typeof n!="string"&&typeof n!="boolean"&&!dp(n))return!1}return!0}function qge(t){if(!It(t))return!1;for(let e of Object.keys(t))if(!vge.has(e))return!1;if(!ke(t,"mode")||typeof t.mode!="string"||!ke(t,"is_shared_live")||typeof t.is_shared_live!="boolean"||!ke(t,"probed")||typeof t.probed!="boolean"||!ke(t,"probe_current_account")||typeof t.probe_current_account!="boolean"||!ke(t,"grant_observed")||typeof t.grant_observed!="boolean"||ke(t,"role")&&t.role!==void 0&&typeof t.role!="string"||ke(t,"artifact_kind")&&t.artifact_kind!==void 0&&typeof t.artifact_kind!="string"||ke(t,"type_lock")&&t.type_lock!==void 0&&typeof t.type_lock!="boolean")return!1;for(let e of kge)if(ke(t,e)&&t[e]!==void 0&&t[e]!==!0)return!1;if(ke(t,"live_paths")&&t.live_paths!==void 0&&!Wl(t.live_paths))return!1;if(ke(t,"capabilities")&&t.capabilities!==void 0){if(!It(t.capabilities)||Buffer.byteLength(JSON.stringify(t.capabilities),"utf8")>Dge)return!1;for(let e of Object.keys(t.capabilities))if(!Wge(e,t.capabilities[e]))return!1}return!0}function Kge(t){if(!It(t))return!1;for(let r of Object.keys(t))if(!yge.has(r))return!1;if(!ke(t,"by_slug")||!It(t.by_slug))return!1;for(let r of Object.keys(t.by_slug)){let n=t.by_slug[r];if(!It(n))return!1;for(let i of Object.keys(n))if(!bge.has(i))return!1;if(ke(n,"share")&&n.share!==void 0&&!qge(n.share)||ke(n,"attested")&&n.attested!==void 0&&typeof n.attested!="string"||ke(n,"notice_pending")&&n.notice_pending!==void 0&&n.notice_pending!==!0||ke(n,"published_env")&&n.published_env!==void 0&&(typeof n.published_env!="string"||!_B.has(n.published_env)))return!1;if(ke(n,"watch")&&n.watch!==void 0){if(!It(n.watch))return!1;for(let i of Object.keys(n.watch))if(!Sge.has(i)||n.watch[i]!==void 0&&n.watch[i]!==!0)return!1}}if(!ke(t,"by_path")||!It(t.by_path))return!1;for(let r of Object.keys(t.by_path)){let n=t.by_path[r];if(!It(n))return!1;for(let i of Object.keys(n))if(!Ege.has(i))return!1;if(ke(n,"slug")&&n.slug!==void 0&&typeof n.slug!="string"||ke(n,"thumbnail_named")&&n.thumbnail_named!==void 0&&!Wl(n.thumbnail_named))return!1}if(!ke(t,"live_docs")||!Array.isArray(t.live_docs))return!1;for(let r of t.live_docs){if(!It(r))return!1;for(let n of Object.keys(r))if(!Rge.has(n))return!1;if(!ke(r,"slug")||typeof r.slug!="string"||!ke(r,"live_path")||typeof r.live_path!="string"||!ke(r,"working_copy")||typeof r.working_copy!="string")return!1}if(!ke(t,"room_armed")||!Wl(t.room_armed)||!ke(t,"type_reads")||!It(t.type_reads))return!1;for(let r of Object.keys(t.type_reads)){let n=t.type_reads[r];if(!It(n))return!1;for(let i of Object.keys(n))if(!Ige.has(i))return!1;if(!ke(n,"declares_room")||typeof n.declares_room!="boolean")return!1}if(ke(t,"last_publish")&&t.last_publish!==void 0){let r=t.last_publish;if(!It(r))return!1;for(let n of Object.keys(r))if(!Age.has(n))return!1;if(!ke(r,"slug")||typeof r.slug!="string"||!ke(r,"env")||typeof r.env!="string"||!_B.has(r.env))return!1}if(!ke(t,"session")||!It(t.session))return!1;let e=t.session;for(let r of Object.keys(e))if(!Tge.has(r))return!1;if(!ke(e,"frame_env")||typeof e.frame_env!="string"||!_B.has(e.frame_env)||!ke(e,"viewer_origin")||typeof e.viewer_origin!="string"||ke(e,"dev_viewer_origin")&&e.dev_viewer_origin!==void 0&&typeof e.dev_viewer_origin!="string")return!1;for(let r of Pge)if(!ke(e,r)||typeof e[r]!="boolean")return!1;for(let r of _ge)if(ke(e,r)&&e[r]!==void 0&&typeof e[r]!="boolean")return!1;return!(ke(e,"inherited_type_grant")&&e.inherited_type_grant!==void 0&&e.inherited_type_grant!==!0||ke(e,"watch_rail")&&e.watch_rail!==void 0&&(typeof e.watch_rail!="string"||!wge.has(e.watch_rail))||!ke(e,"scratchpad_dir")||e.scratchpad_dir!==null&&typeof e.scratchpad_dir!="string"||ke(e,"tool_results_dir")&&e.tool_results_dir!==void 0&&typeof e.tool_results_dir!="string"||ke(t,"truncated")&&t.truncated!==void 0&&typeof t.truncated!="boolean")}function jge(t){if(!Array.isArray(t)||t.length>Cge)throw new tt("safeguards is not a canonical dangerous_tool_use array");for(let e of t){if(!It(e))throw new tt("safeguards entry is not a plain object");for(let r of Object.keys(e))if(!Jme.has(r))throw new tt("safeguards entry contains unsupported key");if(!ke(e,"type")||e.type!=="dangerous_tool_use")throw new tt("safeguards entry type is not dangerous_tool_use");if(ke(e,"classifier_context")&&e.classifier_context!==void 0){let r=e.classifier_context;if(!It(r))throw new tt("safeguards classifier_context is not a plain object");for(let n of Object.keys(r))if(!Yme.has(n))throw new tt("safeguards classifier_context contains unsupported key");if(ke(r,"v")&&r.v!==void 0&&!dp(r.v))throw new tt("safeguards classifier_context.v is not a finite number");for(let n of Qme)if(ke(r,n)&&r[n]!==void 0&&typeof r[n]!="string")throw new tt("safeguards classifier_context string field is invalid");for(let n of Xme)if(ke(r,n)&&r[n]!==void 0&&typeof r[n]!="boolean")throw new tt("safeguards classifier_context boolean field is invalid");if(ke(r,"user_identity")&&r.user_identity!==void 0&&r.user_identity!==null&&typeof r.user_identity!="string")throw new tt("safeguards classifier_context.user_identity is invalid");if(ke(r,"rule_roots")&&r.rule_roots!==void 0){if(!It(r.rule_roots))throw new tt("safeguards classifier_context.rule_roots is invalid");for(let n of Object.keys(r.rule_roots)){let i=r.rule_roots[n];if(!Zme.has(n)||i!==null&&typeof i!="string")throw new tt("safeguards classifier_context.rule_roots is invalid")}}if(ke(r,"trusted_directories")&&r.trusted_directories!==void 0){if(!It(r.trusted_directories))throw new tt("safeguards classifier_context.trusted_directories is invalid");let n=r.trusted_directories;for(let i of Object.keys(n))if(!ege.has(i))throw new tt("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"primary")&&n.primary!==void 0&&n.primary!==null&&!E9(n.primary))throw new tt("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"additional")&&n.additional!==void 0&&(!Array.isArray(n.additional)||!n.additional.every(i=>typeof i=="string"||E9(i))))throw new tt("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"network")&&n.network!==void 0&&!Wl(n.network))throw new tt("safeguards classifier_context.trusted_directories is invalid");if(ke(n,"block_reads_outside_working_directories")&&n.block_reads_outside_working_directories!==void 0&&typeof n.block_reads_outside_working_directories!="boolean")throw new tt("safeguards classifier_context.trusted_directories is invalid")}if(ke(r,"rules")&&r.rules!==void 0){if(!It(r.rules))throw new tt("safeguards classifier_context.rules is invalid");for(let n of Object.keys(r.rules)){let i=r.rules[n];if(!rge.has(n)||!Array.isArray(i))throw new tt("safeguards classifier_context.rules is invalid");for(let o of i){if(!It(o))throw new tt("safeguards classifier_context.rules is invalid");for(let s of Object.keys(o))if(!ige.has(s))throw new tt("safeguards classifier_context.rules is invalid");if(!ke(o,"rule")||typeof o.rule!="string"||!ke(o,"source")||typeof o.source!="string")throw new tt("safeguards classifier_context.rules is invalid");if(ke(o,"canonical")&&o.canonical!==void 0&&typeof o.canonical!="string")throw new tt("safeguards classifier_context.rules is invalid");if(ke(o,"root")&&o.root!==void 0&&o.root!==null&&typeof o.root!="string")throw new tt("safeguards classifier_context.rules is invalid");if(ke(o,"pattern")&&o.pattern!==void 0&&typeof o.pattern!="string")throw new tt("safeguards classifier_context.rules is invalid")}}}if(ke(r,"dropped")&&r.dropped!==void 0){if(!It(r.dropped))throw new tt("safeguards classifier_context.dropped is invalid");for(let n of Object.keys(r.dropped)){let i=r.dropped[n];if(!nge.has(n)||!dp(i))throw new tt("safeguards classifier_context.dropped is invalid")}}if(ke(r,"auto_mode")&&r.auto_mode!==void 0){if(!It(r.auto_mode))throw new tt("safeguards classifier_context.auto_mode is invalid");for(let n of Object.keys(r.auto_mode))if(!oge.has(n)||!Wl(r.auto_mode[n]))throw new tt("safeguards classifier_context.auto_mode is invalid")}if(ke(r,"git_state")&&r.git_state!==void 0&&r.git_state!==null&&!I9(r.git_state))throw new tt("safeguards classifier_context.git_state is invalid");if(ke(r,"chrome_navigation")&&r.chrome_navigation!==void 0&&!A9(r.chrome_navigation))throw new tt("safeguards classifier_context.chrome_navigation is invalid");if(ke(r,"prior_turn_context")&&r.prior_turn_context!==void 0){if(!Array.isArray(r.prior_turn_context))throw new tt("safeguards classifier_context.prior_turn_context is invalid");for(let n of r.prior_turn_context){if(!It(n))throw new tt("safeguards classifier_context.prior_turn_context is invalid");for(let i of Object.keys(n))if(!fge.has(i))throw new tt("safeguards classifier_context.prior_turn_context is invalid");if(!ke(n,"tool_use_ids")||!Wl(n.tool_use_ids))throw new tt("safeguards classifier_context.prior_turn_context is invalid");if(!ke(n,"context")||!It(n.context))throw new tt("safeguards classifier_context.prior_turn_context is invalid");for(let i of Object.keys(n.context))if(!mge.has(i))throw new tt("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"git_state")&&n.context.git_state!==void 0&&n.context.git_state!==null&&!I9(n.context.git_state))throw new tt("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"chrome_navigation")&&n.context.chrome_navigation!==void 0&&!A9(n.context.chrome_navigation))throw new tt("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"live_cwd")&&n.context.live_cwd!==void 0&&typeof n.context.live_cwd!="string")throw new tt("safeguards classifier_context.prior_turn_context is invalid");if(ke(n.context,"platform")&&n.context.platform!==void 0&&typeof n.context.platform!="string")throw new tt("safeguards classifier_context.prior_turn_context is invalid")}}if(ke(r,"system_reminders")&&r.system_reminders!==void 0){if(!Array.isArray(r.system_reminders))throw new tt("safeguards classifier_context.system_reminders is invalid");for(let n of r.system_reminders){if(!It(n))throw new tt("safeguards classifier_context.system_reminders is invalid");for(let i of Object.keys(n))if(!gge.has(i))throw new tt("safeguards classifier_context.system_reminders is invalid");if(!ke(n,"id")||typeof n.id!="string"||!ke(n,"provenance")||typeof n.provenance!="string")throw new tt("safeguards classifier_context.system_reminders is invalid");if(ke(n,"author")&&n.author!==void 0&&typeof n.author!="string")throw new tt("safeguards classifier_context.system_reminders is invalid");if(ke(n,"written")&&n.written!==void 0&&typeof n.written!="string")throw new tt("safeguards classifier_context.system_reminders is invalid")}}if(ke(r,"artifacts")&&r.artifacts!==void 0&&!Kge(r.artifacts))throw new tt("safeguards classifier_context.artifacts is invalid");if(ke(r,"shed")&&r.shed!==void 0&&!Wl(r.shed))throw new tt("safeguards classifier_context.shed is invalid")}}}function Vge(t,e){let r=Hm(t);if(!r.betaHeaderName)return{};let n=e?.[r.betaHeaderName];if(n===void 0||n==="")return{};let i=n.split(",").map(a=>a.trim()).filter(a=>a.length>0),o=i.filter(a=>r.betaTokenAllowlist.has(a)),s=i.filter(a=>!r.betaTokenAllowlist.has(a));return s.length>0&&w.warn("[canonical] dropped non-allowlisted beta tokens",{dropped:s}),o.length===0?{}:{[r.betaHeaderName]:o.join(",")}}function IP(t){let{provider:e,request:r}=t,n=Hm(e);if(t.agentContentType!==void 0&&t.agentContentType.split(";")[0].trim().toLowerCase()!=="application/json")throw new tt("non-JSON content type");let i=r.body;if(i==null||typeof i!="object"||Array.isArray(i))throw new tt("body is not a JSON object");if(ke(i,"model")){let c=i.model;if(typeof c!="string"||!zme.test(c))throw new tt("model is not a canonical model id")}e==="anthropic"&&ke(i,"safeguards")&&jge(i.safeguards);let o=(0,RP.randomUUID)(),s=CB(i),a={...n.synthesizedHeaders,...Vge(e,t.agentHeaders)};return{provider:e,upstreamUrl:n.upstreamBaseUrl+n.upstreamPath,headers:a,body:i,modelCallId:o,requestSha256:s}}function AP(t,e){let r=e.filter(p=>p.length>0),n=[],i=[],o="[REDACTED-SELF-CRED]",s="[REDACTED-SELF-CRED-KEY]",a="[REDACTED-CP7-KEY]",c=p=>r.some(h=>p.includes(h)),l=(p,h)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)?`${p}.${h}`:`${p}['${h.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}']`,d=(p,h)=>{if(typeof p=="string"){if(r.length===0)return p;let m=p,f=!1;for(let g of r)m.includes(g)&&(m=m.split(g).join(o),f=!0);return f&&n.push(h),m}if(Array.isArray(p))return p.map((m,f)=>d(m,`${h}[${f}]`));if(p!==null&&typeof p=="object"){let m=Object.create(null),f=0,g=0;for(let[y,S]of Object.entries(p))if(r.length>0&&c(y)){f+=1;let b=`${s}-${f}`,v=l(h,b);n.push(v),m[b]=d(S,v)}else if($0(y)){g+=1;let b=`${a}-${g}`,v=l(h,b);i.push({field:v,patternClass:"secret_object_key"}),m[b]=d(S,v)}else m[y]=d(S,l(h,y));return m}return p};return{body:d(t,"$"),leakedPaths:n,keyScrubs:i}}var RP,tt,zme,Jme,Yme,Qme,Xme,Zme,ege,tge,rge,nge,ige,oge,sge,age,cge,lge,dge,_9,uge,pge,hge,fge,mge,gge,yge,_B,wge,bge,Sge,vge,kge,Ege,Rge,Ige,Age,Tge,Pge,_ge,Cge,C9,Oge,Dge,Nge,Mge,Lge,Bge,Fge,$ge,Gge,x9,T9,Uge,P9,xB=D(()=>{"use strict";RP=require("node:crypto");EP();Ye();Du();tt=class extends Error{constructor(r){super(r);this.reason=r;this.name="CanonicalRejectError"}},zme=/^[A-Za-z0-9._:/-]{1,200}$/;Jme=new Set(["type","classifier_context"]),Yme=new Set(["v","permission_mode","platform","live_cwd","home_dir","rule_roots","trusted_directories","rules","auto_mode","artifact_consent_holdback","case_insensitive_paths","restricted","is_remote_mode","classify_all_shell","user_identity","git_state","dropped","truncated","chrome_navigation","prior_turn_context","system_reminders","artifacts","shed","tool_host_attached"]),Qme=["permission_mode","platform","live_cwd","home_dir"],Xme=["artifact_consent_holdback","case_insensitive_paths","restricted","is_remote_mode","classify_all_shell","truncated","tool_host_attached"],Zme=new Set(["userSettings","projectSettings","localSettings","flagSettings","policySettings","cliArg","command","session","toolsNarrowing","mcpServerPolicy","hostCredential"]),ege=new Set(["primary","additional","network","block_reads_outside_working_directories"]),tge=new Set(["path","resolved","source"]),rge=new Set(["allow","deny","ask"]),nge=new Set(["allow","deny","ask","auto_mode_allow","auto_mode_soft_deny","auto_mode_hard_deny","auto_mode_environment"]),ige=new Set(["rule","canonical","source","root","pattern"]),oge=new Set(["allow","soft_deny","hard_deny","environment"]),sge=new Set(["cwd","root","branch","default_branch","status","visibility","error","truncated"]),age=new Set(["timeout","not_a_repo","error","pending"]),cge=new Set(["clean","counts","porcelain","truncated"]),lge=new Set(["staged","modified","untracked","untracked_normal"]),dge=new Set(["origin","push_remote","remotes","visibility_cache"]),_9=new Set(["public","private","unknown"]),uge=new Set(["host","remote","visibility"]),pge=new Set(["name","host","remote","visibility"]),hge=new Set(["enabled","baselines","tabs"]),fge=new Set(["tool_use_ids","context"]),mge=new Set(["git_state","chrome_navigation","live_cwd","platform"]),gge=new Set(["id","provenance","author","written"]),yge=new Set(["by_slug","by_path","live_docs","room_armed","type_reads","last_publish","session","truncated"]),_B=new Set(["prod","staging"]),wge=new Set(["live","durable","none"]),bge=new Set(["share","attested","notice_pending","published_env","watch"]),Sge=new Set(["stopped","auto_reply_stopped","auto_reply_swept","replies_declined"]),vge=new Set(["mode","is_shared_live","role","probe_failed","probed","probe_current_account","cowritten","outside_writer","artifact_kind","type_locked","type_lock","type_first_party","caps_read_not_found","live_paths","capabilities","capabilities_unknown","capabilities_cut","grant_observed"]),kge=["probe_failed","cowritten","outside_writer","type_locked","type_first_party","caps_read_not_found","capabilities_unknown","capabilities_cut"],Ege=new Set(["slug","thumbnail_named"]),Rge=new Set(["slug","live_path","working_copy"]),Ige=new Set(["declares_room"]),Age=new Set(["slug","env"]),Tge=new Set(["frame_env","viewer_origin","dev_viewer_origin","toolset","short_links","ant_build","live_edit","live_doc_stream","live_paths_schema","copy_from","types_on","five_class_asks","inherited_type_grant","watch_rail","auto_react","comments_in_schema","db_str_replace","handlers","room_client","eval_stub","scratchpad_dir","tool_results_dir"]),Pge=["ant_build","comments_in_schema","handlers","room_client","eval_stub"],_ge=["toolset","short_links","live_edit","live_doc_stream","live_paths_schema","copy_from","types_on","five_class_asks","auto_react","db_str_replace"],Cge=16;C9=new Set(["artifact","self","downloads","comments","room","db","assets"]),Oge=new Set([...C9,"user","mcp","flags"]),Dge=4e3,Nge=32,Mge=128,Lge=/^[A-Za-z0-9_.-]{1,128}$/,Bge=new Set(["servers","dynamic"]),Fge=new Set(["server","tools"]),$ge=new Set(["rules","wake"]),Gge=new Set(["path","read","write"]),x9=/^(?:[A-Za-z0-9_.~:@+-]+|\{self\})(?:\/(?:[A-Za-z0-9_.~:@+-]+|\{self\}))*$/,T9=new Set(["view","interact","admin","owner"]),Uge=new Set(["scopes"]),P9=/^[a-z][a-z0-9_-]{0,31}$/});function TP(){return up.upstreamBaseUrl+up.upstreamPath}var zge,up,PP,_P,CP,xP=D(()=>{"use strict";zge="0.144.4",up={upstreamBaseUrl:"https://chatgpt.com/backend-api/codex",upstreamPath:"/responses",synthesizedHeaders:{"content-type":"application/json",originator:"codex_cli_rs","user-agent":`codex_cli_rs/${zge}`},assumeSseOn200:!0};PP="https://auth.openai.com/oauth/token",_P="app_EMoamEEZ73f0CkXaXp7hrann",CP="application/x-www-form-urlencoded"});function O9(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}async function Qge(t,e){let r=t.body;if(!r||typeof r.getReader!="function"){let s=await t.text();return Buffer.byteLength(s,"utf8")>e?{rawBody:"",oversized:!0}:{rawBody:s,oversized:!1}}let n=r.getReader(),i=[],o=0;try{for(;;){let{done:s,value:a}=await n.read();if(s)break;if(!(!a||a.byteLength===0)){if(o+a.byteLength>e)return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0};o+=a.byteLength,i.push(a)}}}catch{return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0}}return{rawBody:Buffer.concat(i.map(s=>Buffer.from(s)),o).toString("utf8"),oversized:!1}}function OB(t){let e=new URLSearchParams;return e.set("grant_type","refresh_token"),e.set("refresh_token",t),e.set("client_id",_P),e.toString()}async function OP(t,e,r={}){let n=(r.now?.()??new Date).toISOString(),i;try{i=await e.post({url:PP,body:OB(t.refresh_token),contentType:CP,signal:r.signal})}catch{return{kind:"transient",reason:"transport_error"}}if(i.status===200){let a=D9(i,!1);if(a&&typeof a.access_token=="string"&&a.access_token.length>0){let c={access_token:a.access_token,refresh_token:typeof a.refresh_token=="string"&&a.refresh_token.length>0?a.refresh_token:t.refresh_token,account_id:t.account_id,last_refresh:n},l=typeof a.id_token=="string"&&a.id_token.length>0?a.id_token:t.id_token;return l!==void 0&&(c.id_token=l),{kind:"rotated",bundle:c}}return{kind:"transient",reason:"malformed_success"}}let o=D9(i,!0),s=typeof o?.error=="string"?o.error:void 0;return s==="invalid_grant"?(w.warn("[oauth-refresh] permanent refresh failure (invalid_grant)"),{kind:"permanent",reason:"invalid_grant"}):(w.warn(`[oauth-refresh] transient refresh failure (status=${i.status})`),{kind:"transient",reason:s??`status_${i.status}`})}function D9(t,e){if(t.oversized||e&&(!t.contentType||!t.contentType.includes("application/json"))||!t.rawBody||t.rawBody.length===0)return null;try{let r=JSON.parse(t.rawBody);return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}var Jge,Yge,qm,DB=D(()=>{"use strict";Ye();xP();Jge=64*1024,Yge=3e4,qm=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??Yge,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=()=>i.abort();e.signal&&(e.signal.aborted?i.abort():e.signal.addEventListener("abort",s,{once:!0}));try{let a=await r(e.url,{method:"POST",headers:{"content-type":e.contentType},body:e.body,redirect:"error",signal:i.signal}),{rawBody:c,oversized:l}=await Qge(a,Jge);return w.debug(`[oauth-refresh] POST ${O9(e.url)} -> ${a.status}`),{status:a.status,rawBody:c,contentType:(a.headers.get("content-type")??void 0)?.toLowerCase(),oversized:l}}catch(a){throw w.warn(`[oauth-refresh] transport error POSTing ${O9(e.url)}`,{code:a?.code}),new Error("oauth refresh transport error")}finally{clearTimeout(o),e.signal&&e.signal.removeEventListener("abort",s)}}}});function nye(){return{status:200,body:{models:rye.map(t=>({slug:t.slug,display_name:t.displayName,description:"CodeVibe broker compatibility model metadata.",default_reasoning_level:"medium",supported_reasoning_levels:tye,shell_type:"shell_command",visibility:t.slug==="codex-auto-review"?"hide":"list",supported_in_api:t.supportedInApi,priority:t.priority,additional_speed_tiers:[],service_tiers:[],availability_nux:null,upgrade:null,base_instructions:"You are Codex, a coding agent.",model_messages:null,supports_reasoning_summaries:!1,default_reasoning_summary:"none",reasoning_summary_format:null,support_verbosity:!0,default_verbosity:"low",apply_patch_tool_type:"freeform",web_search_tool_type:"text",truncation_policy:{mode:"tokens",limit:1e4},supports_parallel_tool_calls:!0,supports_image_detail_original:!1,context_window:128e3,max_context_window:128e3,auto_compact_token_limit:null,comp_hash:null,effective_context_window_percent:95,experimental_supported_tools:[],input_modalities:["text"],supports_search_tool:!0,use_responses_lite:!1}))}}}function N9(t,e){return e.class==="oauth_bundle"?{authorization:`Bearer ${e.material.access_token}`,"ChatGPT-Account-Id":e.material.account_id}:t==="anthropic"?e.class==="subscription_token"?{authorization:`Bearer ${e.material}`}:{"x-api-key":e.material,authorization:`Bearer ${e.material}`}:{authorization:`Bearer ${e.material}`}}function iye(t,e){return t==="anthropic"&&e.startsWith("sk-ant-oat")?{class:"subscription_token",material:e}:{class:"api_key",material:e}}function oye(t){return t.class==="oauth_bundle"?[t.material.access_token,t.material.refresh_token]:[t.material]}function sye(t){return t.class==="oauth_bundle"?t.material.refresh_token:t.material}function aye(t,e,r){return`${t}-${e}-${r}`}function cye(t){let e=(o,s)=>Object.prototype.hasOwnProperty.call(o,s)?o[s]:void 0;if(t===void 0)return;if(typeof t=="string")return{kind:"string",bytes:t.length};if(t===null)return{kind:"null"};if(Array.isArray(t))return{kind:"array"};if(typeof t!="object")return{kind:typeof t};let r=e(t,"error");if(typeof r=="string")return{kind:"string-error",bytes:r.length};let n=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:t,i={};for(let o of["message","type","code"]){let s=e(n,o);typeof s=="string"&&(i[o]=s.length)}return{kind:"object",nestedError:n!==t,fields:i}}var M9,L9,B9,F9,Xge,Zge,eye,NB,tye,rye,Km,$9=D(()=>{"use strict";M9=require("node:crypto"),L9=F(require("node:http")),B9=require("node:stream"),F9=require("node:stream/promises");Ye();AB();EP();PB();xB();Du();VS();xP();DB();kc();IB();Xge=1500*1e3,Zge=5e3,eye=12e4,NB=class extends B9.PassThrough{constructor(r,n){super({autoDestroy:!0});this.idleMs=r;this.onIdle=n;this.disarmed=!1}_construct(r){this.arm(),r()}_transform(r,n,i){this.arm(),i(null,r)}_destroy(r,n){this.disarm(),n(r)}arm(){this.disarmed||(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(this.onIdle,this.idleMs),this.idleTimer.unref?.())}disarm(){this.disarmed=!0,this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0)}},tye=[{effort:"low",description:"Fast responses with lighter reasoning"},{effort:"medium",description:"Balances speed and reasoning depth for everyday tasks"},{effort:"high",description:"Greater reasoning depth for complex problems"},{effort:"xhigh",description:"Extra high reasoning depth for complex problems"}],rye=[{slug:"gpt-5.5",displayName:"GPT-5.5",priority:7,supportedInApi:!0},{slug:"gpt-5.4",displayName:"GPT-5.4",priority:16,supportedInApi:!0},{slug:"gpt-5.4-mini",displayName:"GPT-5.4-Mini",priority:23,supportedInApi:!0},{slug:"gpt-5.3-codex",displayName:"GPT-5.3-Codex",priority:26,supportedInApi:!0},{slug:"gpt-5.2",displayName:"GPT-5.2",priority:35,supportedInApi:!0},{slug:"codex-auto-review",displayName:"Codex Auto Review",priority:43,supportedInApi:!0}];Km=class{constructor(e){this.tokenMinter=new Wm;this.server=null;this.boundAddr=null;this.upstreamKeys=new Map;this.issuanceIds=new Map;this.issuanceCounter=0;this.credentialGeneration=new Map;this.inflightRefresh=new Map;this.stopping=!1;this.lifecycleGeneration=0;this.ops=new Set;this.taskId=e.taskId,this.upstreamClient=e.upstreamClient,this.vendorKeyStore=e.vendorKeyStore??new Ii,this.auditSink=e.auditSink??new Um,this.brokerId=`broker-${process.pid}-${Date.now()}`,this.refreshTransport=e.refreshTransport??new qm,this.oauthLock=e.oauthLock,this.proactiveThresholdMs=e.proactiveRefreshThresholdMs??Xge,this.stopDrainTimeoutMs=e.stopDrainTimeoutMs??Zge,this.nowFn=e.now??Date.now,this.delayFn=e.delay??(r=>new Promise(n=>setTimeout(n,r)))}getOAuthLock(e){return this.oauthLock||(this.oauthLock=Ti({lockDir:vc(`vendor-oauth-${e}`)})),this.oauthLock}async start(){this.tokenMinter.mint();let e=L9.createServer((n,i)=>{this.handleHttp(n,i)});await new Promise((n,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>{e.removeListener("error",i),n()})});let r=e.address();return this.server=e,this.boundAddr=`127.0.0.1:${r.port}`,w.info(`[Broker] Started model gateway on ${this.boundAddr}`,{taskId:this.taskId}),{hostBrokerAddr:this.boundAddr}}async healthz(){return this.server!==null}async stop(){let e=!this.stopping;this.stopping=!0,e&&(this.lifecycleGeneration+=1);let r=[...this.ops];r.length>0&&await Promise.race([Promise.allSettled(r.map(i=>i.done)),this.delayFn(this.stopDrainTimeoutMs)]);let n=[...this.ops];for(let i of n)try{i.controller.abort()}catch{}if(await Promise.allSettled(n.map(i=>i.done)),this.upstreamKeys.clear(),this.credentialGeneration.clear(),this.inflightRefresh.clear(),this.tokenMinter.clear(),this.server){let i=this.server;this.server=null,this.boundAddr=null,await new Promise(o=>i.close(()=>o()))}w.info("[Broker] Stopped + zeroized upstream credentials",{taskId:this.taskId})}registerOp(){let e,r=new Promise(i=>{e=i}),n={controller:new AbortController,done:r,resolveDone:e,lifecycleGen:this.lifecycleGeneration};return this.ops.add(n),n}deregisterOp(e){this.ops.delete(e),e.resolveDone()}isStale(e){return this.lifecycleGeneration!==e.lifecycleGen}currentBrokerToken(){return this.tokenMinter.get()}rotateBrokerToken(){return this.server===null?null:this.tokenMinter.rotateWithGrace()}commitBrokerTokenRotation(e){this.tokenMinter.commitRotation(e)}rollbackBrokerTokenRotation(e){this.tokenMinter.rollbackRotation(e)}getVendorKey(e){return this.vendorKeyStore.getVendorKey(e)}setVendorKey(e,r){return this.vendorKeyStore.setVendorKey(e,r)}clearVendorKey(e){return this.vendorKeyStore.clearVendorKey(e)}getVendorOAuthBundle(e){return this.vendorKeyStore.getVendorOAuthBundle(e)}setVendorOAuthBundle(e,r){return this.vendorKeyStore.setVendorOAuthBundle(e,r)}clearVendorOAuthBundle(e){return this.vendorKeyStore.clearVendorOAuthBundle(e)}async handle(e,r){let n=QS.find(o=>o.method===e.method&&o.path===e.path);if(!n)return{status:403,body:{error:"forbidden"}};if(n.path==="/healthz")return{status:200,body:{ok:!0}};if(n.path==="/models"||n.path==="/v1/models")return nye();if(!this.tokenMinter.authenticate(e.brokerToken))return{status:401,body:{error:"invalid broker token"}};let i=kP(e.path);return i?this.gateway(i,e,r):{status:403,body:{error:"forbidden"}}}async gateway(e,r,n){let i=this.registerOp(),o={signal:i.controller.signal,lifecycleGen:i.lifecycleGen};try{return this.stopping?{status:503,body:{error:"broker stopping"}}:await this.gatewayInner(e,r,o,i,n)}finally{this.deregisterOp(i)}}async gatewayInner(e,r,n,i,o){let s=await this.loadVendorCredential(e,n);if(s===null)return{status:503,body:{error:"no upstream credential"}};if(s.class==="oauth_bundle"&&this.isProactiveDue(s.material)){let S=await this.refreshOAuth(e,n,"proactive");if(S.kind==="rotated"||S.kind==="adopted")s={class:"oauth_bundle",material:S.bundle};else{if(S.kind==="revoked")return{status:503,body:{error:"no upstream credential"}};if(S.kind==="permanent")return this.permanentRefreshResponse()}}let a;try{a=IP({provider:e,request:r,agentHeaders:r.agentHeaders,agentQuery:r.agentQuery,agentContentType:r.agentContentType})}catch(S){if(S instanceof tt)return w.warn("[broker] rejected non-canonical model request",{provider:e,reason:S.reason}),{status:400,body:{error:S.reason}};throw S}let{modelCallId:c,requestSha256:l}=a,d=[...oye(s),...this.tokenMinter.acceptedValues()],u=AP(a.body,d),p=KI(u.body);for(let S of u.leakedPaths)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:S,pattern_class:"self_credential"}))return{status:503,body:{error:"audit unavailable"}};for(let S of u.keyScrubs)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:S.field,pattern_class:S.patternClass}))return{status:503,body:{error:"audit unavailable"}};for(let S of p.findings)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:S.field,pattern_class:S.patternClass}))return{status:503,body:{error:"audit unavailable"}};if(!await this.emitGated("model_call",{agent:e,model:this.extractModel(p.scrubbed),model_call_id:c,request_sha256:l,credential_issuance_id:this.lastIssuanceId(e)}))return{status:503,body:{error:"audit unavailable"}};let m=this.genOf(e),f=s,g=this.buildUpstreamTarget(e,f,a.headers,a.upstreamUrl),y=!1;try{for(;;){let S=await this.upstreamClient.post({url:g.url,headers:g.headers,body:p.scrubbed,signal:n.signal}),b=(S.headers["content-type"]??"").toLowerCase().trim(),v=b.length===0,R=b.startsWith("text/event-stream"),E=g.assumeSseOn200,I=S.status===200&&!!o&&(R||v&&E);if(w.info("[Broker] forward decision",{taskId:this.taskId,modelCallId:c,status:S.status,ctAbsent:v,isSse:R,assumeSse:E,decision:I?"streamed":"buffered"}),I&&o)return await this.streamForward(S,o,n,i,c);let k=await S.readText(),P;try{P=k.length?JSON.parse(k):void 0}catch{P=void 0}if(!y&&f.class==="oauth_bundle"&&S.status===401){y=!0;let C=await this.refreshOAuth(e,n,"reactive",m);if(C.kind==="rotated"||C.kind==="adopted"){f={class:"oauth_bundle",material:C.bundle},g=this.buildUpstreamTarget(e,f,a.headers,a.upstreamUrl);continue}if(C.kind==="permanent"){let T=this.permanentRefreshResponse();return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"refresh_permanent"}),T}if(C.kind==="revoked"){let T={status:503,body:{error:"no upstream credential"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"revoked"}),T}}let A=this.mapUpstream({status:S.status,body:P});return await this.emitBestEffort("model_call_result",{model_call_id:c,result:A.status===200?"ok":`upstream_${S.status}`,...this.extractUsage(P)}),A}}catch{let S={status:502,body:{error:"upstream forward failed"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"forward_error"}),S}}async streamForward(e,r,n,i,o){let s,a;try{s=e.bodyStream();let c=(e.headers["content-type"]??"").trim();return r.writeHead(200,{"content-type":c.length?e.headers["content-type"]:"text/event-stream"}),a=new NB(eye,()=>i.controller.abort()),await(0,F9.pipeline)(s,a,r,{signal:n.signal}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"ok_streamed",usageSource:"unavailable_streamed"}),{kind:"handled"}}catch(c){return a?.destroy(),s&&(s.on("error",()=>{}),s.destroy()),i.controller.abort(),r.headersSent?(r.destroy(),w.warn("[Broker] streaming forward failed after headers sent",{errorShape:c instanceof Error?{name:c.name}:{kind:typeof c}}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"stream_error",usageSource:"unavailable_streamed"}),{kind:"handled"}):(await this.emitBestEffort("model_call_result",{model_call_id:o,result:"forward_error",usageSource:"unavailable_streamed"}),{status:502,body:{error:"upstream forward failed"}})}}buildUpstreamTarget(e,r,n,i){if(r.class==="oauth_bundle"){let s={...n,...up.synthesizedHeaders,...N9(e,r)};return{url:TP(),headers:s,assumeSseOn200:up.assumeSseOn200}}let o={...n,...N9(e,r)};if(e==="anthropic"&&r.class==="subscription_token"){let s=o["anthropic-beta"];o["anthropic-beta"]=s?s.includes("oauth-2025-04-20")?s:`${s},oauth-2025-04-20`:"oauth-2025-04-20"}return{url:i,headers:o,assumeSseOn200:!1}}async loadVendorCredential(e,r){let n=this.upstreamKeys.get(e);if(n!==void 0)return n;let i=await this.vendorKeyStore.getVendorKey(e),o=null;if(i!==null)o=iye(e,i);else if(e==="openai"){let a=await this.vendorKeyStore.getVendorOAuthBundle(e);a&&(o={class:"oauth_bundle",material:a})}if(o===null)return null;if(this.isStale(r)||this.stopping)return o;this.upstreamKeys.set(e,o),o.class==="oauth_bundle"&&!this.credentialGeneration.has(e)&&this.credentialGeneration.set(e,0),this.issuanceCounter+=1;let s=aye(this.brokerId,e,this.issuanceCounter);return this.issuanceIds.set(e,s),await this.emitBestEffort("broker_credential_loaded",{provider:e,key_fingerprint:(0,M9.createHash)("sha256").update(sye(o)).digest("hex").slice(0,16),credential_issuance_id:s}),o}genOf(e){return this.credentialGeneration.get(e)??0}currentBundle(e){let r=this.upstreamKeys.get(e);return r&&r.class==="oauth_bundle"?r.material:null}isProactiveDue(e){let r=Date.parse(e.last_refresh);return Number.isNaN(r)?!1:this.nowFn()-r>=this.proactiveThresholdMs}adoptBundle(e,r,n){this.isStale(n)||this.stopping||(this.upstreamKeys.set(e,{class:"oauth_bundle",material:r}),this.credentialGeneration.set(e,this.genOf(e)+1))}async refreshOAuth(e,r,n,i){if(n==="reactive"&&i!==void 0&&i<this.genOf(e)){let s=this.currentBundle(e);return s?{kind:"adopted",bundle:s}:{kind:"transient",reason:"gen_advanced_but_absent"}}let o=this.inflightRefresh.get(e);return o||(o=this.doRefreshUnderLock(e,r).finally(()=>{this.inflightRefresh.delete(e)}),this.inflightRefresh.set(e,o)),o}async doRefreshUnderLock(e,r){let n=this.getOAuthLock(e),i;try{i=await n.acquire()}catch{return{kind:"transient",reason:"lock_unavailable"}}try{let o=await this.vendorKeyStore.getVendorOAuthBundle(e);if(!o)return{kind:"revoked",reason:"cleared"};let s=this.currentBundle(e);if(s&&o.access_token!==s.access_token)return this.adoptBundle(e,o,r),{kind:"adopted",bundle:o};let a=await OP(o,this.refreshTransport,{signal:r.signal});return a.kind==="permanent"?{kind:"permanent",reason:a.reason}:a.kind==="transient"?{kind:"transient",reason:a.reason}:this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:await i.reassertOwnership()?this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:(await this.vendorKeyStore.setVendorOAuthBundle(e,a.bundle),this.adoptBundle(e,a.bundle,r),{kind:"rotated",bundle:a.bundle}):{kind:"transient",reason:"ownership_lost"}}finally{await i.release()}}lastIssuanceId(e){return this.issuanceIds.get(e)??""}permanentRefreshResponse(){return{status:502,body:{error:"upstream auth failed",remediation:"re-run: codevibe vendor-key import-codex"}}}mapUpstream(e){return e.status!==200&&w.warn("[Broker] upstream non-200",{status:e.status,errorShape:cye(e.body)}),e.status===401||e.status===403?{status:502,body:{error:"upstream auth failed"}}:e.status===200?{status:200,body:e.body}:{status:502,body:{error:`upstream_${e.status}`}}}extractModel(e){if(e!==null&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"model")){let r=e.model;if(typeof r=="string")return r}return"unknown"}extractUsage(e){if(e===null||typeof e!="object")return{};let r=e.usage;if(r===null||typeof r!="object")return{};let n=r,i={};return typeof n.input_tokens=="number"&&(i.prompt_tokens=n.input_tokens),typeof n.output_tokens=="number"&&(i.completion_tokens=n.output_tokens),typeof n.prompt_tokens=="number"&&(i.prompt_tokens=n.prompt_tokens),typeof n.completion_tokens=="number"&&(i.completion_tokens=n.completion_tokens),i}async emitGated(e,r){try{return"ack"in await this.auditSink.emit(e,r)}catch{return!1}}async emitBestEffort(e,r){try{await this.auditSink.emit(e,r)}catch{}}async handleHttp(e,r){try{let n=e.method??"GET",i=new URL(e.url??"/","http://127.0.0.1"),o=i.pathname,s={};for(let[p,h]of Object.entries(e.headers))typeof h=="string"?s[p.toLowerCase()]=h:Array.isArray(h)&&(s[p.toLowerCase()]=h.join(","));let a={};for(let[p,h]of i.searchParams.entries())a[p]=h;let c=this.extractBrokerToken(s),l,d=!1;if(n==="POST"){let p=await this.readBody(e);if(p.length>0)try{l=JSON.parse(p)}catch{d=!0}}if(d&&QS.some(p=>p.method===n&&p.path===o)){this.writeJson(r,400,{error:"malformed JSON body"});return}let u=await this.handle({method:n,path:o,brokerToken:c,body:l,agentHeaders:s,agentQuery:a,agentContentType:s["content-type"]},r);if("kind"in u)return;this.writeJson(r,u.status,u.body)}catch(n){w.error("[Broker] HTTP handler error",{error:n instanceof Error?n.message:String(n)}),r.headersSent?r.destroy():this.writeJson(r,502,{error:"broker internal error"})}}extractBrokerToken(e){if(e["x-api-key"])return e["x-api-key"];let r=e.authorization;if(r&&r.toLowerCase().startsWith("bearer "))return r.slice(7).trim()}readBody(e){return new Promise((r,n)=>{let i=[];e.on("data",o=>i.push(o)),e.on("end",()=>r(Buffer.concat(i).toString("utf8"))),e.on("error",n)})}writeJson(e,r,n){let i=JSON.stringify(n??{});e.writeHead(r,{"content-type":"application/json"}),e.end(i)}}});function G9(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}var MB,lye,jm,U9=D(()=>{"use strict";MB=require("node:stream");Ye();lye=12e4;jm=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??lye,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=e.signal,a=()=>i.abort();s&&(s.aborted?i.abort():s.addEventListener("abort",a,{once:!0}));let c=!1,l=()=>{c||(c=!0,s&&s.removeEventListener("abort",a))},d;try{d=await r(e.url,{method:"POST",headers:{...e.headers},body:JSON.stringify(e.body),redirect:"error",signal:i.signal})}catch(f){throw clearTimeout(o),l(),w.warn(`[UpstreamClient] transport error POSTing ${G9(e.url)}`,{code:f?.code}),new Error("upstream transport error")}clearTimeout(o),w.debug(`[UpstreamClient] POST ${G9(e.url)} -> ${d.status}`);let u={};d.headers.forEach((f,g)=>{u[g.toLowerCase()]=f});let p=d,h=!1,m=()=>{if(h)throw new Error("UpstreamResult body already consumed (bodyStream/readText are one-shot; LOCK #643-1)");h=!0};return{status:p.status,headers:u,bodyStream(){if(m(),p.body===null)return l(),MB.Readable.from([]);let f=MB.Readable.fromWeb(p.body);return f.once("close",l),f},async readText(){m();let f=setTimeout(()=>i.abort(),n);s?.aborted&&i.abort();try{return await p.text()}catch{throw new Error("upstream transport error")}finally{clearTimeout(f),l()}}}}}});var LB={};jr(LB,{BROKER_ROUTES:()=>QS,BrokerTokenMinter:()=>Wm,CHATGPT_OAUTH_CLIENT_ID:()=>_P,CHATGPT_REFRESH_CONTENT_TYPE:()=>CP,CHATGPT_TOKEN_ENDPOINT:()=>PP,CHATGPT_UPSTREAM_CONFIG:()=>up,CanonicalRejectError:()=>tt,FetchRefreshTransport:()=>qm,FetchUpstreamClient:()=>jm,KeychainVendorKeyStore:()=>Ii,LocalModelGatewayBroker:()=>Km,OAuthAccountLock:()=>sg,StubStrictAuditSink:()=>Um,buildCanonicalRequest:()=>IP,buildRefreshBody:()=>OB,chatGptUpstreamUrl:()=>TP,createOAuthAccountLock:()=>Ti,defaultOAuthLockDir:()=>vc,getProviderConfig:()=>Hm,providerForPath:()=>kP,refreshOAuthToken:()=>OP,requestSha256:()=>CB,scrubRequestBody:()=>KI,selfCredentialGuard:()=>AP});var DP=D(()=>{"use strict";IB();$9();U9();AB();VS();PB();xP();DB();kc();xB();Du();EP()});function NP(t){let e={},r=process.execPath.slice(0,process.execPath.lastIndexOf("/"));e.PATH=`${t.path??ZS}:${r}`,e.HOME=t.sandboxHome;let n=t.safeSource??{};for(let i of XS){let o=n[i];typeof o=="string"&&o.length>0&&(e[i]=o)}return t.provider==="anthropic"?e.ANTHROPIC_BASE_URL=t.sandboxBrokerUrl:e.OPENAI_BASE_URL=`${t.sandboxBrokerUrl.replace(/\/+$/,"")}/v1`,t.provider==="anthropic"?(e.CLAUDE_CONFIG_DIR=t.sandboxBootstrapDir,e.CLAUDE_CODE_TMPDIR=t.claudeScratchDir??t.sandboxBootstrapDir):e.CODEX_HOME=t.sandboxBootstrapDir,e}function ev(t){let e=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL"]);for(let r of Object.keys(t))if(!e.has(r)){for(let n of dye)if(n.test(r))throw new Error(`sanitizedEnv I1 violation: credential-shaped key "${r}" present in the agent env \u2014 refusing to launch (allow-list bug)`)}}var XS,ZS,dye,BB=D(()=>{"use strict";XS=["LANG","LC_ALL","LC_CTYPE","TERM","TZ"],ZS="/usr/local/bin:/usr/bin:/bin";dye=[/^ANTHROPIC_API_KEY$/i,/^ANTHROPIC_AUTH_TOKEN$/i,/^OPENAI_API_KEY$/i,/_API_KEY$/i,/_SECRET$/i,/_SECRET_ACCESS_KEY$/i,/^AWS_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/^GOOGLE_/i,/_TOKEN$/i,/^SSH_/i]});function $B(t){return t==="CLAUDE"?"anthropic":t==="CODEX"?"openai":null}function FB(t,e){if(t===e)return!0;let r=gn.relative(e,t);return r.length>0&&!r.startsWith("..")&&!gn.isAbsolute(r)}function fye(t){let e=t.split(gn.sep);for(let i=e.length-2;i>=0;i--)if(e[i]===hye&&e[i+1]===pye){let o=[...e];return o[i+1]=uye,gn.join(o.join(gn.sep),H9)}let r=gn.dirname(t),n=gn.basename(t);return gn.join(r,".codevibe-audit",n,H9)}async function mye(t,e){let r;try{r=await pp.promises.realpath(e)}catch{throw new Error(`CP-7 W3: cannot realpath workdir "${e}" \u2014 refusing to launch (audit containment fail-closed)`)}let n=gn.dirname(t);await pp.promises.mkdir(n,{recursive:!0});let i;try{i=await pp.promises.realpath(n)}catch{throw new Error(`CP-7 W3: cannot realpath audit dir "${n}" \u2014 refusing to launch (fail-closed)`)}let o=gn.join(i,gn.basename(t)),s;try{s=await pp.promises.lstat(o)}catch{s=void 0}let a=o;if(s?.isSymbolicLink())try{a=await pp.promises.realpath(o)}catch{throw new Error(`CP-7 W3: audit leaf "${o}" is a symlink that does not resolve (dangling) \u2014 refusing to launch (fail-closed). The audit file must be a regular file in the sibling .codevibe/audit/ tree.`)}if(FB(i,r)||FB(o,r)||FB(a,r))throw new Error(`CP-7 W3: audit path "${o}" (resolved target "${a}") is inside the agent workdir "${r}" \u2014 the agent could truncate/forge the forensic record (Stage-1 r1 HIGH fail-closed). The audit MUST live in the sibling .codevibe/audit/ tree, never under .codevibe/state/<group>/<track>/.`);return o}async function Vm(t){if(t.webBrowsingActive)return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`Agent web browsing active for ${t.agentKind} \u2014 running in reduced-trust mode with shadow-diff capture and guarded web tools`,teardown:async()=>{}};let e=$B(t.agentKind);if(e===null)return t.requireConfined?yye(t):{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${t.agentKind} is a reduced-trust agent (\xA76 Q4) \u2014 no vendor broker; runs on the legacy spawn path with shadow-diff capture`,teardown:async()=>{}};let r=await Wu(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:r.reducedTrustReason,teardown:async()=>{}};let n,i=null;if(t.brokerDeps?.auditSink)n=t.brokerDeps.auditSink;else{let y=t.auditPath??fye(t.workdir),S=await mye(y,t.workdir);i=gn.dirname(S),n=new Tu(t.taskId,S)}let o=t.upstreamClient??new jm,s=(t.makeBroker??(y=>new Km(y)))({taskId:t.taskId,upstreamClient:o,...t.brokerDeps?.vendorKeyStore?{vendorKeyStore:t.brokerDeps.vendorKeyStore}:{},auditSink:n}),a;try{({hostBrokerAddr:a}=await s.start())}catch(y){let S=Object.assign(new Error("CP-7: broker failed to start \u2014 refusing to launch the implementor (fail-closed)"),{cause:y});try{await s.stop()}catch(b){throw Object.assign(new Error("CP-7: broker start failed and cleanup also failed"),{causes:[S,b]})}throw S}let c=s.currentBrokerToken();if(!c){let y=new Error("CP-7: broker minted no token \u2014 refusing to launch (fail-closed)");try{await s.stop()}catch(S){throw Object.assign(new Error("CP-7: broker minted no token and cleanup also failed"),{causes:[y,S]})}throw y}let l=c.value,d=r.tier==="docker"?`http://127.0.0.1:${cm}`:`http://${a}`,u=r.tier==="docker"?Qb:t.workdir,p=r.tier==="docker"?NR:null,h=r.tier==="docker"?GD:null,m,f,g;try{m=await pf.create({provider:e,sandboxBrokerUrl:d,initialToken:l,...p!==null?{sandboxDir:p,sandboxConfigDir:h??GD}:{sandboxDirEqualsHostDir:!0,configDirEqualsHostDir:!0},hostRoot:t.bootstrapHostRoot,...r.tier==="sandbox_exec"&&e==="anthropic"?{claudeScratchHostRoot:t.claudeScratchHostRoot??"/tmp"}:{},workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{}});let y=p!==null?{hostDir:m.hostDir,sandboxDir:p}:{hostDir:m.hostDir,sandboxDir:m.hostDir},S=h!==null?{hostDir:m.configHostDir,sandboxDir:h}:{hostDir:m.configHostDir,sandboxDir:m.configHostDir},b=m.claudeScratchSpec,v=NP({provider:e,sandboxBrokerUrl:d,sandboxHome:u,sandboxBootstrapDir:S.sandboxDir,...b!==null?{claudeScratchDir:b.sandboxDir}:{},safeSource:t.localeSource});ev(v);let R=AD(t.role,v,t.processTreeId),E={isolationTech:r.tier==="docker"?"docker":"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:a,sandboxBrokerUrl:d,taskId:t.taskId,sanitizedEnv:R,agentBootstrap:y,agentConfig:S,...b!==null?{agentScratch:b}:{},...i!==null?{auditDir:i}:{}};f=await r.substrate.launch(E),w.info(`[CP-7] Substrate engaged (tier=${r.tier}, egress=${f.egressFidelity}) \u2014 agent is creditless, broker holds the key`,{taskId:t.taskId,agent:t.agentKind});let I=m,k=f,P=s,A=null,C,T=()=>C||(C=(async()=>{A&&(clearInterval(A),A=null);let N=[];for(let $ of[()=>k.teardown(),()=>P.stop(),()=>I.destroy()])try{await $()}catch(L){N.push(L)}if(N.length>0)throw w.warn("[CP-7] substrate cleanup failed \u2014 task cannot pass",{taskId:t.taskId,failureCount:N.length,...Rn(N[0])}),N.length===1?N[0]:Object.assign(new Error("CP-7 substrate cleanup failed"),{causes:N})})(),C);g=T;let _=`launch-${t.taskId}-${Date.now()}`,O=k.egressFidelity==="strict"?"structural_deny_network_none":"coarse_loopback_only",V;try{V=await n.emit("egress_denied",{destination:"*",protocol:"all",denial_reason:O,caller_event_id:_})}catch(N){throw Object.assign(new Error("CP-7 W3: egress-posture audit emit failed \u2014 refusing to launch the creditless agent (audit-before-effect fail-closed)"),{cause:N})}if(!("ack"in V))throw new Error("CP-7 W3: egress-posture audit was rejected \u2014 refusing to launch the creditless agent (no durable egress posture \u2192 no agent)");let z=t.tokenRefreshIntervalMs??600*1e3,H=null,W=async()=>{if(!(typeof P.rotateBrokerToken=="function"&&typeof P.commitBrokerTokenRotation=="function"&&typeof P.rollbackBrokerTokenRotation=="function")){let L=P.currentBrokerToken();L&&await I.refresh(L.value);return}let $=P.rotateBrokerToken();if($)try{await I.refresh($.token.value),P.commitBrokerTokenRotation($)}catch(L){P.rollbackBrokerTokenRotation($),w.warn("[CP-7] broker-token refresh write FAILED \u2014 rolled back to the prior token and tearing down (fail-closed)",{taskId:t.taskId,...Rn(L)});let K=Object.assign(new Error("CP-7 broker-token refresh failed"),{cause:L});try{await T()}catch(re){throw Object.assign(new Error("CP-7 broker-token refresh failed and cleanup also failed"),{causes:[K,re]})}throw K}},Z=async()=>{let $=(H??Promise.resolve()).catch(()=>{}).then(()=>W());H=$;try{await $}finally{H===$&&(H=null)}};return z>0&&(A=setInterval(()=>{Z().catch(()=>{})},z),A.unref?.()),{mode:"substrate",tier:r.tier,reducedTrust:r.reducedTrust,reducedTrustReason:r.tier==="sandbox_exec"?r.reducedTrustReason:void 0,substrateHandle:k,agentConfigDir:S.sandboxDir,finalEnv:R,refreshBrokerToken:Z,teardown:T}}catch(y){let S=y instanceof Error?y:new Error("CP-7 substrate launch failed"),b=[];if(g)try{await g()}catch(v){b.push(v)}else for(let v of[...f?[()=>f.teardown()]:[],...m?[()=>m.destroy()]:[],()=>s.stop()])try{await v()}catch(R){b.push(R)}throw b.length>0?(w.warn("[CP-7] failed launch also failed cleanup",{taskId:t.taskId,failureCount:b.length,...Rn(b[0])}),Object.assign(new Error("CP-7 substrate launch failed and cleanup also failed"),{causes:[S,...b]})):S}}async function yye(t){let e=t.agentKind;if(e!=="GEMINI"&&e!=="ANTIGRAVITY")throw new Error(`engageWriteConfinedResolverSandbox: unmapped broker-less agent ${e}`);let r=await Wu(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable \u2014 no sandbox substrate on this host (${r.reducedTrustReason}); the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};if(r.tier==="docker")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable on the docker tier \u2014 the A1 image cannot carry the host-installed ${e} binary + its file-based auth; the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};let n=W9.homedir(),i=gn.join(n,...gye[e]);await pp.promises.mkdir(i,{recursive:!0}).catch(()=>{});let o={},s=process.execPath.slice(0,process.execPath.lastIndexOf("/"));o.PATH=`${ZS}:${s}`,o.HOME=n;let a=t.localeSource??{};for(let u of XS){let p=a[u];typeof p=="string"&&p.length>0&&(o[u]=p)}ev(o);let c=AD(t.role,o,t.processTreeId),l={isolationTech:"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:"",sandboxBrokerUrl:"",taskId:t.taskId,sanitizedEnv:c,agentConfig:{hostDir:i,sandboxDir:i},networkPosture:"open"},d=await r.substrate.launch(l);return w.info(`[A1d] Resolver-confinement row engaged (tier=sandbox_exec, egress=open) \u2014 writes fenced to the disposable workspace; ${e} runs on its own file-based auth (no broker)`,{taskId:t.taskId,agent:e}),{mode:"substrate",tier:"sandbox_exec",reducedTrust:!0,reducedTrustReason:`${e} class-2 resolver: write-confined to the disposable merge workspace (A5 Seatbelt); egress OPEN (broker-less \u2014 the agent dials its vendor directly with its own file-based auth)`,substrateHandle:d,agentConfigDir:i,finalEnv:c,refreshBrokerToken:async()=>{},teardown:async()=>{await d.teardown().catch(()=>{})}}}var pp,W9,gn,uye,pye,hye,H9,gye,q9=D(()=>{"use strict";pp=require("node:fs"),W9=F(require("node:os")),gn=F(require("node:path"));DP();qO();MI();Ye();RR();SA();wA();MR();vA();BB();uye="audit",pye="state",hye=".codevibe",H9="audit.jsonl";gye={GEMINI:[".gemini"],ANTIGRAVITY:[".gemini","antigravity-cli"]}});function MP(t){return bye.has(t.toUpperCase())||Sye.test(t)?!1:wye.some(e=>e.test(t))}function GB(t){return Object.keys(t).filter(MP)}function UB(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(MP(r)||(e[r]=n));return e[tv]="1",e}function LP(t={}){let e=t.platform??process.platform,r=t.env??process.env,n=t.exit??(u=>process.exit(u));if(e!=="darwin")return!1;let i=GB(r);if(i.length===0)return!1;if(r[tv])throw new Error(`[le-env-scrub] Refusing to launch the Local Executor: the scrub marker (${tv}) is set but credential-shaped env vars are still present (${i.join(", ")}). A genuine re-exec'd child has NO credential-shaped vars; this indicates a spoofed marker or a broken scrub. Fail closed (CP-7 I1, A5 parent-procargs vector) \u2014 never launch the LE with a vendor credential in its exec-time procargs.`);let o=t.spawnSyncFn??K9.spawnSync,s=t.execPath??process.execPath,a=t.argv??process.argv.slice(1),c=t.cwd??process.cwd(),l=UB(r);try{t.onScrub?.(i)}catch{}let d=o(s,a,{env:l,stdio:"inherit",cwd:c});return d.signal?n(1):n(d.status??1),!0}var K9,tv,wye,bye,Sye,j9=D(()=>{"use strict";K9=require("node:child_process"),tv="CODEVIBE_LE_ENV_SCRUBBED",wye=[/^ANTHROPIC_/i,/^OPENAI_/i,/^GOOGLE_/i,/^GEMINI_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/_API_KEY$/i,/_ACCESS_KEY_ID$/i,/_SECRET_ACCESS_KEY$/i,/_SECRET$/i,/_TOKEN$/i],bye=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL","GOOGLE_BASE_URL"]),Sye=/_BASE_URL$/i});var HB={};jr(HB,{ApiKeyBootstrap:()=>pf,CODEX_PROVIDER_ID:()=>Iw,CP7_CANONICAL_FORM_VERSION:()=>T0,Cp7AuditWriter:()=>Tu,GENESIS_PREV_HASH:()=>NI,HELPER_SCRIPT_NAME:()=>OR,IMPLEMENTOR_CREDENTIAL_MISSING:()=>hM,ImplementorCredentialMissingError:()=>Gu,LE_ENV_SCRUBBED_MARKER:()=>tv,REVIEWER_CREDENTIAL_MISSING:()=>Gb,ReviewerCredentialMissingError:()=>$u,SAFE_ENV_ALLOWLIST:()=>XS,SANDBOX_BOOTSTRAP_DIR:()=>NR,SANDBOX_DEFAULT_PATH:()=>ZS,TOKEN_FILE_NAME:()=>DR,assertImplementorVendorCredential:()=>qb,assertNoAmbientCreds:()=>ev,assertReviewerVendorCredential:()=>Wb,buildSanitizedBaseEnv:()=>NP,buildScrubbedLeEnv:()=>UB,canonicalEntryBytes:()=>fb,canonicalJson:()=>qf,computeEntryHash:()=>Kf,engageSubstrate:()=>Vm,findCredShapedKeys:()=>GB,implementorProviderFor:()=>Hb,isCredShapedEnvKey:()=>MP,providerForAgent:()=>$B,reviewerProviderFor:()=>Ub,scrubLeEnvOrReexec:()=>LP,selectSubstrate:()=>Wu,verifyChain:()=>P0,withImplementorCredentialPreflight:()=>Uu,withReviewerCredentialPreflight:()=>sm});var BP=D(()=>{"use strict";q9();vA();BB();MR();fM();j9();MI()});function rv(t,e,r){let n=zd(e.prompt_template,"AntigravityReviewerProvider"),i=[];e.model_hint!==null&&i.push("--model",e.model_hint);let o=Math.max(1,Math.floor(e.timeout_ms/1e3)-5);i.push("--print-timeout",`${o}s`),i.push("--add-dir",r),i.push("--print",n);let s=nt({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:i,env:s}}async function vye(t,e,r,n){if(!r.exit_success){let a=qu(r.stderr)??"spawn_failed";throw new Ft({kind:"spawn_failed",agent:t.agent,reason:`agy exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:a})}let i=r.stdout,o={verdict_id:(0,V9.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:null,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:kr("provider_unsupported",r.elapsed_ms)};if(n!==void 0){let a=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),c=gm(a,i);return{...o,...c}}let s=Pl(i);if(!s.ok)throw new Ft({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...o,verdict:s.verdict.kind,reasoning:s.verdict.reasoning,suggested_changes:s.verdict.suggested_changes,residual_observations:s.verdict.residual_observations}}var V9,zm,WB=D(()=>{"use strict";V9=require("uuid");af();fm();Tl();hm();tS();Xc();_A();mm();Or();zm=class{constructor(e={}){this.executable=e.executable??"agy"}async evaluate(e,r,n){if(e.agent!=="antigravity")throw new Error(`AntigravityReviewerProvider called with non-Antigravity spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);if(n?.substrate!==void 0)throw new Ft({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider received a substrate handle \u2014 agy is reduced-trust (never substrate-contained, \xA76 Q4); the loop must pre-route antigravity seats to the legacy path",failureReason:"spawn_failed"});let i=n?.workdir;if(i===void 0||i.length===0)throw new Ft({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider requires opts.workdir (agy is workspace-centric \u2014 without --add-dir it cannot read the repo); the evaluate site must thread the loop workingDir",failureReason:"spawn_failed"});let o;try{o=rv(this.executable,e,i)}catch(a){throw new Ft({kind:"spawn_failed",agent:e.agent,reason:a instanceof Error?a.message:String(a),failureReason:"spawn_failed"})}let s;try{s=await oa({command:o.command,args:o.args,env:o.env,prompt:"",timeout_ms:e.timeout_ms})}catch(a){throw a instanceof Pn?new Ft(ym(e.agent,a.detail)):a}return vye(e,r,s,n?.classifyVerdict)}}});function nv(t,e,r=!1){let n=[];n.push("--print"),n.push("--output-format","json"),n.push("--allowed-tools",e.tool_allowlist.join(",")),n.push("--tools",e.tool_allowlist.join(",")),n.push("--disallowed-tools","WebFetch,WebSearch,Agent,Task,Workflow,SendMessage,ListAgents"),n.push("--strict-mcp-config"),e.model_hint!==null&&n.push("--model",e.model_hint);let i=r?{}:nt({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:n,env:i}}async function kye(t,e,r,n){if(!r.exit_success){let c=pc(r.stdout)??qu(r.stderr)??"spawn_failed";throw new Ft({kind:"spawn_failed",agent:t.agent,reason:`claude exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:c})}let{text:i}=Oa(r.stdout),o=Pd(r.stdout,r.elapsed_ms),s={verdict_id:(0,z9.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:o.totalTokens,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:o};if(n!==void 0){let c=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),l=gm(c,i);return{...s,...l}}let a=Pl(i);if(!a.ok)throw new Ft({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...s,verdict:a.verdict.kind,reasoning:a.verdict.reasoning,suggested_changes:a.verdict.suggested_changes,residual_observations:a.verdict.residual_observations}}var z9,Jm,qB=D(()=>{"use strict";z9=require("uuid");fm();Tl();hm();tS();_A();mm();Xc();Or();Jm=class{constructor(e={}){this.executable=e.executable??"claude"}async evaluate(e,r,n){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 i=n?.substrate!==void 0,o=nv(this.executable,e,i),s;try{s=await oa({command:o.command,args:o.args,env:o.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms,...n?.substrate!==void 0?{substrate:n.substrate}:{}})}catch(a){throw a instanceof Pn?new Ft(ym(e.agent,a.detail)):a}return kye(e,r,s,n?.classifyVerdict)}}});function FP(){return new iv().with("claude",new Jm).with("codex",new wm).with("antigravity",new zm)}var iv,KB=D(()=>{"use strict";Tl();WB();qB();nS();iv=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,n){let i=this.providers.get(e.agent);if(i===void 0)throw new Ft({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 i.evaluate(e,r,n)}}});function Q9(){return{schemaVersion:1,choice:"not_configured",artifactId:null,ollamaModel:null,updatedAt:new Date(0).toISOString()}}function Eye(t=process.env){return t.NODE_ENV==="test"&&t.CODEVIBE_HOME_OVERRIDE?t.CODEVIBE_HOME_OVERRIDE:$P.default.join(Y9.default.homedir(),".codevibe")}function Rye(t=process.env){return $P.default.join(Eye(t),"local-model-state.json")}function J9(t){if(!t||typeof t!="object")return Q9();let e=t;return{schemaVersion:1,choice:e.choice==="skipped"||e.choice==="enabled"?e.choice:"not_configured",artifactId:typeof e.artifactId=="string"&&e.artifactId.trim()?e.artifactId:null,ollamaModel:typeof e.ollamaModel=="string"&&e.ollamaModel.trim()?e.ollamaModel:null,updatedAt:typeof e.updatedAt=="string"&&e.updatedAt?e.updatedAt:new Date(0).toISOString()}}async function VB(t=GP){return t.read()}async function zB(t,e=null,r=GP){await r.write({schemaVersion:1,choice:"enabled",artifactId:t,ollamaModel:e,updatedAt:new Date().toISOString()})}var ov,Y9,$P,jB,GP,JB=D(()=>{"use strict";ov=require("fs"),Y9=F(require("os")),$P=F(require("path"));jB=class{constructor(e=Rye()){this.filePath=e}async read(){try{let e=await ov.promises.readFile(this.filePath,"utf8");return J9(JSON.parse(e))}catch{return Q9()}}async write(e){await ov.promises.mkdir($P.default.dirname(this.filePath),{recursive:!0,mode:448}),await ov.promises.writeFile(this.filePath,`${JSON.stringify(J9(e),null,2)}
5884
5884
  `,{mode:384})}async clear(){await ov.promises.rm(this.filePath,{force:!0})}},GP=new jB});function Cye(t){let e=t?.trim();return e||null}function xye(t){if(!t?.trim())return[];let e;try{e=JSON.parse(t)}catch{return null}return!Array.isArray(e)||e.some(r=>typeof r!="string")?null:e}function Oye(t){if(!t?.trim())return Iye;let e=Number(t);return!Number.isSafeInteger(e)||e<=0||e>Aye?null:e}function YB(t){return t.includes("\0")}function UP(t,e=process.env){let r=Cye(e.CODEVIBE_LOCAL_MODEL_COMMAND);if(!r)return{ok:!1,reason:"CODEVIBE_LOCAL_MODEL_COMMAND is not configured. It must point to the verified local Gemma runner."};if(YB(r)||YB(t))return{ok:!1,reason:"local Gemma runtime command or model path is invalid."};let n=xye(e.CODEVIBE_LOCAL_MODEL_ARGS_JSON);if(!n||n.some(YB))return{ok:!1,reason:"CODEVIBE_LOCAL_MODEL_ARGS_JSON must be a JSON array of string arguments."};let i=Oye(e.CODEVIBE_LOCAL_MODEL_TIMEOUT_MS);return i?{ok:!0,config:{command:r,args:n,modelPath:t,timeoutMs:i,env:e}}:{ok:!1,reason:"CODEVIBE_LOCAL_MODEL_TIMEOUT_MS must be a positive integer no greater than 300000."}}function X9(t,e,r){let n=t+e.toString("utf8");return Buffer.byteLength(n,"utf8")<=r?n:n.slice(0,r)+`
5885
5885
  [truncated]
5886
5886
  `}function Dye(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))throw new Error("local Gemma process stdout must be strict JSON only");try{JSON.parse(e)}catch(r){throw new Error(`local Gemma process stdout was not valid JSON: ${r.message}`)}return e}var Z9,e8,Iye,Aye,Tye,Pye,_ye,Ym,QB=D(()=>{"use strict";Z9=require("child_process"),e8=F(require("path"));Or();gh();Iye=3e4,Aye=5*6e4,Tye=1e3,Pye=256*1024,_ye=64*1024;Ym=class{constructor(e){this.config=e;this.providerKind="local";this.runtimeLabel=`local-gemma-process:${e8.default.basename(e.command)}`}async classify(e){return this.invoke(e,"classify")}async generateAdvisory(e,r){return this.invoke(e,"advisory",{responseFormat:r?.responseFormat??"json"})}async probe(){let e=Date.now();try{let r=await this.invoke(["You are CodeVibe local Gemma health check.","Return STRICT JSON ONLY:",'{"action":"advisory_response","rationale":"health check","advisory_summary":"ok"}'].join(`
@@ -6006,7 +6006,7 @@ ${f.message}
6006
6006
  `),r(i);return}else if(a===""){e.setRawMode(!1),e.pause(),e.removeListener("data",o),process.stdout.write(`
6007
6007
  `),n(new Error("cancelled"));return}else a==="\x7F"||a==="\b"?i=i.slice(0,-1):i+=a};e.on("data",o)}else{let o="";e.resume();let s=c=>{o+=c;let l=o.indexOf(`
6008
6008
  `);l>=0&&(e.removeListener("data",s),e.removeListener("end",a),e.pause(),r(o.slice(0,l).replace(/\r$/,"")))},a=()=>{e.removeListener("data",s),r(o.replace(/\r$/,""))};e.on("data",s),e.on("end",a)}})}function xwe(t){process.stdout.write(t);let e=process.stdin;return new Promise(r=>{let n="";e.setEncoding("utf8"),e.resume();let i=a=>{e.removeListener("data",o),e.removeListener("end",s),e.pause();let c=a.trim().toLowerCase();r(c==="y"||c==="yes")},o=a=>{n+=a;let c=n.indexOf(`
6009
- `);c>=0&&i(n.slice(0,c))},s=()=>i(n);e.on("data",o),e.on("end",s)})}var s3,a3,vF,c3,lv,vwe,f3=D(()=>{"use strict";s3=F(require("node:os")),a3=F(require("node:path")),vF=require("node:fs"),c3=require("node:child_process");Or();VS();Ap();kc();lv="openai",vwe=20});var Ebe={};jr(Ebe,{AGY_ARG_PROMPT_MAX_UTF8_BYTES:()=>mw,AUDIT_SUMMARY_PRO_MAX_HEADLINE:()=>OT,AUDIT_SUMMARY_UPGRADE_HINT:()=>DT,AgentType:()=>LC,AppSyncClient:()=>xs,AppSyncGraphQLError:()=>Ut,AuditKeys:()=>eD,AuthService:()=>lh,CONTEXT_SESSION_PSEUDO_TASK_NAMESPACE:()=>JI,CREDENTIAL_STORAGE_UNAVAILABLE_EXIT_CODE:()=>ny,CompositeAdvisoryRunner:()=>Gl,CompositePlannerAdapter:()=>Fl,Continuation:()=>_F,ConversationPane:()=>Py,CredentialBroker:()=>LB,CryptoError:()=>As,CryptoService:()=>Tp,DEFAULT_REPLAY_MAX_FRAME_BYTES:()=>DF,DEFAULT_REPLAY_READ_BYTES:()=>OF,DeliveryStatus:()=>fg,DesktopSyncReadClient:()=>Nc,DurableDesktopSyncWriter:()=>Bc,E1_PROMPT_ID_DOMAIN:()=>_v,ENCRYPTION_VERSION:()=>Pp,EventSource:()=>xp,EventType:()=>ga,FileDurableTeamDeliveryJournal:()=>rc,FlockRolloutLock:()=>fv,HostedGemmaAdvisoryRunner:()=>$l,ImplementorCredentialMissingError:()=>Gu,InProcessRolloutLock:()=>n_,KeychainError:()=>ma,KeychainManager:()=>Jl,LedgerEntrySchema:()=>HC,LedgerFileSchema:()=>Nk,LegacyOwnedFileSchema:()=>Mk,LocalExecutorImpl:()=>El,Logger:()=>jl,MAX_BRAINSTORM_PAGE_BYTES:()=>IS,MAX_BRAINSTORM_PAGE_CHARS:()=>RT,MAX_BRAINSTORM_PAGE_TOKENS:()=>IT,MAX_DYNAMIC_FETCH_CHARS:()=>fR,MAX_FETCHES_PER_TURN:()=>cD,MAX_MOBILE_PROGRESS_MESSAGE_LENGTH:()=>OS,MAX_SEARCHES_PER_TURN:()=>aD,MAX_SYNC_SOURCE_ANCHOR_BYTES:()=>Zo,OllamaGemmaPlannerRunner:()=>zc,PLAIN_DESKTOP_SYNC_TYPES:()=>Dp,PORT_RANGE_SIZE:()=>ch,PRIMARY_PORT:()=>ah,Planner:()=>dB,PromptPublicationTracker:()=>Rc,QuorumLoop:()=>zu,RETAINED_PAGE_MAX_CHARS:()=>Qu,ReplayCursorStateSchema:()=>e_,ReplayFrameTooLargeError:()=>Zm,RetiredSessionCannotReactivateError:()=>lp,RevertManifestStore:()=>Cu,Reviewer:()=>TF,ReviewerCredentialMissingError:()=>$u,ReviewerRole:()=>jC,SEARCH_API_KEY_NAMES:()=>Kv,SESSION_KEY_GEN_ABSENT_SENTINEL:()=>Di,SessionMapRecordSchema:()=>i_,SessionStatus:()=>Jp,SocketRolloutLock:()=>eg,StructuralSummary:()=>V_,Substrate:()=>PF,SubstrateLaunch:()=>HB,SyncEventClientError:()=>ve,SyncJournalError:()=>Ge,SyncReadClientError:()=>Tt,ToolActivityConsolidator:()=>c_,ToolActivityDetailSchema:()=>FC,ToolActivityGroupSchema:()=>$C,ToolActivityLedger:()=>Zp,ToolActivityManifestSchema:()=>GC,ToolActivityOccurrenceSchema:()=>BC,ToolActivityOutbox:()=>eh,ToolActivityOutboxEnvelopeSchema:()=>Fc,ToolActivitySessionMap:()=>o_,ToolReplayCursor:()=>t_,V1_ORCHESTRATION_OPTIONS:()=>Vy,V1_ORCHESTRATION_PROMPT_KIND:()=>BO,WebExtractAbortError:()=>Yh,WebExtractTimeoutError:()=>nw,WorkspaceShadow:()=>Qs,_resetPrepareEventTimestampForTesting:()=>SB,acknowledgeMobileInputDelivery:()=>oh,acknowledgeMobileInputExecution:()=>sh,adaptSnapshotMergeResult:()=>Kw,assertImplementorVendorCredential:()=>qb,assertReviewerVendorCredential:()=>Wb,atomicWriteJsonSync:()=>pu,auditPartitionTaskIdFor:()=>j0,authService:()=>xo,bindOAuthServer:()=>iy,buildAntigravityReviewerCommand:()=>rv,buildAuditBrowserModel:()=>PS,buildClaudeReviewerCommand:()=>nv,buildContextItemWireRow:()=>Cb,buildImplementorArgv:()=>Vs,canRecoverPromptRaise:()=>E_,captureWorkspaceRootAuthority:()=>Le,claimOutageNotificationOnDisk:()=>zA,classifyMobilePromptInput:()=>A3,cleanArbiterSafely:()=>Vu,compileAuditSummary:()=>lc,composeBrainstormPanelBrief:()=>AS,createLogger:()=>p_,createOrchestrationStore:()=>Iy,createRolloutLock:()=>U3,createShellEventEmitter:()=>hc,createSnapshotTrackBundle:()=>uu,createTaskProgressRelay:()=>DS,createToolActivitySyncTransport:()=>Xg,cryptoService:()=>Xe,decryptContextItemWireRow:()=>xb,defaultOutageNotificationRoot:()=>Ju,deriveOpenPromptId:()=>fa,deriveSessionPseudoTaskId:()=>YI,describeStoredAuthFailure:()=>ih,desktopDeferredInputSha256:()=>ad,detectInstalledAgents:()=>En,digestOf:()=>O3,emitShellEvent:()=>Zu,emitTeamCompletionSummary:()=>hu,encryptForEmit:()=>S_,enforceCommand:()=>rl,errorWasBeaconed:()=>ig,executeGitStatusSummary:()=>Pm,extractMcpServerConfig:()=>gw,extractQueryRelevantSnippets:()=>Ws,fireAuthCompletedBeacon:()=>ng,fireAuthFailedBeacon:()=>Ai,formatAuditExport:()=>rp,formatElapsed:()=>ao,formatFetchedContent:()=>uD,formatMobileProgressMessage:()=>$T,getConfig:()=>Bt,getEnvironment:()=>jn,getErrorReason:()=>f_,getInkRuntime:()=>it,handleShellUserInput:()=>aB,htmlToText:()=>Qh,htmlToTextWorker:()=>uR,implementorProviderFor:()=>Hb,initInkRuntime:()=>vy,installDaemonProcessGuards:()=>I_,isNetworkClass:()=>hg,isOpenPromptRaise:()=>k_,isOutageNotificationDeliveredOnDisk:()=>aS,isPersistedEventResult:()=>Ov,isPromptRelevantToRetainedPage:()=>Hd,isRetiredSessionCannotReactivateError:()=>gB,isSessionKeyStaleError:()=>q3,isSpinnerPhase:()=>Kx,isTaskCompletionAuditSummary:()=>pM,isTerminalSessionError:()=>BF,keychainManager:()=>_e,loadConfig:()=>Ev,logger:()=>w,makeImplementorCommandScope:()=>lf,mapOptionNumberToUserDecisionKind:()=>eR,mapOptionToUserDecisionKind:()=>FO,markErrorBeaconed:()=>Ro,markOutageNotificationDeliveredOnDisk:()=>Cl,mintOwnerToken:()=>ug,mutations:()=>tt,newPromptRaise:()=>pg,normalizeSnapshot:()=>IF,parseActiveTerminalMenu:()=>I3,parseInteractivePrompt:()=>QP,pickMode:()=>fh,prepareEventTimestamp:()=>bB,prepareSessionEncryption:()=>$m,probeAgentClis:()=>yP,probeAuthPreflight:()=>wP,probeBackendConnectivity:()=>bP,probeOrphanStatus:()=>JS,processMarkers:()=>tp,pushDetectedAgents:()=>jy,queries:()=>qt,raiseFieldsFromRecord:()=>Cp,readDesktopSyncFile:()=>Uk,readStandaloneCompanionStatus:()=>$k,registerDeviceEncryptionKey:()=>cp,rekeySessionForNewDevices:()=>ap,releaseOutageNotificationClaimOnDisk:()=>JA,releaseRecoveryLock:()=>VA,renderAuditBrowserText:()=>_m,renderAuditResultText:()=>Ml,renderConversationEntry:()=>Oh,renderEntryAsLine:()=>XA,renderProgressLine:()=>_d,renderSummaryMarkdown:()=>dc,requiresSyncInputDeliveryReceipt:()=>Os,resumeOrCreateSession:()=>yB,reviewerProviderFor:()=>Ub,routeBrowse:()=>pS,runAuditBrowser:()=>np,runAuditSummary:()=>_S,runAuthCli:()=>VP,runCompanionMode:()=>dF,runDoctorCli:()=>YS,runLineLogFallback:()=>lS,runOrchestrationShell:()=>aP,runSnapshotMergeGate:()=>Hw,runSnapshotMergeWithObservedCleanup:()=>Ff,sanitizeUrlForAudit:()=>lD,scrubSearchApiKeys:()=>nt,selectTerminalMenuOption:()=>R3,setupAgyWebPlugin:()=>TR,shouldRenderPlain:()=>Ds,stableStringify:()=>uv,startAgentWebTurn:()=>gR,startDeviceKeyWatcher:()=>wB,stripAgyWebPlugin:()=>il,stripClaudeWebArgs:()=>ww,stripCodexWebArgs:()=>bw,subscriptions:()=>Ao,sweepOrphanedFallbackDirs:()=>mR,tryAcquireRecoveryLock:()=>jA,validateAgyArgPrompt:()=>zd,wireSnapshotMergeObserver:()=>qw,wireTeamMergeAuditSummary:()=>ZT,withImplementorCredentialPreflight:()=>Uu,withReviewerCredentialPreflight:()=>sm,withRoleMarker:()=>yL});module.exports=GF(Ebe);Nn();Dn();Dn();Dn();R_();var kQ=/ENOTFOUND|ECONNREFUSED|ETIMEDOUT|ECONNRESET|EAI_AGAIN|EPIPE|ENETUNREACH|EHOSTUNREACH|EHOSTDOWN|ECONNABORTED|socket hang up/i;function hg(t){if(t==null)return!1;let e=t.code,r=t.message,n=typeof e=="string"?e:"",i=typeof r=="string"?r:"";return kQ.test(`${n} ${i}`)}function I_(t,e={}){let r=n=>{e.onFatal?e.onFatal(n):process.exit(1)};process.on("unhandledRejection",n=>{if(hg(n)){t.error("unhandledRejection network-class (non-fatal; daemon continues, #638)",{reason:String(n)});return}t.error("unhandledRejection fatal (daemon shutting down, #638)",{reason:String(n)}),r(n instanceof Error?n:new Error(String(n)))}),process.on("uncaughtException",n=>{if(hg(n)){t.error("uncaughtException network-class (non-fatal; daemon continues, #638)",{code:n?.code,message:n?.message});return}t.error("uncaughtException fatal (daemon shutting down, #638)",{error:n}),r(n)})}Sn();Sn();Sn();Sn();Sn();Sn();Sn();Sn();Sn();Sn();Dk();oy();oy();oy();Rs();zl();var ze={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function Owe(){console.log(`${ze.cyan}CodeVibe Login${ze.reset}
6009
+ `);c>=0&&i(n.slice(0,c))},s=()=>i(n);e.on("data",o),e.on("end",s)})}var s3,a3,vF,c3,lv,vwe,f3=D(()=>{"use strict";s3=F(require("node:os")),a3=F(require("node:path")),vF=require("node:fs"),c3=require("node:child_process");Or();VS();Ap();kc();lv="openai",vwe=20});var Ebe={};jr(Ebe,{AGY_ARG_PROMPT_MAX_UTF8_BYTES:()=>mw,AUDIT_SUMMARY_PRO_MAX_HEADLINE:()=>OT,AUDIT_SUMMARY_UPGRADE_HINT:()=>DT,AgentType:()=>LC,AppSyncClient:()=>xs,AppSyncGraphQLError:()=>Ut,AuditKeys:()=>eD,AuthService:()=>lh,CONTEXT_SESSION_PSEUDO_TASK_NAMESPACE:()=>JI,CREDENTIAL_STORAGE_UNAVAILABLE_EXIT_CODE:()=>ny,CompositeAdvisoryRunner:()=>Gl,CompositePlannerAdapter:()=>Fl,Continuation:()=>_F,ConversationPane:()=>Py,CredentialBroker:()=>LB,CryptoError:()=>As,CryptoService:()=>Tp,DEFAULT_REPLAY_MAX_FRAME_BYTES:()=>DF,DEFAULT_REPLAY_READ_BYTES:()=>OF,DeliveryStatus:()=>fg,DesktopSyncReadClient:()=>Nc,DurableDesktopSyncWriter:()=>Bc,E1_PROMPT_ID_DOMAIN:()=>_v,ENCRYPTION_VERSION:()=>Pp,EventSource:()=>xp,EventType:()=>ga,FileDurableTeamDeliveryJournal:()=>rc,FlockRolloutLock:()=>fv,HostedGemmaAdvisoryRunner:()=>$l,ImplementorCredentialMissingError:()=>Gu,InProcessRolloutLock:()=>n_,KeychainError:()=>ma,KeychainManager:()=>Jl,LedgerEntrySchema:()=>HC,LedgerFileSchema:()=>Nk,LegacyOwnedFileSchema:()=>Mk,LocalExecutorImpl:()=>El,Logger:()=>jl,MAX_BRAINSTORM_PAGE_BYTES:()=>IS,MAX_BRAINSTORM_PAGE_CHARS:()=>RT,MAX_BRAINSTORM_PAGE_TOKENS:()=>IT,MAX_DYNAMIC_FETCH_CHARS:()=>fR,MAX_FETCHES_PER_TURN:()=>cD,MAX_MOBILE_PROGRESS_MESSAGE_LENGTH:()=>OS,MAX_SEARCHES_PER_TURN:()=>aD,MAX_SYNC_SOURCE_ANCHOR_BYTES:()=>Zo,OllamaGemmaPlannerRunner:()=>zc,PLAIN_DESKTOP_SYNC_TYPES:()=>Dp,PORT_RANGE_SIZE:()=>ch,PRIMARY_PORT:()=>ah,Planner:()=>dB,PromptPublicationTracker:()=>Rc,QuorumLoop:()=>zu,RETAINED_PAGE_MAX_CHARS:()=>Qu,ReplayCursorStateSchema:()=>e_,ReplayFrameTooLargeError:()=>Zm,RetiredSessionCannotReactivateError:()=>lp,RevertManifestStore:()=>Cu,Reviewer:()=>TF,ReviewerCredentialMissingError:()=>$u,ReviewerRole:()=>jC,SEARCH_API_KEY_NAMES:()=>Kv,SESSION_KEY_GEN_ABSENT_SENTINEL:()=>Di,SessionMapRecordSchema:()=>i_,SessionStatus:()=>Jp,SocketRolloutLock:()=>eg,StructuralSummary:()=>V_,Substrate:()=>PF,SubstrateLaunch:()=>HB,SyncEventClientError:()=>ve,SyncJournalError:()=>Ge,SyncReadClientError:()=>Tt,ToolActivityConsolidator:()=>c_,ToolActivityDetailSchema:()=>FC,ToolActivityGroupSchema:()=>$C,ToolActivityLedger:()=>Zp,ToolActivityManifestSchema:()=>GC,ToolActivityOccurrenceSchema:()=>BC,ToolActivityOutbox:()=>eh,ToolActivityOutboxEnvelopeSchema:()=>Fc,ToolActivitySessionMap:()=>o_,ToolReplayCursor:()=>t_,V1_ORCHESTRATION_OPTIONS:()=>Vy,V1_ORCHESTRATION_PROMPT_KIND:()=>BO,WebExtractAbortError:()=>Yh,WebExtractTimeoutError:()=>nw,WorkspaceShadow:()=>Qs,_resetPrepareEventTimestampForTesting:()=>SB,acknowledgeMobileInputDelivery:()=>oh,acknowledgeMobileInputExecution:()=>sh,adaptSnapshotMergeResult:()=>Kw,assertImplementorVendorCredential:()=>qb,assertReviewerVendorCredential:()=>Wb,atomicWriteJsonSync:()=>pu,auditPartitionTaskIdFor:()=>j0,authService:()=>xo,bindOAuthServer:()=>iy,buildAntigravityReviewerCommand:()=>rv,buildAuditBrowserModel:()=>PS,buildClaudeReviewerCommand:()=>nv,buildContextItemWireRow:()=>Cb,buildImplementorArgv:()=>Vs,canRecoverPromptRaise:()=>E_,captureWorkspaceRootAuthority:()=>Le,claimOutageNotificationOnDisk:()=>zA,classifyMobilePromptInput:()=>A3,cleanArbiterSafely:()=>Vu,compileAuditSummary:()=>lc,composeBrainstormPanelBrief:()=>AS,createLogger:()=>p_,createOrchestrationStore:()=>Iy,createRolloutLock:()=>U3,createShellEventEmitter:()=>hc,createSnapshotTrackBundle:()=>uu,createTaskProgressRelay:()=>DS,createToolActivitySyncTransport:()=>Xg,cryptoService:()=>Xe,decryptContextItemWireRow:()=>xb,defaultOutageNotificationRoot:()=>Ju,deriveOpenPromptId:()=>fa,deriveSessionPseudoTaskId:()=>YI,describeStoredAuthFailure:()=>ih,desktopDeferredInputSha256:()=>ad,detectInstalledAgents:()=>En,digestOf:()=>O3,emitShellEvent:()=>Zu,emitTeamCompletionSummary:()=>hu,encryptForEmit:()=>S_,enforceCommand:()=>rl,errorWasBeaconed:()=>ig,executeGitStatusSummary:()=>Pm,extractMcpServerConfig:()=>gw,extractQueryRelevantSnippets:()=>Ws,fireAuthCompletedBeacon:()=>ng,fireAuthFailedBeacon:()=>Ai,formatAuditExport:()=>rp,formatElapsed:()=>ao,formatFetchedContent:()=>uD,formatMobileProgressMessage:()=>$T,getConfig:()=>Bt,getEnvironment:()=>jn,getErrorReason:()=>f_,getInkRuntime:()=>it,handleShellUserInput:()=>aB,htmlToText:()=>Qh,htmlToTextWorker:()=>uR,implementorProviderFor:()=>Hb,initInkRuntime:()=>vy,installDaemonProcessGuards:()=>I_,isNetworkClass:()=>hg,isOpenPromptRaise:()=>k_,isOutageNotificationDeliveredOnDisk:()=>aS,isPersistedEventResult:()=>Ov,isPromptRelevantToRetainedPage:()=>Hd,isRetiredSessionCannotReactivateError:()=>gB,isSessionKeyStaleError:()=>q3,isSpinnerPhase:()=>Kx,isTaskCompletionAuditSummary:()=>pM,isTerminalSessionError:()=>BF,keychainManager:()=>_e,loadConfig:()=>Ev,logger:()=>w,makeImplementorCommandScope:()=>lf,mapOptionNumberToUserDecisionKind:()=>eR,mapOptionToUserDecisionKind:()=>FO,markErrorBeaconed:()=>Ro,markOutageNotificationDeliveredOnDisk:()=>Cl,mintOwnerToken:()=>ug,mutations:()=>et,newPromptRaise:()=>pg,normalizeSnapshot:()=>IF,parseActiveTerminalMenu:()=>I3,parseInteractivePrompt:()=>QP,pickMode:()=>fh,prepareEventTimestamp:()=>bB,prepareSessionEncryption:()=>$m,probeAgentClis:()=>yP,probeAuthPreflight:()=>wP,probeBackendConnectivity:()=>bP,probeOrphanStatus:()=>JS,processMarkers:()=>tp,pushDetectedAgents:()=>jy,queries:()=>qt,raiseFieldsFromRecord:()=>Cp,readDesktopSyncFile:()=>Uk,readStandaloneCompanionStatus:()=>$k,registerDeviceEncryptionKey:()=>cp,rekeySessionForNewDevices:()=>ap,releaseOutageNotificationClaimOnDisk:()=>JA,releaseRecoveryLock:()=>VA,renderAuditBrowserText:()=>_m,renderAuditResultText:()=>Ml,renderConversationEntry:()=>Oh,renderEntryAsLine:()=>XA,renderProgressLine:()=>_d,renderSummaryMarkdown:()=>dc,requiresSyncInputDeliveryReceipt:()=>Os,resumeOrCreateSession:()=>yB,reviewerProviderFor:()=>Ub,routeBrowse:()=>pS,runAuditBrowser:()=>np,runAuditSummary:()=>_S,runAuthCli:()=>VP,runCompanionMode:()=>dF,runDoctorCli:()=>YS,runLineLogFallback:()=>lS,runOrchestrationShell:()=>aP,runSnapshotMergeGate:()=>Hw,runSnapshotMergeWithObservedCleanup:()=>Ff,sanitizeUrlForAudit:()=>lD,scrubSearchApiKeys:()=>nt,selectTerminalMenuOption:()=>R3,setupAgyWebPlugin:()=>TR,shouldRenderPlain:()=>Ds,stableStringify:()=>uv,startAgentWebTurn:()=>gR,startDeviceKeyWatcher:()=>wB,stripAgyWebPlugin:()=>il,stripClaudeWebArgs:()=>ww,stripCodexWebArgs:()=>bw,subscriptions:()=>Ao,sweepOrphanedFallbackDirs:()=>mR,tryAcquireRecoveryLock:()=>jA,validateAgyArgPrompt:()=>zd,wireSnapshotMergeObserver:()=>qw,wireTeamMergeAuditSummary:()=>ZT,withImplementorCredentialPreflight:()=>Uu,withReviewerCredentialPreflight:()=>sm,withRoleMarker:()=>yL});module.exports=GF(Ebe);Nn();Dn();Dn();Dn();R_();var kQ=/ENOTFOUND|ECONNREFUSED|ETIMEDOUT|ECONNRESET|EAI_AGAIN|EPIPE|ENETUNREACH|EHOSTUNREACH|EHOSTDOWN|ECONNABORTED|socket hang up/i;function hg(t){if(t==null)return!1;let e=t.code,r=t.message,n=typeof e=="string"?e:"",i=typeof r=="string"?r:"";return kQ.test(`${n} ${i}`)}function I_(t,e={}){let r=n=>{e.onFatal?e.onFatal(n):process.exit(1)};process.on("unhandledRejection",n=>{if(hg(n)){t.error("unhandledRejection network-class (non-fatal; daemon continues, #638)",{reason:String(n)});return}t.error("unhandledRejection fatal (daemon shutting down, #638)",{reason:String(n)}),r(n instanceof Error?n:new Error(String(n)))}),process.on("uncaughtException",n=>{if(hg(n)){t.error("uncaughtException network-class (non-fatal; daemon continues, #638)",{code:n?.code,message:n?.message});return}t.error("uncaughtException fatal (daemon shutting down, #638)",{error:n}),r(n)})}Sn();Sn();Sn();Sn();Sn();Sn();Sn();Sn();Sn();Sn();Dk();oy();oy();oy();Rs();zl();var ze={reset:"\x1B[0m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m"};async function Owe(){console.log(`${ze.cyan}CodeVibe Login${ze.reset}
6010
6010
  `);try{let t=await xo.getStatus();if(t.authenticated&&t.tokens){console.log(`${ze.yellow}Already logged in as: ${t.tokens.email}${ze.reset}`),console.log(`Token expires: ${new Date(t.tokens.expiresAt).toLocaleString()}`),console.log(`
6011
6011
  Run '${ze.dim}codevibe logout${ze.reset}' to sign out first.`),process.exit(0);return}console.log("Opening browser for authentication..."),console.log(`${ze.dim}Waiting for callback...${ze.reset}
6012
6012
  `);let e=await xo.login();if(e){console.log(`