craby-gateway 0.23.6 → 0.24.0
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.
- package/dist-sea/gateway.cjs +20 -20
- package/package.json +1 -1
package/dist-sea/gateway.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`module`),h=require(`node:child_process`),g=require(`node:module`),_=require(`node:url`),v=require(`node:readline`);v=c(v);let y=require(`node:process`);y=c(y);let b=require(`node:util`),x=require(`node:http`),S=require(`node:https`),C=require(`node:stream/promises`),w=require(`path`);w=c(w);let T=require(`node:string_decoder`),E=require(`net`),D=require(`child_process`),O=require(`@anthropic-ai/claude-agent-sdk`);var k={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.23.6`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.92`,"@fastify/compress":`^8.3.1`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const A=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function j(e){let t=e.match(A);return t?t[0]:null}function M(e){return typeof e==`string`?j(e):null}function N(e,t){let n=F(e),r=F(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function P(e,t){return N(e,t)>=0}function F(e){let t=e.match(A);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const I=k,L=I.dependencies??{};function R(e){return L[e]??``}const z={packageName:`craby-gateway`,cliName:`craby-gateway`,version:I.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:R(`@anthropic-ai/claude-agent-sdk`),minimumVersion:M(R(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ee(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=B(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function B(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var V=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),te=o((e=>{var t=V();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),H=o((e=>{var t=V(),n=te();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`module`),h=require(`node:child_process`),g=require(`node:module`),_=require(`node:url`),v=require(`node:readline`);v=c(v);let y=require(`node:process`);y=c(y);let b=require(`node:util`),x=require(`node:http`),S=require(`node:https`),C=require(`node:stream/promises`),w=require(`path`);w=c(w);let T=require(`node:string_decoder`),E=require(`net`),D=require(`child_process`),O=require(`@anthropic-ai/claude-agent-sdk`);var k={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.24.0`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.92`,"@fastify/compress":`^8.3.1`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const A=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function j(e){let t=e.match(A);return t?t[0]:null}function M(e){return typeof e==`string`?j(e):null}function N(e,t){let n=F(e),r=F(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function P(e,t){return N(e,t)>=0}function F(e){let t=e.match(A);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const I=k,L=I.dependencies??{};function R(e){return L[e]??``}const z={packageName:`craby-gateway`,cliName:`craby-gateway`,version:I.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:R(`@anthropic-ai/claude-agent-sdk`),minimumVersion:M(R(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ee(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=B(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function B(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var V=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),te=o((e=>{var t=V();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),H=o((e=>{var t=V(),n=te();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
3
3
|
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),ne=o((e=>{var t=V(),n=te();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),re=o((e=>{function t(e,n,r,i){if(i&&typeof i==`object`)if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return e.call(n,r,i)}e.applyReviver=t})),ie=o((e=>{var t=V();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),ae=o((e=>{var t=re(),n=V(),r=ie();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),oe=o((e=>{var t=ne(),n=te(),r=V(),i=ae(),a=ie(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),se=o((e=>{var t=V(),n=ae(),r=ie();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ce=o((e=>{var t=oe(),n=V(),r=se();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??=c(e),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),le=o((e=>{var t=ce(),n=V(),r=ae();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),ue=o((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
4
4
|
`)?n(r,t):r.includes(`
|
|
5
5
|
`)?`
|
|
@@ -501,27 +501,27 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
501
501
|
`).map(function(e){return e+`
|
|
502
502
|
`});return t?n.pop():n.push(n.pop().slice(0,-1)),n}const wT=1024*1024;var TT=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return LT(r,await jT(r,t),n,[])}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await MT(void 0,n),i=await MT(e,n),a=p.default.parse(i).root;return LT(a,i,t,await NT(r,a))}async createDirectoryUnrestricted(e,t,n=200,r=f.default.homedir()){let i=IT(t),a=await MT(void 0,r),o=await MT(e,r),s=p.default.join(o,i);await d.default.mkdir(s,{recursive:!1});let c=await d.default.realpath(s),l=p.default.parse(c).root;return LT(l,c,n,await NT(a,l))}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await ET(e,t);return{path:r,absolutePath:n,content:await d.default.readFile(n,`utf8`)}}async diffFile(e,t,n=``){let{absolutePath:r,normalizedPath:i}=await ET(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:ST(i,i,n,a,`base`,`current`),currentContent:a}}async listTree(e,t=`.`,n=500){let r=await d.default.realpath(p.default.resolve(e)),i=DT(t),a=await OT(r,i),o=[];async function s(e,t){let r=await d.default.readdir(e,{withFileTypes:!0});for(let i of r){if(o.length>=n)return;let r=p.default.join(e,i.name),a=t?p.default.join(t,i.name):i.name;i.isSymbolicLink()||(i.isDirectory()?(o.push({path:a,kind:`dir`}),await s(r,a)):o.push({path:a,kind:`file`}))}}return await s(a,``),{root:i,entries:o}}async resolveProjectRelativeFile(e,t){let{absolutePath:n}=await ET(e,t);return zT(n)}async resolveAbsoluteFile(e){let t=e.trim();if(!t)throw Error(`Path is required`);if(!p.default.isAbsolute(t))throw Error(`Path must be absolute: ${e}`);return zT(t)}async readTextFile(e,t={}){let n=await this.resolveAbsoluteFile(e);if(!n.capabilities.canReadText)throw Error(`File is not readable as text: ${n.canonicalPath}`);let r=Math.max(1,Math.floor(t.startLine??1)),i=Math.min(5e3,Math.max(1,Math.floor(t.maxLines??400))),a=Math.min(wT,Math.max(1,Math.floor(t.maxBytes??wT))),o=await d.default.stat(n.canonicalPath),{content:s,endLineExclusive:c,totalLines:l,truncated:u}=await VT(n.canonicalPath,{startLine:r,maxLines:i,maxBytes:a,totalBytes:o.size});return{content:s,encoding:`utf8`,startLine:r,endLineExclusive:c,...l===void 0?{}:{totalLines:l},totalBytes:o.size,truncated:u}}async readFileContentRange(e,t={}){let n=await this.resolveAbsoluteFile(e),r=await d.default.stat(n.canonicalPath),i=r.size,a=BT(r),o=r.mtime.toISOString(),s=t.includeBody!==!1,c=t.rangeHeader?.trim();if(!c)return{statusCode:200,totalSize:i,contentLength:i,buffer:s?await d.default.readFile(n.canonicalPath):void 0,etag:a,lastModified:o};let l=JT(c,i);if(!l)return{statusCode:416,totalSize:i,contentLength:0,contentRange:`bytes */${i}`,etag:a,lastModified:o};let{start:u,end:f}=l,p=f-u+1,m=s?await d.default.open(n.canonicalPath,`r`):null;try{let e;return m&&(e=Buffer.alloc(p),await m.read(e,0,p,u)),{statusCode:206,totalSize:i,contentLength:p,start:u,end:f,contentRange:`bytes ${u}-${f}/${i}`,buffer:e,etag:a,lastModified:o}}finally{await m?.close()}}async openFileContentRangeStream(e,t={}){let n=await this.resolveAbsoluteFile(e),r=await d.default.stat(n.canonicalPath),i=r.size,a=BT(r),o=r.mtime.toISOString(),s=t.includeBody!==!1,c=t.rangeHeader?.trim();if(!c)return{statusCode:200,totalSize:i,contentLength:i,stream:s?(0,u.createReadStream)(n.canonicalPath):void 0,etag:a,lastModified:o};let l=JT(c,i);if(!l)return{statusCode:416,totalSize:i,contentLength:0,contentRange:`bytes */${i}`,etag:a,lastModified:o};let{start:f,end:p}=l;return{statusCode:206,totalSize:i,contentLength:p-f+1,start:f,end:p,contentRange:`bytes ${f}-${p}/${i}`,stream:s?(0,u.createReadStream)(n.canonicalPath,{start:f,end:p}):void 0,etag:a,lastModified:o}}async listEntriesProjectRelative(e,t=`.`,n=200){let r=await d.default.realpath(p.default.resolve(e));return RT(r,await jT(r,t.trim()||`.`),n,r)}async listEntriesAbsolute(e,t=200,n=f.default.homedir()){let r=await MT(e,n);return RT(p.default.parse(r).root,r,t)}};async function ET(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=DT(t),i=await OT(n,r),a=await d.default.realpath(i);return kT(n,a,r),{absolutePath:a,normalizedPath:r}}function DT(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function OT(e,t){if(p.default.isAbsolute(t))throw Error(`Path must be relative to project root: ${t}`);let n=p.default.resolve(e,t);return kT(e,n,t),n}function kT(e,t,n){let r=AT(e),i=AT(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function AT(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function jT(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;kT(e,r,n??`.`);let i=await d.default.realpath(r);if(kT(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function MT(e,t=f.default.homedir()){let n=e?.trim(),r=p.default.resolve(t),i=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(r,n):r,a=await d.default.realpath(i);if(!(await d.default.stat(a)).isDirectory())throw Error(`Path is not a directory: ${a}`);return a}async function NT(e,t){let n=[{kind:`home`,path:e},{kind:`desktop`,path:p.default.join(e,`Desktop`)},{kind:`documents`,path:p.default.join(e,`Documents`)},{kind:`downloads`,path:p.default.join(e,`Downloads`)},{kind:`root`,path:t}],r=new Set,i=[];for(let e of n){let t=await PT(e.path);if(!t)continue;let n=FT(t);r.has(n)||(r.add(n),i.push({kind:e.kind,path:t}))}return i}async function PT(e){try{let t=await d.default.realpath(e);return(await d.default.stat(t)).isDirectory()?t:null}catch{return null}}function FT(e){let t=p.default.normalize(e);return process.platform===`win32`?t.toLowerCase():t}function IT(e){let t=e.trim();if(!t)throw Error(`Directory name is required`);if(t===`.`||t===`..`)throw Error(`Directory name is invalid`);if(t.includes(`/`)||t.includes(`\\`))throw Error(`Directory name must not include path separators`);return t}async function LT(e,t,n,r){let i=(await d.default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,Math.max(1,n)).map(e=>({name:e.name,path:p.default.join(t,e.name)}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),shortcuts:r,directories:i}}async function RT(e,t,n,r){let i=[...await d.default.readdir(t,{withFileTypes:!0})].filter(e=>!e.isSymbolicLink()).sort((e,t)=>e.isDirectory()===t.isDirectory()?e.name.localeCompare(t.name):e.isDirectory()?-1:1).slice(0,Math.max(1,n)),a=await Promise.all(i.map(async e=>{let n=p.default.join(t,e.name),i=await d.default.stat(n);if(e.isDirectory())return{name:e.name,path:r?p.default.relative(r,n)||`.`:n,kind:`dir`,updatedAt:i.mtime.toISOString()};let a=await zT(n);return{name:e.name,path:r?p.default.relative(r,a.canonicalPath)||e.name:a.canonicalPath,kind:`file`,sizeBytes:a.sizeBytes,mimeType:a.mimeType,extension:a.extension,updatedAt:a.updatedAt,previewCategory:a.previewCategory}}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),entries:a}}async function zT(e){let t=await d.default.realpath(p.default.resolve(e)),n=await d.default.stat(t);if(!n.isFile())throw Error(`Path is not a regular file: ${t}`);let r=p.default.extname(t).replace(/^\./,``).toLowerCase()||`bin`,i=UT(r),a=WT(r,i),o=GT(a);return{canonicalPath:t,displayName:p.default.basename(t),sizeBytes:n.size,mimeType:i,extension:r,updatedAt:n.mtime.toISOString(),etag:BT(n),previewCategory:a,preferredPreviewAction:o,capabilities:{canReadText:KT(a,i),canPreparePreview:!0,supportsRange:qT(a)}}}function BT(e){return`${e.size}-${Math.floor(e.mtimeMs)}`}async function VT(e,t){let n=t.startLine+t.maxLines,r=new T.StringDecoder(`utf8`),i=Buffer.allocUnsafe(65536),a=[],o=0,s=1,c=t.startLine,l=0,u=!1,f=!1,p=!1,m=``,h=await d.default.open(e,`r`),g=e=>e>=t.startLine&&e<n,_=e=>{if(!e)return!0;let n=HT(e,t.maxBytes-o);return n&&(a.push(n),o+=Buffer.byteLength(n,`utf8`)),Buffer.byteLength(n,`utf8`)<Buffer.byteLength(e,`utf8`)?(u=!0,!1):!0},v=()=>{g(s)&&(c=Math.max(c,s+1))},y=(e,r=!1)=>{let i=`${m}${e}`;m=``,!r&&i.endsWith(`\r`)&&(m=`\r`,i=i.slice(0,-1));let a=0;for(;a<i.length&&!u&&!f;){let e=i.indexOf(`
|
|
503
503
|
`,a),t=e===-1?i.length:e,r=i.slice(a,t).replace(/\r$/u,``);if(g(s)&&!_(r))return;if(e===-1)break;v();let o=s+1;if(g(s)&&o<n&&!_(`
|
|
504
|
-
`))return;s+=1,a=e+1,s>=n&&(f=!0)}r&&t.totalBytes>0&&!u&&!f&&v()};try{for(;!u&&!f;){let{bytesRead:e}=await h.read(i,0,i.length,null);if(e===0){y(r.end(),!0),p=!0;break}l+=e,y(r.write(i.subarray(0,e))),s>=n&&l<t.totalBytes&&(f=!0)}}finally{await h.close()}return{content:a.join(``),endLineExclusive:a.length===0?t.startLine:c,...p?{totalLines:s}:{},truncated:u||f||!p}}function HT(e,t){if(t<=0||e.length===0)return``;if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=0,r=[];for(let i of e){let e=Buffer.byteLength(i,`utf8`);if(n+e>t)break;r.push(i),n+=e}return r.join(``)}function UT(e){switch(e){case`ts`:case`tsx`:return`text/typescript`;case`js`:case`jsx`:case`mjs`:case`cjs`:return`text/javascript`;case`json`:return`application/json`;case`jsonl`:return`application/x-ndjson`;case`md`:case`markdown`:return`text/markdown`;case`txt`:case`log`:case`yaml`:case`yml`:case`xml`:case`csv`:case`sh`:case`zsh`:case`bash`:case`py`:case`rb`:case`go`:case`rs`:case`java`:case`kt`:case`swift`:case`css`:case`scss`:case`html`:return`text/plain`;case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`gif`:return`image/gif`;case`webp`:return`image/webp`;case`svg`:return`image/svg+xml`;case`mp4`:return`video/mp4`;case`mov`:return`video/quicktime`;case`m4v`:return`video/x-m4v`;case`webm`:return`video/webm`;case`mp3`:return`audio/mpeg`;case`wav`:return`audio/wav`;case`m4a`:return`audio/mp4`;case`pdf`:return`application/pdf`;case`doc`:return`application/msword`;case`docx`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`xls`:return`application/vnd.ms-excel`;case`xlsx`:return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;case`ppt`:return`application/vnd.ms-powerpoint`;case`pptx`:return`application/vnd.openxmlformats-officedocument.presentationml.presentation`;case`zip`:return`application/zip`;case`tar`:return`application/x-tar`;case`gz`:return`application/gzip`;default:return`application/octet-stream`}}function WT(e,t){return t.startsWith(`image/`)?`image`:t.startsWith(`video/`)?`video`:t.startsWith(`audio/`)?`audio`:t===`application/pdf`?`pdf`:t===`application/msword`||t.includes(`officedocument`)||t.includes(`ms-excel`)||t.includes(`ms-powerpoint`)?`office`:e===`md`||e===`markdown`?`markdown`:YT.has(e)?`code`:XT.has(e)||t.startsWith(`text/`)||t===`application/json`||t===`application/x-ndjson`?`text`:ZT.has(e)?`archive`:`binary`}function GT(e){switch(e){case`text`:case`code`:case`markdown`:return`inline_text`;case`image`:case`video`:case`audio`:return`inline_media`;case`pdf`:return`browser`;case`office`:return`share_sheet`;case`archive`:case`binary`:case`unknown`:return`download`}}function KT(e,t){return e===`text`||e===`code`||e===`markdown`||t.startsWith(`text/`)||t===`application/json`||t===`application/x-ndjson`}function qT(e){return e!==`text`&&e!==`code`&&e!==`markdown`}function JT(e,t){if(!e.startsWith(`bytes=`))return null;let n=e.slice(6).trim();if(!n||n.includes(`,`))return null;let[r,i]=n.split(`-`,2);if(r===void 0||i===void 0)return null;let a,o;if(r.length===0){let e=Number(i);if(!Number.isFinite(e)||e<=0)return null;a=Math.max(0,t-e),o=Math.max(0,t-1)}else a=Number(r),o=i.length>0?Number(i):t-1;return!Number.isFinite(a)||!Number.isFinite(o)||a<0||o<a||a>=t?null:(o=Math.min(o,t-1),{start:a,end:o})}const YT=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rb`,`go`,`rs`,`java`,`kt`,`swift`,`css`,`scss`,`html`,`sql`,`toml`,`ini`]),XT=new Set([`txt`,`log`,`yaml`,`yml`,`xml`,`csv`,`json`,`jsonl`,`sh`,`zsh`,`bash`]),ZT=new Set([`zip`,`tar`,`gz`,`tgz`,`bz2`,`xz`,`7z`]),QT=new Set([`thread/status/changed`,`skills/changed`,`mcpServer/startupStatus/updated`]),$T=16*1024;function eE(e,t=`full
|
|
505
|
-
`).length,i=aE(t,n,r),a=
|
|
506
|
-
`)}function oE(e,t,n){return Buffer.from(e,`utf8`).subarray(t,n).toString(`utf8`)}function sE(e,t){let n=Buffer.from(e,`utf8`);return n.subarray(Math.max(0,n.length-t)).toString(`utf8`)}function cE(e){if(e.type===`item.completed`||e.type===`item.updated`){let t=_E(e.payload.raw),n=_E(t.item);return lE(n)?{item:n,replace:n=>({...e,payload:{...e.payload,raw:{...t,item:n}}})}:null}if(e.type!==`native.raw`)return null;let t=_E(e.payload.raw),n=_E(t.message),r=_E(n.params),i=vE(n.method)??vE(t.method);if(i===`item/completed`||i===`item/updated`){let i=_E(r.item);return lE(i)?{item:i,replace:i=>({...e,payload:{...e.payload,raw:{...t,message:{...n,params:{...r,item:i}}}}})}:null}if((vE(t.source)??``).startsWith(`codex.history.thread_read`)&&vE(n.scope)===`item`){let r=_E(n.item);return lE(r)?{item:r,replace:r=>({...e,payload:{...e.payload,raw:{...t,message:{...n,item:r}}}})}:null}return null}function lE(e){let t=hE(e);return t===`commandExecution`||t===`command_execution`}function uE(e){let t=_E(e.payload);return vE(e.aggregatedOutput)??vE(e.aggregated_output)??vE(e.output_delta)??vE(e.outputDelta)??vE(t.output_delta)??vE(t.outputDelta)??null}function dE(e){if(e.type===`item.started`||e.type===`item.completed`){let t=_E(_E(e.payload.raw).item);return{phase:e.type===`item.started`?`started`:`completed`,item:t,itemKey:mE(e.sessionId,t)}}if(e.type!==`native.raw`)return null;let t=_E(e.payload.raw),n=_E(t.message),r=_E(n.params),i=vE(n.method)??vE(t.method);if(i===`item/started`||i===`item/completed`){let t=_E(r.item);return{phase:i===`item/started`?`started`:`completed`,item:t,itemKey:mE(e.sessionId,t),nativeMethod:i,nativeMessage:n,nativeParams:r,nativeItemLocation:`params.item`}}if((vE(t.source)??``).startsWith(`codex.history.thread_read`)&&vE(n.scope)===`item`){let t=_E(n.item);return{phase:`completed`,item:t,itemKey:mE(e.sessionId,t),nativeMessage:n,nativeItemLocation:`message.item`}}return null}function fE(e){if(e.type!==`native.raw`)return null;let t=_E(e.payload.raw);return vE(_E(t.message).method)??vE(t.method)??null}function pE(e){if(e.type!==`native.raw`)return!1;let t=_E(e.payload.raw);if(vE(t.source)!==`codex.app_server`)return!1;let n=_E(t.message);return vE(n.method)??vE(t.method)?!1:!!vE(_E(_E(n.result).turn).id)}function mE(e,t){let n=vE(t.id)??vE(t.item_id)??vE(t.itemId);return n?`${e}|${n}`:null}function hE(e){return vE(e.type)??null}function gE(e){let t=Array.isArray(e.summary)?e.summary:[],n=Array.isArray(e.content)?e.content:[];return t.length===0&&n.length===0}function _E(e){return typeof e==`object`&&e?e:{}}function vE(e){return typeof e==`string`&&e.length>0?e:void 0}var yE=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await SE(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=xE({existing:r,canonicalPath:n,title:bE(t)??void 0,now:i});return r&&r.id!==a.id&&this.projects.delete(r.id),this.projects.set(a.id,a),this.projectByPath.set(n,a),await this.enqueueWrite(async()=>{await this.persistIndex()}),a}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await SE(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)if(!(typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`)){if(e.id!==e.path)throw Error(`Legacy tracked project ids are no longer supported in ${this.indexPath}; clear the project store and restart the gateway.`);this.projects.set(e.id,e),this.projectByPath.set(e.path,e)}}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function bE(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}function xE(e){let t=p.default.basename(e.canonicalPath)||e.canonicalPath;return e.existing?{...e.existing,id:e.canonicalPath,path:e.canonicalPath,title:e.title??bE(e.existing.title)??t,updatedAt:e.now}:{id:e.canonicalPath,title:e.title??t,path:e.canonicalPath,createdAt:e.now,updatedAt:e.now}}async function SE(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}var CE=o(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),wE=o(((e,t)=>{let{EMPTY_BUFFER:n}=CE(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),TE=o(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),EE=o(((e,t)=>{let n=require(`zlib`),r=wE(),i=TE(),{kStatusCode:a}=CE(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),DE=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=CE(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),OE=o(((e,t)=>{let{Writable:n}=require(`stream`),r=EE(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=CE(),{concat:c,toArrayBuffer:l,unmask:u}=wE(),{isValidStatusCode:d,isValidUTF8:f}=DE(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),kE=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=EE(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=CE(),{isBlob:c,isValidStatusCode:l}=DE(),{mask:u,toBuffer:d}=wE(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),AE=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=CE(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),jE=o(((e,t)=>{let{tokenChars:n}=DE();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),ME=o(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=EE(),p=OE(),m=kE(),{isBlob:h}=DE(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=CE(),{EventTarget:{addEventListener:T,removeEventListener:E}}=AE(),{format:D,parse:O}=jE(),{toBuffer:k}=wE(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),F(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,B),i.on(`drain`,V),i.on(`error`,te),i.on(`message`,ne),i.on(`ping`,re),i.on(`pong`,ie),a.onerror=oe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ce),t.on(`data`,le),t.on(`end`,ue),t.on(`error`,de),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),se(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ee(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ee(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ee(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function F(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;I(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?R:L),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{z(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,I(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){z(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{I(e,SyntaxError(`Invalid URL: ${i}`));return}F(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||z(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){z(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){z(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){z(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){z(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){z(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function I(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function L(e){return e.path=e.socketPath,a.connect(e)}function R(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function z(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,z),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(I,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ee(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function B(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,le),process.nextTick(ae,n._socket),e===1005?n.close():n.close(e,t))}function V(){let e=this[C];e.isPaused||e._socket.resume()}function te(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,le),process.nextTick(ae,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function H(){this[C].emitClose()}function ne(e,t){this[C].emit(`message`,e,t)}function re(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ie(e){this[C].emit(`pong`,e)}function ae(e){e.resume()}function oe(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,se(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function se(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function ce(){let e=this[C];if(this.removeListener(`close`,ce),this.removeListener(`data`,le),this.removeListener(`end`,ue),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,H),e._receiver.on(`finish`,H))}function le(e){this[C]._receiver.write(e)||this.pause()}function ue(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function de(){let e=this[C];this.removeListener(`error`,de),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),NE=o(((e,t)=>{ME();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),PE=o(((e,t)=>{let{tokenChars:n}=DE();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),FE=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=jE(),s=EE(),c=PE(),l=ME(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=CE(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
504
|
+
`))return;s+=1,a=e+1,s>=n&&(f=!0)}r&&t.totalBytes>0&&!u&&!f&&v()};try{for(;!u&&!f;){let{bytesRead:e}=await h.read(i,0,i.length,null);if(e===0){y(r.end(),!0),p=!0;break}l+=e,y(r.write(i.subarray(0,e))),s>=n&&l<t.totalBytes&&(f=!0)}}finally{await h.close()}return{content:a.join(``),endLineExclusive:a.length===0?t.startLine:c,...p?{totalLines:s}:{},truncated:u||f||!p}}function HT(e,t){if(t<=0||e.length===0)return``;if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=0,r=[];for(let i of e){let e=Buffer.byteLength(i,`utf8`);if(n+e>t)break;r.push(i),n+=e}return r.join(``)}function UT(e){switch(e){case`ts`:case`tsx`:return`text/typescript`;case`js`:case`jsx`:case`mjs`:case`cjs`:return`text/javascript`;case`json`:return`application/json`;case`jsonl`:return`application/x-ndjson`;case`md`:case`markdown`:return`text/markdown`;case`txt`:case`log`:case`yaml`:case`yml`:case`xml`:case`csv`:case`sh`:case`zsh`:case`bash`:case`py`:case`rb`:case`go`:case`rs`:case`java`:case`kt`:case`swift`:case`css`:case`scss`:case`html`:return`text/plain`;case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`gif`:return`image/gif`;case`webp`:return`image/webp`;case`svg`:return`image/svg+xml`;case`mp4`:return`video/mp4`;case`mov`:return`video/quicktime`;case`m4v`:return`video/x-m4v`;case`webm`:return`video/webm`;case`mp3`:return`audio/mpeg`;case`wav`:return`audio/wav`;case`m4a`:return`audio/mp4`;case`pdf`:return`application/pdf`;case`doc`:return`application/msword`;case`docx`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`xls`:return`application/vnd.ms-excel`;case`xlsx`:return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;case`ppt`:return`application/vnd.ms-powerpoint`;case`pptx`:return`application/vnd.openxmlformats-officedocument.presentationml.presentation`;case`zip`:return`application/zip`;case`tar`:return`application/x-tar`;case`gz`:return`application/gzip`;default:return`application/octet-stream`}}function WT(e,t){return t.startsWith(`image/`)?`image`:t.startsWith(`video/`)?`video`:t.startsWith(`audio/`)?`audio`:t===`application/pdf`?`pdf`:t===`application/msword`||t.includes(`officedocument`)||t.includes(`ms-excel`)||t.includes(`ms-powerpoint`)?`office`:e===`md`||e===`markdown`?`markdown`:YT.has(e)?`code`:XT.has(e)||t.startsWith(`text/`)||t===`application/json`||t===`application/x-ndjson`?`text`:ZT.has(e)?`archive`:`binary`}function GT(e){switch(e){case`text`:case`code`:case`markdown`:return`inline_text`;case`image`:case`video`:case`audio`:return`inline_media`;case`pdf`:return`browser`;case`office`:return`share_sheet`;case`archive`:case`binary`:case`unknown`:return`download`}}function KT(e,t){return e===`text`||e===`code`||e===`markdown`||t.startsWith(`text/`)||t===`application/json`||t===`application/x-ndjson`}function qT(e){return e!==`text`&&e!==`code`&&e!==`markdown`}function JT(e,t){if(!e.startsWith(`bytes=`))return null;let n=e.slice(6).trim();if(!n||n.includes(`,`))return null;let[r,i]=n.split(`-`,2);if(r===void 0||i===void 0)return null;let a,o;if(r.length===0){let e=Number(i);if(!Number.isFinite(e)||e<=0)return null;a=Math.max(0,t-e),o=Math.max(0,t-1)}else a=Number(r),o=i.length>0?Number(i):t-1;return!Number.isFinite(a)||!Number.isFinite(o)||a<0||o<a||a>=t?null:(o=Math.min(o,t-1),{start:a,end:o})}const YT=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rb`,`go`,`rs`,`java`,`kt`,`swift`,`css`,`scss`,`html`,`sql`,`toml`,`ini`]),XT=new Set([`txt`,`log`,`yaml`,`yml`,`xml`,`csv`,`json`,`jsonl`,`sh`,`zsh`,`bash`]),ZT=new Set([`zip`,`tar`,`gz`,`tgz`,`bz2`,`xz`,`7z`]),QT=new Set([`thread/status/changed`,`skills/changed`,`mcpServer/startupStatus/updated`]),$T=16*1024;function eE(e,t=`full`,n={}){if(t!==`compact`||e.length===0)return e;let r=tE(e),i=[];for(let t of e)nE(t,r)||i.push(rE(t,r,n));return i}function tE(e){let t=new Set;for(let n of e){let e=fE(n);e?.phase===`completed`&&e.itemKey&&t.add(e.itemKey)}return t}function nE(e,t){let n=pE(e);if(n&&QT.has(n)||mE(e))return!0;let r=fE(e);if(!r)return!1;let i=gE(r.item);return i?r.phase===`started`?i===`userMessage`||i===`user_message`||i===`agentMessage`||i===`agent_message`||i===`reasoning`&&_E(r.item)?!!(r.itemKey&&t.has(r.itemKey)):!1:i===`reasoning`&&_E(r.item):!1}function rE(e,t,n){let r=cE(e);if(!r||n.compactIncompleteCommandOutput===!1&&r.itemKey&&!t.has(r.itemKey)||uE(r.item))return e;let i=dE(r.item);return i?r.replace(iE(r.item,i)):e}function iE(e,t){let n=Buffer.byteLength(t,`utf8`),r=t.split(`
|
|
505
|
+
`).length,i=aE(t,n,r),a=vE(e.payload),o={...e};if(delete o.aggregatedOutput,delete o.aggregated_output,delete o.output_delta,delete o.outputDelta,o.history_detail_level=`compact`,o.historyDetailLevel=`compact`,o.output_delta=i,Object.keys(a).length>0){let e={...a};delete e.output_delta,delete e.outputDelta,o.payload=e}return i!==t&&(o.history_detail_omitted=!0,o.history_output_omitted=!0,o.history_output_byte_length=n,o.history_output_line_count=r,o.historyDetailOmitted=!0,o.historyOutputOmitted=!0,o.historyOutputByteLength=n,o.historyOutputLineCount=r),o}function aE(e,t,n){if(t<=$T)return e;let r=Math.floor($T/2),i=$T-r,a=oE(e,0,r),o=sE(e,i),s=Buffer.byteLength(a,`utf8`)+Buffer.byteLength(o,`utf8`);return[`[compact history preview: omitted ${Math.max(0,t-s).toLocaleString(`en-US`)} of ${t.toLocaleString(`en-US`)} bytes across ${n.toLocaleString(`en-US`)} lines]`,``,a,``,`[...]`,``,o].join(`
|
|
506
|
+
`)}function oE(e,t,n){return Buffer.from(e,`utf8`).subarray(t,n).toString(`utf8`)}function sE(e,t){let n=Buffer.from(e,`utf8`);return n.subarray(Math.max(0,n.length-t)).toString(`utf8`)}function cE(e){if(e.type===`item.completed`||e.type===`item.updated`){let t=vE(e.payload.raw),n=vE(t.item);return lE(n)?{item:n,itemKey:hE(e.sessionId,n),replace:n=>({...e,payload:{...e.payload,raw:{...t,item:n}}})}:null}if(e.type!==`native.raw`)return null;let t=vE(e.payload.raw),n=vE(t.message),r=vE(n.params),i=yE(n.method)??yE(t.method);if(i===`item/completed`||i===`item/updated`){let i=vE(r.item);return lE(i)?{item:i,itemKey:hE(e.sessionId,i),replace:i=>({...e,payload:{...e.payload,raw:{...t,message:{...n,params:{...r,item:i}}}}})}:null}if((yE(t.source)??``).startsWith(`codex.history.thread_read`)&&yE(n.scope)===`item`){let r=vE(n.item);return lE(r)?{item:r,itemKey:hE(e.sessionId,r),replace:r=>({...e,payload:{...e.payload,raw:{...t,message:{...n,item:r}}}})}:null}return null}function lE(e){let t=gE(e);return t===`commandExecution`||t===`command_execution`}function uE(e){return yE(e.history_detail_level)===`compact`||yE(e.historyDetailLevel)===`compact`||e.history_output_omitted===!0||e.historyOutputOmitted===!0}function dE(e){let t=vE(e.payload);return yE(e.aggregatedOutput)??yE(e.aggregated_output)??yE(e.output_delta)??yE(e.outputDelta)??yE(t.output_delta)??yE(t.outputDelta)??null}function fE(e){if(e.type===`item.started`||e.type===`item.completed`){let t=vE(vE(e.payload.raw).item);return{phase:e.type===`item.started`?`started`:`completed`,item:t,itemKey:hE(e.sessionId,t)}}if(e.type!==`native.raw`)return null;let t=vE(e.payload.raw),n=vE(t.message),r=vE(n.params),i=yE(n.method)??yE(t.method);if(i===`item/started`||i===`item/completed`){let t=vE(r.item);return{phase:i===`item/started`?`started`:`completed`,item:t,itemKey:hE(e.sessionId,t),nativeMethod:i,nativeMessage:n,nativeParams:r,nativeItemLocation:`params.item`}}if((yE(t.source)??``).startsWith(`codex.history.thread_read`)&&yE(n.scope)===`item`){let t=vE(n.item);return{phase:`completed`,item:t,itemKey:hE(e.sessionId,t),nativeMessage:n,nativeItemLocation:`message.item`}}return null}function pE(e){if(e.type!==`native.raw`)return null;let t=vE(e.payload.raw);return yE(vE(t.message).method)??yE(t.method)??null}function mE(e){if(e.type!==`native.raw`)return!1;let t=vE(e.payload.raw);if(yE(t.source)!==`codex.app_server`)return!1;let n=vE(t.message);return yE(n.method)??yE(t.method)?!1:!!yE(vE(vE(n.result).turn).id)}function hE(e,t){let n=yE(t.id)??yE(t.item_id)??yE(t.itemId);return n?`${e}|${n}`:null}function gE(e){return yE(e.type)??null}function _E(e){let t=Array.isArray(e.summary)?e.summary:[],n=Array.isArray(e.content)?e.content:[];return t.length===0&&n.length===0}function vE(e){return typeof e==`object`&&e?e:{}}function yE(e){return typeof e==`string`&&e.length>0?e:void 0}var bE=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await CE(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=SE({existing:r,canonicalPath:n,title:xE(t)??void 0,now:i});return r&&r.id!==a.id&&this.projects.delete(r.id),this.projects.set(a.id,a),this.projectByPath.set(n,a),await this.enqueueWrite(async()=>{await this.persistIndex()}),a}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await CE(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)if(!(typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`)){if(e.id!==e.path)throw Error(`Legacy tracked project ids are no longer supported in ${this.indexPath}; clear the project store and restart the gateway.`);this.projects.set(e.id,e),this.projectByPath.set(e.path,e)}}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function xE(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}function SE(e){let t=p.default.basename(e.canonicalPath)||e.canonicalPath;return e.existing?{...e.existing,id:e.canonicalPath,path:e.canonicalPath,title:e.title??xE(e.existing.title)??t,updatedAt:e.now}:{id:e.canonicalPath,title:e.title??t,path:e.canonicalPath,createdAt:e.now,updatedAt:e.now}}async function CE(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}var wE=o(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),TE=o(((e,t)=>{let{EMPTY_BUFFER:n}=wE(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),EE=o(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),DE=o(((e,t)=>{let n=require(`zlib`),r=TE(),i=EE(),{kStatusCode:a}=wE(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),OE=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=wE(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),kE=o(((e,t)=>{let{Writable:n}=require(`stream`),r=DE(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=wE(),{concat:c,toArrayBuffer:l,unmask:u}=TE(),{isValidStatusCode:d,isValidUTF8:f}=OE(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),AE=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=DE(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=wE(),{isBlob:c,isValidStatusCode:l}=OE(),{mask:u,toBuffer:d}=TE(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),jE=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=wE(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),ME=o(((e,t)=>{let{tokenChars:n}=OE();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),NE=o(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=DE(),p=kE(),m=AE(),{isBlob:h}=OE(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=wE(),{EventTarget:{addEventListener:T,removeEventListener:E}}=jE(),{format:D,parse:O}=ME(),{toBuffer:k}=TE(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),F(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,B),i.on(`drain`,V),i.on(`error`,te),i.on(`message`,ne),i.on(`ping`,re),i.on(`pong`,ie),a.onerror=oe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ce),t.on(`data`,le),t.on(`end`,ue),t.on(`error`,de),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),se(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ee(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ee(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ee(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){z(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function F(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;I(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?R:L),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{z(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,I(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){z(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{I(e,SyntaxError(`Invalid URL: ${i}`));return}F(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||z(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){z(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){z(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){z(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){z(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){z(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{z(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function I(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function L(e){return e.path=e.socketPath,a.connect(e)}function R(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function z(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,z),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(I,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ee(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function B(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,le),process.nextTick(ae,n._socket),e===1005?n.close():n.close(e,t))}function V(){let e=this[C];e.isPaused||e._socket.resume()}function te(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,le),process.nextTick(ae,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function H(){this[C].emitClose()}function ne(e,t){this[C].emit(`message`,e,t)}function re(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ie(e){this[C].emit(`pong`,e)}function ae(e){e.resume()}function oe(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,se(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function se(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function ce(){let e=this[C];if(this.removeListener(`close`,ce),this.removeListener(`data`,le),this.removeListener(`end`,ue),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,H),e._receiver.on(`finish`,H))}function le(e){this[C]._receiver.write(e)||this.pause()}function ue(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function de(){let e=this[C];this.removeListener(`error`,de),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),PE=o(((e,t)=>{NE();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),FE=o(((e,t)=>{let{tokenChars:n}=OE();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),IE=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=ME(),s=DE(),c=FE(),l=NE(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=wE(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
507
507
|
`).join(`\r
|
|
508
508
|
`)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
509
509
|
`)+`\r
|
|
510
510
|
\r
|
|
511
|
-
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));NE(),OE(),kE();var IE=c(ME(),1);FE();var LE=IE.default,RE=120,zE=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${ow(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await BE(RE);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function BE(e){return new Promise(t=>setTimeout(t,e))}var VE=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new zE(this.provider,e)}};function HE(e){let t=KE(WE(e)),n=qE(t.type);return n&&(t.type=UE(n)),t}function UE(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return GE(e)}}function WE(e){if(Array.isArray(e))return e.map(e=>WE(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[GE(n)]=WE(r);return t}return e}function GE(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function KE(e){return typeof e==`object`&&e?e:{}}function qE(e){if(typeof e==`string`)return e}function JE(e){return typeof e==`string`||typeof e==`number`?String(e):``}var YE=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],XE=1e4,ZE=100,QE=2e3;function $E(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function eD(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var tD=new Map;async function nD(e){return sD(e).createConnection()}async function rD(){let e=[...tD.values()];await Promise.allSettled(e.map(e=>e.shutdown())),tD.clear()}async function iD(e){let t=tD.size>0?[...tD.values()]:[sD(e)];await Promise.all(t.map(e=>e.restart()))}function aD(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();return t?oD(t):{command:`codex`,args:[]}}function oD(e){let t=w.default.resolve(e),n=w.default.extname(t).toLowerCase();return n===`.js`||n===`.cjs`||n===`.mjs`?{command:process.execPath,args:[t]}:{command:t,args:[]}}function sD(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=tD.get(t);if(n)return n;let r=new cD(e);return tD.set(t,r),r}var cD=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await uD(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise){await this.shutdownPromise;return}this.shutdownPromise=this.shutdownInternal();try{await this.shutdownPromise}finally{this.shutdownPromise=null}}async restart(){await this.shutdown();let e=await this.ensureRunning();await(await uD(e.url,()=>this.buildStartupError(e.stderrTail))).close()}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await mD(e.child,QE)||(e.child.kill(`SIGKILL`),await mD(e.child,QE)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await pD()}`,t=aD(this.codexBinOverride),n=(0,D.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await fD(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await mD(n,QE)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},lD=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){if(!this.closed){if(this.closed=!0,this.socket.readyState<=1)try{this.socket.close(1e3,`Client closing`)}catch(e){eD(`connection.close_failed`,{readyState:this.socket.readyState,...$E(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=hD(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function uD(e,t){let n=Date.now()+XE,r=null;for(;Date.now()<n;)try{return await dD(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await gD(ZE)}throw r??Error(t())}async function dD(e,t){let n=new LE(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),eD(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){eD(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...$E(r)})}i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new lD(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(r,o)=>{if(a)return;a=!0,s();let c=typeof r==`number`?r:`unknown`,l=o.length>0?`: ${o.toString(`utf8`)}`:``;eD(`connect.closed_before_open`,{url:e,timeoutMs:t,readyState:n.readyState,closeCode:c,closeReason:l||null}),i(Error(`Connection closed before open (${String(c)})${l}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function fD(e,t,n){let r=Date.now()+XE;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await dD(e,500)).close(),!0}catch{await gD(ZE)}}return!1}async function pD(){let e=(0,E.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function mD(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function hD(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function gD(e){return new Promise(t=>{setTimeout(t,e)})}var _D=15e3,vD=5e3,yD={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},bD=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??_D,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:yD,capabilities:{experimentalApi:!1,optOutNotificationMethods:YE}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=JE(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=qE(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=JE(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=KE(e.error),r=qE(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function xD(e,t={}){let n=new bD(await CD(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function SD(e={}){try{return await xD(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??vD}),!0}catch{return!1}}async function CD(e){return e.spawnProcess?new TD(e.spawnProcess()):new wD(await nD(e.codexBinOverride))}var wD=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},TD=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
|
|
511
|
+
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));PE(),kE(),AE();var LE=c(NE(),1);IE();var RE=LE.default,zE=120,BE=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${ow(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await VE(zE);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function VE(e){return new Promise(t=>setTimeout(t,e))}var HE=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new BE(this.provider,e)}};function UE(e){let t=qE(GE(e)),n=JE(t.type);return n&&(t.type=WE(n)),t}function WE(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return KE(e)}}function GE(e){if(Array.isArray(e))return e.map(e=>GE(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[KE(n)]=GE(r);return t}return e}function KE(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function qE(e){return typeof e==`object`&&e?e:{}}function JE(e){if(typeof e==`string`)return e}function YE(e){return typeof e==`string`||typeof e==`number`?String(e):``}var XE=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],ZE=1e4,QE=100,$E=2e3;function eD(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function tD(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var nD=new Map;async function rD(e){return cD(e).createConnection()}async function iD(){let e=[...nD.values()];await Promise.allSettled(e.map(e=>e.shutdown())),nD.clear()}async function aD(e){let t=nD.size>0?[...nD.values()]:[cD(e)];await Promise.all(t.map(e=>e.restart()))}function oD(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();return t?sD(t):{command:`codex`,args:[]}}function sD(e){let t=w.default.resolve(e),n=w.default.extname(t).toLowerCase();return n===`.js`||n===`.cjs`||n===`.mjs`?{command:process.execPath,args:[t]}:{command:t,args:[]}}function cD(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=nD.get(t);if(n)return n;let r=new lD(e);return nD.set(t,r),r}var lD=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await dD(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise){await this.shutdownPromise;return}this.shutdownPromise=this.shutdownInternal();try{await this.shutdownPromise}finally{this.shutdownPromise=null}}async restart(){await this.shutdown();let e=await this.ensureRunning();await(await dD(e.url,()=>this.buildStartupError(e.stderrTail))).close()}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await hD(e.child,$E)||(e.child.kill(`SIGKILL`),await hD(e.child,$E)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await mD()}`,t=oD(this.codexBinOverride),n=(0,D.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await pD(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await hD(n,$E)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},uD=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){if(!this.closed){if(this.closed=!0,this.socket.readyState<=1)try{this.socket.close(1e3,`Client closing`)}catch(e){tD(`connection.close_failed`,{readyState:this.socket.readyState,...eD(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=gD(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function dD(e,t){let n=Date.now()+ZE,r=null;for(;Date.now()<n;)try{return await fD(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await _D(QE)}throw r??Error(t())}async function fD(e,t){let n=new RE(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),tD(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){tD(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...eD(r)})}i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new uD(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(r,o)=>{if(a)return;a=!0,s();let c=typeof r==`number`?r:`unknown`,l=o.length>0?`: ${o.toString(`utf8`)}`:``;tD(`connect.closed_before_open`,{url:e,timeoutMs:t,readyState:n.readyState,closeCode:c,closeReason:l||null}),i(Error(`Connection closed before open (${String(c)})${l}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function pD(e,t,n){let r=Date.now()+ZE;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await fD(e,500)).close(),!0}catch{await _D(QE)}}return!1}async function mD(){let e=(0,E.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function hD(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function gD(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function _D(e){return new Promise(t=>{setTimeout(t,e)})}var vD=15e3,yD=5e3,bD={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},xD=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??vD,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:bD,capabilities:{experimentalApi:!1,optOutNotificationMethods:XE}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=YE(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=JE(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=YE(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=qE(e.error),r=JE(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function SD(e,t={}){let n=new xD(await wD(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function CD(e={}){try{return await SD(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??yD}),!0}catch{return!1}}async function wD(e){return e.spawnProcess?new ED(e.spawnProcess()):new TD(await rD(e.codexBinOverride))}var TD=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},ED=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
|
|
512
512
|
`)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}async close(){this.closed||(this.closed=!0,this.process.stdin.destroyed||this.process.stdin.end(),!this.process.killed&&this.process.exitCode===null&&this.process.kill())}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}),this.process.on(`error`,e=>{this.fail(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.closed)return;let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.fail(`Codex app-server exited unexpectedly (${i})${r}`)})}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
513
|
-
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},ED=3,DD=250;function OD(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function kD(e,t){let n=Math.max(1,t?.maxAttempts??ED),r=Math.max(0,t?.retryDelayMs??DD),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!OD(e)||t>=n)throw e;r>0&&await AD(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function AD(e){return new Promise(t=>{setTimeout(t,e)})}function jD(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function MD(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var ND=3e4,PD=1e3,FD=2e3,ID=1e3,LD={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},RD=class e{constructor(e,t,n,r,i,a){this.process=t,this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.logger=e.logger,this.requestTimeoutMs=n,this.closeInterruptTimeoutMs=r,this.closeGraceTimeoutMs=i,this.forceKillTimeoutMs=a,this.processExitPromise=new Promise(e=>{this.resolveProcessExit=e}),this.bindProcess()}id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;requestTimeoutMs;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;interruptRequested=!1;interruptIssuedTurnId;titleReadInFlight=!1;stdoutBuffer=``;stderrTail=``;closeInterruptTimeoutMs;closeGraceTimeoutMs;forceKillTimeoutMs;processExitPromise;resolveProcessExit=null;closePromise=null;static async create(t,n={}){let r=new e(t,n.spawnProcess?.()??zD(),n.requestTimeoutMs??ND,n.closeInterruptTimeoutMs??PD,n.closeGraceTimeoutMs??FD,n.forceKillTimeoutMs??ID);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.resetInterruptState();try{let n=t?.model??this.activeModel,r=jD(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=VD(this.activeSessionConfig.reasoningEffort),o,s=HD(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&UD(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:HD(t?.mode,n,`low`)})}let c=qE(o.turn?.id);c&&(this.activeTurnId=c),this.flushQueuedInterrupt(`turn_start_response`)}catch(e){throw this.turnInProgress=!1,this.resetInterruptState(),e}}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async interrupt(){this.ensureOpen(),this.turnInProgress&&(this.interruptRequested=!0,await this.requestActiveTurnInterrupt())}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;if(r.method===`item/commandExecution/requestApproval`||r.method===`execCommandApproval`){let e={decision:i};this.sendResponse(r.rpcId,e)}else{let e={decision:i};this.sendResponse(r.rpcId,e)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=GD(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:MD(r),inputMethod:n.method})}async bootstrap(){let e={clientInfo:LD,capabilities:{experimentalApi:!0,optOutNotificationMethods:YE}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return qE((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return qE((await kD(()=>this.sendRequest(`thread/resume`,i))).thread?.id)}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.consumeStderrChunk(String(e))}),this.process.on(`error`,e=>{this.handleProcessFailure(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.resolveProcessExit?.(),this.resolveProcessExit=null,this.closed){this.log(`info`,`codex app-server process exited during shutdown`,{exitCode:e,signal:t});return}let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.handleProcessFailure(`Codex app-server exited unexpectedly (${i})${r}`)})}async closeInternal(){if(this.closed)return;let e=Date.now(),t={threadId:this.threadId,activeTurnId:this.activeTurnId};this.log(`info`,`codex app-server shutdown starting`,{...t,turnInProgress:this.turnInProgress,pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,closeInterruptTimeoutMs:this.closeInterruptTimeoutMs,closeGraceTimeoutMs:this.closeGraceTimeoutMs,forceKillTimeoutMs:this.forceKillTimeoutMs});let n=await this.tryInterruptTurnForClose();this.log(n.result===`failed`?`warn`:`info`,`codex app-server shutdown turn interrupt completed`,{...t,interrupt:n}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.pendingApprovals.clear(),this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.endProcessStdin();let r=Date.now();if(await this.waitForProcessExit(this.closeGraceTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`graceful_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r});return}this.log(`warn`,`codex app-server shutdown grace period elapsed; sending SIGTERM`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r}),this.tryKillProcess(`SIGTERM`);let i=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigterm_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i});return}this.log(`warn`,`codex app-server shutdown SIGTERM grace elapsed; sending SIGKILL`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i}),this.tryKillProcess(`SIGKILL`);let a=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigkill_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a});return}this.log(`error`,`codex app-server shutdown did not observe process exit after SIGKILL`,{...t,result:`sigkill_timeout`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a})}async tryInterruptTurnForClose(){let e=Date.now();if(!this.threadId||!this.activeTurnId)return{attempted:!1,result:`skipped`,durationMs:Date.now()-e,reason:this.threadId?`missing_active_turn_id`:`missing_thread_id`};try{return await KD(this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:this.activeTurnId}),this.closeInterruptTimeoutMs,`Codex app-server turn/interrupt timed out during close`),{attempted:!0,result:`submitted`,durationMs:Date.now()-e}}catch(t){return{attempted:!0,result:`failed`,durationMs:Date.now()-e,error:String(t)}}}endProcessStdin(){if(!(this.process.stdin.destroyed||this.process.stdin.writableEnded))try{this.process.stdin.end()}catch{}}async waitForProcessExit(e){if(this.process.exitCode!==null)return!0;if(!Number.isFinite(e)||e<=0)return await this.processExitPromise,!0;let t;try{await Promise.race([this.processExitPromise,new Promise(n=>{t=setTimeout(n,e)})])}finally{t&&clearTimeout(t)}return this.process.exitCode!==null}tryKillProcess(e){if(this.process.exitCode===null)try{this.process.kill(e)}catch{}}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,processPid:this.process.pid??void 0,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
514
|
-
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t&&this.handleIncomingLine(t)}}consumeStderrChunk(e){this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}handleIncomingLine(e){let t;try{t=JSON.parse(e)}catch{this.emit({type:`native.raw`,source:`codex.app_server`,parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON line from codex app-server`,line:e});return}this.emit({type:`native.raw`,source:`codex.app_server`,message:t});let n=
|
|
515
|
-
`)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=BD(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated(qE(e.thread?.name)??qE(e.thread?.preview),qE(e.thread?.name)?`codex.thread_read_name`:`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleProcessFailure(e){if(this.closed)return;let t=this.threadId,n=this.activeTurnId;this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.process`,...t?{thread_id:t}:{},...n?{turn_id:n}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}resetInterruptState(){this.interruptRequested=!1,this.interruptIssuedTurnId=void 0}flushQueuedInterrupt(e){this.interruptRequested&&this.requestActiveTurnInterrupt().catch(t=>{this.log(`warn`,`codex app-server queued interrupt failed`,{reason:e,error:t instanceof Error?t.message:String(t)})})}async requestActiveTurnInterrupt(){if(!this.turnInProgress||!this.threadId||!this.activeTurnId)return;let e=this.activeTurnId;if(this.interruptIssuedTurnId!==e){this.interruptIssuedTurnId=e;try{await this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:e})}catch(t){throw this.turnInProgress&&this.activeTurnId===e&&(this.interruptIssuedTurnId=void 0),t}}}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function zD(){let e=aD();return(0,D.spawn)(e.command,[...e.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function BD(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function VD(e){return e?e===`max`?`xhigh`:e:null}function HD(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function UD(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function WD(e){let t=KE(e),n=qE(t.id),r=qE(t.header),i=qE(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=KE(e),n=qE(t.label),r=qE(t.description)??n,i=qE(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:t.isOther===!0,isSecret:t.isSecret===!0,options:o}}function GD(e){let t={};for(let[n,r]of Object.entries(e??{}))n&&(t[n]=Array.isArray(r)?r.map(e=>String(e)):[]);return t}async function KD(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}var qD=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new VE(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await SD()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??RD.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function JD(e,t){let n=[],r=null,i=eO(t?.maxThreads),a=t?.sortKey,o=t?.updatedAfterUnixSeconds;do{let t=i===null?100:Math.max(0,i-n.length);if(t===0)break;let s=await YD({cwd:e,archived:!1,cursor:r,limit:i===null?100:Math.min(100,t),sortKey:a}),c=!1;for(let t of s.threads)if(t.cwd===e){if(o!==void 0&&t.updatedAt<o){if(a===`updated_at`){c=!0;break}continue}if(n.push(t),i!==null&&n.length>=i){c=!0;break}}if(c)break;r=s.nextCursor}while(r);return n}async function YD(e){return xD(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>$D(e)),nextCursor:n.nextCursor}})}async function XD(e,t=!0){return xD(async n=>$D((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function ZD(e){return xD(async t=>{let n=!1;try{let r=await kD(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,rO(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function QD(){let e=[],t=null;do{let n=await xD(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>nO(e))),t=n.nextCursor}while(t);return e}function $D(e){let t=qE(KE(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,status:tO(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:aO(e.source),gitInfo:e.gitInfo?KE(WE(e.gitInfo)):null,turns:e.turns.map(e=>iO(e))}}function eO(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function tO(e){let t=qE(KE(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function nO(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function rO(e){let t=oO(e.model),n=sO(e.reasoningEffort),r=cO(e.approvalPolicy),i=lO(e.sandbox),a=r!==null||i!==null;return t||n!==null||a?{model:t,sessionTurnConfig:{mode:`default`,model:t??null,reasoningEffort:n,...a?{execution:{codex:{approvalPolicy:r,sandboxMode:i}}}:{}},sessionTurnConfigUpdatedAt:new Date(e.thread.updatedAt*1e3).toISOString()}:null}function iO(e){return{id:e.id,status:e.status,error:e.error?KE(WE(e.error)):null,items:e.items.map(e=>HE(e))}}function aO(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function oO(e){return qE(e)?.trim()||void 0}function sO(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function cO(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function lO(e){let t=typeof e==`string`?e:qE(KE(e).type);return t===`read-only`||t===`readOnly`?`read-only`:t===`workspace-write`||t===`workspaceWrite`?`workspace-write`:t===`danger-full-access`||t===`dangerFullAccess`?`danger-full-access`:null}var uO=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;activeTurnTerminalEmitted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=jD(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=hO(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:MD(r),questions:pO(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{let t=null;try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=PO(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:FO(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(n){if(this.closed||this.activeQuery!==e)return;let r=n instanceof Error?n.message:String(n);this.interruptRequested?t=r:this.emit({type:`error`,message:r})}finally{if(this.closed||this.activeQuery!==e)return;if(this.interruptRequested&&!this.activeTurnTerminalEmitted){let e=this.buildInterruptedTerminalEvents(t??`Operation aborted`);for(let t of e)this.emit(t)}this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>fO(e,t)?this.requestUserInput(e,t,n):dO(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${ow(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=pO(t),i=`req_${ow(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1}captureResumeSessionId(e){let t=PO(e),n=FO(t.session_id)??FO(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${ow(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=zO(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=FO(e.tool_id)??FO(e.tool_use_id)??LO(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=FO(e.uuid);if(n)return this.activeToolItemId=n,n;let r=BO(FO(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}buildInterruptedTerminalEvents(e){return this.activeTurnTerminalEmitted=!0,[...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,status:`interrupted`,error:{message:e},turn_id:this.activeTurnId,source_event_type:`abort`}]}mapClaudeMessage(e){let t=PO(e),n=FO(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!kO(t))return[];let n=AO(PO(t.message));return n?[{type:`item.completed`,item:{id:FO(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:FO(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=OO(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=PO(t.event);if(FO(e.type)===`message_start`){let t=zO(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=jO(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||FO(t.subtype)?.startsWith(`error_`)===!0){let n=MO(t);return this.activeTurnTerminalEmitted=!0,[...e,{type:`turn.failed`,error:{message:n},usage:NO(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:NO(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=FO(t.summary)??`tool summary`,i=FO(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=FO(t.tool_name)??`tool`,i=FO(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=FO(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(FO(t.session_id)??FO(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:FO(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=FO(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=gO(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=_O(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=vO({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function dO(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function fO(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function pO(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=mO(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function mO(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function hO(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function gO(e){let t=PO(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=PO(e);if(t.type!==`tool_use`)continue;let n=FO(t.id),i=FO(t.name),a=PO(t.input);if(!(!n||!i)){if(i===`Task`){let e=FO(a.subagent_type),t=FO(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:FO(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=FO(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=FO(a.file_path);r.push({id:n,toolName:`Write`,title:CO(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function _O(e){let t=PO(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=PO(e);if(t.type!==`tool_result`)continue;let n=FO(t.tool_use_id);if(n)return{toolUseId:n}}return null}function vO(e){let t=PO(e.raw.tool_use_result),n=yO(t.content)??AO(PO(e.raw.message)),r=PO(t.usage),i=RO(t.totalTokens)??RO(r.total_tokens)??RO(r.output_tokens),a=RO(t.totalToolUseCount),o=RO(t.totalDurationMs),s=FO(t.agentId),c=FO(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=xO(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=bO(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=IO(t.content),r=SO(TO(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function yO(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=PO(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
516
|
-
`):void 0}function
|
|
517
|
-
`).length}function
|
|
518
|
-
`)}function jO(e){let t=PO(PO(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function MO(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):FO(e.subtype)||`Claude turn failed`}function NO(e){let t=PO(e);return{input_tokens:RO(t.input_tokens)??RO(t.inputTokens)??0,cached_input_tokens:RO(t.cached_input_tokens)??RO(t.cache_read_input_tokens)??RO(t.cacheReadInputTokens)??0,output_tokens:RO(t.output_tokens)??RO(t.outputTokens)??0}}function PO(e){return typeof e==`object`&&e?e:{}}function FO(e){if(typeof e==`string`&&e.trim())return e}function IO(e){if(typeof e==`string`&&e.length>0)return e}function LO(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function RO(e){if(typeof e==`number`&&Number.isFinite(e))return e}function zO(e){let t=FO(PO(e.message).id);if(t)return t;let n=FO(PO(PO(e.event).message).id);if(n)return n}function BO(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var VO=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=HO(e);for(let e of this.listeners)e(t)};if(typeof e?.subscribe==`function`){let n=e.subscribe(e=>t(e));typeof n==`function`&&(this.unsubscribe=n);return}if(typeof e?.on==`function`){let n=e=>t(e);e.on(`event`,n),this.unsubscribe=()=>{typeof e?.off==`function`&&e.off(`event`,n)};return}throw Error(`Native session does not expose a known event subscription API`)}};function HO(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var UO=`@anthropic-ai/claude-agent-sdk`,WO=`claude-sonnet-4-6`,GO=1e4,KO=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(UO),!0}catch{return!1}}async createSession(e){if(!this.preferNative)throw Error(`Claude native provider is disabled. Set ENABLE_NATIVE_PROVIDERS=true to use Claude sessions.`);try{let t=await import(UO),n=await qO(JO(t,e),GO,`Claude native query session creation timed out`);if(n)return n;let r=await qO(YO(t,e),GO,`Claude legacy native session creation timed out`);if(r)return r;throw this.requireNative,Error(`Claude SDK loaded but no supported stable session API was found`)}catch(e){throw Error(`Claude native session creation failed: ${String(e)}`)}}};async function qO(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}async function JO(e,t){let n=XO(e);if(!n)return null;let r=t.model??WO;return new uO(t.sessionId,r,({prompt:e,model:i,sessionConfig:a,resume:o,abortController:s,canUseTool:c})=>{let l=a?.permissionMode??t.sessionConfig?.permissionMode??`default`,u={model:i??r,includePartialMessages:!0,abortController:s,canUseTool:c,permissionMode:l},d=ZO(a?.reasoningEffort??t.sessionConfig?.reasoningEffort);return d&&(u.effort=d),l===`bypassPermissions`&&(u.allowDangerouslySkipPermissions=!0),t.cwd&&(u.cwd=t.cwd),o&&(u.resume=o,u.forkSession=!1),n({prompt:e,options:u})},t.resumeSessionId,{cwd:t.cwd})}async function YO(e,t){if(typeof e?.createSession==`function`){let n=await e.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new VO(`claude`,t.sessionId,t.model,n)}if(typeof e?.ClaudeAgentClient==`function`){let n=new e.ClaudeAgentClient;if(typeof n?.createSession==`function`){let e=await n.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new VO(`claude`,t.sessionId,t.model,e)}}if(typeof e?.default?.createSession==`function`){let n=await e.default.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new VO(`claude`,t.sessionId,t.model,n)}return null}function XO(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function ZO(e){if(e){if(e===`max`)return`max`;if(e===`high`||e===`medium`||e===`low`)return e;if(e===`xhigh`)return`max`;if(e===`minimal`||e===`none`)return`low`}}function QO(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new qD(n,r):new KO(n,r)}const $O=p.default.join(`.claude`,`projects`),ek=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function tk(e){return(await(0,O.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>ck(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function nk(e,t){let n=ok(e,t?.homeDir),r=p.default.resolve(e);try{let i=await lk(e,n,r,{maxSessions:Rk(t?.maxSessions),updatedAfterMs:Lk(t?.updatedAfterMs)});if(i.length>0)return i}catch{}return uk(n,{maxSessions:Rk(t?.maxSessions),updatedAfterMs:Lk(t?.updatedAfterMs)})}async function rk(e){let t=await Ck(e.nativeSessionId,e.projectPath),n=await wk(e.projectPath,e.nativeSessionId,e.homeDir),r=pk(t,{createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),i=mk(r.updatedAt,n.mtimeMs);return{rawEvents:ik({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),model:r.model,updatedAt:i,status:hk(t),nativeWatchPath:ak(e.projectPath,e.nativeSessionId,e.homeDir)}}function ik(e){let t=[],n=pk(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function ak(e,t,n){return p.default.join(ok(e,n),`${t}.jsonl`)}function ok(e,t){let n=t??f.default.homedir();return p.default.join(n,$O,sk(e))}function sk(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function ck(e){let t=Nk(e.customTitle)??Nk(e.summary)??Nk(e.firstPrompt),n=xk(e.createdAt??e.lastModified),r=xk(e.lastModified);return{nativeSessionId:e.sessionId,cwd:bk(e.cwd),title:t,createdAt:n,updatedAt:r,status:`idle`}}async function lk(e,t,n,r){let i=Math.max(1,Math.min(r.maxSessions??100,100)),a=[],o=0,s=!1;for(;r.maxSessions===void 0||a.length<r.maxSessions;){let c=r.maxSessions===void 0?i:Math.max(1,Math.min(i,r.maxSessions-a.length)),l=await(0,O.listSessions)({dir:e,limit:c,offset:o});if(l.length===0)break;for(let e of l){let i=Lk(e.lastModified);if(r.updatedAfterMs!==void 0&&i!==void 0&&i<r.updatedAfterMs){s=!0;break}let o=ck(e);if(typeof o.cwd!=`string`||p.default.resolve(o.cwd)!==n)continue;let c=await dk(t,{nativeSessionId:o.nativeSessionId,sdkSession:o});if(c&&(a.push(c),r.maxSessions!==void 0&&a.length>=r.maxSessions))break}if(s||r.maxSessions!==void 0&&a.length>=r.maxSessions||l.length<c)break;o+=l.length}return fk(a,r)}async function uk(e,t){let n=[];try{n=await d.default.readdir(e,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}let r=[];for(let t of n){if(!t.isFile()||!t.name.endsWith(`.jsonl`))continue;let n=await dk(e,{nativeSessionId:t.name.slice(0,-6)});n&&r.push(n)}return fk(r,t)}async function dk(e,t){let n=p.default.join(e,`${t.nativeSessionId}.jsonl`),r;try{r=await Sk(n)}catch(e){if(e.code===`ENOENT`)return t.sdkSession;throw e}if(!yk(r))return;let i=await d.default.stat(n),a=t.sdkSession?.createdAt?Ik(t.sdkSession.createdAt):void 0,o=t.sdkSession?.updatedAt?Ik(t.sdkSession.updatedAt):void 0,s=pk(r,{createdAtFallbackMs:a??i.birthtimeMs,updatedAtFallbackMs:o??i.mtimeMs});return{nativeSessionId:t.nativeSessionId,model:s.model,title:t.sdkSession?.title??s.title,createdAt:s.createdAt,updatedAt:t.sdkSession?.updatedAt??s.updatedAt,status:hk(r)}}function fk(e,t){let n=e.filter(e=>{if(t.updatedAfterMs===void 0)return!0;let n=Ik(e.updatedAt);return n===void 0?!0:n>=t.updatedAfterMs}).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return t.maxSessions===void 0?n:n.slice(0,t.maxSessions)}function pk(e,t){let n,r,i,a;for(let t of e)if(t.timestampMs!==void 0&&(i=i===void 0?t.timestampMs:Math.min(i,t.timestampMs),a=a===void 0?t.timestampMs:Math.max(a,t.timestampMs)),!r&&t.type===`user`&&(r=Ak(Ok(jk(t.raw.message)))),t.type===`assistant`){let e=Mk(jk(t.raw.message).model);e&&(n=e)}let o=i??Lk(t.createdAtFallbackMs)??0,s=a??Lk(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function mk(e,t){let n=Ik(e)??0,r=Lk(t)??0;return new Date(Math.max(n,r)).toISOString()}function hk(e,t=Date.now()){let n=null;for(let t of e){let e=gk(t);e&&(n=e)}return!n?.unresolved||n.timestampMs!==void 0&&t-n.timestampMs>6e5?`idle`:`running`}function gk(e){let t=e.timestampMs??Ik(e.timestamp??``);switch(e.type){case`assistant`:case`result`:case`tool_use_summary`:return{unresolved:!1,timestampMs:t};case`stream_event`:case`tool_progress`:return{unresolved:!0,timestampMs:t};case`user`:return _k(e.raw,t);default:return null}}function _k(e,t){let n=jk(e);if(n.isMeta===!0)return null;let r=jk(n.message);if(Dk(r).length>0)return{unresolved:!0,timestampMs:t};let i=Ok(r);return i?vk(i)?{unresolved:!1,timestampMs:t}:{unresolved:!0,timestampMs:t}:null}function vk(e){let t=e.toLowerCase();return t.includes(`<command-name>/exit</command-name>`)||t.includes(`<command-message>exit</command-message>`)||t.includes(`<local-command-stdout>catch you later!</local-command-stdout>`)}function yk(e){for(let t of e){if(t.type===`user`){let e=jk(t.raw.message);if(Ok(e)||Dk(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=jk(t.raw.message);if(Ok(e)||Ek(e).length>0||Mk(t.raw.error))return!0}return!1}function bk(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function xk(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Sk(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
|
519
|
-
`),n=[];for(let e=0;e<t.length;e+=1){let r=t[e]?.trim();if(!r)continue;let i;try{i=JSON.parse(r)}catch{continue}let a=
|
|
520
|
-
`))}function kk(e){let t=Array.isArray(e.text_elements)?e.text_elements:Array.isArray(e.textElements)?e.textElements:[];if(t.length===0)return;let n=[];for(let e of t){let t=jk(e),r=Mk(t.text)??Mk(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function Ak(e,t=60){if(!e)return;let n=Fk(e).replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function jk(e){return typeof e==`object`&&e?e:{}}function Mk(e){return typeof e==`string`&&e.trim()||void 0}function Nk(e){if(typeof e==`string`)return Pk(e)}function Pk(e){if(!e)return;let t=Fk(e).trim();return t.length>0?t:void 0}function Fk(e){return e.replace(ek,``)}function Ik(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function Lk(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.round(e)}function Rk(e){if(e===void 0||!Number.isFinite(e))return;let t=Math.floor(e);return t>0?t:void 0}var zk=class{constructor(e){this.options=e}async init(){await this.options.store.init()}async getProjects(){await this.init();let e=await this.options.store.getIndex();return e?{generatedAt:e.generatedAt,source:`cache`,providers:e.providers,projects:e.projects}:this.refreshProjects()}async refreshProjects(){await this.init();let e=new Map,[t,n]=await Promise.all([this.scanCodexSessions(e),this.scanClaudeSessions(e)]),r=new Date().toISOString(),i={codex:t.status,claude:n.status},{projects:a,projectSessions:o}=Vk(r,[t,n]);if(Hk(i)){let e=await this.options.store.getSnapshot();if(e)return await this.options.store.writeSnapshot({...e,providers:i}),{generatedAt:e.generatedAt,source:`cache`,providers:i,projects:e.projects}}return await this.options.store.writeSnapshot({generatedAt:r,providers:i,projects:a,projectSessions:o}),{generatedAt:r,source:`fresh_scan`,providers:i,projects:a}}async listProjectSessions(e){await this.init();let t=e.trim(),n=await this.options.store.getIndex(),r=!1;n||(n=Wk(await this.refreshProjects()),r=!0);let i=await Uk(n.projects,t);if(!i)throw ww(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Wk(await this.refreshProjects()),i=await Uk(n.projects,t),!i)throw ww(t);if(a=await this.options.store.getProject(i.key),!a)throw Error(`Discovery cache missing project sessions: ${i.path}`)}if(!a)throw Error(`Discovery cache missing project sessions: ${i.path}`);return{canonicalProjectPath:i.path,project:a.project,providers:a.providers,sessions:a.sessions}}async scanCodexSessions(e){let t=new Date().toISOString();try{let n=new Map;for(let e of[!1,!0]){let t=null;do{let r=await YD({archived:e,cursor:t,limit:100});for(let e of r.threads)n.set(e.id,e);t=r.nextCursor}while(t)}let r=await Bk({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>qk(e.cwd),mapSession:e=>{let t=Jk(e.createdAt),n=Jk(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:qk(e.name)??qk(e.preview),model:qk(e.model),createdAt:t,updatedAt:n}}});return{records:r.records,status:{scannedAt:t,sessionCount:r.records.length,status:r.skippedCount>0?`partial`:`ready`,...r.skippedCount>0?{error:`Skipped ${r.skippedCount} Codex session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}async scanClaudeSessions(e){let t=new Date().toISOString();try{let n=await Bk({sessions:await tk(),canonicalPathCache:e,getRawPath:e=>qk(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:qk(e.title),model:qk(e.model),createdAt:qk(e.createdAt),updatedAt:e.updatedAt})});return{records:n.records,status:{scannedAt:t,sessionCount:n.records.length,status:n.skippedCount>0?`partial`:`ready`,...n.skippedCount>0?{error:`Skipped ${n.skippedCount} Claude session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}};async function Bk(e){let t=[],n=0;for(let r of e.sessions){let i=e.getRawPath(r);if(!i){n+=1;continue}try{let n=await Gk(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Vk(e,t){let n=new Map;for(let e of t)for(let t of e.records){let e=n.get(t.canonicalProjectPath);e||(e={path:t.canonicalProjectPath,key:Kk(t.canonicalProjectPath),title:p.default.basename(t.canonicalProjectPath)||t.canonicalProjectPath,providerCounts:{codex:0,claude:0},sessionsByKey:new Map},n.set(t.canonicalProjectPath,e));let r=`${t.session.provider}:${t.session.nativeSessionId}`,i=e.sessionsByKey.get(r);i||(e.providerCounts[t.session.provider]+=1);let a=Yk(i,t.session);e.sessionsByKey.set(r,a),(!e.lastSessionAt||t.session.updatedAt>e.lastSessionAt)&&(e.lastSessionAt=t.session.updatedAt)}let r=[...n.values()].map(t=>({project:{key:t.key,path:t.path,title:t.title,lastSessionAt:t.lastSessionAt,sessionCount:t.sessionsByKey.size,providerCounts:t.providerCounts,lastDiscoveryAt:e},sessions:[...t.sessionsByKey.values()].sort(Zk)})).sort((e,t)=>Xk(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function Hk(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Uk(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await SE(t);return e.find(e=>e.path===r)}function Wk(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function Gk(e,t){let n=t.get(e);return n||(n=SE(e),t.set(e,n)),n}function Kk(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function qk(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Jk(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Yk(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function Xk(e,t){let n=e.lastSessionAt??e.lastDiscoveryAt,r=t.lastSessionAt??t.lastDiscoveryAt;return n===r?e.path.localeCompare(t.path):r.localeCompare(n)}function Zk(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Qk=class{indexPath;projectsDir;ready;writeQueue=Promise.resolve();indexCache=null;projectCache=new Map;constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`discovery-index.json`),this.projectsDir=p.default.join(e,`discovery-projects`),this.ready=this.loadFromDisk()}async init(){await this.ready}async getIndex(){return await this.ready,this.indexCache?structuredClone(this.indexCache):null}async getProject(e){await this.ready;let t=this.projectCache.get(e);if(t)return structuredClone(t);let n=await $k(this.getProjectPath(e),nA);return n?(this.projectCache.set(e,n),structuredClone(n)):null}async getSnapshot(){if(await this.ready,!this.indexCache)return null;let e=[];for(let t of this.indexCache.projects){let n=await this.getProject(t.key);if(!n)return null;e.push({project:n.project,sessions:n.sessions})}return{generatedAt:this.indexCache.generatedAt,providers:structuredClone(this.indexCache.providers),projects:structuredClone(this.indexCache.projects),projectSessions:e}}async writeSnapshot(e){await this.ready;let t={v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects},n=e.projectSessions.map(t=>({v:1,projectKey:t.project.key,canonicalProjectPath:t.project.path,project:t.project,providers:e.providers,sessions:t.sessions}));await this.enqueueWrite(async()=>{await d.default.mkdir(this.projectsDir,{recursive:!0});let e=new Set(n.map(e=>e.projectKey)),r=[];try{r=await d.default.readdir(this.projectsDir,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}await Promise.all(n.map(async e=>{await eA(this.getProjectPath(e.projectKey),e)})),await Promise.all(r.map(async t=>{if(!t.isFile()||!t.name.endsWith(`.json`))return;let n=t.name.slice(0,-5);e.has(n)||(await d.default.rm(p.default.join(this.projectsDir,t.name),{force:!0}),this.projectCache.delete(n))})),await eA(this.indexPath,t),this.indexCache=t,this.projectCache.clear();for(let e of n)this.projectCache.set(e.projectKey,e)})}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0}),await d.default.mkdir(this.projectsDir,{recursive:!0}),this.indexCache=await $k(this.indexPath,tA)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function $k(e,t){try{let n=await d.default.readFile(e,`utf8`),r=JSON.parse(n);return t(r)?r:null}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function eA(e,t){let n=`${JSON.stringify(t,null,2)}\n`;try{if(await d.default.readFile(e,`utf8`)===n)return}catch(e){if(e.code!==`ENOENT`)throw e}await d.default.mkdir(p.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await d.default.writeFile(r,n,`utf8`),await d.default.rename(r,e)}function tA(e){return!rA(e)||e.v!==1||typeof e.generatedAt!=`string`||!ed.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>td.safeParse(e).success)}function nA(e){return!rA(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!td.safeParse(e.project).success||!ed.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>nd.safeParse(e).success)}function rA(e){return typeof e==`object`&&!!e}const iA=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function aA(e){let t=Rd.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=Af(Nf(lA(i.export({format:`jwk`})))),o=bf({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a}}),s=(0,l.sign)(null,Buffer.from(o,`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`);return{gatewayHello:zd.parse({version:t.version,securityLevel:t.securityLevel,cipherSuite:t.cipherSuite,gatewayId:e.gatewayId,deviceId:t.deviceId,clientNonce:t.clientNonce,gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a,signatureAlgorithm:`ed25519`,signature:s}),gatewayEphemeralPrivateKey:r}}function oA(e){let t=Rd.parse(e.clientHello),n=zd.parse(e.gatewayHello),r=Bd.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!Od.safeParse(t.cipherSuite).success||n.cipherSuite!==t.cipherSuite||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported_version`);if(r.gatewayId!==e.gatewayId||n.gatewayId!==e.gatewayId)throw Error(`transcript_invalid`);if(r.deviceId!==t.deviceId||n.deviceId!==t.deviceId||r.deviceIdentityFingerprint!==t.deviceIdentity.publicKeyFingerprint)throw Error(`identity_mismatch`);let i=(0,l.createPublicKey)({format:`der`,type:`spki`,key:Buffer.concat([iA,jf(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(xf({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,jf(r.signature)))throw Error(`transcript_invalid`)}function sA(e){let t=zd.parse(e.gatewayHello),n=Bd.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:Mf(jf(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return wf({role:`gateway`,keySchedule:Cf({gatewayId:e.gatewayId,clientHello:Rd.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function cA(e){return Jd.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function lA(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}const uA=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;let dA=null;function fA(e){dA=e}function pA(e,t){uA&&(console.log(`[session-fetch][gateway] ${e}`,t),dA?.info({event:e,...t},`session fetch debug`))}const mA=64*1024;var hA=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}sendProviderRaw(e){this.onPayload(e)}close(){this.readyState=3}},gA=class{mobileConnections=new Map;constructor(e){this.dependencies=e}async handleFrame(e){switch(e.type){case`mobile.connected`:this.addMobileConnection(e.mobileId??``,e.payload.deviceId,e.payload.deliveryMode,e.payload.gatewayAvailableAtConnect);return;case`mobile.disconnected`:this.removeMobileConnection(e.mobileId??``,`mobile.disconnected`);return;case`secure.client_hello`:await this.handleSecureClientHello(e.mobileId,e.payload);return;case`secure.client_auth`:await this.handleSecureClientAuth(e.mobileId,e.payload);return;case`from_mobile`:await this.handleFromMobile(e);return;case`rpc.request`:await this.handleRpcRequest(e);return;case`pairing.claim.forward`:await this.handlePairingClaim(e.requestId,e.payload);return;case`auth.refresh.forward`:await this.handleRefresh(e.requestId,e.payload);return;case`file.content.forward`:await this.handleFileContent(e.requestId,e.payload);return;case`file.content.upload.started`:this.dependencies.handleFileContentUploadStarted?.(e.requestId);return;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e,`bridge.close`)}addMobileConnection(e,t,n,r){if(!e)return;this.removeMobileConnection(e,`mobile.replaced`);let i={mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}};this.mobileConnections.set(e,i),this.dependencies.relayTransportSecurityLevel!==`e2ee-relay`&&this.ensureReadyMobileClient(i),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(_f.parse({type:`secure.handshake_required`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,gatewayId:this.dependencies.gatewayId,deviceId:t,reason:r?`gateway_restarted`:`gateway_available`,retryable:!0}}))}removeMobileConnection(e,t){let n=this.mobileConnections.get(e);if(!n)return;let r=n.clientId?this.dependencies.describeClientState?.(n.clientId)??{}:{};this.dependencies.logger?.info?.({mobileId:e,deviceId:n.deviceId,clientId:n.clientId??null,reason:t,hadSocket:!!n.socket,socketReadyState:n.socket?.readyState??null,...r},`relay mobile connection removed`),n.socket?.close(),n.clientId&&this.dependencies.sessionHub.removeClient(n.clientId),this.mobileConnections.delete(e)}async handleFromMobile(e){let t=e.mobileId;if(!t){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile frame requires mobileId`});return}let n=this.mobileConnections.get(t);if(!n){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${t}`});return}if(n.handshake.status===`ready`&&n.clientId){let r=n,i=r.clientId;if(!i){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let a=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>hc.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(!a)return;await this.dependencies.dispatchCommand(a,r.deviceId,i);return}if(this.dependencies.relayTransportSecurityLevel===`e2ee-relay`){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}if(this.ensureReadyMobileClient(n),!n.clientId)return;if(e.payload===void 0){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`plaintext relay payload missing`});return}let r=hc.parse(e.payload);await this.dependencies.dispatchCommand(r,n.deviceId,n.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(_f.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...SA(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(_f.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...SA(t,`auth.refresh`)})}}async handleFileContent(e,t){try{let n=await this.dependencies.handleFileContentRequest(e,t);this.dependencies.sendFrame(_f.parse({type:`file.content.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...SA(t,`file.content`)})}}async handleRpcRequest(e){let t=e.mobileId,n=e.requestId,r=this.mobileConnections.get(t);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:{...xA(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status===`ready`){let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>Yd.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(!a)return;try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(_f.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let r=Qd.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...r.success?r.data:xA(`INTERNAL`,500,String(e)),method:a.method})})}return}if(this.dependencies.relayTransportSecurityLevel===`e2ee-relay`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}if(e.payload===void 0){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:xA(`BAD_REQUEST`,400,`plaintext relay payload missing`)});return}let i=Yd.parse(e.payload);try{let e=await this.dependencies.handleRpcRequest(i,{mobileId:t,deviceId:r.deviceId});this.dependencies.sendFrame(_f.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(r,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let a=Qd.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(r,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...a.success?a.data:xA(`INTERNAL`,500,String(e)),method:i.method})})}}async handleSecureClientHello(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_hello frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status!==`awaiting_client_hello`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_hello`);return}if(t.deviceId!==n.deviceId){this.sendSecureError(e,n.deviceId,`identity_mismatch`,`deviceId does not match relay token`);return}if(t.version!==1||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`){this.sendSecureError(e,n.deviceId,`unsupported_version`,`unsupported secure handshake version`);return}let r=aA({gatewayId:this.dependencies.gatewayId,gatewayIdentity:this.dependencies.gatewayIdentity,privateKeyPem:this.dependencies.gatewayIdentityPrivateKeyPem,clientHello:t});n.handshake={status:`awaiting_client_auth`,clientHello:t,gatewayHello:r.gatewayHello,gatewayEphemeralPrivateKey:r.gatewayEphemeralPrivateKey},this.mobileConnections.set(e,n),this.dependencies.sendFrame(_f.parse({type:`secure.gateway_hello`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:r.gatewayHello}))}async handleSecureClientAuth(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_auth frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status===`ready`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_auth`);return}if(n.handshake.status!==`awaiting_client_auth`){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure.client_hello missing`);return}try{oA({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,CA(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=sA({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t,gatewayEphemeralPrivateKey:n.handshake.gatewayEphemeralPrivateKey});this.ensureReadyMobileClient(n),n.handshake={status:`ready`,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,session:i},this.mobileConnections.set(e,n),this.dependencies.sendFrame(_f.parse({type:`secure.ready`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,securityLevel:`e2ee-relay`,cipherSuite:i.cipherSuite,gatewayId:this.dependencies.gatewayId,deviceId:n.deviceId,keyEpoch:i.keyEpoch,deviceIdentityFingerprint:r.publicKeyFingerprint??n.handshake.clientHello.deviceIdentity.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus??`active`}}))}catch(t){this.sendSecureError(e,n.deviceId,TA(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new hA(t=>{try{let n=_f.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,...this.createRelayBusinessPayloadFields(e,{frameType:`to_mobile`,messageType:`event`},t)});this.dependencies.sendFrame(n)}catch(t){this.sendSecureError(e.mobileId,e.deviceId,wA(t),`relay secure payload failed: ${String(t)}`)}}),n=this.dependencies.sessionHub.addClient(e.deviceId,t);e.socket=t,e.clientId=n}sendSecureError(e,t,n,r){this.dependencies.sendFrame({type:`secure.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:cA({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`||n===`key_epoch_mismatch`})})}sendRelayError(e){this.dependencies.sendFrame({type:`relay.error`,gatewayId:this.dependencies.gatewayId,...e.mobileId?{mobileId:e.mobileId}:{},...e.requestId?{requestId:e.requestId}:{},messageType:`system`,payload:xA(e.code,e.status,e.message)})}decodeRelayBusinessPayload(e){if(e.payload!==void 0)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload must be encrypted`),null;if(!e.encryptedPayload)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload missing`),null;try{return kf({session:e.connection.handshake.session,metadata:{frameType:e.frameType,messageType:e.messageType,gatewayId:this.dependencies.gatewayId,...e.requestId?{requestId:e.requestId}:{}},encryptedPayload:e.encryptedPayload,parse:e.parse})}catch(t){return this.sendSecureError(e.mobileId,e.connection.deviceId,wA(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){let r=pd({payload:n,compressionThresholdBytes:_A(t.frameType,n)?mA:void 0});if(vA(n)){let i=yA(n),a=bA(n);pA(`relay.snapshot.chunk.outbound`,{mobileId:e.mobileId,deviceId:e.deviceId,frameType:t.frameType,messageType:t.messageType,sessionId:n.sessionId,projectId:n.projectId??null,snapshotId:i.snapshotId??a?.snapshotId??null,chunkIndex:i.chunkIndex??a?.chunkIndex??null,totalChunks:i.totalChunks??a?.totalChunks??null,snapshotFormat:n.kind===`session.readable.snapshot.chunk`?`readable`:a?`raw+readable`:`raw`,chunkEventCount:i.events.length||null,chunkTimelineItemCount:a?.timelineItems?.length??null,handshakeStatus:e.handshake.status,payloadTransport:e.handshake.status===`ready`?`encryptedPayload`:r.compression===`gzip`?`compressedPayload`:`payload`,compression:r.compression,compressionThresholdBytes:mA,uncompressedByteLength:r.uncompressedByteLength,compressedByteLength:r.compressedByteLength})}if(e.handshake.status!==`ready`){let e=md(r);return e?{compressedPayload:e}:{payload:n}}return{encryptedPayload:Of({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},preparedPayload:r})}}};function _A(e,t){return e===`to_mobile`&&vA(t)}function vA(e){return typeof e==`object`&&!!e&&`kind`in e&&(e.kind===`session.stream.snapshot.chunk`||e.kind===`session.readable.snapshot.chunk`)}function yA(e){return e.kind===`session.readable.snapshot.chunk`?{snapshotId:e.payload.readable.snapshotId,chunkIndex:e.payload.readable.chunkIndex,totalChunks:e.payload.readable.totalChunks,events:[]}:e.payload.raw}function bA(e){return e.kind===`session.readable.snapshot.chunk`||`readable`in e.payload?e.payload.readable:void 0}function xA(e,t,n){return Qd.parse({code:e,status:t,message:n})}function SA(e,t){if(cw(e))switch(e.code){case`PAIRING_CODE_INVALID`:case`PAIRING_CODE_EXPIRED`:return{code:`BAD_REQUEST`,status:e.status,message:String(e)};case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:case`PREVIEW_TICKET_INVALID`:case`PREVIEW_TICKET_EXPIRED`:return{code:`UNAUTHORIZED`,status:e.status,message:String(e)};default:return{code:e.status>=500?`INTERNAL`:`BAD_REQUEST`,status:e.status,message:String(e)}}let n=String(e),r=EA(e);return t===`pairing.claim`&&(r===`Invalid pairing code`||r===`Pairing code expired`)?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(r===`Refresh token revoked`||r===`Device revoked`||r===`Device revoked or not found`||r===`Refresh token device mismatch`||Ow(e))||t===`file.content`&&Ow(e)?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function CA(e){return DA(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function wA(e){return DA(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function TA(e){if(cw(e))switch(e.code){case`DEVICE_REVOKED`:return`device_revoked`;case`DEVICE_IDENTITY_NOT_REGISTERED`:case`DEVICE_IDENTITY_MISMATCH`:return`identity_mismatch`;default:return`transcript_invalid`}let t=EA(e);return t===`Device revoked`||t===`Device revoked or not found`?`device_revoked`:t===`Device identity mismatch`||t===`Device identity not registered`?`identity_mismatch`:`transcript_invalid`}function EA(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function DA(e,t){let n=EA(e);return t.find(e=>e===n)}function OA(e){return e?e.readyState:null}function kA(e){return(typeof e.extensions==`string`?e.extensions.trim():``)||null}var AA=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;heartbeatIntervalMs;heartbeatTimeoutMs;webSocketFactory;socket;reconnectTimer;heartbeatIntervalTimer;heartbeatTimeoutTimer;reconnectAttempt=0;connectAttemptId=0;state=`idle`;stopped=!1;constructor(e){this.options=e,this.logger=e.logger??{},this.reconnectBaseDelayMs=e.reconnectBaseDelayMs??1e3,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??15e3,this.heartbeatIntervalMs=e.heartbeatIntervalMs??15e3,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??2e4,this.webSocketFactory=e.webSocketFactory??NA}start(){this.stopped&&=!1,!(this.socket||this.reconnectTimer)&&this.connect()}close(){this.stopped=!0,this.state=`stopped`,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),void 0);let e=this.socket;if(this.socket=void 0,this.stopHeartbeat(),!e)return;let t=OA(e);try{e.close(1e3,`Gateway shutting down`)}catch(n){this.logger.error?.({err:n,readyState:t},`relay websocket close threw during shutdown`);try{e.terminate()}catch(e){this.logger.error?.({err:e,readyState:t},`relay websocket terminate threw after close failure`)}}}isConnected(){let e=this.socket;return this.state===`connected`&&!!e&&e.readyState===e.OPEN}send(e){let t=this.socket;if(!t||t.readyState!==t.OPEN)return!1;let n=_f.parse(e);return t.send(JSON.stringify(n)),!0}async connect(){if(this.stopped)return;let e=++this.connectAttemptId,t;try{t=await this.resolveGatewayAccessToken()}catch(e){this.state=`idle`,this.logger.warn?.({err:e},`failed to resolve relay gateway access token`),this.scheduleReconnect();return}if(this.stopped||e!==this.connectAttemptId)return;let n=jA(this.options.relayUrl);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.on(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,this.startHeartbeat(r),this.logger.info?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,negotiatedExtensions:kA(r)},`relay gateway websocket connected`),this.send({type:`gateway.hello`,gatewayId:this.options.gatewayId,messageType:`system`,payload:{name:this.options.machineName,relayBaseUrl:this.options.relayUrl,directBaseUrls:this.options.directBaseUrls,transportSecurityLevel:this.options.relayTransportSecurityLevel,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=_f.parse(JSON.parse(MA(e)));Promise.resolve(this.options.onFrame(t)).catch(e=>{this.logger.error?.({err:e},`failed to handle relay frame`)})}catch(e){this.logger.warn?.({err:e},`failed to parse relay frame from relay`)}}}),r.on(`error`,e=>{this.socket===r&&this.logger.warn?.({err:e},`relay websocket emitted error`)}),r.on(`pong`,()=>{this.socket===r&&this.ackHeartbeat(r)}),r.on(`close`,(e,t)=>{if(this.socket===r){if(this.socket=void 0,this.stopHeartbeat(),this.stopped){this.state=`stopped`;return}this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,closeCode:e,closeReason:t.toString(`utf8`)},`relay websocket closed`),this.state=`idle`,this.scheduleReconnect()}})}async resolveGatewayAccessToken(){let e=this.options.relayGatewayAccessToken.trim();if(e)return e;let t=this.options.resolveRelayGatewayAccessToken;if(t)return t();throw Error(`Gateway relay access token is not configured`)}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;let e=Math.min(this.reconnectMaxDelayMs,this.reconnectBaseDelayMs*Math.max(1,2**this.reconnectAttempt));this.reconnectAttempt+=1,this.logger.info?.({delayMs:e},`scheduling relay reconnect`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatIntervalTimer=setInterval(()=>{if(!(this.socket!==e||this.stopped)&&!(e.readyState!==e.OPEN||this.heartbeatTimeoutTimer)){try{e.ping()}catch(t){this.logger.warn?.({err:t},`failed to send relay websocket heartbeat ping`),e.terminate();return}this.heartbeatTimeoutTimer=setTimeout(()=>{this.heartbeatTimeoutTimer=void 0,!(this.socket!==e||this.stopped||e.readyState!==e.OPEN)&&(this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,heartbeatTimeoutMs:this.heartbeatTimeoutMs},`relay websocket heartbeat timed out`),e.terminate())},this.heartbeatTimeoutMs)}},this.heartbeatIntervalMs)}ackHeartbeat(e){this.socket===e&&(this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0))}stopHeartbeat(){this.heartbeatIntervalTimer&&=(clearInterval(this.heartbeatIntervalTimer),void 0),this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0)}};function jA(e){let t=new URL(e);return t.protocol===`http:`?t.protocol=`ws:`:t.protocol===`https:`&&(t.protocol=`wss:`),t.pathname=`/ws/gateway`,t.toString()}function MA(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):String(e)}function NA(e){return new LE(e,void 0,{perMessageDeflate:!0})}function PA(e){let t={gatewayId:e.gatewayId.trim(),gatewayIdentity:e.gatewayIdentity,requestedAt:e.requestedAt??new Date().toISOString()};if(!t.gatewayId)throw Error(`gatewayId must not be empty when requesting a guest relay gateway access token.`);return{grantType:`guest`,payload:t,signatureAlgorithm:`ed25519`,signature:(0,l.sign)(null,Buffer.from(vf(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function FA(e){let t=e.fetchImpl??globalThis.fetch;if(!t)throw Error(`fetch is not available when requesting a guest relay gateway access token.`);let n=await t(IA(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(PA({gatewayId:e.gatewayId,gatewayIdentity:e.gatewayIdentity,privateKeyPem:e.privateKeyPem}))}),r=await n.text();if(!n.ok)throw Error(`Failed to request a guest relay gateway access token (${n.status}): ${r}`);return af.parse(JSON.parse(r)).token}function IA(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=`/api/gateway-token/guest`,t.search=``,t.toString()}function LA(e){return e?.trim()||void 0}function RA(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function zA(e,t){return{modeDefault:`default`,model:LA(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function BA(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function VA(e,t){let n=BA(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function HA(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function UA(e){let t=VA(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||LA(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?WA({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function WA(e){let t=VA(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?HA(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=VA(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=LA(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??LA(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:RA(r.execution)}}}const GA=[],KA=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],qA=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],JA=Fa.options,YA=[`read-only`,`workspace-write`,`danger-full-access`],XA=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],ZA={codex:[{version:`codex-mobile-v1`,defaults:{reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]};function QA(e,t){let n=t?.trim().toLowerCase();return n?(ZA[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function $A(e,t,n){return e.some(e=>e.id===t)?e.map(e=>({...e,isDefault:e.id===t})):[{id:t,label:t,isDefault:!0,...n===`codex`?{supportedReasoningEfforts:qA}:{}},...e.map(e=>({...e,isDefault:!1}))]}function ej(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function tj(e){let t=new Set;for(let n of e){let e=ej(n);e&&t.add(e)}return[...t]}function nj(e){return e?.trim()||void 0}function rj(e){let t=nj(e.runtimeModel);if(t)return t;let n=nj(e.discoveredModel);if(n)return n;let r=nj(e.existingModel),i=nj(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function ij(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,description:e.description,isDefault:e.isDefault,supportedReasoningEfforts:tj(e.supportedReasoningEfforts)}));return t.length===0?GA:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function aj(e){let t=Date.now();try{let n=ij(await QD());return e?.info?.({provider:`codex`,durationMs:Date.now()-t,modelCount:n.length},`provider capabilities codex model load completed`),n}catch(n){return e?.warn?.({provider:`codex`,durationMs:Date.now()-t,err:n},`provider capabilities codex model load failed`),null}}async function oj(e){let t=Date.now();try{let n=await import(`@anthropic-ai/claude-agent-sdk`),r=n.query??n.default?.query;if(typeof r!=`function`)return null;let i=r,a=p.default.join(_m(),`claude-capability-probe`);await d.default.mkdir(a,{recursive:!0,mode:448});let o=i({prompt:`/clear`,options:{cwd:a,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let n=await o.supportedModels(),r=[];for(let e of n){let t=typeof e.value==`string`?e.value:``;if(!t)continue;let n=Array.isArray(e.supportedEffortLevels)&&e.supportedEffortLevels.length>0,i=cj(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?tj(e.supportedEffortLevels??[]):i===`haiku`?[]:void 0;r.push({id:t,label:e.displayName||t,description:typeof e.description==`string`&&e.description.trim()?e.description.trim():void 0,isDefault:t===`default`,supportedReasoningEfforts:a})}return r.length===0?null:(r.some(e=>e.isDefault)||(r[0]={...r[0],isDefault:!0}),e?.info?.({provider:`claude`,durationMs:Date.now()-t,modelCount:r.length},`provider capabilities claude model load completed`),r)}finally{o.close()}}catch(n){return e?.warn?.({provider:`claude`,durationMs:Date.now()-t,err:n},`provider capabilities claude model load failed`),null}}function sj(e){let t=(e.find(e=>e.isDefault)??e[0])?.supportedReasoningEfforts??[];if(t.includes(`medium`))return`medium`;if(t.includes(`high`))return`high`;if(t.length>0)return t[0]}function cj(...e){for(let t of e){let e=t?.trim().toLowerCase();if(e){if(e.includes(`haiku`))return`haiku`;if(e.includes(`opus`))return`opus`;if(e.includes(`sonnet`)||e.includes(`sonnect`))return`sonnet`}}}var lj=class{cache=new Map;inFlight=new Map;constructor(e){this.options=e}async getProviderCapabilities(e,t,n){return(await this.resolveProviderCapabilities(e,t,n)).capabilities}async getAgentConfig(e,t){let n=await this.resolveProviderCapabilities(e,t?.projectId,t?.agentVersion);return{agent:{provider:e,requestedVersion:t?.agentVersion?.trim()||null,resolvedVersion:n.resolvedAgentVersion},capabilities:n.capabilities}}async warmStartupProviderCapabilities(){if(!this.options.preferNativeProviders)return;let e=ZA.claude.length>0?ZA.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async getProviderDefaults(e,t,n){return zA(e,await this.getProviderCapabilities(e,t,n))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw gw(t);let r=QA(e,n),i=r?.version??`default`,a=`${e}::${i}`,o={provider:e,projectId:t??null,requestedAgentVersion:n?.trim()||null,resolvedAgentVersion:i},s=Date.now(),c=this.cache.get(a);if(c){if(c.expiresAt>s)return this.options.logger?.info?.({...o,cacheStatus:`hit`,source:c.value.capabilities.source,modelCount:c.value.capabilities.models.length},`provider capabilities cache hit`),c.value;this.cache.delete(a)}let l=this.inFlight.get(a);if(l)return this.options.logger?.info?.({...o,cacheStatus:`in_flight`},`provider capabilities awaiting in-flight load`),l;let u=Date.now(),d=(async()=>{let t=QO(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=Date.now(),a=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1;this.options.logger?.info?.({...o,cacheStatus:`miss`,nativeAvailable:a,durationMs:Date.now()-n},`provider capabilities native availability checked`);let s=a?`native`:`fallback`,c=e===`codex`&&a?await aj(this.options.logger)??GA:GA,l=e===`claude`&&a?await oj(this.options.logger)??KA:KA,d=tj(l.flatMap(e=>e.supportedReasoningEfforts??[])),f=e===`codex`?{provider:e,source:s,models:c,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:qA,approvalPolicies:JA,sandboxModes:YA,permissionModes:[]},defaults:{model:c.find(e=>e.isDefault)?.id??c[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:s,models:l,support:{reasoningEffort:d.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:d,approvalPolicies:[],sandboxModes:[],permissionModes:XA},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:sj(l),permissionMode:`default`}};if(!r){let e={capabilities:f,resolvedAgentVersion:i};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:e.capabilities.source,modelCount:e.capabilities.models.length},`provider capabilities resolved`),e}let p={...f.defaults,...r.defaults},m=p.model?.trim(),h=s===`native`?f.models:m?$A(f.models,m,e):f.models,g={capabilities:{...f,models:h,defaults:p},resolvedAgentVersion:r.version};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:g.capabilities.source,modelCount:g.capabilities.models.length},`provider capabilities resolved`),g})();this.inFlight.set(a,d);try{let e=await d;return this.cache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}catch(e){throw this.options.logger?.warn?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,err:e},`provider capabilities resolution failed`),e}finally{this.inFlight.delete(a)}}};const uj=`.meta.json`;function dj(){let e=process.env.CODEX_HOME?.trim();return e?p.default.resolve(e):p.default.join(f.default.homedir(),`.codex`)}function fj(){return p.default.join(dj(),`auth.json`)}function pj(){return p.default.join(_m(),`codex-accounts`)}var mj=class{currentAuthFilePath;snapshotsDir;readAccountMetadata;constructor(e={}){this.currentAuthFilePath=e.currentAuthFilePath??fj(),this.snapshotsDir=e.snapshotsDir??pj(),this.readAccountMetadata=e.readAccountMetadata??_j}async getAccountsOverview(){let e=await this.getCurrentAccount();return{current:e,savedAccounts:await this.listSavedAccounts(e?.accountId??null)}}async getCurrentAccount(){let e=await this.readCurrentAuthFileOrNull();if(!e)return null;let t=await this.readAccountMetadataOrNull();if(!t)return null;let n=t.accountType===`chatgpt`?await this.resolveSnapshotStatus(t.accountId,e.canonicalContent):`missing`;return{accountId:t.accountId,accountType:t.accountType,authMode:e.authMode,planType:t.planType,lastRefreshAt:e.lastRefreshAt,hasSavedSnapshot:n!==`missing`,snapshotStatus:n,rateLimits:t.rateLimits}}async saveCurrentAccount(){let e=await this.readCurrentAuthFile(),t=await this.readSnapshotSupportedAccountMetadata();return await this.writeSnapshot(t.accountId,e,t),{current:{accountId:t.accountId,accountType:t.accountType,authMode:e.authMode,planType:t.planType,lastRefreshAt:e.lastRefreshAt,hasSavedSnapshot:!0,snapshotStatus:`current`,rateLimits:t.rateLimits},savedAccounts:await this.listSavedAccounts(t.accountId)}}async applySavedAccount(e){let t=await Pj(this.currentAuthFilePath),n=await this.readSavedSnapshot(e);return await Fj(this.currentAuthFilePath,n.rawContent),{previousRawContent:t}}async restoreCurrentAuthFile(e){await Fj(this.currentAuthFilePath,e)}async listSavedAccounts(e){let t=await Nj(this.snapshotsDir);return(await Promise.all(t.filter(e=>e.isFile()&&Mj(e.name)).map(async t=>{let n=jj(t.name);if(!n)return null;let r=p.default.join(this.snapshotsDir,t.name);try{let t=hj(await d.default.readFile(r,`utf8`),r),i=await this.readSnapshotMetadata(n),a=await d.default.stat(r);return{accountId:i?.accountId??n,accountType:i?.accountType??`unknown`,authMode:t.authMode,planType:i?.planType??null,lastRefreshAt:t.lastRefreshAt,savedAt:i?.savedAt??a.mtime.toISOString(),isCurrent:e===n,rateLimits:i?.rateLimits??null}}catch{return null}}))).filter(e=>e!==null).sort((e,t)=>e.isCurrent===t.isCurrent?t.savedAt.localeCompare(e.savedAt):e.isCurrent?-1:1)}async resolveSnapshotStatus(e,t){let n=await Pj(this.getSnapshotPath(e));if(n===null)return`missing`;try{return hj(n,this.getSnapshotPath(e)).canonicalContent===t?`current`:`stale`}catch{return`stale`}}async writeSnapshot(e,t,n){let r=new Date().toISOString();await Fj(this.getSnapshotPath(e),t.rawContent),await Fj(this.getSnapshotMetadataPath(e),JSON.stringify({accountId:n.accountId,accountType:n.accountType,planType:n.planType,rateLimits:n.rateLimits,savedAt:r},null,2))}async readSavedSnapshot(e){let t=this.getSnapshotPath(e),n=await Pj(t);if(n===null)throw Sw(e);return hj(n,t)}async readSnapshotMetadata(e){let t=await Pj(this.getSnapshotMetadataPath(e));if(t===null)return null;try{return gj(t)}catch{return null}}async readCurrentAuthFile(){let e=await this.readCurrentAuthFileOrNull();if(!e)throw Cw(`Current Codex auth.json is missing or unreadable`);return e}async readCurrentAuthFileOrNull(){let e=await Pj(this.currentAuthFilePath);if(e===null)return null;try{return hj(e,this.currentAuthFilePath)}catch{return null}}async readAccountMetadataOrNull(){try{return await this.readAccountMetadata()}catch{return null}}async readSnapshotSupportedAccountMetadata(){let e=await this.readAccountMetadataOrNull();if(!e||e.accountType!==`chatgpt`)throw Cw(`Current Codex account does not expose a ChatGPT email via account/read`);return e}getSnapshotPath(e){return p.default.join(this.snapshotsDir,`${Aj(e)}.json`)}getSnapshotMetadataPath(e){return p.default.join(this.snapshotsDir,`${Aj(e)}${uj}`)}};function hj(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Cw(`Codex auth file is not valid JSON: ${t}`,{error:String(e)})}if(!n||typeof n!=`object`||Array.isArray(n))throw Cw(`Codex auth file is not an object: ${t}`);let r=n;return{authMode:vj(r.auth_mode),lastRefreshAt:Sj(r.last_refresh),rawContent:e,canonicalContent:Oj(n)}}function gj(e){let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`invalid snapshot metadata`);let n=t,r=bj(n.accountId);if(!r)throw Error(`missing snapshot metadata accountId`);return{accountId:r,accountType:xj(n.accountType),planType:yj(n.planType),rateLimits:Cj(n.rateLimits),savedAt:Sj(n.savedAt)??new Date(0).toISOString()}}async function _j(){return xD(async e=>{let t=Dj(await e.sendRequest(`account/read`,{refreshToken:!1}));if(!t)return null;let n=Dj(t.account);if(!n)return null;let r=null;try{let t=Dj(await e.sendRequest(`account/rateLimits/read`,void 0));r=t?Cj(Dj(t.rateLimits)):null}catch{r=null}let i=xj(n.type);if(i===`chatgpt`){let e=bj(n.email);return e?{accountId:e,accountType:i,planType:yj(n.planType)??r?.planType??null,rateLimits:r}:null}return i===`apiKey`?{accountId:`API Key`,accountType:i,planType:yj(n.planType)??r?.planType??null,rateLimits:r}:null})}function vj(e){return typeof e==`string`&&e.trim()?e.trim():`unknown`}function yj(e){return typeof e==`string`&&e.trim()?e.trim():null}function bj(e){return typeof e==`string`&&e.trim()?e.trim().toLowerCase():null}function xj(e){return e===`chatgpt`||e===`apiKey`?e:`unknown`}function Sj(e){if(typeof e!=`string`||!e.trim())return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toISOString()}function Cj(e){let t=Dj(e);if(!t)return null;let n=wj(t.primary),r=wj(t.secondary),i=yj(t.planType??t.plan_type),a=Dj(t.credits),o=yj(t.creditsBalance??a?.balance);return!n&&!r&&!i&&!o?null:{...n?{primary:n}:{},...r?{secondary:r}:{},...i?{planType:i}:{},...o?{creditsBalance:o}:{}}}function wj(e){let t=Dj(e);if(!t)return null;let n=Tj(t.usedPercent??t.used_percent);return n===null?null:{usedPercent:n,windowMinutes:Ej(t.windowMinutes??t.windowDurationMins??t.window_minutes),resetsAt:Tj(t.resetsAt??t.resets_at)}}function Tj(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Ej(e){return typeof e==`number`&&Number.isFinite(e)?Math.trunc(e):null}function Dj(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Oj(e){return JSON.stringify(kj(e))}function kj(e){return Array.isArray(e)?e.map(e=>kj(e)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,kj(t)])):e}function Aj(e){let t=bj(e);if(!t)throw Cw(`Codex account identifier cannot be empty`);return encodeURIComponent(t)}function jj(e){if(!Mj(e))return null;try{return bj(decodeURIComponent(e.slice(0,-5)))}catch{return null}}function Mj(e){return e.endsWith(`.json`)&&!e.endsWith(uj)}async function Nj(e){try{return await d.default.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Pj(e){try{return await d.default.readFile(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Fj(e,t){let n=p.default.dirname(e),r=p.default.join(n,`.${p.default.basename(e)}.${process.pid}.${Date.now()}.tmp`);await d.default.mkdir(n,{recursive:!0,mode:448}),await d.default.writeFile(r,t,{encoding:`utf8`,mode:384}),await d.default.rename(r,e)}const Ij=[`## Code review guidelines:`,`# Review guidelines:`,``,`You are acting as a reviewer for a proposed code change made by another engineer.`,``,`Below are some default guidelines for determining whether the original author would appreciate the issue being flagged.`,``,`These are not the final word in determining whether an issue is a bug. In many cases, you will encounter other, more specific guidelines. These may be present elsewhere in a developer message, a user message, a file, or even elsewhere in this system message.`,`Those guidelines should be considered to override these general instructions.`,``,`Here are the general guidelines for determining whether something is a bug and should be flagged.`,``,`1. It meaningfully impacts the accuracy, performance, security, or maintainability of the code.`,`2. The bug is discrete and actionable (i.e. not a general issue with the codebase or a combination of multiple issues).`,`3. Fixing the bug does not demand a level of rigor that is not present in the rest of the codebase (e.g. one doesn't need very detailed comments and input validation in a repository of one-off scripts in personal projects).`,`4. The bug was introduced in the change under review (pre-existing bugs should not be flagged).`,`5. The author of the original change would likely fix the issue if they were made aware of it.`,`6. The bug does not rely on unstated assumptions about the codebase or the author's intent.`,`7. It is not enough to speculate that a change may disrupt another part of the codebase; to be considered a bug, one must identify the other parts of the code that are provably affected.`,`8. The bug is clearly not just an intentional change by the original author.`,``,`When flagging a bug, you will also provide an accompanying comment. Once again, these guidelines are not the final word on how to construct a comment; defer to any subsequent guidelines that you encounter.`,``,`1. The comment should be clear about why the issue is a bug.`,`2. The comment should appropriately communicate the severity of the issue. It should not claim that an issue is more severe than it actually is.`,`3. The comment should be brief. The body should be at most 1 paragraph. It should not introduce line breaks within the natural language flow unless it is necessary for the code fragment.`,`4. The comment should not include any chunks of code longer than 3 lines. Any code chunks should be wrapped in markdown inline code tags or a code block.`,`5. The comment should clearly and explicitly communicate the scenarios, environments, or inputs that are necessary for the bug to arise. The comment should immediately indicate that the issue's severity depends on these factors.`,`6. The comment's tone should be matter-of-fact and not accusatory or overly positive. It should read as a helpful AI assistant suggestion without sounding too much like a human reviewer.`,`7. The comment should be written such that the original author can immediately grasp the idea without close reading.`,`8. The comment should avoid excessive flattery and comments that are not helpful to the original author. The comment should avoid phrasing like "Great job ..." or "Thanks for ...".`,``,`Below are some more detailed guidelines that you should apply to this specific review.`,``,`HOW MANY FINDINGS TO RETURN:`,``,`Output all findings that the original author would fix if they knew about them. If there is no finding that a person would definitely appreciate and fix, prefer outputting no findings. Do not stop at the first qualifying finding. Continue until you have listed every qualifying finding.`,``,`GUIDELINES:`,``,`- Ignore trivial style unless it obscures meaning or violates documented standards.`,`- Use one comment per distinct issue (or a multi-line range if necessary).`,"- Use ```suggestion``` blocks only for concrete replacement code (minimal lines; no commentary inside the block).","- In every ```suggestion``` block, preserve the exact leading whitespace of the replaced lines (spaces vs tabs, number of spaces).",`- Do not introduce or remove outer indentation levels unless that is the actual fix.`,``,`The comments will be presented in the code review as inline comments. Avoid unnecessary location details in the comment body. Always keep the line range as short as possible for interpreting the issue. Avoid ranges longer than 5-10 lines; instead, choose the most suitable subrange that pinpoints the problem.`,``,`At the beginning of the finding title, tag the bug with a priority level. For example "[P1] Un-padding slices along wrong tensor dimensions".`,`- [P0]: Drop everything to fix. Blocking release, operations, or major usage. Only use this for universal issues that do not depend on assumptions about the inputs.`,`- [P1]: Urgent. Should be addressed in the next cycle.`,`- [P2]: Normal. To be fixed eventually.`,`- [P3]: Low. Nice to have.`,``,"Additionally, include a numeric priority field in the JSON output for each finding: set `priority` to 0 for P0, 1 for P1, 2 for P2, or 3 for P3. If a priority cannot be determined, omit the field or use null.",``,`At the end of your findings, output an overall correctness verdict of whether or not the patch should be considered correct.`,`Correct implies that existing code and tests will not break, and the patch is free of bugs and other blocking issues.`,`Ignore non-blocking issues such as style, formatting, typos, documentation, and other nits.`,``,`FORMATTING GUIDELINES:`,`The finding description should be one paragraph.`,``,`OUTPUT FORMAT:`,``,`## Output schema - MUST MATCH exactly`,``,"```json",`{`,` "findings": [`,` {`,` "title": "<= 80 chars, imperative",`,` "body": "<valid Markdown explaining why this is a problem; cite files/lines/functions>",`,` "confidence_score": <float 0.0-1.0>,`,` "priority": <int 0-3, optional>,`,` "code_location": {`,` "absolute_file_path": "<file path>",`,` "line_range": {"start": <int>, "end": <int>}`,` }`,` }`,` ],`,` "overall_correctness": "patch is correct" | "patch is incorrect",`,` "overall_explanation": "<1-3 sentence explanation justifying the overall_correctness verdict>",`,` "overall_confidence_score": <float 0.0-1.0>`,`}`,"```",``,`- Do not wrap the JSON in markdown fences or extra prose.`,"- The `code_location` field is required and must include `absolute_file_path` and `line_range`.",`- Line ranges must be as short as possible for interpreting the issue (avoid ranges over 5-10 lines; pick the most suitable subrange).`,"- The `code_location` should overlap with the diff under review.",`- Do not generate a fix patch.`,`- Your initial response to the user must always use the JSON schema above.`,`- After the initial response, choose the format based on the user's request:`,` - If they explicitly ask for another review (for example, "re-review" or "rerun the review"), return the findings in the exact JSON schema again.`,` - If they ask you to fix something, answer follow-up questions, or otherwise request non-review help, respond in plain text (no JSON or schema output).`,`- All review instructions apply to the overall code review conversation. Continue following the guidelines in every response, only switching between JSON and plain text as described above.`];function Lj(e,t){let n=e.provider===`codex`?e.codex:void 0;if(!n)throw Error(`Codex review config is required`);return[...Ij,``,zj(n.target),`## My request for Codex:`,Rj(e,t)].join(`
|
|
521
|
-
`)}function Rj(e,t){let n=e.provider===`codex`?e.codex:void 0;if(!n)throw Error(`Codex review config is required`);let r=n.target,i=r.type===`baseBranch`?`Please review the code changes against the base branch ${r.branch}.`:r.type===`commit`?`Please review the code changes introduced by commit ${Bj(r.sha,r.title)}.`:r.type===`custom`?r.instructions:`Please review my uncommitted changes.`,a=Vj(t);return a?`${i}\n\nAdditional review instructions:\n${a}`:i}function zj(e){return e.type===`baseBranch`?`Review the code changes against the base branch ${e.branch} and provide prioritized, actionable findings.`:e.type===`commit`?`Review the code changes introduced by commit ${Bj(e.sha,e.title)} and provide prioritized, actionable findings.`:e.type===`custom`?`Review the requested code changes and provide prioritized, actionable findings.`:`Review the current code changes (staged, unstaged, and untracked files) and provide prioritized, actionable findings.`}function Bj(e,t){let n=Vj(t);return n?`${e} (${JSON.stringify(n)})`:e}function Vj(e){return e?.trim()||void 0}const Hj=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function Uj(e){return e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt}function Wj(e,t){Hj&&(!e.startsWith(`config.get`)&&!e.startsWith(`raw-events`)&&!e.startsWith(`sync-external`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function Gj(e){return e?{sessionFound:!0,sessionId:e.id,nativeSessionId:e.nativeSessionId??null,sessionSource:e.source??null,sessionModel:e.model??null,sessionUpdatedAt:e.updatedAt,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt??null,sessionTurnConfigModel:e.sessionTurnConfig?.model??null,sessionTurnConfigReasoningEffort:e.sessionTurnConfig?.reasoningEffort??null,sessionTurnConfigApprovalPolicy:e.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,sessionTurnConfigSandboxMode:e.sessionTurnConfig?.execution?.codex?.sandboxMode??null,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null,lastHydratedExternalConfigFreshnessAt:e.lastHydratedExternalConfigFreshnessAt??null}:{sessionFound:!1}}function Kj(e,t){return e?.status===`running`?{status:`running`}:t?{status:`running`,interactionLockReason:`external_turn_running`}:{status:`idle`}}function qj(e){return e.status===`active`?!0:e.turns.some(e=>e.status===`inProgress`||e.status===`in_progress`)}function Jj(e,t){if(!t)return qj(e);for(let n of e.turns)if(!(n.status!==`inProgress`&&n.status!==`in_progress`)&&!t.terminalTurnStatusById.has(n.id))return!0;return!1}function Yj(e){return e.startsWith(`sess_`)}function Xj(e){return e.source===`native_discovered`?!0:e.providerMode===`native`&&(e.provider===`codex`||e.provider===`claude`)}function Zj(e){return e.nativeSessionId?.trim()??``?!0:e.provider===`codex`&&!Yj(e.id)}function Qj(e){return Yj(e.id)?e.nativeSessionId??e.id:e.id}function $j(e){return e.provider!==`codex`&&e.provider!==`claude`||e.providerMode!==`native`?!1:Zj(e)}function eM(e){return e instanceof Error&&/^Session .+ is closed$/i.test(e.message)}function tM(e,t){if(e.provider!==`codex`||t.type!==`error.runtime`)return!1;if(vN(t.source)?.startsWith(`codex.app_server`))return!0;let n=vN(t.message)??``;return/\bclosed\b/i.test(n)}const nM={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function rM(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function iM(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}var aM=class{sessions=new Map;providerCapabilities;codexAccounts;nextRawSeqBySession=new Map;preparingRuntimeDispatches=new Set;queuedInterruptsBeforeDispatch=new Set;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.providerCapabilities=new lj({preferNativeProviders:e.preferNativeProviders,projectStore:e.projectStore,logger:e.logger}),this.codexAccounts=e.codexAccountService??new mj,this.runtimeLifecycle={idleTtlMs:rM(e.runtimeLifecycle?.idleTtlMs,nM.idleTtlMs),sweepIntervalMs:iM(e.runtimeLifecycle?.sweepIntervalMs,nM.sweepIntervalMs),maxSessions:rM(e.runtimeLifecycle?.maxSessions,nM.maxSessions),maxCodexSessions:rM(e.runtimeLifecycle?.maxCodexSessions,nM.maxCodexSessions),maxClaudeSessions:rM(e.runtimeLifecycle?.maxClaudeSessions,nM.maxClaudeSessions)},this.runtimeLifecycle.sweepIntervalMs<=0){this.sweepTimer=null;return}this.sweepTimer=setInterval(()=>{this.sweepRuntimeSessions().catch(e=>{console.error(`[session-runtime] sweep failed: ${String(e)}`)})},this.runtimeLifecycle.sweepIntervalMs),this.sweepTimer.unref?.()}async shutdown(){this.shuttingDown=!0,this.sweepTimer&&clearInterval(this.sweepTimer);let e=[...this.sessions.keys()];this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown starting`),await Promise.allSettled(e.map(e=>this.closeRuntimeSession(e,`shutdown`))),await rD(),this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown completed`)}async listProjects(){let e=await this.options.projectStore.list(),t=this.buildProjectStatsMap();return e.map(e=>this.attachProjectStats(e,t))}async createProject(e){let t=await this.options.projectStore.upsertByPath(e.path,e.title);return this.attachProjectStats(t,this.buildProjectStatsMap())}async deleteProject(e){if(this.listProjectSessionsWithRuntime(e,`running`).length>0)throw bw(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.getRunningRuntimeSessionCount();if(e>0)throw xw(e);let t=[...this.sessions.values()].filter(e=>e.provider===`codex`).map(e=>e.id);return await Promise.allSettled(t.map(e=>this.closeRuntimeSession(e,`codex_restart`))),await iD(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.app_server.restart`,detail:{closedRuntimeSessionCount:t.length}}),{restarted:!0,closedRuntimeSessionCount:t.length}}async getCodexAccounts(){return this.codexAccounts.getAccountsOverview()}async saveCurrentCodexAccount(){let e=await this.codexAccounts.saveCurrentAccount();return await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.account.save`,detail:{currentAccountId:e.current?.accountId??null,savedAccountCount:e.savedAccounts.length}}),{saved:!0,accounts:e}}async switchCodexAccount(e){let t=await this.codexAccounts.getCurrentAccount();if(t?.accountId===e)return{switched:!0,closedRuntimeSessionCount:0,accounts:t.accountType===`chatgpt`?await this.codexAccounts.saveCurrentAccount():await this.codexAccounts.getAccountsOverview()};let n=this.getRunningRuntimeSessionCount();if(n>0)throw xw(n);let r=[...this.sessions.values()].filter(e=>e.provider===`codex`).map(e=>e.id);await Promise.allSettled(r.map(e=>this.closeRuntimeSession(e,`codex_restart`))),t?.accountType===`chatgpt`&&await this.codexAccounts.saveCurrentAccount(),await rD();let i=null;try{i=await this.codexAccounts.applySavedAccount(e),await iD()}catch(e){if(i?.previousRawContent)try{await this.codexAccounts.restoreCurrentAuthFile(i.previousRawContent),await iD()}catch{}throw e}let a=await this.codexAccounts.getAccountsOverview();return await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.account.switch`,detail:{previousAccountId:t?.accountId??null,nextAccountId:a.current?.accountId??e,closedRuntimeSessionCount:r.length}}),{switched:!0,closedRuntimeSessionCount:r.length,accounts:a}}async getProject(e){return this.options.projectStore.getById(e)}getRunningRuntimeSessionCount(){let e=0;for(let t of this.sessions.values())t.status===`running`&&(e+=1);return e}buildProjectStatsMap(){let e=new Map,t=this.listAllSessionsWithRuntime(`all`);for(let n of t){let t=e.get(n.projectId)??{runningCount:0,idleCount:0,totalCount:0,lastSessionAt:void 0};n.status===`running`?t.runningCount+=1:t.idleCount+=1,t.totalCount+=1;let r=n.updatedAt||n.createdAt;(!t.lastSessionAt||r>t.lastSessionAt)&&(t.lastSessionAt=r),e.set(n.projectId,t)}return e}attachProjectStats(e,t){let n=t.get(e.id),r=n?.idleCount??0;return{...e,lastSessionAt:n?.lastSessionAt,runningCount:n?.runningCount??0,idleCount:r,totalCount:n?.totalCount??0,endedCount:r}}async getProviderCapabilities(e,t,n){return this.providerCapabilities.getProviderCapabilities(e,t,n)}async getAgentConfig(e,t){return this.providerCapabilities.getAgentConfig(e,t)}async warmStartupProviderCapabilities(){if(!this.shuttingDown)return this.providerCapabilities.warmStartupProviderCapabilities()}async getProviderDefaults(e,t,n){return this.providerCapabilities.getProviderDefaults(e,t,n)}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw gw(e);if(n?.syncExternal){let e=Date.now(),n=this.options.historyStore.listProjectSessions(r.id,`all`).length;this.options.logger?.info?.({projectId:r.id,projectPath:r.path,requestedStatus:t,sessionCountBeforeSync:n},`project external session sync started`);let[i,a]=await Promise.all([this.syncCodexSessionsForProject(r),this.syncClaudeSessionsForProject(r)]);this.options.logger?.info?.({projectId:r.id,projectPath:r.path,requestedStatus:t,sessionCountBeforeSync:n,sessionCountAfterSync:this.options.historyStore.listProjectSessions(r.id,`all`).length,totalDurationMs:Date.now()-e,codexSync:i,claudeSync:a},`project external session sync completed`)}return this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){let n=this.options.historyStore.getProjectSession(e,t);return this.getRuntimeSessionSummary(e,t,n)||this.maybeHydrateClaudeExternalSessionSummary(n)}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(Wj(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:Gj(n),runtime:Gj(r)}),r)return Wj(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...Gj(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return Wj(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...Gj(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw gw(e);let r=this.options.historyStore.getProjectSession(e,t);if(!r&&this.options.preferNativeProviders&&(await this.syncCodexSessionsForProject(n),await this.syncClaudeSessionsForProject(n),r=this.options.historyStore.getProjectSession(e,t)),!r)throw _w(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.options.historyStore.getSessionStoredRawEvents(r.id,2**53-1),o=await this.syncExternalRawHistory(r,e,i,a),s=o.session??this.options.historyStore.getProjectSession(e,r.id)??r,c=ZM(i,o.rawEvents);Wj(`sync-external.classify`,XM({projectId:e,sessionId:t,session:s,previousEvents:i,nextEvents:o.rawEvents,classification:c}));let l=s.status!==r.status||(s.interactionLockReason??``)!==(r.interactionLockReason??``);return{session:s,rawEvents:o.rawEvents,historyUpdated:c.historyUpdated,statusChanged:l,refreshMode:c.refreshMode,fromRawSeq:c.fromRawSeq,toRawSeq:c.toRawSeq,nativeWatchPath:o.nativeWatchPath}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw gw(e);let i=0,a=0,o,s=(s,c)=>{Wj(`raw-events.read`,{projectId:e,sessionId:t,limit:n,provider:o?.provider,source:o?.source,providerMode:o?.providerMode,localReadDurationMs:i,finalCount:a,outcome:s,totalDurationMs:Date.now()-r,...c})},c=this.options.historyStore.getProjectSession(e,t);if(!c&&this.getRuntimeSessionSummary(e,t))return s(`runtime_session_empty`),[];if(!c)throw _w(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEvents(c.id,Math.max(n,300));return i=Date.now()-l,a=u.slice(-Math.max(1,n)).length,s(`local_only_cached`,{localEventCount:u.length}),u.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompacted(r.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3){let i=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsSinceSeq(i.id,n,r)}async getProjectSessionRawSeqRange(e,t){let n=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawSeqRange(n.id)}async resolveProjectSessionForRawRead(e,t){if(!await this.options.projectStore.getById(e))throw gw(e);let n=this.options.historyStore.getProjectSession(e,t);if(n||=this.getRuntimeSessionSummary(e,t),!n)throw _w(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${ow(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=QO(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?VA(e.provider,e.sessionTurnConfig):UA({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=WA({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!a&&this.preparingRuntimeDispatches.has(e))throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(i?.interactionLockReason===`external_turn_running`)throw yw(e,`an external native turn is still running`,{reason:`external_turn_running`,status:i.status,interactionLockReason:i.interactionLockReason,provider:i.provider,providerMode:i.providerMode});if(a?.status===`running`)throw yw(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&Xj(i))throw yw(e,`the native session is still running`,{reason:`persisted_running`,status:i.status,provider:i.provider,providerMode:i.providerMode,source:i.source});let o=!a,s=a,c=!1;try{if(o&&this.preparingRuntimeDispatches.add(e),s=a??await this.resumeSessionFromHistory(e),!s)throw vw(e);let i=await this.getProviderDefaults(s.provider,s.projectId),l=WA({provider:s.provider,providerDefaults:i,currentSessionTurnConfig:s.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});if(s.dispatchInFlight=!0,this.touchSession(s),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:l.model,sessionConfig:r?.sessionConfig,mode:l.mode,config:r?.config,resolvedSessionConfig:l.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(this.options.historyStore.getSession(s.id)||await this.persistSessionSnapshot(s),this.consumeQueuedInterruptBeforeDispatch(e)))throw c=!0,this.createInterruptedBeforeDispatchError(e);if(s=await this.sendInputWithRuntimeRecovery(e,s,t,{model:l.model,sessionConfig:l.sessionConfig,mode:l.mode}),!s.title){let e=gN(t);e&&this.setSessionTitle(s,e)}let u=new Date().toISOString();s.sessionTurnConfig=VA(s.provider,l.sessionTurnConfig),s.sessionTurnConfigUpdatedAt=u,l.model&&s.model!==l.model&&(s.model=l.model),s.updatedAt=u,await this.persistSessionSnapshot(s)}finally{o&&this.preparingRuntimeDispatches.delete(e),this.queuedInterruptsBeforeDispatch.delete(e);let t=!1;c&&o&&s&&(await this.closeRuntimeSession(s.id,`dispatch_cancelled`,{suppressAudit:!0}),t=!0),!t&&s&&(s.dispatchInFlight=!1,this.touchSession(s))}}async startReview(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!a&&this.preparingRuntimeDispatches.has(e))throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(i?.interactionLockReason===`external_turn_running`)throw yw(e,`an external native turn is still running`,{reason:`external_turn_running`,status:i.status,interactionLockReason:i.interactionLockReason,provider:i.provider,providerMode:i.providerMode});if(a?.status===`running`)throw yw(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&Xj(i))throw yw(e,`the native session is still running`,{reason:`persisted_running`,status:i.status,provider:i.provider,providerMode:i.providerMode,source:i.source});let o=!a,s=a,c=!1;try{if(o&&this.preparingRuntimeDispatches.add(e),s=a??await this.resumeSessionFromHistory(e),!s)throw vw(e);if(s.provider!==t.provider)throw Error(`Review provider mismatch for session ${e}`);if(t.provider!==`codex`||!t.codex)throw Error(`Only Codex review is currently supported`);let i=await this.getProviderDefaults(s.provider,s.projectId),l=WA({provider:s.provider,providerDefaults:i,currentSessionTurnConfig:s.sessionTurnConfig,config:r?.turnConfig});if(s.dispatchInFlight=!0,this.touchSession(s),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`review.start`,deviceId:n,sessionId:e,detail:{input:r?.input,config:t,turnConfig:r?.turnConfig,resolvedModel:l.model,resolvedSessionConfig:l.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(this.options.historyStore.getSession(s.id)||await this.persistSessionSnapshot(s),this.consumeQueuedInterruptBeforeDispatch(e)))throw c=!0,this.createInterruptedBeforeDispatchError(e);let u=Lj(t,r?.input);if(s=await this.sendInputWithRuntimeRecovery(e,s,u,{model:l.model,sessionConfig:l.sessionConfig}),!s.title){let e=_N(t,r?.input);e&&this.setSessionTitle(s,e)}let d=new Date().toISOString();s.sessionTurnConfig=VA(s.provider,l.sessionTurnConfig),s.sessionTurnConfigUpdatedAt=d,l.model&&s.model!==l.model&&(s.model=l.model),s.updatedAt=d,await this.persistSessionSnapshot(s)}finally{o&&this.preparingRuntimeDispatches.delete(e),this.queuedInterruptsBeforeDispatch.delete(e);let t=!1;c&&o&&s&&(await this.closeRuntimeSession(s.id,`dispatch_cancelled`,{suppressAudit:!0}),t=!0),!t&&s&&(s.dispatchInFlight=!1,this.touchSession(s))}}async sendInputWithRuntimeRecovery(e,t,n,r){try{return await t.providerSession.sendInput(n,r),t}catch(i){if(!eM(i))throw i;let a=i;this.options.logger?.warn?.({sessionId:e,runtimeSessionId:t.id,nativeSessionId:t.nativeSessionId,provider:t.provider,providerMode:t.providerMode,projectId:t.projectId,projectPath:t.projectPath,model:t.model,error:a.message},`provider runtime session sendInput hit closed session; resuming from history`),await this.closeRuntimeSession(t.id,`provider_error`,{suppressAudit:!0});let o=await this.resumeSessionFromHistory(e);if(!o)throw a;return o.dispatchInFlight=!0,this.touchSession(o),await o.providerSession.sendInput(n,r),o}}async respondToolPermission(e,t,n,r,i){let a=this.mustGetSession(e);if(!a.pendingToolApprovals.has(t))throw Error(`Unknown tool approval request: ${t}`);if(typeof a.providerSession.respondToolPermission!=`function`){a.pendingToolApprovals.delete(t),a.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(a);return}await a.providerSession.respondToolPermission(t,n,r),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`tool.approval.respond`,deviceId:i,sessionId:e,detail:{requestId:t,decision:n,reason:r}})}async respondUserInput(e,t,n,r){let i=this.mustGetSession(e);if(!i.pendingUserInputs.has(t))throw Error(`Unknown user input request: ${t}`);if(typeof i.providerSession.respondUserInput!=`function`){i.pendingUserInputs.delete(t),i.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(i);return}await i.providerSession.respondUserInput(t,n),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`user.input.respond`,deviceId:r,sessionId:e,detail:{requestId:t,answeredCount:yN(n)}})}async interruptSession(e,t){let n=this.sessions.get(e),r=this.preparingRuntimeDispatches.has(e)||!!n?.dispatchInFlight;r&&this.queuedInterruptsBeforeDispatch.add(e),n&&await n.providerSession.interrupt(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.interrupt`,deviceId:t,sessionId:e,detail:{runtimeSessionFound:!!n,queuedBeforeDispatch:r}})}async closeSession(e){throw Error(`session.close is deprecated. Use session.interrupt instead.`)}getSessionExecutionContext(e){let t=this.sessions.get(e);if(t)return{provider:t.provider,projectId:t.projectId,projectPath:t.projectPath};let n=this.options.historyStore.getSession(e);if(!n)throw vw(e);return{provider:n.provider,projectId:n.projectId,projectPath:n.projectPath}}async emitExternalEvent(e){let t=this.options.historyStore.getSession(e.sessionId),n={v:`1.0`,kind:`provider.raw`,rawSeq:await this.nextRawSeq(e.sessionId),provider:e.provider,sessionId:e.sessionId,projectId:e.projectId??t?.projectId,eventId:`raw_${ow(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:e.type,payload:{raw:{...e.raw,type:e.type}}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}async resumeSessionFromHistory(e){let t=this.options.historyStore.getSession(e);if(!t)return;let n=t.provider===`codex`&&this.options.requireNativeCodex,r=QO(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=VA(t.provider,t.sessionTurnConfig),o=WA({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`?Qj(t):t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}consumeQueuedInterruptBeforeDispatch(e){return this.queuedInterruptsBeforeDispatch.delete(e)}createInterruptedBeforeDispatchError(e){return yw(e,`the pending turn was interrupted before provider dispatch started`,{reason:`interrupt_requested_before_dispatch`})}async syncCodexSessionsForProject(e){let t=Date.now();if(!this.options.preferNativeProviders)return{provider:`codex`,status:`disabled`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:0,applyDurationMs:0,totalDurationMs:Date.now()-t};let n=Date.now(),r,i=Math.floor((Date.now()-14400*60*1e3)/1e3);try{r=await JD(e.path,{maxThreads:100,sortKey:`updated_at`,updatedAfterUnixSeconds:i})}catch(r){let i={provider:`codex`,status:`error`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:Date.now()-n,applyDurationMs:0,totalDurationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)};return this.options.logger?.warn?.({projectId:e.id,projectPath:e.path,...i},`project external session sync provider failed`),i}let a=Date.now()-n,o=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),s=Date.now(),c=0;for(let t of r){if(t.cwd!==e.path)continue;let n=[...o.values()].find(e=>e.provider===`codex`&&(e.id===t.id||e.nativeSessionId===t.id)),r=n?.id??t.id,i=this.sessions.get(r)??this.sessions.get(t.id),a=bN(t.createdAt),s=bN(t.updatedAt),l=Kj(i,qj(t)),u=l.status,d=u===`running`?i?.pendingToolApprovals.size??0:0,f=u===`running`?i?.pendingUserInputs.size??0:0,p={id:r,nativeSessionId:t.id,source:n?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:i?.providerMode??n?.providerMode??`native`,model:rj({runtimeModel:i?.model,discoveredModel:t.model,existingModel:n?.model,modelProvider:t.modelProvider}),title:i?.title??gN(t.name??t.preview)??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??a,updatedAt:u===`running`?i?.updatedAt??s:s,status:u,interactionLockReason:l.interactionLockReason,pendingApprovals:d,pendingUserInputs:f,pendingActions:d+f};await this.options.historyStore.upsertSession(p),o.set(r,p),c+=1}let l={provider:`codex`,status:`ok`,discoveredCount:r.filter(t=>t.cwd===e.path).length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxThreads:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async syncClaudeSessionsForProject(e){let t=Date.now();if(!this.options.preferNativeProviders)return{provider:`claude`,status:`disabled`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:0,applyDurationMs:0,totalDurationMs:Date.now()-t};let n=Date.now(),r,i=Date.now()-14400*60*1e3;try{r=await nk(e.path,{maxSessions:100,updatedAfterMs:i})}catch(r){let i={provider:`claude`,status:`error`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:Date.now()-n,applyDurationMs:0,totalDurationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)};return this.options.logger?.warn?.({projectId:e.id,projectPath:e.path,...i},`project external session sync provider failed`),i}let a=Date.now()-n,o=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),s=Date.now(),c=0;for(let t of r){let n=[...o.values()].find(e=>e.provider===`claude`&&(e.id===t.nativeSessionId||e.nativeSessionId===t.nativeSessionId)),r=n?.id??t.nativeSessionId,i=this.sessions.get(r),a=Kj(i,t.status===`running`),s=a.status,l=s===`running`?i?.pendingToolApprovals.size??0:0,u=s===`running`?i?.pendingUserInputs.size??0:0,d={id:r,nativeSessionId:t.nativeSessionId,source:n?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:i?.providerMode??n?.providerMode??`native`,model:i?.model??n?.model??t.model,title:i?.title??t.title??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??t.createdAt,updatedAt:s===`running`?i?.updatedAt??t.updatedAt:t.updatedAt,status:s,interactionLockReason:a.interactionLockReason,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),o.set(r,d),c+=1}let l={provider:`claude`,status:`ok`,discoveredCount:r.length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxSessions:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=Uj(e),n=RM([e.nativeSessionId,e.id]);for(let r of n)try{Wj(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:r,...Gj(e)});let n=await ZD(r);if(!n){Wj(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:r});continue}let i={...e,model:nj(n.model)??e.model,sessionTurnConfig:n.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:n.sessionTurnConfigUpdatedAt,...t?{lastHydratedExternalConfigFreshnessAt:t}:{}};return await this.options.historyStore.upsertSession(i),Wj(`config.get.probe.result`,{projectId:e.projectId,sessionId:e.id,threadId:r,snapshotModel:n.model??null,snapshotSessionTurnConfigModel:n.sessionTurnConfig?.model??null,snapshotReasoningEffort:n.sessionTurnConfig?.reasoningEffort??null,snapshotApprovalPolicy:n.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,snapshotSandboxMode:n.sessionTurnConfig?.execution?.codex?.sandboxMode??null,snapshotUpdatedAt:n.sessionTurnConfigUpdatedAt,next:Gj(i)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??i}catch(t){Wj(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:r,error:String(t)})}return e}async maybeHydrateClaudeExternalSessionSummary(e){if(!e||e.provider!==`claude`||!Xj(e)||!Zj(e))return e;let t=BM(e);if(!t)return e;try{let n=await rk({projectPath:e.projectPath,nativeSessionId:t,provider:e.provider,sessionId:e.id,projectId:e.projectId});return this.patchObservedExternalSessionSummary(e,{updatedAt:n.updatedAt,externallyRunning:n.status===`running`,model:n.model})}catch(t){if(e.source===`native_discovered`&&zM(t))return e;throw t}}shouldHydrateCodexExternalSessionConfig(e){if(!this.options.preferNativeProviders||e.provider!==`codex`||!$j(e)||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=Uj(e),n=e.sessionTurnConfigUpdatedAt||``;if(!e.sessionTurnConfig||!nj(e.model)||!n)return!0;if(!t)return!1;let r=e.lastHydratedExternalConfigFreshnessAt;return r?t.localeCompare(r)>0:!0}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw gw(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await xN(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw gw(e);return await xN(t.path),t}return this.options.projectStore.upsertByPath(t)}async attachRuntimeSession(e){let t=this.sessions.get(e.id);t&&await this.closeRuntimeSession(t.id,`replaced`,{suppressAudit:!0});let n={...e,unsubscribe:()=>{}};return await this.initializeRawSeqCursor(n.id),n.unsubscribe=n.providerSession.onEvent(e=>{if(!n.streamReady){n.bufferedProviderEvents.push(e);return}this.handleProviderEvent(n,e)}),this.sessions.set(n.id,n),n}handleProviderEvent(e,t){let n=this.ensureProviderRequestId(t);if(this.emitRawEnvelope(e,n),this.maybePersistUpdatedNativeSessionId(e),e.updatedAt=new Date().toISOString(),this.touchSession(e),n.type===`thread.title.updated`){let t=vN(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=vN(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e),tM(e,n)&&this.closeRuntimeSession(e.id,`provider_error`,{suppressAudit:!0});return}if(n.type===`tool.permission.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingToolApprovals.add(t),this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.resolved`&&typeof n.requestId==`string`){e.pendingToolApprovals.delete(n.requestId),this.persistSessionSnapshot(e);return}if(n.type===`user.input.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingUserInputs.add(t),this.persistSessionSnapshot(e);return}if(n.type===`user.input.resolved`&&typeof n.requestId==`string`){e.pendingUserInputs.delete(n.requestId),this.persistSessionSnapshot(e);return}}emitRawEnvelope(e,t){let n={v:`1.0`,kind:`provider.raw`,rawSeq:this.nextRawSeqSync(e.id),provider:e.provider,sessionId:e.id,projectId:e.projectId,eventId:`raw_${ow(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:t.type,payload:{raw:t}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}nextRawEnvelopeTimestamp(){let e=Date.now(),t=e>this.lastRawEnvelopeTimestampMs?e:this.lastRawEnvelopeTimestampMs+1;return this.lastRawEnvelopeTimestampMs=t,new Date(t).toISOString()}async initializeRawSeqCursor(e){if(this.nextRawSeqBySession.has(e))return;let t=await this.options.historyStore.getSessionRawSeqRange(e),n=t?t.max+1:1;this.nextRawSeqBySession.set(e,n)}async nextRawSeq(e){return await this.initializeRawSeqCursor(e),this.nextRawSeqSync(e)}nextRawSeqSync(e){let t=this.nextRawSeqBySession.get(e)??1;return this.nextRawSeqBySession.set(e,t+1),t}touchSession(e){e.lastActiveAtMs=Date.now()}isSessionEvictable(e){return!(e.closing||e.status!==`idle`||e.pendingToolApprovals.size>0||e.pendingUserInputs.size>0||e.dispatchInFlight)}async closeRuntimeSession(e,t,n){let r=this.sessions.get(e);if(!r||r.closing)return!1;r.closing=!0;let i=Date.now();this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,statusBefore:r.status,projectId:r.projectId,projectPath:r.projectPath,model:r.model,pendingApprovalCount:r.pendingToolApprovals.size,pendingUserInputCount:r.pendingUserInputs.size,dispatchInFlight:r.dispatchInFlight},`provider runtime session close starting`);try{r.unsubscribe()}catch{}let a;try{await r.providerSession.close()}catch(n){a=n,console.error(`[session-runtime] failed closing session ${e}:`,n),this.options.logger?.error?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,error:String(n),err:n},`provider runtime session close failed`)}finally{r.status=`idle`,r.updatedAt=new Date().toISOString(),r.pendingToolApprovals.clear(),r.pendingUserInputs.clear();let t=this.sessions.get(e);if(!(t&&t!==r))try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}this.sessions.get(e)===r&&this.sessions.delete(e),r.dispatchInFlight=!1,r.closing=!1}if(this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,result:a?`error`:`success`,durationMs:Date.now()-i},`provider runtime session close completed`),!n?.suppressAudit)try{await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.runtime.close`,sessionId:e,detail:{reason:t,provider:r.provider}})}catch(e){console.error(`[session-runtime] failed to record runtime close audit log: ${String(e)}`)}return!0}async sweepRuntimeSessions(){if(this.shuttingDown||this.sessions.size===0)return;let e=Date.now(),t=this.runtimeLifecycle.idleTtlMs,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs);for(let r of n)e-r.lastActiveAtMs<t||await this.closeRuntimeSession(r.id,`idle_ttl`);await this.enforceProviderSessionCap(`codex`,this.runtimeLifecycle.maxCodexSessions),await this.enforceProviderSessionCap(`claude`,this.runtimeLifecycle.maxClaudeSessions),await this.enforceGlobalSessionCap(this.runtimeLifecycle.maxSessions)}async enforceProviderSessionCap(e,t){let n=[...this.sessions.values()].filter(t=>t.provider===e);if(n.length<=t)return;let r=n.length-t,i=n.filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),a=0;for(let e of i){if(a>=r)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(a+=1)}a<r&&console.warn(`[session-runtime] ${e} sessions exceed cap (${n.length}/${t}), no more idle sessions to evict`)}async enforceGlobalSessionCap(e){if(this.sessions.size<=e)return;let t=this.sessions.size-e,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),r=0;for(let e of n){if(r>=t)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(r+=1)}r<t&&console.warn(`[session-runtime] session count exceeds cap (${this.sessions.size}/${e}), no more idle sessions to evict`)}ensureProviderRequestId(e){return e.type===`tool.permission.requested`||e.type===`user.input.requested`?typeof e.requestId==`string`&&e.requestId.trim()?e:{...e,requestId:`req_${ow(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n,r){if(!r)return n;let i=await this.options.historyStore.mergeSessionRawEvents(e.id,n,{replaceMissing:!0,baseEventIds:t.map(e=>e.eventId)}),a=i[i.length-1]?.rawSeq;return typeof a==`number`&&Number.isFinite(a)&&a>0&&this.nextRawSeqBySession.set(e.id,a+1),i}async syncExternalRawHistory(e,t,n,r=n){if(e.provider===`claude`){let i=BM(e);if(!i)return{rawEvents:n};try{let a=Date.now(),o=await rk({projectPath:e.projectPath,nativeSessionId:i,provider:e.provider,sessionId:e.id,projectId:t}),s=Date.now(),c=await this.finalizeExternalRawHistorySync(e,r,o.rawEvents,o.updatedAt),l=await this.patchObservedExternalSessionSummary(e,{updatedAt:o.updatedAt,externallyRunning:o.status===`running`,model:o.model});return Wj(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,localStoredEventCount:r.length,historyEventCount:o.rawEvents.length,resultEventCount:c.length,readHistoryDurationMs:s-a,finalizeDurationMs:Date.now()-s}),{rawEvents:c,session:l,nativeWatchPath:o.nativeWatchPath}}catch(i){return e.source===`native_discovered`&&zM(i)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),Wj(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,localStoredEventCount:r.length,error:i instanceof Error?i.message:String(i)}),{rawEvents:n}}}if(e.provider!==`codex`)return{rawEvents:n};let i=_M(n,(this.sessions.get(e.id)??(e.nativeSessionId?this.sessions.get(e.nativeSessionId):void 0))?.status===`running`),a=RM([e.nativeSessionId,e.id]);for(let o of a)try{let a=Date.now(),s=await XD(o,!0),c=Date.now(),l,u;if(e.source===`gateway`&&n.length>0)l=lN({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n,localCodexLiveTurnState:i}),u=`gateway_incremental`;else if(e.source===`native_discovered`&&n.length>0){let r=$M({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n});r?(l=r,u=`native_tail_incremental`):(l=QM({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localCodexLiveTurnState:i}),u=`full`)}else l=QM({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localCodexLiveTurnState:i}),u=`full`;let d=Date.now(),f=await this.finalizeExternalRawHistorySync(e,r,l,bN(s.updatedAt),i),p=await this.patchObservedExternalSessionSummary(e,{updatedAt:bN(s.updatedAt),externallyRunning:e.source===`gateway`?Jj(s,i):qj(s)});return Wj(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:o,threadStatus:s.status,threadUpdatedAt:bN(s.updatedAt),threadTurnCount:s.turns.length,threadTurns:s.turns.slice(-3).map(e=>({id:e.id,status:e.status,itemCount:e.items.length,lastItemId:e.items[e.items.length-1]?.id??null,lastItemType:e.items[e.items.length-1]?.type??null})),externallyRunning:e.source===`gateway`?Jj(s,i):qj(s),localEventCount:n.length,localStoredEventCount:r.length,historyBuildMode:u,historyEventCount:l.length,resultEventCount:f.length,readThreadDurationMs:c-a,buildHistoryDurationMs:d-c,finalizeDurationMs:Date.now()-d}),{rawEvents:f,session:p,nativeWatchPath:s.path??void 0}}catch(i){Wj(`sync-external.codex.read.error`,{projectId:t,sessionId:e.id,source:e.source,threadId:o,localEventCount:n.length,localStoredEventCount:r.length,error:i instanceof Error?i.message:String(i)})}return Wj(`sync-external.codex.read.exhausted`,{projectId:t,sessionId:e.id,source:e.source,attemptedThreadIds:a,localEventCount:n.length}),{rawEvents:n}}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt,i){let a=Date.now(),o=sM(e.provider,t,n,i),s=Date.now(),c=await this.maybePersistSyncedExternalRawEvents(e,t,o,!0);return await this.markExternalHistoryHydrated(e.id,r),Wj(`sync-external.finalize`,{sessionId:e.id,provider:e.provider,source:e.source,localEventCount:t.length,historyEventCount:n.length,mergedEventCount:o.length,persistedEventCount:c.length,hydratedExternalUpdatedAt:r,mergeDurationMs:s-a,persistDurationMs:Date.now()-s}),c}async patchObservedExternalSessionSummary(e,t){let n=this.options.historyStore.getSession(e.id)??e,r=this.sessions.get(e.id)??(e.nativeSessionId?this.sessions.get(e.nativeSessionId):void 0),i=Kj(r,t.externallyRunning),a=i.status===`running`?r?.pendingToolApprovals.size??0:0,o=i.status===`running`?r?.pendingUserInputs.size??0:0,s={...n,updatedAt:i.status===`running`?r?.updatedAt??t.updatedAt:t.updatedAt,status:i.status,model:r?.model??nj(t.model)??n.model,interactionLockReason:i.interactionLockReason,pendingApprovals:a,pendingUserInputs:o,pendingActions:a+o};return await this.options.historyStore.upsertSession(s),this.options.historyStore.getSession(e.id)??s}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw vw(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,interactionLockReason:void 0,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=hN(t);!n||n===e.title||(e.title=n,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}resolveCanonicalSessionId(e,t,n){return e===`codex`&&t.getNativeSessionId?.()||n}resolveNativeSessionId(e,t,n){return e!==`codex`&&e!==`claude`?n:t.getNativeSessionId?.()||n}maybePersistUpdatedNativeSessionId(e){let t=this.resolveNativeSessionId(e.provider,e.providerSession,e.nativeSessionId);!t||t===e.nativeSessionId||this.shouldPersistNativeSessionId(e,t)&&(e.nativeSessionId=t,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}shouldPersistNativeSessionId(e,t){return e.source===`native_discovered`?!1:e.nativeSessionId?e.nativeSessionId===e.id&&e.id.startsWith(`sess_`)?t!==e.nativeSessionId:!1:!0}};const oM=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function sM(e,t,n,r){if(e===`claude`)return lM(e,bM(t,n),n);if(e!==`codex`)return lM(e,t,n);if(t.length===0)return n.slice().sort((e,t)=>e.ts.localeCompare(t.ts));let i=r??_M(t),a=cM(e,t.filter(e=>!pM(e))),o=wM(e),s=t.filter(t=>{if(gM(t,i))return!1;if(!pM(t))return!0;let n=TM(e,t,o);if(n.length===0||n.some(e=>(a.get(e)??0)<=0))return!0;for(let e of n){let t=(a.get(e)??0)-1;t>0?a.set(e,t):a.delete(e)}return!1}),c=new Map,l=new Map,u=new Set,d=wM(e),f=wM(e),p=yM(t)??yM(n)??Date.now();for(let[t,n]of s.entries()){c.set(n.eventId,n),l.set(n.eventId,t);for(let t of TM(e,n,d))u.add(t)}for(let t of n){if(gM(t,i))continue;let n=TM(e,t,f);if(!c.has(t.eventId)&&n.length>0&&n.every(e=>u.has(e)))continue;let r=c.get(t.eventId);if(r){if(!uM(r,t))continue;let e=l.get(t.eventId),n=vM(r,t);e!==void 0&&(s[e]=n),c.set(n.eventId,n)}else{p+=1;let e={...t,ts:new Date(p).toISOString()};c.set(e.eventId,e),l.set(e.eventId,s.length),s.push(e)}for(let e of n)u.add(e)}return s}function cM(e,t){let n=new Map,r=wM(e);for(let i of t)for(let t of TM(e,i,r))n.set(t,(n.get(t)??0)+1);return n}function lM(e,t,n){let r=new Map,i=new Set,a=wM(e),o=wM(e);for(let n of t){r.set(n.eventId,n);for(let t of TM(e,n,a))i.add(t)}for(let t of n){let n=TM(e,t,o);if(!(!r.has(t.eventId)&&n.length>0&&n.every(e=>i.has(e)))){r.set(t.eventId,t);for(let e of n)i.add(e)}}return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function uM(e,t){return dM(e)&&dM(t)}function dM(e){return e.type===`native.raw`?$(Q(e.payload.raw).source)===`codex.history.thread_read`:!1}function fM(e){return e===`codex.history.thread_read`||e===`codex.history.thread_read.incremental`}function pM(e){let t=Q(e.payload.raw),n=$(t.source);return t.historyReplay===!0||fM(n)}function mM(e){let t=Q(e.payload.raw),n=Q(t.item),r=Q(t.turn);if(e.type===`turn.started`||e.type===`turn.completed`||e.type===`turn.failed`)return $(t.turn_id)??$(t.turnId)??$(r.id)??$(n.turn_id)??$(n.turnId);if(e.type===`item.started`||e.type===`item.updated`||e.type===`item.completed`)return $(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId)??$(r.id);if(e.type!==`native.raw`)return;let i=$(t.source),a=Q(t.message);if(i===`codex.app_server`){let e=$(a.method),t=Q(a.params);return e===`turn/started`||e===`turn/completed`||e===`turn/failed`||e===`turn/interrupted`?$(Q(t.turn).id)??$(t.turn_id)??$(t.turnId):e===`item/started`||e===`item/updated`||e===`item/completed`?$(t.turn_id)??$(t.turnId)??$(Q(t.item).turn_id)??$(Q(t.item).turnId):void 0}if(i!==`codex.history.thread_read`)return;let o=$(a.scope);if(o===`turn`)return $(Q(a.turn).id);if(o===`item`)return $(a.turn_id)??$(Q(a.item).turn_id)}function hM(e){let t=Q(e.payload.raw);if(e.type===`turn.completed`||e.type===`turn.failed`){let n=$(t.status)??(e.type===`turn.completed`?`completed`:`failed`);return n&&pN(n)?n:void 0}if(e.type!==`native.raw`)return;let n=$(t.source),r=Q(t.message);if(n===`codex.app_server`){let e=$(r.method);if(e!==`turn/completed`&&e!==`turn/failed`&&e!==`turn/interrupted`)return;let t=$(Q(Q(r.params).turn).status)??(e===`turn/completed`?`completed`:e===`turn/interrupted`?`interrupted`:`failed`);return t&&pN(t)?t:void 0}if(n!==`codex.history.thread_read`||$(r.scope)!==`turn`)return;let i=$(Q(r.turn).status);return i&&pN(i)?i:void 0}function gM(e,t){if(!pM(e))return!1;let n=mM(e),r=hM(e);return!n||!r?!1:mN(t.terminalTurnStatusById.get(n),r)}function _M(e,t=!1){let n=new Set,r=new Map;for(let t of e){if(pM(t))continue;let e=mM(t);e&&n.add(e);let i=hM(t);e&&i&&r.set(e,i)}let i=new Set;if(t)for(let e of n)r.has(e)||i.add(e);return{activeTurnIds:i,terminalTurnStatusById:r}}function vM(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function yM(e){let t;for(let n of e){let e=Date.parse(n.ts);Number.isFinite(e)&&(t=t===void 0?e:Math.max(t,e))}return t}function bM(e,t){let n=xM(e);if(n.size===0)return e;let r=new Set(e.map(e=>e.eventId)),i=new Set;for(let e of t){if(r.has(e.eventId))continue;let t=CM(e);if(!t)continue;let a=n.get(t.text);if(!a||a.length===0)continue;let o,s=1/0;for(let e of a){if(e.consumed)continue;let n=t.tsMs-e.tsMs;if(n>3e4||n<0)continue;let r=Math.abs(n);r>=s||(o=e,s=r)}if(o){o.consumed=!0;for(let e of o.eventIds)i.add(e)}}return i.size===0?e:e.filter(e=>!i.has(e.eventId))}function xM(e){let t=new Map,n=new Map;for(let r of e){let e=SM(r);if(!e)continue;let i=t.get(e.text)??[],a=e.syntheticMessageId?`${e.text}\u0000${e.syntheticMessageId}`:``,o=a?n.get(a):void 0;if(o)o.tsMs=Math.min(o.tsMs,e.tsMs),o.eventIds.push(r.eventId);else{let t={text:e.text,tsMs:e.tsMs,eventIds:[r.eventId],consumed:!1};i.push(t),a&&n.set(a,t)}t.set(e.text,i)}return t}function SM(e){let t=Date.parse(e.ts);if(!Number.isFinite(t))return;if(e.type===`item.completed`){let n=Q(Q(e.payload.raw).item);if($(n.type)!==`user_message`||$(n.source_event_type)!==`claude.synthetic.user_input`)return;let r=IM(n);return r?{text:r,tsMs:t,syntheticMessageId:vN(n.id)??vN(n.item_id)??vN(n.itemId)}:void 0}if(e.type!==`native.raw`)return;let n=Q(e.payload.raw);if($(n.source)!==`claude.synthetic.user_input`||($(n.native_type)??$(Q(n.message).type))!==`user`)return;let r=LM(Q(Q(n.message).message));if(r)return{text:r,tsMs:t,syntheticMessageId:vN(Q(n.message).uuid)}}function CM(e){if(e.type!==`native.raw`)return;let t=Date.parse(e.ts);if(!Number.isFinite(t))return;let n=Q(e.payload.raw),r=$(n.source);if(!r||!oM.has(r))return;let i=Q(n.message);if(($(n.native_type)??$(i.type))!==`user`)return;let a=LM(Q(i.message));if(a)return{text:a,tsMs:t}}function wM(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function TM(e,t,n){return e===`codex`?EM(t,n):e===`claude`?MM(t):[]}function EM(e,t){let n=Q(e.payload.raw),r=new Set,i=NM(e.type,n);if(i){let a=DM(e.type,n);a?r.add(AM(a,t,n)):r.add(i)}if(e.type!==`native.raw`)return[...r];let a=$(n.source);if(a===`codex.app_server`){let e=Q(n.message),i=$(e.method),a=Q(e.params);if(i===`turn/started`)return r.add(PM(`turn.started`,{turn:Q(a.turn)})),[...r];if(i===`turn/completed`)return r.add(PM(`turn.completed`,{status:`completed`,turn:Q(a.turn)})),[...r];if(i===`turn/failed`||i===`turn/interrupted`)return r.add(PM(`turn.failed`,{status:i===`turn/interrupted`?`interrupted`:`failed`,turn:Q(a.turn)})),[...r];if(i===`item/started`||i===`item/updated`||i===`item/completed`){let e=i.replace(`/`,`.`),n={turn_id:$(a.turn_id)??$(a.turnId)??$(Q(a.item).turn_id),item:Q(a.item)},o=DM(e,n);return o?r.add(AM(o,t,n)):r.add(PM(e,n)),[...r]}return[...r]}if(a!==`codex.history.thread_read`)return[...r];let o=Q(n.message),s=$(o.scope);if(s===`thread`){let e=Q(o.thread),t=$(e.id);t&&r.add(PM(`thread.started`,{thread_id:t,thread:e}));let n=gN(FM(e.preview)??FM(e.name)??``);return n&&r.add(PM(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(s===`turn`){let e=Q(o.turn),t=$(e.status);return r.add(PM(`turn.started`,{turn:e})),t===`completed`?r.add(PM(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(PM(`turn.failed`,{status:t,turn:e})),[...r]}if(s===`item`){let e={turn_id:$(o.turn_id)??$(Q(o.item).turn_id),item:Q(o.item)},n=DM(`item.completed`,e);return n?r.add(AM(n,t,e)):r.add(PM(`item.completed`,e)),[...r]}return[...r]}function DM(e,t){if(!e.startsWith(`item.`))return;let n=Q(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=OM($(n.type));if(!(!r||!i))return[`codex`,e,r,i,kM(i,$(n.phase)),$(n.status)??``,JM($(n.command)),JM(IM(n))].join(`|`)}function OM(e){if(!e)return;let t=e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase();return t.length>0?t:void 0}function kM(e,t){return e===`agent_message`&&(!t||t===`final_answer`)?``:t??``}function AM(e,t,n){let r=jM(n);if(r!==void 0)return`${e}|${r}`;let i=t?.codexTurnScopedItemOccurrences;if(!i)return e;let a=(i.get(e)??0)+1;return i.set(e,a),`${e}|${a}`}function jM(e){if(!e)return;let t=e.semantic_occurrence??e.semanticOccurrence;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return t;if(typeof t==`string`){let e=Number.parseInt(t,10);if(Number.isInteger(e)&&e>0)return e}}function MM(e){let t=Q(e.payload.raw),n=NM(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!oM.has(r))return[];let i=Q(t.message),a=$(t.native_type)??$(i.type),o=Q(i.message);if(a===`user`){let e=LM(o),t=$(i.uuid);return!e||!t?[]:[PM(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=LM(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[PM(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function NM(e,t){switch(e){case`thread.started`:case`thread.title.updated`:case`turn.started`:case`turn.completed`:case`turn.failed`:case`item.started`:case`item.updated`:case`item.completed`:return PM(e,t);default:return}}function PM(e,t){let n=Q(t.item),r=Q(t.turn),i=Q(t.thread),a=$(n.id)??``,o=$(t.turn_id)??$(t.turnId)??$(r.id)??$(n.turn_id)??``,s=$(r.status)??$(t.status)??``,c=$(t.thread_id)??$(t.threadId)??$(i.id)??``,l=$(n.type)??``,u=$(n.phase)??``,d=$(n.status)??``,f=JM($(n.command)),p=JM(IM(n)),m=JM(FM(t.message)),h=JM(FM(t.title));return e.startsWith(`item.`)?[e,a,l,u,d,f,p||m].join(`|`):e.startsWith(`turn.`)?[e,o,s].join(`|`):e===`thread.title.updated`?[e,c,h].join(`|`):[e,c,o,a,l,h||m].join(`|`)}function Q(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function FM(e){if(typeof e==`string`)return e.length>0?e:void 0}function IM(e){let t=FM(e.text);if(t)return t;let n=Array.isArray(e.content)?e.content:[];if(n.length>0){let e=[];for(let t of n){let n=FM(Q(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
522
|
-
`)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>
|
|
523
|
-
`)}return``}function
|
|
524
|
-
`)}function RM(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function zM(e){return String(e).includes(`returned no messages from getSessionMessages`)}function BM(e){return Qj(e)}function VM(e){return e?{rawSeq:e.rawSeq,type:e.type,eventId:e.eventId,ts:e.ts}:null}function HM(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(!UM(n,i))return r}return e.length===t.length?null:n}function UM(e,t){return KM(WM(e))===KM(WM(t))}function WM(e){let{ts:t,...n}=e;return n}function GM(e){if(typeof e==`string`)return qM(e);if(Array.isArray(e))return e.map(e=>GM(e));if(!e||typeof e!=`object`)return e;let t=e,n={};for(let e of Object.keys(t).sort())n[e]=GM(t[e]);return n}function KM(e){return JSON.stringify(GM(e))}function qM(e){return e.length<=4096?e:{__type:`hashed_text`,length:e.length,sha256:(0,l.createHash)(`sha256`).update(e).digest(`hex`)}}function JM(e){if(!e)return``;let t=qM(e);return typeof t==`string`?t:`sha256:${t.length}:${t.sha256}`}function YM(e,t,n,r){if(!n.historyUpdated)return`unchanged`;if(n.refreshMode===`delta`)return`append_only_delta`;if(t.length<e.length)return`history_shrunk`;let i=Math.min(e.length,t.length);return r!==null&&r<i?`prefix_rewrite`:`snapshot_fallback`}function XM(e){let t=e.previousEvents[e.previousEvents.length-1]?.rawSeq??null,n=e.nextEvents[e.nextEvents.length-1]?.rawSeq??null,r=HM(e.previousEvents,e.nextEvents),i=r??Math.min(e.previousEvents.length,e.nextEvents.length);return{projectId:e.projectId,sessionId:e.sessionId,provider:e.session.provider,source:e.session.source,providerMode:e.session.providerMode,decision:e.classification.refreshMode,reason:YM(e.previousEvents,e.nextEvents,e.classification,r),historyUpdated:e.classification.historyUpdated,fromRawSeq:e.classification.fromRawSeq??null,toRawSeq:e.classification.toRawSeq??null,previousEventCount:e.previousEvents.length,nextEventCount:e.nextEvents.length,sharedPrefixCount:i,appendedCount:Math.max(0,e.nextEvents.length-e.previousEvents.length),firstMismatchIndex:r,previousLastRawSeq:t,nextLastRawSeq:n,previousMismatchEvent:VM(r===null?void 0:e.previousEvents[r]),nextMismatchEvent:VM(r===null?void 0:e.nextEvents[r])}}function ZM(e,t){let n=e[e.length-1]?.rawSeq,r=t[t.length-1]?.rawSeq;return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&UM(e,r)})?{historyUpdated:!1,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}:t.length>e.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&UM(e,r)})?{historyUpdated:!0,refreshMode:`delta`,fromRawSeq:n??0,toRawSeq:r??n??0}:{historyUpdated:!0,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}}function QM(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,n+=1,new Date(n).toISOString()),a=(n,a)=>{let o=t.length+1;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:o,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:cN(e.sessionId,r,a),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};a({scope:`thread`,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo}},[`thread`,e.thread.id,e.thread.updatedAt]);for(let t of e.thread.turns){let n=e.localCodexLiveTurnState?e.localCodexLiveTurnState.terminalTurnStatusById.has(t.id)||e.localCodexLiveTurnState.activeTurnIds.has(t.id):!1,r=e.localCodexLiveTurnState?.terminalTurnStatusById.get(t.id);(pN(t.status)?!mN(r,t.status):!n)&&a({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}},[`turn`,t.id,t.status]);for(let n of t.items)a({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,vN(n.id)??null])}return t}function $M(e){let t=eN(e.localEvents);if(!t.hasHistoryReplay||!t.hasThreadEnvelope)return null;let n=e.thread.turns.map(e=>e.id);if(t.turnOrder.length>n.length)return null;for(let[e,r]of t.turnOrder.entries())if(n[e]!==r)return null;let r=[],i=Math.max(yM(e.localEvents)??0,e.thread.updatedAt>0?e.thread.updatedAt*1e3:Date.now()),a=0,o=()=>(a+=1,i+=1,new Date(i).toISOString()),s=(t,n)=>{r.push({v:`1.0`,kind:`provider.raw`,rawSeq:r.length+1,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:cN(e.sessionId,a,n),ts:o(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:t,historyReplay:!0,replaySynthetic:!0}}})},c=t.turnOrder.length-1;for(let[n,r]of e.thread.turns.entries()){let i=t.turnsById.get(r.id);if(!i){s({scope:`turn`,thread_id:e.thread.id,turn:{id:r.id,status:r.status,error:r.error}},[`turn`,r.id,r.status]);for(let t of r.items)s({scope:`item`,thread_id:e.thread.id,turn_id:r.id,item:t},[`item`,r.id,vN(t.id)??null]);continue}let a=n!==c,o=nN(i,r);if(!o.safe||a&&(o.appendedItems.length>0||o.statusChanged))return null;if(!a){o.statusChanged&&s({scope:`turn`,thread_id:e.thread.id,turn:{id:r.id,status:r.status,error:r.error}},[`turn`,r.id,r.status]);for(let t of o.appendedItems)s({scope:`item`,thread_id:e.thread.id,turn_id:r.id,item:t},[`item`,r.id,vN(t.id)??null])}}return r}function eN(e){let t={hasHistoryReplay:!1,hasThreadEnvelope:!1,turnOrder:[],turnsById:new Map};for(let n of e){if(n.type!==`native.raw`)continue;let e=Q(n.payload.raw);if($(e.source)!==`codex.history.thread_read`)continue;let r=Q(e.message),i=$(r.scope);if(t.hasHistoryReplay=!0,i===`thread`){t.hasThreadEnvelope=!0;continue}if(i===`turn`){let e=Q(r.turn),n=$(e.id);if(!n)continue;let i=tN(t,n),a=$(e.status);a&&(i.status=a),i.fingerprint=oN(e);continue}if(i!==`item`)continue;let a=Q(r.item),o=$(r.turn_id)??$(a.turn_id);if(!o)continue;let s=tN(t,o),c=rN(o,a,void 0,s.itemOccurrenceByBaseKey);c&&(s.itemFingerprintByKey.has(c)||s.itemOrder.push(c),s.itemFingerprintByKey.set(c,aN(a)))}return t}function tN(e,t){let n=e.turnsById.get(t);if(n)return n;let r={itemOrder:[],itemFingerprintByKey:new Map,itemOccurrenceByBaseKey:new Map};return e.turnsById.set(t,r),e.turnOrder.push(t),r}function nN(e,t){if(t.items.length<e.itemOrder.length)return{safe:!1,appendedItems:[],statusChanged:!1};let n=new Map;for(let[r,i]of e.itemOrder.entries()){let a=t.items[r];if(!a||rN(t.id,a,r,n)!==i||e.itemFingerprintByKey.get(i)!==aN(a))return{safe:!1,appendedItems:[],statusChanged:!1}}return e.fingerprint!==void 0&&e.fingerprint!==oN(t)&&(e.status??``)===t.status?{safe:!1,appendedItems:[],statusChanged:!1}:{safe:!0,appendedItems:t.items.slice(e.itemOrder.length),statusChanged:(e.status??``)!==t.status}}function rN(e,t,n,r){let i=iN(e,t,n);if(!i)return;if(!r)return i;let a=(r.get(i)??0)+1;return r.set(i,a),`${i}|${a}`}function iN(e,t,n){let r=DM(`item.completed`,{turn_id:e,item:t});if(r)return r;let i=vN(t.id);if(i)return`id:${i}`;if(n!==void 0)return`${e}::${n}`}function aN(e){let t=OM($(e.type)),n=t?kM(t,$(e.phase)):$(e.phase),r={};for(let[i,a]of Object.entries(e))if(!(i===`id`||i===`turn_id`||i===`turnId`)){if(i===`type`){t&&(r.type=t);continue}if(i===`phase`){n&&(r.phase=n);continue}r[i]=a}return t&&r.type===void 0&&(r.type=t),KM(r)}function oN(e){return KM({status:$(e.status)??null,error:Q(e.error)})}function sN(e){return String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``)}function cN(e,t,n){let r=n.map(sN).filter(e=>e.length>0);return r.length===0?`raw_hist_codex_${e}_${t.toString().padStart(6,`0`)}`:`raw_hist_codex_${e}_${r.join(`_`)}`}function lN(e){let t=e.localCodexLiveTurnState??_M(e.localEvents),n=new Set,r=uN(e.localEvents),i=new Map,a=0,o=1;for(let t of e.localEvents){let e=Date.parse(t.ts);Number.isFinite(e)&&(a=Math.max(a,e)),o=Math.max(o,t.rawSeq+1);let r=Q(t.payload.raw),s=$(r.source),c=s===`codex.history.thread_read.incremental`;if(t.type===`turn.started`){let e=$(r.turn_id)??$(Q(r.turn).id);e&&!c&&n.add(e);continue}if(t.type===`turn.completed`||t.type===`turn.failed`){let e=$(r.turn_id)??$(Q(r.turn).id);if(!e)continue;c||n.add(e);let a=$(r.status)??(t.type===`turn.completed`?`completed`:`failed`);i.set(e,a)}if(t.type!==`native.raw`||s!==`codex.history.thread_read`)continue;let l=Q(r.message);if($(l.scope)===`turn`){let e=Q(l.turn),t=$(e.id);if(!t)continue;let n=$(e.status);n&&pN(n)&&i.set(t,n);continue}}let s=Math.max(a,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),c=0,l=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),u=t=>{let n=t.map(l).filter(e=>e.length>0);return n.length===0?`raw_sync_codex_${e.sessionId}_${o.toString().padStart(6,`0`)}`:`raw_sync_codex_${e.sessionId}_${n.join(`_`)}`},d=()=>(c+=1,new Date(s+c).toISOString()),f=[],p=(t,n,r)=>{let i=d();f.push({v:`1.0`,kind:`provider.raw`,rawSeq:o,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:u(r),ts:i,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),o+=1};for(let a of e.thread.turns){let e=i.get(a.id),s=mN(e,a.status);!(n.has(a.id)||t.activeTurnIds.has(a.id))&&!s&&p(`turn.started`,{type:`turn.started`,turn:{id:a.id,status:a.status,items:[],error:a.error}},[`turn_started`,a.id]);let c=new Map;for(let e of a.items){let t=$(e.id),n=rN(a.id,e,void 0,c);if(n&&r.has(n))continue;let i=n?dN(n):void 0;p(`item.completed`,{type:`item.completed`,turn_id:a.id,item:e,...i?{semantic_occurrence:i}:{}},[`item_completed`,a.id,t??`seq_${o}`])}if(pN(a.status)&&e!==a.status){if(a.status===`completed`){p(`turn.completed`,{type:`turn.completed`,status:a.status,turn:{id:a.id,status:a.status,items:[],error:a.error}},[`turn_terminal`,a.id]);continue}p(`turn.failed`,{type:`turn.failed`,status:a.status,turn:{id:a.id,status:a.status,items:[],error:a.error},...a.error?{error:a.error}:{}},[`turn_terminal`,a.id])}}return f}function uN(e){let t=new Set,n=new Map;for(let r of e){let e=fN(r);if(!e)continue;let i=rN(e.turnId,e.item,void 0,n);i&&t.add(i)}return t}function dN(e){let t=e.lastIndexOf(`|`);if(t<0||t===e.length-1)return;let n=Number.parseInt(e.slice(t+1),10);return Number.isInteger(n)&&n>0?n:void 0}function fN(e){let t=Q(e.payload.raw);if(e.type===`item.completed`){let e=Q(t.item),n=$(t.turn_id)??$(t.turnId)??$(e.turn_id)??$(e.turnId);return!n||Object.keys(e).length===0?null:{turnId:n,item:e}}if(e.type!==`native.raw`)return null;let n=$(t.source);if(n===`codex.app_server`){let e=Q(t.message);if($(e.method)!==`item/completed`)return null;let n=Q(e.params),r=Q(n.item),i=$(n.turn_id)??$(n.turnId)??$(r.turn_id)??$(r.turnId);return!i||Object.keys(r).length===0?null:{turnId:i,item:r}}if(n===`codex.history.thread_read`){let e=Q(t.message);if($(e.scope)!==`item`)return null;let n=Q(e.item),r=$(e.turn_id)??$(n.turn_id)??$(n.turnId);return!r||Object.keys(n).length===0?null:{turnId:r,item:n}}return null}function pN(e){return e===`completed`||e===`failed`||e===`interrupted`}function mN(e,t){return e===t&&pN(t)}function hN(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function gN(e,t=60){let n=hN(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function _N(e,t){if(t){let e=gN(t);if(e)return e}if(e.provider!==`codex`||!e.codex)return gN(`代码审查`);let n=e.codex.target;return n.type===`baseBranch`?gN(`审查 ${n.branch} 分支改动`):n.type===`custom`?gN(n.instructions):n.type===`commit`?gN(n.title||`审查提交 ${n.sha.slice(0,12)}`):gN(`审查未提交更改`)}function vN(e){if(typeof e!=`string`)return;let t=hN(e);if(t)return t}function yN(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function bN(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function xN(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var SN=class{indexPath;eventsDir;sessions=new Map;rawEventsCacheBySession=new Map;compactedRawEventsCacheBySession=new Map;pendingRawMutationsBySession=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`session-index.json`),this.eventsDir=p.default.join(e,`session-events`),this.ready=this.loadFromDisk()}async init(){await this.ready}async flushRawCompactions(e){await this.ready}async shutdown(){await this.ready}async upsertSession(e){await this.ready;let t=CN(e),n=this.sessions.get(t.id);this.sessions.set(t.id,{...n,...t}),await this.enqueueWrite(async()=>{await this.persistIndex()})}async patchSession(e,t){await this.ready;let n=this.sessions.get(e);return n?(this.sessions.set(e,CN({...n,...t})),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async setSessionStatus(e,t,n){await this.ready;let r=this.sessions.get(e);r&&(this.sessions.set(e,{...r,status:t,updatedAt:n,interactionLockReason:void 0,pendingApprovals:t===`running`?r.pendingApprovals:0,pendingUserInputs:t===`running`?r.pendingUserInputs:0,pendingActions:t===`running`?r.pendingActions:0}),await this.enqueueWrite(async()=>{await this.persistIndex()}))}async removeSession(e){if(await this.ready,!this.sessions.has(e))return;this.sessions.delete(e),this.rawEventsCacheBySession.delete(e),this.compactedRawEventsCacheBySession.delete(e);let t=p.default.join(this.eventsDir,`${e}.jsonl`),n=p.default.join(this.eventsDir,`${e}.raw.jsonl`);await this.enqueueWrite(async()=>{await Promise.all([this.persistIndex(),d.default.rm(t,{force:!0}),d.default.rm(n,{force:!0})])})}hasSession(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}getProjectSession(e,t){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return n}listSessions(e=`all`){return[...this.sessions.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessions(e,t=`all`){return this.listSessions(t).filter(t=>t.projectId===e)}async appendRawEvent(e){await this.ready;let t=this.normalizeRawEventProjectIdentity(e);this.sessions.has(t.sessionId)&&(HN(t)||await this.enqueueRawSessionWrite(t.sessionId,async()=>{if(PN(t)){let e=VN([...await this.readSessionRawEventsLocked(t.sessionId),t]);await this.replaceRawEventFile(t.sessionId,e),this.rawEventsCacheBySession.set(t.sessionId,e),this.compactedRawEventsCacheBySession.set(t.sessionId,kN(e));return}await this.appendRawEventLine(t),this.appendRawEventToCache(t)}))}async mergeSessionRawEvents(e,t,n){if(await this.ready,!this.sessions.has(e))return[];let r=t.filter(t=>t.sessionId===e).map(e=>this.normalizeRawEventProjectIdentity(e)),i=[];return await this.enqueueRawSessionWrite(e,async()=>{let t=FN(await this.readSessionRawEventsLocked(e),r,n);await this.replaceRawEventFile(e,t);let a=kN(t);i=AN(a),this.rawEventsCacheBySession.set(e,t),this.compactedRawEventsCacheBySession.set(e,a)}),i}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionStoredRawEvents(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsLocked(e)).slice(-n)}),i}async getSessionRawEventsCompacted(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsCompactedFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),i}async getSessionRawEventsSinceSeq(e,t,n=2e3){if(await this.ready,!this.sessions.has(e))return[];let r=Math.max(1,n),i=this.readSessionRawEventsFromCache(e);if(i!==void 0)return Pp(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=Pp((await this.readSessionRawEventsLocked(e)).filter(e=>e.rawSeq>t)).slice(0,r)}),a}async getSessionRawSeqRange(e){if(await this.ready,!this.sessions.has(e))return null;let t=this.readSessionRawEventsFromCache(e);if(t!==void 0)return DN(t);let n=null;return await this.enqueueWrite(async()=>{n=DN(await this.readSessionRawEventsLocked(e))}),n}async loadFromDisk(){await d.default.mkdir(this.eventsDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.sessions))return;for(let e of t.sessions)if(e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath){if(e.projectId!==e.projectPath)throw Error(`Legacy session project ids are no longer supported in ${this.indexPath}; clear the session history store and restart the gateway.`);this.sessions.set(e.id,{...e,status:`idle`,interactionLockReason:void 0,pendingApprovals:0,pendingUserInputs:0,pendingActions:0})}}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,sessions:[...this.sessions.values()].sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}async enqueueRawSessionWrite(e,t){this.incrementPendingRawMutation(e);try{let e;return await this.enqueueWrite(async()=>{e=await t()}),e}finally{this.decrementPendingRawMutation(e)}}async appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${EN(e)}\n`;await d.default.appendFile(t,n,`utf8`)}async replaceRawEventFile(e,t){let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r=t.map(e=>EN(e)).join(`
|
|
525
|
-
`);await
|
|
526
|
-
`).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!
|
|
527
|
-
`),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}normalizeRawEventProjectIdentity(e){let t=this.sessions.get(e.sessionId);return!t||!t.projectId||e.projectId===t.projectId?e:{...e,projectId:t.projectId}}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return AN(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=kN(n);return this.compactedRawEventsCacheBySession.set(e,r),AN(r)}incrementPendingRawMutation(e){this.pendingRawMutationsBySession.set(e,(this.pendingRawMutationsBySession.get(e)??0)+1)}decrementPendingRawMutation(e){let t=(this.pendingRawMutationsBySession.get(e)??0)-1;if(t>0){this.pendingRawMutationsBySession.set(e,t);return}this.pendingRawMutationsBySession.delete(e)}hasPendingRawMutation(e){return(this.pendingRawMutationsBySession.get(e)??0)>0}};function CN(e){let t=e.projectPath?.trim()||e.projectId;return t===e.projectId?e:{...e,projectId:t}}function wN(e){return typeof e==`object`&&!!e}function TN(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function EN(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n})}function DN(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function ON(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{await d.default.writeFile(n,t,`utf8`),await d.default.rename(n,e)}catch(e){try{await d.default.rm(n,{force:!0})}catch{}throw e}}function kN(e){let t=Np(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ip(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function AN(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function jN(e,t){let n=Ip(t);if(!n){e.slots.push(t),e.dense=null;return}let r=e.indexByKey.get(n.key);if(r===void 0){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let i=e.slots[r];if(!i){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let a=Lp(i,t);if(!a){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}e.slots[r]=null,e.slots.push(a),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null}function MN(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function NN(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=wN(e.payload.raw)?e.payload.raw:{},n=wN(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function PN(e){if(NN(e)||e.type===`turn.completed`||e.type===`turn.failed`)return!0;if(e.type!==`native.raw`)return!1;let t=wN(e.payload.raw)?e.payload.raw:{},n=wN(t.message)?t.message:{},r=typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``;return r===`turn/completed`||r===`turn/failed`||r===`turn/interrupted`}function FN(e,t,n){if(n?.replaceMissing)return IN(e,t,n);let r=[...e].sort(BN),i=new Map,a=1;for(let[e,t]of r.entries())i.set(t.eventId,e),a=Math.max(a,t.rawSeq+1);for(let e of t){let t=i.get(e.eventId);if(t!==void 0){let n=r[t];n&&LN(n,e)&&(r[t]=zN(n,e));continue}let n={...e,rawSeq:a};a+=1,i.set(n.eventId,r.length),r.push(n)}return VN(r.sort(BN)).sort(BN)}function IN(e,t,n){let r=new Map(e.map(e=>[e.eventId,e])),i=new Set(t.map(e=>e.eventId)),a=n?.baseEventIds?new Set(n.baseEventIds):null,o=a?e.filter(e=>!a.has(e.eventId)&&!i.has(e.eventId)):[],s=[...t,...o].sort(BN),c=1;for(let t of e)c=Math.max(c,t.rawSeq+1);return VN(s.map(e=>{let t=r.get(e.eventId);if(t)return LN(t,e)?zN(t,e):{...e,rawSeq:t.rawSeq};let n={...e,rawSeq:c};return c+=1,n})).sort(BN)}function LN(e,t){return RN(e)&&RN(t)}function RN(e){return e.type===`native.raw`?qN((wN(e.payload.raw)?e.payload.raw:{}).source)===`codex.history.thread_read`:!1}function zN(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function BN(e,t){let n=e.rawSeq-t.rawSeq;if(n!==0)return n;let r=e.ts.localeCompare(t.ts);return r===0?e.eventId.localeCompare(t.eventId):r}function VN(e){let t=Fp(e).filter(e=>!HN(e)),n=new Set;for(let e of t){let t=UN(e);t&&n.add(t)}return n.size===0?t:t.filter(e=>{let t=WN(e);return!t||!n.has(t)})}function HN(e){if(e.type!==`native.raw`)return!1;let t=wN(e.payload.raw)?e.payload.raw:{};if(qN(t.source)!==`codex.app_server`)return!1;let n=wN(t.message)?t.message:{};return qN(n.method)??qN(t.method)?!1:wN((wN(n.result)?n.result:{}).turn)}function UN(e){if(e.type===`item.completed`){let t=wN(e.payload.raw)?e.payload.raw:{},n=wN(t.item)?t.item:{};return GN(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=wN(e.payload.raw)?e.payload.raw:{},n=wN(t.message)?t.message:{},r=wN(n.params)?n.params:{};if((qN(n.method)??qN(t.method))!==`item/completed`)return null;let i=wN(r.item)?r.item:{};return GN(e.sessionId,i)}function WN(e){if(e.type===`item.updated`){let t=wN(e.payload.raw)?e.payload.raw:{},n=wN(t.item)?t.item:{},r=qN(n.original_method)??qN(n.originalMethod)??``,i=wN(n.payload)?n.payload:{};return!(typeof i.delta==`string`||typeof i.output_delta==`string`||typeof i.outputDelta==`string`||typeof n.output_delta==`string`||typeof n.outputDelta==`string`||typeof n.text==`string`)&&!KN(r)?null:GN(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=wN(e.payload.raw)?e.payload.raw:{},n=wN(t.message)?t.message:{},r=wN(n.params)?n.params:{};if(!KN(qN(n.method)??qN(t.method)??``))return null;let i=wN(r.msg)?r.msg:{},a=qN(r.itemId)??qN(r.item_id)??qN(i.itemId)??qN(i.item_id);return a?`${e.sessionId}|${a}`:null}function GN(e,t){let n=qN(t.id)??qN(t.item_id)??qN(t.itemId);return n?`${e}|${n}`:null}function KN(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function qN(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function JN(e){return!e||e.providerMode!==`native`?!1:e.interactionLockReason===`external_turn_running`?!0:e.status!==`running`}function YN(e,t){if(e&&e!==t)throw pw()}async function XN(e){let t=ZN(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:QN(t)},`auth refresh attempt`);try{let t=await e.execute(),n=ZN(e.authService,e.refreshToken),r=ZN(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:QN(n),nextRefreshToken:QN(r)},`auth refresh succeeded`),t}catch(t){let n=ZN(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:QN(n),error:$N(t)},`auth refresh failed`),t}}function ZN(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function QN(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:eP(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:eP(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function $N(e){return cw(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function eP(e){return e?e.slice(-8):null}function tP(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:nP(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:om(e.identity,e.privateKeyPem,i)}}function nP(e){return e.replace(/\s+/gu,``).toUpperCase()}async function rP(e,t){try{let n=Yd.parse(e);switch(n.method){case`auth.refresh`:{let e=await XN({authService:t.authService,execute:()=>t.authService.refreshAccessToken(n.params.refreshToken),logger:t.logger,refreshToken:n.params.refreshToken,requestedDeviceId:n.params.deviceId??t.relayDeviceId,source:`relay_rpc`});return YN(n.params.deviceId??t.relayDeviceId,e.deviceId),Xd.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Xd.parse({method:n.method,result:{projects:e}})}case`codex.accounts.get`:{let e=await t.sessionManager.getCodexAccounts();return Xd.parse({method:n.method,result:e})}case`codex.accounts.save`:{let e=await t.sessionManager.saveCurrentCodexAccount();return Xd.parse({method:n.method,result:e})}case`codex.accounts.switch`:{let e=await t.sessionManager.switchCodexAccount(n.params.accountId);return Xd.parse({method:n.method,result:e})}case`gateway.settings.get`:return Xd.parse({method:n.method,result:t.gatewaySettings.get()});case`gateway.settings.update`:{let e=await t.gatewaySettings.update(n.params);return Xd.parse({method:n.method,result:e})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Xd.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return Xd.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Xd.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Xd.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Xd.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Xd.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw aP(n.method,`NOT_FOUND`,404,`Project not found`);return Xd.parse({method:n.method,result:{removed:!0}});case`workspace.directories.list`:{let e=await t.fsService.listDirectoriesUnrestricted(n.params.path,n.params.limit??200);return Xd.parse({method:n.method,result:e})}case`workspace.directories.create`:{let e=await t.fsService.createDirectoryUnrestricted(n.params.path,n.params.name,200);return Xd.parse({method:n.method,result:e})}case`workspace.entries.list`:{let e=await t.workspaceFileService.listEntries(n.params.locator,n.params.limit??200);return Xd.parse({method:n.method,result:e})}case`workspace.files.resolve`:{let e=await t.workspaceFileService.resolveFile(n.params.locator);return Xd.parse({method:n.method,result:e})}case`workspace.files.readText`:{let e=await t.workspaceFileService.readTextFile(n.params.locator,{startLine:n.params.startLine,maxLines:n.params.maxLines,maxBytes:n.params.maxBytes});return Xd.parse({method:n.method,result:e})}case`workspace.files.preparePreview`:{let e=t.relayPreviewBaseUrl?.trim(),r=t.gatewayId?.trim();if(!e||!r)throw aP(n.method,`BAD_REQUEST`,400,`Relay preview base url is not configured`);let i=await t.workspaceFileService.preparePreview(n.params.locator,{deviceId:t.relayDeviceId,disposition:n.params.disposition,buildPreviewUrl:t=>`${e.replace(/\/+$/,``)}/api/gateways/${encodeURIComponent(r)}/workspace/files/content/${encodeURIComponent(t)}`});return Xd.parse({method:n.method,result:i})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return Xd.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Xd.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw aP(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Xd.parse({method:n.method,result:{session:e}})}case`sessions.config.get`:{let e=await t.sessionManager.getProjectSessionConfig(n.params.projectId,n.params.sessionId);if(!e)throw aP(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Xd.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return e.historyUpdated&&await t.refreshDetailSessionSnapshots?.({projectId:n.params.projectId,sessionId:n.params.sessionId,reason:`explicit_history_sync`,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}),Xd.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged,refreshMode:e.refreshMode,...e.fromRawSeq===void 0?{}:{fromRawSeq:e.fromRawSeq},...e.toRawSeq===void 0?{}:{toRawSeq:e.toRawSeq}}})}case`sessions.rawEvents.list`:{let e=n.params.limit===`all`?2**53-1:n.params.limit,r=await t.buildRawEventsListResult({sessionManager:t.sessionManager,projectId:n.params.projectId,sessionId:n.params.sessionId,limit:e,fromRawSeqExclusive:n.params.fromRawSeqExclusive,detailLevel:n.params.detailLevel,requestSource:`rpc`});return Xd.parse({method:n.method,result:r})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),Xd.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Xd.parse({method:n.method,result:e})}case`devices.list`:return Xd.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw aP(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Xd.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw aP(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw iP(e)}}function iP(e){if(cw(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return aP(`UNAUTHORIZED`,e.status,String(e),e.details);case`PROJECT_NOT_FOUND`:case`DISCOVERED_PROJECT_NOT_FOUND`:case`PROJECT_SESSION_NOT_FOUND`:case`SESSION_NOT_FOUND`:case`CODEX_ACCOUNT_NOT_FOUND`:return aP(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return aP(`BAD_REQUEST`,e.status,String(e),e.details);default:return aP(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Qd.safeParse(e);if(t.success)return t.data;let n=Zd.safeParse(e);if(n.success)return aP(void 0,n.data.code,n.data.status,n.data.message,n.data.details);if(e&&typeof e==`object`&&`code`in e&&`status`in e&&`message`in e&&typeof e.code==`string`&&typeof e.status==`number`&&typeof e.message==`string`){let t=e;return aP(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?aP(`BAD_REQUEST`,400,r):oP(e)?aP(`UNAUTHORIZED`,401,r):sP(r)?aP(`BAD_REQUEST`,400,r):aP(`INTERNAL`,500,r)}function aP(e,t,n,r,i){let a=typeof t==`string`,o=a?e:void 0,s=a?t:e,c=a?n:t,l=a?r:n,u=a?i:r;return Qd.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function oP(e){return cw(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||Ow(e)}function sP(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}function cP(e,t){return e.length===0?[]:t===void 0?[...e]:e.filter(e=>e.rawSeq>t)}function lP(e){return{baseFilteredRawEvents:eE(Np(e.rawEvents.filter(t=>t.rawSeq<=e.cursorRawSeq)),e.detailLevel),nextFilteredRawEvents:eE(Np(e.rawEvents),e.detailLevel)}}function uP(e,t){return t&&`kind`in t&&t.kind===`bootstrapping`?t:{kind:`bootstrapping`,sessionId:e,previousReadyState:t??null,queuedEnvelopes:[]}}function dP(e,t){let n=e.previousReadyState;if(!n)return{previousReadyState:null,nextReadyState:null,replayedEnvelopes:[]};let r=cP(e.queuedEnvelopes,n.rawEvents[n.rawEvents.length-1]?.rawSeq),i=n;for(let e of r)i=t(i,e);return{previousReadyState:n,nextReadyState:i,replayedEnvelopes:r}}function fP(e){return{v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${ow(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}}function pP(e){return{v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events},...e.timelineItems?{readable:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,...e.timelineItems?{timelineItems:e.timelineItems}:{}}}:{}}}}function mP(e){return{v:`1.0`,kind:`session.readable.snapshot.chunk`,type:`session.readable.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`readable_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{readable:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,timelineItems:e.timelineItems,...e.pendingApprovals?{pendingApprovals:e.pendingApprovals}:{},...e.pendingUserInputs?{pendingUserInputs:e.pendingUserInputs}:{},...e.contextUsage===void 0?{}:{contextUsage:e.contextUsage}}}}}function hP(e){return{v:`1.0`,kind:`session.readable.delta`,type:`session.readable.delta`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`readable_delta_${e.sessionId}_${e.toRawSeq}`,ts:new Date().toISOString(),payload:{readable:{...e.fromRawSeq===void 0?{}:{fromRawSeq:e.fromRawSeq},toRawSeq:e.toRawSeq,timelineUpserts:e.timelineUpserts,timelineRemovals:e.timelineRemovals,...e.timelineTextDeltaPatches&&e.timelineTextDeltaPatches.length>0?{timelineTextDeltaPatches:e.timelineTextDeltaPatches}:{},...e.pendingApprovalUpserts&&e.pendingApprovalUpserts.length>0?{pendingApprovalUpserts:e.pendingApprovalUpserts}:{},...e.pendingApprovalRemovals&&e.pendingApprovalRemovals.length>0?{pendingApprovalRemovals:e.pendingApprovalRemovals}:{},...e.pendingUserInputUpserts&&e.pendingUserInputUpserts.length>0?{pendingUserInputUpserts:e.pendingUserInputUpserts}:{},...e.pendingUserInputRemovals&&e.pendingUserInputRemovals.length>0?{pendingUserInputRemovals:e.pendingUserInputRemovals}:{},...e.sessionSummary?{sessionSummary:e.sessionSummary}:{},...e.contextUsage===void 0?{}:{contextUsage:e.contextUsage}}}}}function gP(e){return{v:`1.0`,kind:`session.external.update`,type:`session.external.update`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`session_external_update_${ow(12)}`,ts:new Date().toISOString(),payload:{raw:{updatedAt:e.updatedAt,status:e.status,interactionLockReason:e.interactionLockReason,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged}}}}function _P(e,t){if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}const vP=1e3,yP=(e,t)=>`${e}::${t}`,bP=e=>e.purpose===`detail_view`&&e.bootstrapMode===`readable`,xP=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},SP=e=>({kind:`ready`,sessionId:e.target.sessionId,projectId:e.target.projectId,provider:e.target.provider,detailLevel:e.target.detailLevel,rawEvents:[...e.rawEvents],contextUsage:e.contextUsage??null,timelineItems:[...e.timelineItems],pendingApprovals:[...e.pendingApprovals],pendingUserInputs:[...e.pendingUserInputs]}),CP=e=>typeof e==`object`&&e?e:{},wP=(e,...t)=>{for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}},TP=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=CP(n),r=wP(e,`id`),i=wP(e,`header`),a=wP(e,`question`);if(!r||!i||!a)continue;let o=Array.isArray(e.options)?e.options.map(e=>{let t=CP(e),n=wP(t,`label`);if(!n)return null;let r=wP(t,`description`)??n,i=wP(t,`markdown`);return{label:n,description:r,...i?{markdown:i}:{}}}).filter(e=>e!==null):null;t.push({id:r,header:i,question:a,multiSelect:e.multiSelect===!0,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:o})}return t},EP=e=>e.filter(e=>!(e.kind===`system`&&e.title===`Turn Usage`)),DP=(e,t)=>{let n=ep(e,t),r=new Map,i=new Map;for(let e of n){if(e.type===`tool.permission.requested`){let t=CP(e.payload.raw),n=wP(t,`requestId`,`request_id`);if(!n)continue;let i=CP(t.rawParams??t.raw_params),a=CP(i.networkApprovalContext??i.network_approval_context);r.set(n,{requestId:n,sessionId:e.sessionId,...wP(t,`toolName`,`tool_name`)?{toolName:wP(t,`toolName`,`tool_name`)}:{},...wP(t,`reason`)?{reason:wP(t,`reason`)}:{},...wP(i,`command`)?{command:wP(i,`command`)}:{},...wP(i,`cwd`)?{cwd:wP(i,`cwd`)}:{},...wP(i,`grantRoot`,`grant_root`)?{grantRoot:wP(i,`grantRoot`,`grant_root`)}:{},...wP(a,`host`)?{networkHost:wP(a,`host`)}:{},...wP(a,`protocol`)?{networkProtocol:wP(a,`protocol`)}:{},...wP(t,`itemId`,`item_id`)?{itemId:wP(t,`itemId`,`item_id`)}:{},...wP(t,`turnId`,`turn_id`)?{turnId:wP(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`tool.permission.resolved`){let t=wP(CP(e.payload.raw),`requestId`,`request_id`);t&&r.delete(t);continue}if(e.type===`user.input.requested`){let t=CP(e.payload.raw),n=wP(t,`requestId`,`request_id`);if(!n)continue;i.set(n,{requestId:n,sessionId:e.sessionId,questions:TP(t.questions),...wP(t,`itemId`,`item_id`)?{itemId:wP(t,`itemId`,`item_id`)}:{},...wP(t,`turnId`,`turn_id`)?{turnId:wP(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`user.input.resolved`){let t=wP(CP(e.payload.raw),`requestId`,`request_id`);t&&i.delete(t)}}return{pendingApprovals:[...r.values()],pendingUserInputs:[...i.values()]}},OP=e=>{let t=e.target.purpose===`detail_view`?Sc({provider:e.target.provider,rawEvents:e.filteredRawEvents}):null,n=e.target.purpose===`detail_view`?EP(tp(e.target.sessionId,e.filteredRawEvents,[])):[],r=e.target.purpose===`detail_view`?_o({rawEvents:e.filteredRawEvents,messages:n}):{timelineItems:[],consumedMessageIds:[]},i=e.target.purpose===`detail_view`?DP(e.target.sessionId,e.filteredRawEvents):{pendingApprovals:[],pendingUserInputs:[]};return{rawEvents:[...e.filteredRawEvents],contextUsage:t,timelineItems:r.timelineItems,pendingApprovals:i.pendingApprovals,pendingUserInputs:i.pendingUserInputs}},kP=e=>SP({target:e.target,...OP(e)}),AP=(e,t)=>{let n=eE(Np([...e.rawEvents,t]),e.detailLevel),r=_o({rawEvents:n,messages:EP(tp(e.sessionId,n,[]))}),i=DP(e.sessionId,n);return{...e,rawEvents:n,contextUsage:Sc({provider:e.provider,rawEvents:n}),timelineItems:r.timelineItems,pendingApprovals:i.pendingApprovals,pendingUserInputs:i.pendingUserInputs}},jP=e=>Buffer.byteLength(JSON.stringify(mP(e)),`utf8`),MP=e=>{let t=Math.max(1,Math.floor(e.maxChunkBytes??524288)),n=[],r=(t,n)=>jP({provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,snapshotId:e.snapshotId,chunkIndex:t,totalChunks:1,timelineItems:n,pendingApprovals:t===0?e.pendingApprovals:void 0,pendingUserInputs:t===0?e.pendingUserInputs:void 0,contextUsage:t===0?e.contextUsage:void 0});if(e.timelineItems.length===0)return[{timelineItems:[],estimatedByteLength:r(0,[])}];let i=[];for(let a of e.timelineItems){let e=n.length,o=[...i,a],s=r(e,o);if(i.length>0&&s>t){n.push({timelineItems:i,estimatedByteLength:r(e,i)}),i=[a];continue}i=o}return n.push({timelineItems:i,estimatedByteLength:r(n.length,i)}),n},NP=(e,t)=>{let n=new Map(e.map(e=>[e.requestId,JSON.stringify(e)])),r=new Map(t.map(e=>[e.requestId,JSON.stringify(e)]));return{upserts:t.filter(e=>n.get(e.requestId)!==r.get(e.requestId)),removals:e.filter(e=>!r.has(e.requestId)).map(e=>e.requestId)}},PP=(e,t)=>{let n=new Map(e.map(e=>[e.requestId,JSON.stringify(e)])),r=new Map(t.map(e=>[e.requestId,JSON.stringify(e)]));return{upserts:t.filter(e=>n.get(e.requestId)!==r.get(e.requestId)),removals:e.filter(e=>!r.has(e.requestId)).map(e=>e.requestId)}},FP=(e,t,n,r)=>{let i={},a=ep(e,[t]),o=a.find(e=>e.type===`thread.title.updated`),s=a.find(e=>e.type===`turn.started`||e.type===`turn.completed`||e.type===`turn.failed`);if(o){let e=wP(CP(o.payload.raw),`title`);e&&(i.title=e)}return s&&(i.updatedAt=s.ts,i.status=s.type===`turn.started`?`running`:`idle`,i.interactionLockReason=void 0),n.pendingApprovals.length!==r.pendingApprovals.length&&(i.pendingApprovals=r.pendingApprovals.length),n.pendingUserInputs.length!==r.pendingUserInputs.length&&(i.pendingUserInputs=r.pendingUserInputs.length),n.pendingApprovals.length+n.pendingUserInputs.length!==r.pendingApprovals.length+r.pendingUserInputs.length&&(i.pendingActions=r.pendingApprovals.length+r.pendingUserInputs.length),Object.keys(i).length>0?i:void 0},IP=e=>e?{stateFound:!0,kind:e.kind,sessionId:e.sessionId,projectId:e.projectId,provider:e.provider,detailLevel:e.detailLevel,rawEventCount:e.rawEvents.length,firstRawSeq:e.rawEvents[0]?.rawSeq??null,lastRawSeq:e.rawEvents[e.rawEvents.length-1]?.rawSeq??null,timelineItemCount:e.timelineItems.length,pendingApprovalCount:e.pendingApprovals.length,pendingUserInputCount:e.pendingUserInputs.length,hasContextUsage:!!e.contextUsage}:{stateFound:!1},LP=e=>e?e.kind===`ready`?IP(e):{stateFound:!0,kind:e.kind,sessionId:e.sessionId,queuedEnvelopeCount:e.queuedEnvelopes.length,previousReadyState:IP(e.previousReadyState)}:{stateFound:!1},RP=(e,t)=>{let n,r,i;try{n=Is(e.previousState.timelineItems,e.nextState.timelineItems),r=NP(e.previousState.pendingApprovals,e.nextState.pendingApprovals),i=PP(e.previousState.pendingUserInputs,e.nextState.pendingUserInputs)}catch(n){throw t?.(`stream.readable.delta.build.error`,{sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,previousState:IP(e.previousState),nextState:IP(e.nextState),sessionSummaryKeys:e.sessionSummary?Object.keys(e.sessionSummary):[],errorMessage:n instanceof Error?n.message:String(n)}),n}let a=JSON.stringify(e.previousState.contextUsage??null)!==JSON.stringify(e.nextState.contextUsage??null);if(n.upserts.length===0&&n.removals.length===0&&n.textDeltaPatches.length===0&&r.upserts.length===0&&r.removals.length===0&&i.upserts.length===0&&i.removals.length===0&&!a&&!e.sessionSummary)return null;let o=e.nextState.rawEvents[e.nextState.rawEvents.length-1]?.rawSeq;return o===void 0?null:{provider:e.previousState.provider,sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,fromRawSeq:e.previousState.rawEvents[e.previousState.rawEvents.length-1]?.rawSeq,toRawSeq:o,timelineUpserts:n.upserts,timelineRemovals:n.removals,timelineTextDeltaPatches:n.textDeltaPatches,pendingApprovalUpserts:r.upserts,pendingApprovalRemovals:r.removals,pendingUserInputUpserts:i.upserts,pendingUserInputRemovals:i.removals,sessionSummary:e.sessionSummary,contextUsage:a?e.nextState.contextUsage:void 0}};function zP(e){return e?{sessionFound:!0,sessionId:e.id,projectId:e.projectId,nativeSessionId:e.nativeSessionId??null,provider:e.provider,providerMode:e.providerMode,source:e.source??null,status:e.status,interactionLockReason:e.interactionLockReason??null,updatedAt:e.updatedAt,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null}:{sessionFound:!1}}var BP=class{stateByClientSession=new Map;pendingDeltaByClientSession=new Map;constructor(e,t,n,r){this.sessionHub=e,this.sessionManager=t,this.readableLiveDeltaCoalesceMs=n,this.log=r}shutdown(){for(let e of this.pendingDeltaByClientSession.values())clearTimeout(e.timer);this.pendingDeltaByClientSession.clear(),this.stateByClientSession.clear()}handleSessionStreamSubscribeCommand=async(e,t,n)=>{let r=xP(t),i=new Set(r.map(e=>e.sessionId)),a=this.sessionHub.getSubscriptions(e);this.log(`stream.subscribe.received`,{clientId:e,replace:n,incomingSubscriptionCount:t.length,dedupedSubscriptionCount:r.length,subscriptions:r.map(e=>({sessionId:e.sessionId,projectId:e.projectId??null,purpose:e.purpose??null,detailLevel:e.detailLevel??null,bootstrapMode:e.bootstrapMode??null,cursorKind:e.cursor.kind,rawSeq:e.cursor.kind===`raw_seq`?e.cursor.rawSeq:null}))}),this.primeReadableBootstrapForSubscriptions(e,r);for(let t of i)this.sessionHub.pauseSession(e,t);this.sessionHub.replaceSubscriptions(e,r,n),this.syncReadableLiveProjectionSubscriptions(e,a,r,n);try{for(let t of r)try{await this.syncSessionStreamSubscription(e,t)}catch(n){throw bP(t)&&this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:e,sessionId:t.sessionId}),n}}finally{for(let t of i)this.sessionHub.resumeSession(e,t)}};clearState=(e,t)=>{let n=yP(e,t),r=this.stateByClientSession.get(n);this.stateByClientSession.delete(n);let i=this.pendingDeltaByClientSession.get(n);i&&(clearTimeout(i.timer),this.pendingDeltaByClientSession.delete(n)),(r||i)&&this.log(`readable.state.cleared`,{clientId:e,sessionId:t,hadState:!!r,previousState:LP(r),hadPendingDelta:!!i,pendingDeltaFromRawSeq:i?.previousState.rawEvents[i.previousState.rawEvents.length-1]?.rawSeq??null,pendingDeltaToRawSeq:i?.nextState.rawEvents[i.nextState.rawEvents.length-1]?.rawSeq??null})};clearStatesForClient=e=>{let t=`${e}::`;for(let e of this.stateByClientSession.keys())e.startsWith(t)&&this.stateByClientSession.delete(e);for(let[e,n]of this.pendingDeltaByClientSession)e.startsWith(t)&&(clearTimeout(n.timer),this.pendingDeltaByClientSession.delete(e))};routeReadableLiveDelta=e=>{let t=this.sessionHub.getClientSubscriptionsForSession(e.sessionId,`detail_view`);if(t.length!==0)for(let{clientId:n,subscription:r}of t){if(!bP(r))continue;let t=yP(n,e.sessionId),i=this.stateByClientSession.get(t);if(!i)continue;if(i.kind===`bootstrapping`){i.queuedEnvelopes.push(e);continue}let a=AP(i,e);this.stateByClientSession.set(t,a);let o=FP(e.sessionId,e,i,a);this.enqueueReadableLiveDelta({clientId:n,previousState:i,nextState:a,sessionSummary:o})}};refreshDetailSessionSnapshots=async e=>{let t=this.sessionHub.getClientSubscriptionsForSession(e.sessionId,`detail_view`);for(let{clientId:n,subscription:r}of t){let t=r.projectId?.trim()??``;if(!(t&&t!==e.projectId)){this.sessionHub.pauseSession(n,e.sessionId);try{let t=await this.resolveSessionStreamTarget(r);if(t.bootstrapMode===`readable`){let r=this.getReadableRefreshDeltaBase({clientId:n,sessionId:e.sessionId,projectId:e.projectId,detailLevel:t.detailLevel,refreshMode:e.refreshMode,reason:e.reason});if(r){this.startReadableLiveProjectionBootstrap({clientId:n,sessionId:e.sessionId,previousReadyState:r.previousReadyState}),await this.sendSessionReadableResumeDelta(n,t,r.cursor,r.reason);continue}this.startReadableLiveProjectionBootstrap({clientId:n,sessionId:e.sessionId}),await this.sendSessionReadableSnapshot(n,t,e.reason)}else await this.sendSessionSnapshot(n,t,e.reason)}catch(t){throw bP(r)&&this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:n,sessionId:e.sessionId}),t}finally{this.sessionHub.resumeSession(n,e.sessionId)}}}};sendSessionSnapshot=async(e,t,n)=>{let r=`snap_${ow(12)}`,{compactedRawEvents:i,filteredRawEvents:a,lastRawSeq:o,slimReadableProjection:s,pendingApprovals:c,pendingUserInputs:l}=await this.buildReadableSnapshotProjection(t);this.sessionHub.sendStreamMessage(e,fP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...o===void 0?{}:{toRawSeq:o}}));let u=_P(a,vP),d=t.purpose===`detail_view`?_P(s.timelineItems,vP):[],f=t.purpose===`detail_view`?`raw+readable`:`raw`,p=Math.max(u.length,d.length,1);this.log(`stream.snapshot.prepared`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,provider:t.provider,detailLevel:t.detailLevel,reason:n,snapshotId:r,snapshotFormat:f,compactedEventCount:i.length,filteredEventCount:a.length,readableTimelineItemCount:s.timelineItems.length,totalChunks:p,firstRawSeq:a[0]?.rawSeq??null,lastRawSeq:o??null});for(let n=0;n<p;n+=1){let i=u[n]??[],a=d[n]??[];this.sessionHub.sendStreamMessage(e,pP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:p,events:i,timelineItems:t.purpose===`detail_view`?a:void 0}))}};sendSessionReadableSnapshot=async(e,t,n)=>{let r=`snap_${ow(12)}`,i=this.startReadableLiveProjectionBootstrap({clientId:e,sessionId:t.sessionId});try{let{compactedRawEvents:a,filteredRawEvents:o,contextUsage:s,lastRawSeq:c,slimReadableProjection:l,pendingApprovals:u,pendingUserInputs:d}=await this.buildReadableSnapshotProjection(t),f=this.sessionHub.getSubscriptions(e).find(e=>e.sessionId===t.sessionId),p=f?.projectId?.trim()??``;if(!f||!bP(f)||p&&p!==t.projectId||(f.detailLevel??`full`)!==t.detailLevel){this.clearState(e,t.sessionId);return}let m=SP({target:t,rawEvents:o,contextUsage:s,timelineItems:l.timelineItems,pendingApprovals:u,pendingUserInputs:d}),h=this.stateByClientSession.get(i),g=cP(h?.kind===`bootstrapping`?h.queuedEnvelopes:[],c);for(let e of g)m=AP(m,e);this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:m.rawEvents,contextUsage:m.contextUsage,timelineItems:m.timelineItems,pendingApprovals:m.pendingApprovals,pendingUserInputs:m.pendingUserInputs});let _=m.rawEvents[m.rawEvents.length-1]?.rawSeq;this.sessionHub.sendStreamMessage(e,fP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,..._===void 0?{}:{toRawSeq:_}}));let v=MP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,timelineItems:m.timelineItems,pendingApprovals:m.pendingApprovals,pendingUserInputs:m.pendingUserInputs,contextUsage:m.contextUsage}),y=Math.max(v.length,1);this.log(`stream.snapshot.prepared`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,provider:t.provider,detailLevel:t.detailLevel,bootstrapMode:t.bootstrapMode,reason:n,snapshotId:r,snapshotFormat:`readable`,compactedEventCount:a.length,filteredEventCount:m.rawEvents.length,readableTimelineItemCount:m.timelineItems.length,bufferedReadableDeltaCount:g.length,readableChunkTargetBytes:524288,readableChunkItemCounts:v.map(e=>e.timelineItems.length),readableChunkEstimatedBytes:v.map(e=>e.estimatedByteLength),totalChunks:y,firstRawSeq:m.rawEvents[0]?.rawSeq??null,lastRawSeq:_??null});for(let n=0;n<y;n+=1){let i=v[n];this.sessionHub.sendStreamMessage(e,mP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:y,timelineItems:i?.timelineItems??[],pendingApprovals:n===0?m.pendingApprovals:void 0,pendingUserInputs:n===0?m.pendingUserInputs:void 0,contextUsage:n===0?m.contextUsage:void 0}))}}catch(n){throw this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:e,sessionId:t.sessionId}),n}};sendSessionReadableResumeDelta=async(e,t,n,r)=>{let i=yP(e,t.sessionId),a=await this.sessionManager.getProjectSessionRawEvents(t.projectId,t.sessionId,2**53-1),{baseFilteredRawEvents:o,nextFilteredRawEvents:s}=lP({rawEvents:a,detailLevel:t.detailLevel,cursorRawSeq:n}),c=kP({target:t,filteredRawEvents:o}),l=kP({target:t,filteredRawEvents:s}),u=this.stateByClientSession.get(i),d=cP(u?.kind===`bootstrapping`?u.queuedEnvelopes:[],l.rawEvents[l.rawEvents.length-1]?.rawSeq);for(let e of d)l=AP(l,e);this.log(`stream.readable.resume.prepared`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,provider:t.provider,detailLevel:t.detailLevel,reason:r,cursorRawSeq:n,rawEventCount:a.length,baseFilteredRawEventCount:o.length,nextFilteredRawEventCount:s.length,bootstrapState:LP(u),bufferedEnvelopeCount:d.length,previousState:IP(c),nextState:IP(l)}),this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:l.rawEvents,contextUsage:l.contextUsage,timelineItems:l.timelineItems,pendingApprovals:l.pendingApprovals,pendingUserInputs:l.pendingUserInputs});let f=l.rawEvents[l.rawEvents.length-1]?.rawSeq??n;this.sessionHub.sendStreamMessage(e,fP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`delta`,reason:r,fromRawSeq:n,...f===void 0?{}:{toRawSeq:f}}));let p=RP({previousState:c,nextState:l},this.log);this.log(`stream.readable.resume.delta`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,reason:r,cursorRawSeq:n,emittedDelta:!!p,deltaFromRawSeq:p?.fromRawSeq??n,deltaToRawSeq:p?.toRawSeq??f??null,timelineUpsertCount:p?.timelineUpserts.length??0,timelineRemovalCount:p?.timelineRemovals.length??0,timelineTextDeltaPatchCount:p?.timelineTextDeltaPatches.length??0,pendingApprovalUpsertCount:p?.pendingApprovalUpserts.length??0,pendingUserInputUpsertCount:p?.pendingUserInputUpserts.length??0}),this.sessionHub.sendSessionMessageToClient(e,t.sessionId,hP(p??{provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,fromRawSeq:n,toRawSeq:f,timelineUpserts:[],timelineRemovals:[]}))};syncReadableLiveProjectionSubscriptions(e,t,n,r){let i=new Set(n.filter(bP).map(e=>e.sessionId));if(r)for(let n of t)i.has(n.sessionId)||this.clearState(e,n.sessionId);for(let t of n)bP(t)||this.clearState(e,t.sessionId)}startReadableLiveProjectionBootstrap(e){let t=yP(e.clientId,e.sessionId),n=this.stateByClientSession.get(t),r=this.pendingDeltaByClientSession.get(t),i=e.previousReadyState??(n?.kind===`bootstrapping`?n.previousReadyState:this.getReadableDeliveredReadyState(e.clientId,e.sessionId)),a=this.getReadablePendingDeltaReplayEnvelopes(i,r);r&&(clearTimeout(r.timer),this.pendingDeltaByClientSession.delete(t));let o=n?.kind===`bootstrapping`?n:i,s=uP(e.sessionId,o);if(a.length>0){let e=new Set(s.queuedEnvelopes.map(e=>e.rawSeq));for(let t of a)e.has(t.rawSeq)||(s.queuedEnvelopes.push(t),e.add(t.rawSeq))}return this.stateByClientSession.set(t,s),this.log(`readable.bootstrap.started`,{clientId:e.clientId,sessionId:e.sessionId,replacedState:LP(n),clearedPendingDelta:!!r,carriedPendingEnvelopeCount:a.length}),t}getReadableDeliveredReadyState(e,t){let n=yP(e,t),r=this.pendingDeltaByClientSession.get(n);if(r)return r.previousState;let i=this.stateByClientSession.get(n);return i?.kind===`ready`?i:null}getReadablePendingDeltaReplayEnvelopes(e,t){return t?cP(t.nextState.rawEvents,e?.rawEvents[e.rawEvents.length-1]?.rawSeq):[]}getReadableRefreshDeltaBase(e){let t=this.getReadableRefreshDeltaReason(e.reason);if(!t||e.refreshMode!==`delta`)return null;let n=this.getReadableDeliveredReadyState(e.clientId,e.sessionId);if(!n||n.projectId!==e.projectId||n.detailLevel!==e.detailLevel)return null;let r=n.rawEvents[n.rawEvents.length-1]?.rawSeq;return typeof r==`number`?{cursor:r,previousReadyState:n,reason:t}:null}getReadableRefreshDeltaReason(e){return e===`external_history_updated`||e===`explicit_history_sync`?`${e}_delta`:null}seedReadableLiveProjectionState(e){let t=SP(e);this.stateByClientSession.set(yP(e.clientId,e.target.sessionId),t),this.log(`readable.state.seeded`,{clientId:e.clientId,sessionId:e.target.sessionId,projectId:e.target.projectId,provider:e.target.provider,detailLevel:e.target.detailLevel,state:IP(t)})}primeReadableBootstrapForSubscriptions(e,t){for(let n of t)bP(n)&&this.startReadableLiveProjectionBootstrap({clientId:e,sessionId:n.sessionId})}async syncSessionStreamSubscription(e,t){let n=await this.resolveSessionStreamTarget(t);if(n.bootstrapMode===`readable`){if(t.cursor.kind===`all`){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`all`,requestedRawSeq:null,decision:`snapshot`,reason:`readable_bootstrap_snapshot`}),await this.sendSessionReadableSnapshot(e,n,`readable_bootstrap_snapshot`);return}let r=await this.sessionManager.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:t.cursor.rawSeq,decision:`snapshot`,reason:`readable_empty_history_snapshot`,rangeMin:null,rangeMax:null}),await this.sendSessionReadableSnapshot(e,n,`readable_empty_history_snapshot`);return}let i=t.cursor.rawSeq,a=Math.max(0,r.min-1);if(i<a||i>r.max){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`snapshot`,reason:`readable_cursor_out_of_range_snapshot`,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a}),await this.sendSessionReadableSnapshot(e,n,`readable_cursor_out_of_range_snapshot`);return}let o=n.status===`running`?`readable_cursor_resumed_delta`:`readable_session_idle_delta`;this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`delta`,reason:o,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a}),await this.sendSessionReadableResumeDelta(e,n,i,o);return}if(t.cursor.kind===`all`){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`all`,requestedRawSeq:null,decision:`snapshot`,reason:`cursor_all`}),await this.sendSessionSnapshot(e,n,`cursor_all`);return}let r=await this.sessionManager.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:t.cursor.rawSeq,decision:`snapshot`,reason:`empty_history_snapshot`,rangeMin:null,rangeMax:null}),await this.sendSessionSnapshot(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq,a=Math.max(0,r.min-1);if(i<a||i>r.max){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`snapshot`,reason:`cursor_out_of_range_snapshot`,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a}),await this.sendSessionSnapshot(e,n,`cursor_out_of_range_snapshot`);return}let o=await this.sessionManager.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),s=o[o.length-1]?.rawSeq??i;this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a,backlogCount:o.length,backlogFirstRawSeq:o[0]?.rawSeq??null,backlogLastRawSeq:s}),this.sessionHub.sendStreamMessage(e,fP({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:s}));for(let t of o)this.sessionHub.sendStreamMessage(e,t)}async resolveSessionStreamTarget(e){let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let r=await this.sessionManager.getProjectSessionSummary(n,t);if(!r)throw _w(n,t);let i={sessionId:t,projectId:n,provider:r.provider,status:r.status,detailLevel:e.detailLevel??`full`,purpose:e.purpose??null,bootstrapMode:e.bootstrapMode??`stream`};return this.log(`stream.subscribe.target.resolved`,{sessionId:t,requestedProjectId:n,resolvedProjectId:i.projectId,purpose:i.purpose,detailLevel:i.detailLevel,bootstrapMode:i.bootstrapMode,targetProvider:i.provider,targetStatus:i.status,resolvedViaExecutionContext:!1,summary:zP(r)}),i}let r=this.sessionManager.getSessionExecutionContext(t),i=await this.sessionManager.getProjectSessionSummary(r.projectId,t),a={sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`,detailLevel:e.detailLevel??`full`,purpose:e.purpose??null,bootstrapMode:e.bootstrapMode??`stream`};return this.log(`stream.subscribe.target.resolved`,{sessionId:t,requestedProjectId:null,resolvedProjectId:a.projectId,purpose:a.purpose,detailLevel:a.detailLevel,bootstrapMode:a.bootstrapMode,targetProvider:a.provider,targetStatus:a.status,resolvedViaExecutionContext:!0,executionContextProvider:r.provider,summary:zP(i)}),a}async buildReadableSnapshotProjection(e){let t=await this.sessionManager.getProjectSessionRawEventsCompacted(e.projectId,e.sessionId,2**53-1),n=eE(t,e.detailLevel),r=e.purpose===`detail_view`?Sc({provider:e.provider,rawEvents:n}):null,i=t[t.length-1]?.rawSeq,a=e.purpose===`detail_view`?EP(tp(e.sessionId,n,[])):[],o=e.purpose===`detail_view`?_o({rawEvents:n,messages:a}):{timelineItems:[],consumedMessageIds:[]},s=e.purpose===`detail_view`?DP(e.sessionId,n):{pendingApprovals:[],pendingUserInputs:[]};return{compactedRawEvents:t,filteredRawEvents:n,contextUsage:r,lastRawSeq:i,slimReadableProjection:o,pendingApprovals:s.pendingApprovals,pendingUserInputs:s.pendingUserInputs}}restoreReadableLiveProjectionAfterBootstrapFailure(e){let t=yP(e.clientId,e.sessionId),n=this.stateByClientSession.get(t);if(!n||n.kind!==`bootstrapping`)return;let r=this.sessionHub.getSubscriptions(e.clientId).find(t=>t.sessionId===e.sessionId),i=r?.projectId?.trim()??``,a=dP(n,AP);if(!a.previousReadyState||!r||!bP(r)||i&&i!==a.previousReadyState.projectId||(r.detailLevel??`full`)!==a.previousReadyState.detailLevel||!a.nextReadyState){this.log(`readable.bootstrap.recovery.discarded`,{clientId:e.clientId,sessionId:e.sessionId,bootstrapState:LP(n),currentSubscriptionFound:!!r,currentSubscriptionProjectId:i||null,currentSubscriptionDetailLevel:r?.detailLevel??null,previousReadyState:IP(a.previousReadyState),nextReadyState:IP(a.nextReadyState)}),this.clearState(e.clientId,e.sessionId);return}if(this.stateByClientSession.set(t,a.nextReadyState),a.replayedEnvelopes.length===0){this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:0,nextReadyState:IP(a.nextReadyState)});return}let o,s=a.previousReadyState;for(let t of a.replayedEnvelopes){let n=AP(s,t),r=FP(e.sessionId,t,s,n);r&&(o={...o??{},...r}),s=n}let c=RP({previousState:a.previousReadyState,nextState:a.nextReadyState,sessionSummary:o},this.log);if(!c){this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:IP(a.nextReadyState),emittedDelta:!1});return}this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:IP(a.nextReadyState),emittedDelta:!0,deltaFromRawSeq:c.fromRawSeq??null,deltaToRawSeq:c.toRawSeq}),this.sessionHub.sendSessionMessageToClient(e.clientId,a.previousReadyState.sessionId,hP(c))}sendReadableLiveDeltaNow(e){let t=RP({previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary},this.log);t&&this.sessionHub.sendSessionMessageToClient(e.clientId,e.previousState.sessionId,hP(t))}flushPendingReadableLiveDelta(e,t){let n=yP(e,t),r=this.pendingDeltaByClientSession.get(n);r&&(clearTimeout(r.timer),this.pendingDeltaByClientSession.delete(n),this.sendReadableLiveDeltaNow({clientId:e,previousState:r.previousState,nextState:r.nextState,sessionSummary:r.sessionSummary}))}enqueueReadableLiveDelta(e){if(this.readableLiveDeltaCoalesceMs<=0){this.sendReadableLiveDeltaNow(e);return}let t=yP(e.clientId,e.previousState.sessionId),n=this.pendingDeltaByClientSession.get(t);if(n){let t=VP({existing:{previousState:n.previousState,nextState:n.nextState,sessionSummary:n.sessionSummary},next:{previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary}});n.previousState=t.previousState,n.nextState=t.nextState,n.sessionSummary=t.sessionSummary;return}let r=setTimeout(()=>{this.flushPendingReadableLiveDelta(e.clientId,e.previousState.sessionId)},this.readableLiveDeltaCoalesceMs);r.unref?.(),this.pendingDeltaByClientSession.set(t,{clientId:e.clientId,sessionId:e.previousState.sessionId,previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary,timer:r})}};function VP(e){let t=(e,t)=>{let n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0};return e.existing?{previousState:e.existing.previousState,nextState:e.next.nextState,sessionSummary:t(e.existing.sessionSummary,e.next.sessionSummary)}:{previousState:e.next.previousState,nextState:e.next.nextState,sessionSummary:t(void 0,e.next.sessionSummary)}}function HP(e){return e.sendProviderRaw?`relay_ws`:`direct_ws`}function UP(e){let t=performance.now(),n=JSON.stringify(e);return{payload:n,byteLength:Buffer.byteLength(n),serializeDurationMs:Number((performance.now()-t).toFixed(3))}}function WP(e){return e.kind===`session.readable.snapshot.chunk`?{snapshotId:e.payload.readable.snapshotId,chunkIndex:e.payload.readable.chunkIndex,totalChunks:e.payload.readable.totalChunks,snapshotFormat:`readable`,chunkEventCount:null,chunkTimelineItemCount:e.payload.readable.timelineItems.length}:e.kind===`session.stream.snapshot.chunk`?{snapshotId:e.payload.raw.snapshotId,chunkIndex:e.payload.raw.chunkIndex,totalChunks:e.payload.raw.totalChunks,snapshotFormat:e.payload.readable?`raw+readable`:`raw`,chunkEventCount:e.payload.raw.events.length,chunkTimelineItemCount:e.payload.readable?.timelineItems?.length??null}:null}var GP=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${ow(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}getWatchSubscriptions(e){let t=new Map;for(let n of this.clients.values())for(let r of n.subscriptionsBySessionId.values())r.purpose===e&&t.set(r.sessionId,r);return[...t.values()]}getClientSubscriptionsForSession(e,t){let n=this.clientIdsBySessionId.get(e);if(!n||n.size===0)return[];let r=[];for(let i of n){let n=this.clients.get(i),a=n?.subscriptionsBySessionId.get(e);!n||!a||t&&a.purpose!==t||r.push({clientId:i,subscription:a})}return r}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=null;for(let r of t){let t=this.clients.get(r),i=t?.subscriptionsBySessionId.get(e.sessionId);if(!t||!i||!this.shouldDeliverProviderRaw(i))continue;let a=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(a?.paused){a.queued.push({message:e});continue}if(t.socket.readyState===t.socket.OPEN){if(t.socket.sendProviderRaw){t.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),t.socket.send(n)}}}routeSessionMessage(e,t){let n=this.clientIdsBySessionId.get(e.sessionId);if(!n||n.size===0)return;let r=null;for(let i of n){let n=this.clients.get(i),a=n?.subscriptionsBySessionId.get(e.sessionId);if(!n||!a||!t(a))continue;let o=this.deliveryStateByClientSession.get(this.clientSessionKey(i,e.sessionId));if(o?.paused){o.queued.push({message:e});continue}n.socket.readyState===n.socket.OPEN&&(r=this.sendGatewayStreamMessage(n,e,r))}}sendSessionMessageToClient(e,t,n){let r=this.clients.get(e),i=r?.subscriptionsBySessionId.get(t);if(!r||!i)return;let a=this.deliveryStateByClientSession.get(this.clientSessionKey(e,t));if(a?.paused){a.queued.push({message:n});return}r.socket.readyState===r.socket.OPEN&&this.sendGatewayStreamMessage(r,n)}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued];r.queued=[];for(let e of a){if(e.message.kind===`provider.raw`&&i.socket.sendProviderRaw){i.socket.sendProviderRaw(e.message);continue}this.sendGatewayStreamMessage(i,e.message)}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||this.sendGatewayStreamMessage(n,t)}sendBroadcastMessage(e,t){let n=null;for(let r of this.clients.values())if(r.socket.readyState===r.socket.OPEN){if(t?.sessionId){let e=r.subscriptionsBySessionId.get(t.sessionId);if(!e||t.purpose&&e.purpose!==t.purpose)continue}n=this.sendGatewayStreamMessage(r,e,n)}}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}sendGatewayStreamMessage(e,t,n=null){let r=n??UP(t),i=WP(t);return i&&pA(`stream.snapshot.chunk.outbound`,{clientId:e.id,deviceId:e.deviceId,transport:HP(e.socket),provider:t.provider,sessionId:t.sessionId,projectId:t.projectId??null,messageKind:t.kind,messageType:t.type,snapshotId:i.snapshotId,chunkIndex:i.chunkIndex,totalChunks:i.totalChunks,snapshotFormat:i.snapshotFormat,chunkEventCount:i.chunkEventCount,chunkTimelineItemCount:i.chunkTimelineItemCount,serializedByteLength:r.byteLength,serializeDurationMs:r.serializeDurationMs}),e.socket.send(r.payload),r}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}shouldDeliverProviderRaw(e){return!(e.purpose===`detail_view`&&e.bootstrapMode===`readable`)}};const KP=1200,qP=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var JP=class{statesByKey=new Map;targetsByClientId=new Map;constructor(e){this.options=e}getClientWatchTargets(e){let t=this.targetsByClientId.get(e);return t?[...t.values()]:[]}setClientWatchTargets(e,t,n){let r=new Map;for(let e of t){let t=e.sessionId.trim(),n=e.projectId?.trim()??``;!t||!n||r.set(this.stateKey(n,t),{sessionId:t,projectId:n})}let i=this.targetsByClientId.get(e)??new Map,a=n?new Map:new Map(i);for(let[e,t]of r)a.set(e,t);for(let[t,n]of i)a.has(t)||this.removeClientFromState(e,n.projectId??``,n.sessionId);for(let[t,n]of a)i.get(t)||this.addClientToState(e,n.projectId??``,n.sessionId);return this.targetsByClientId.set(e,a),[...a.values()]}removeClient(e){let t=this.targetsByClientId.get(e);if(t){for(let n of t.values())this.removeClientFromState(e,n.projectId??``,n.sessionId);this.targetsByClientId.delete(e)}}close(){for(let e of this.statesByKey.values())this.disposeState(e);this.statesByKey.clear(),this.targetsByClientId.clear()}logDebug(e,t){qP&&(console.log(`[native-watch][gateway]`,e,t),this.options.logger.info?.({event:e,...t},`native session watch debug`))}addClientToState(e,t,n){if(!t||!n)return;let r=this.stateKey(t,n),i=this.statesByKey.get(r);i||(i={provider:`codex`,sessionId:n,projectId:t,ownerClientIds:new Set,fileWatcher:null,debounceTimer:null,catchupRetryTimer:null,reconcileTimer:setInterval(()=>{this.requestSync(r,`reconcile`)},25e3),syncInFlight:!1,rerunRequested:!1,stableIdleSyncCount:0,watchCatchupRetryCount:0,lastObservedRawSeq:0,lastObservedRawEventCount:0,lastTriggeredAt:0,lastSyncStartedAt:null,lastSyncCompletedAt:null},this.statesByKey.set(r,i),this.logDebug(`state.created`,{clientId:e,projectId:t,sessionId:n})),i.ownerClientIds.add(e),this.logDebug(`lease.added`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:i.ownerClientIds.size}),this.requestSync(r,`lease_added`)}removeClientFromState(e,t,n){let r=this.statesByKey.get(this.stateKey(t,n));r&&(r.ownerClientIds.delete(e),this.logDebug(`lease.removed`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:r.ownerClientIds.size}),!(r.ownerClientIds.size>0)&&(this.disposeState(r),this.statesByKey.delete(this.stateKey(t,n))))}disposeState(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null),this.clearCatchupRetry(e,{resetAttempts:!0}),clearInterval(e.reconcileTimer),e.fileWatcher?.close(),e.fileWatcher=null,this.logDebug(`state.disposed`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:e.watchedPath})}async requestSync(e,t){let n=this.statesByKey.get(e);if(n){if(n.lastTriggeredAt=Date.now(),n.syncInFlight){n.rerunRequested=!0;return}n.syncInFlight=!0,n.rerunRequested=!1,n.lastSyncStartedAt=Date.now(),this.logDebug(`sync.begin`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,ownerClientCount:n.ownerClientIds.size,watchedPath:n.watchedPath,watchedDir:n.watchedDir,watchedBaseName:n.watchedBaseName,stableIdleSyncCount:n.stableIdleSyncCount});try{let r=await this.options.sessionManager.getProjectSessionSummary(n.projectId,n.sessionId);if(!r||r.providerMode!==`native`||r.provider!==`codex`&&r.provider!==`claude`){this.logDebug(`sync.stop.unwatchable_summary`,{projectId:n.projectId,sessionId:n.sessionId,summarySource:r?.source,summaryProvider:r?.provider,summaryProviderMode:r?.providerMode,summaryStatus:r?.status}),this.stopState(e);return}if(n.provider=r.provider,!JN(r)){this.clearCatchupRetry(n,{resetAttempts:!0}),n.stableIdleSyncCount=0,this.logDebug(`sync.skip.gateway_live`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,summaryStatus:r.status,interactionLockReason:r.interactionLockReason,watchedPath:n.watchedPath,ownerClientCount:n.ownerClientIds.size});return}let i=await this.options.sessionManager.syncProjectSessionHistory(n.projectId,n.sessionId);n.lastSyncCompletedAt=Date.now(),this.applyWatchPath(n,i.nativeWatchPath);let a=n.lastObservedRawSeq,o=n.lastObservedRawEventCount,s=this.resolveObservedRawSeq(i),c=s>a||i.rawEvents.length>o;if(c?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,s),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),i.session.status!==`running`&&!i.historyUpdated?n.stableIdleSyncCount+=1:n.stableIdleSyncCount=0,this.logDebug(`sync.result`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,status:i.session.status,interactionLockReason:i.session.interactionLockReason,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,nativeWatchPath:i.nativeWatchPath,rawEventCount:i.rawEvents.length,cursorAdvanced:c,previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount}),i.historyUpdated||i.statusChanged){let e=this.options.createExternalUpdateMessage({provider:i.session.provider,sessionId:i.session.id,projectId:i.session.projectId,updatedAt:i.session.updatedAt,status:i.session.status,interactionLockReason:i.session.interactionLockReason,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e)}i.historyUpdated&&await this.options.refreshDetailSessionSnapshots?.({projectId:n.projectId,sessionId:n.sessionId,reason:`external_history_updated`,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq})}catch(e){this.options.logger.warn({err:e,projectId:n.projectId,sessionId:n.sessionId,reason:t},`native session watch sync failed`)}finally{let n=this.statesByKey.get(e);if(!n)return;n.syncInFlight=!1,n.rerunRequested&&(this.logDebug(`sync.rerun`,{projectId:n.projectId,sessionId:n.sessionId,reason:t}),n.rerunRequested=!1,this.requestSync(e,`rerun`))}}}stopState(e){let t=this.statesByKey.get(e);if(t){this.disposeState(t),this.statesByKey.delete(e);for(let t of this.targetsByClientId.values())t.delete(e)}}applyWatchPath(e,t){let n=t?.trim()??``;if(!n)return;let r=p.default.resolve(n);if(e.watchedPath===r&&e.fileWatcher)return;let i=p.default.dirname(r),a=p.default.basename(r);e.fileWatcher?.close(),e.fileWatcher=null,e.watchedPath=r,e.watchedDir=i,e.watchedBaseName=a,this.logDebug(`watch.path.applied`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,watchedDir:i,watchedBaseName:a});try{e.fileWatcher=this.createPathWatcher(r,(t,n)=>{let i=n?Buffer.isBuffer(n)?n.toString(`utf8`):n:void 0;this.logDebug(`watch.fs.event`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,eventType:t,filename:i}),this.scheduleDebouncedSync(this.stateKey(e.projectId,e.sessionId))}),e.fileWatcher.on(`error`,t=>{this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`native session watcher error`)})}catch(t){this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`failed to start native session watcher`)}}createPathWatcher(e,t){return this.options.createWatcher?this.options.createWatcher(e,t):(0,u.watch)(e,(e,n)=>{t(e,n)})}scheduleDebouncedSync(e){let t=this.statesByKey.get(e);if(!t)return;let n=!!t.debounceTimer;t.debounceTimer&&clearTimeout(t.debounceTimer),this.clearCatchupRetry(t,{resetAttempts:!0}),this.logDebug(`watch.debounce.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath,delayMs:300,replacedExistingTimer:n}),t.debounceTimer=setTimeout(()=>{t.debounceTimer=null,this.logDebug(`watch.debounce.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath}),this.requestSync(e,`watch`)},300)}resolveObservedRawSeq(e){let t=e.rawEvents[e.rawEvents.length-1],n=t&&typeof t==`object`&&t&&`rawSeq`in t&&typeof t.rawSeq==`number`?t.rawSeq:void 0;return e.toRawSeq??n??0}clearCatchupRetry(e,t){e.catchupRetryTimer&&=(clearTimeout(e.catchupRetryTimer),null),t?.resetAttempts&&(e.watchCatchupRetryCount=0)}maybeScheduleWatchCatchupRetry(e,t,n,r,i){n!==`watch`&&n!==`watch_catchup`||t.ownerClientIds.size!==0&&(t.watchCatchupRetryCount>=2||(t.catchupRetryTimer||=(t.watchCatchupRetryCount+=1,this.logDebug(`watch.catchup.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,reason:n,delayMs:KP,historyUpdated:r.historyUpdated,refreshMode:r.refreshMode,previousObservedRawSeq:i.previousObservedRawSeq,previousObservedRawEventCount:i.previousObservedRawEventCount,nextObservedRawSeq:i.nextObservedRawSeq,nextObservedRawEventCount:i.nextObservedRawEventCount,watchCatchupRetryCount:t.watchCatchupRetryCount}),setTimeout(()=>{t.catchupRetryTimer=null,this.logDebug(`watch.catchup.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchCatchupRetryCount:t.watchCatchupRetryCount}),this.requestSync(e,`watch_catchup`)},KP))))}stateKey(e,t){return JSON.stringify([e,t])}},YP=class{constructor(e){this.config=e}issue(e){let t=XP(e.sizeBytes??0),n=ZC.default.sign({sub:e.deviceId,type:`workspace_preview`,gatewayId:this.config.gatewayId,path:e.canonicalPath,disposition:e.disposition},this.config.accessSecret,{expiresIn:t}),r=ZC.default.decode(n);return{ticket:n,expiresAt:r?.exp?new Date(r.exp*1e3).toISOString():new Date().toISOString()}}getExpiresAt(e){let t=ZC.default.decode(e);return t?.exp?new Date(t.exp*1e3).toISOString():new Date().toISOString()}verify(e){let t;try{t=ZC.default.verify(e,this.config.accessSecret)}catch(e){if(e instanceof Error){if(e.name===`TokenExpiredError`)throw hw();if(e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)throw mw()}throw e}if(t.type!==`workspace_preview`||t.gatewayId!==this.config.gatewayId)throw mw();return t}};function XP(e){return e>20971520?7200:600}var ZP=class{constructor(e){this.dependencies=e}async listEntries(e,t=200){if(e.kind===`absolute`)return this.dependencies.fsService.listEntriesAbsolute(e.path,t);let n=await this.requireProject(e.projectId);return this.dependencies.fsService.listEntriesProjectRelative(n.path,e.path??`.`,t)}async resolveFile(e){return{file:(await this.resolveLocator(e)).descriptor}}async readTextFile(e,t={}){let n=await this.resolveLocator(e),r=await this.dependencies.fsService.readTextFile(n.canonicalPath,t);return{file:n.descriptor,...r}}async preparePreview(e,t){let n=await this.resolveLocator(e),r=t.disposition??(n.descriptor.preferredPreviewAction===`share_sheet`||n.descriptor.preferredPreviewAction===`download`?`attachment`:`inline`),i=this.dependencies.previewTicketService.issue({canonicalPath:n.canonicalPath,deviceId:t.deviceId??``,disposition:r,sizeBytes:n.descriptor.sizeBytes}),a=i.ticket,o=i.expiresAt;return{file:n.descriptor,preview:{url:t.buildPreviewUrl(a),expiresAt:o,supportsRange:n.descriptor.capabilities.supportsRange,contentType:n.descriptor.mimeType,contentDisposition:r}}}async readPreviewContent(e,t={}){let n=this.dependencies.previewTicketService.verify(e),r=await this.dependencies.fsService.resolveAbsoluteFile(n.path),i=await this.dependencies.fsService.readFileContentRange(r.canonicalPath,{rangeHeader:t.rangeHeader,includeBody:t.includeBody});return{statusCode:i.statusCode,headers:{contentType:r.mimeType,contentDisposition:$P(n.disposition,r.displayName),contentLength:i.contentLength,etag:i.etag,...r.capabilities.supportsRange?{acceptRanges:`bytes`}:{},...i.contentRange?{contentRange:i.contentRange}:{},...i.lastModified?{lastModified:i.lastModified}:{},cacheControl:`private, max-age=300`},body:i.buffer}}async openPreviewContentStream(e,t={}){let n=this.dependencies.previewTicketService.verify(e),r=await this.dependencies.fsService.resolveAbsoluteFile(n.path),i=await this.dependencies.fsService.openFileContentRangeStream(r.canonicalPath,{rangeHeader:t.rangeHeader,includeBody:t.includeBody});return{statusCode:i.statusCode,headers:{contentType:r.mimeType,contentDisposition:$P(n.disposition,r.displayName),contentLength:i.contentLength,etag:i.etag,...r.capabilities.supportsRange?{acceptRanges:`bytes`}:{},...i.contentRange?{contentRange:i.contentRange}:{},...i.lastModified?{lastModified:i.lastModified}:{},cacheControl:`private, max-age=300`},bodyStream:i.stream}}async resolveLocator(e){if(e.kind===`absolute`){let t=await this.dependencies.fsService.resolveAbsoluteFile(e.path);return{canonicalPath:t.canonicalPath,descriptor:{locator:{kind:`absolute`,path:t.canonicalPath},canonicalPath:t.canonicalPath,displayName:t.displayName,kind:`file`,sizeBytes:t.sizeBytes,mimeType:t.mimeType,extension:t.extension,updatedAt:t.updatedAt,etag:t.etag,previewCategory:t.previewCategory,preferredPreviewAction:t.preferredPreviewAction,capabilities:t.capabilities}}}if(e.kind===`project_relative`){let t=await this.requireProject(e.projectId),n=await this.dependencies.fsService.resolveProjectRelativeFile(t.path,e.path),r=QP(p.default.relative(t.path,n.canonicalPath));return{canonicalPath:n.canonicalPath,descriptor:{locator:{kind:`project_relative`,projectId:t.id,path:r},canonicalPath:n.canonicalPath,displayName:n.displayName,projectId:t.id,relativePath:r,kind:`file`,sizeBytes:n.sizeBytes,mimeType:n.mimeType,extension:n.extension,updatedAt:n.updatedAt,etag:n.etag,previewCategory:n.previewCategory,preferredPreviewAction:n.preferredPreviewAction,capabilities:n.capabilities}}}let t=this.dependencies.sessionManager.getSessionExecutionContext(e.sessionId),n=await this.dependencies.fsService.resolveProjectRelativeFile(t.projectPath,e.path),r=QP(p.default.relative(t.projectPath,n.canonicalPath));return{canonicalPath:n.canonicalPath,descriptor:{locator:{kind:`session_relative`,sessionId:e.sessionId,path:r},canonicalPath:n.canonicalPath,displayName:n.displayName,projectId:t.projectId,relativePath:r,kind:`file`,sizeBytes:n.sizeBytes,mimeType:n.mimeType,extension:n.extension,updatedAt:n.updatedAt,etag:n.etag,previewCategory:n.previewCategory,preferredPreviewAction:n.preferredPreviewAction,capabilities:n.capabilities}}}async requireProject(e){let t=await this.dependencies.sessionManager.getProject(e);if(!t)throw gw(e);return t}};function QP(e){return e.split(p.default.sep).join(`/`)}function $P(e,t){return`${e}; filename="${t.replace(/["\\]/g,`_`)}"`}function eF(e){return e.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`},purpose:e.purpose,detailLevel:e.detailLevel,bootstrapMode:e.bootstrapMode}))}const tF=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG;let nF=null;const rF={perMessageDeflate:{threshold:1024}},iF={globalDecompression:!1,threshold:1024,customTypes:/^text\/(?!event-stream)|(?:\+|\/)json(?:;|$)|(?:\+|\/)text(?:;|$)|(?:\+|\/)xml(?:;|$)/u},aF=4096;function oF(e,t){tF&&(console.log(`[native-watch][gateway]`,e,t),nF?.info({event:e,...t},`native session watch debug`))}function sF(e){return e?typeof e==`string`?e:e.toString(`utf8`):``}function cF(e){return{sessionId:e.sessionId,projectId:e.projectId??null,purpose:e.purpose??null,detailLevel:e.detailLevel??null,bootstrapMode:e.bootstrapMode??null,cursorKind:e.cursor.kind,rawSeq:e.cursor.kind===`raw_seq`?e.cursor.rawSeq:null}}async function lF(e){let t=e.limit??300,n=e.detailLevel??`full`,r=(r,i)=>{pA(`raw-events.list`,{requestSource:e.requestSource,projectId:e.projectId,sessionId:e.sessionId,limit:t,detailLevel:n,requestedCursor:e.fromRawSeqExclusive??null,decision:r.decision,reason:r.reason,fromRawSeqExclusive:r.fromRawSeqExclusive??null,toRawSeq:r.toRawSeq??null,returnedCount:r.events.length,returnedFirstRawSeq:r.events[0]?.rawSeq??null,returnedLastRawSeq:r.events[r.events.length-1]?.rawSeq??null,...i})};if(e.fromRawSeqExclusive===void 0){let i=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),a={decision:`snapshot`,reason:i.length===0?`empty_history_snapshot`:`initial_snapshot`,toRawSeq:i[i.length-1]?.rawSeq,events:eE(i,n)};return r(a),a}let i=await e.sessionManager.getProjectSessionRawSeqRange(e.projectId,e.sessionId);if(!i){let e={decision:`snapshot`,reason:`empty_history_snapshot`,events:[]};return r(e,{rangeMin:null,rangeMax:null,minExpectedCursor:null}),e}let a=Math.max(0,i.min-1);if(e.fromRawSeqExclusive<a||e.fromRawSeqExclusive>i.max){let o=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),s={decision:`snapshot`,reason:`cursor_out_of_range`,toRawSeq:o[o.length-1]?.rawSeq,events:eE(o,n)};return r(s,{rangeMin:i.min,rangeMax:i.max,minExpectedCursor:a}),s}let o=await e.sessionManager.getProjectSessionRawEventsSinceSeq(e.projectId,e.sessionId,e.fromRawSeqExclusive,t),s={decision:`delta`,reason:`cursor_valid_delta`,fromRawSeqExclusive:e.fromRawSeqExclusive,toRawSeq:o[o.length-1]?.rawSeq??e.fromRawSeqExclusive,events:eE(o,n)};return r(s,{rangeMin:i.min,rangeMax:i.max,minExpectedCursor:a}),s}async function uF(e,t={}){await mg(e.gatewayLogPath);let n=fF(e,t),r=dF(e,n.instance);fA(r.log),nF=r.log,await r.register($C.default,{origin:!0}),await r.register(ew.default,iF),await r.register(QC.default,{options:rF});let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new kw(e);await s.init();let c=new zw(e.auditLogPath),l=new GP,u=new TT,d=new yE(e.projectStoreDir),f=new SN(e.sessionHistoryDir);await f.init();let m=new Qk(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new zk({store:m});await h.init();let g,_=null,v=new Map,y=await rm(e.authStoreDir),b=new YP(e),x=e.relayEnabled?wh({relayUrl:e.relayUrl,gatewayHost:e.host}):``,S=e=>{let t=v.get(e);t&&(clearTimeout(t.timeout),v.delete(e),t.resolve())},C=(e,t)=>{let n=v.get(e);n&&(clearTimeout(n.timeout),v.delete(e),n.reject(t instanceof Error?t:Error(String(t))))},w=(e,t)=>new Promise((n,r)=>{C(e,Error(`Duplicate pending relay file upload start for request ${e}`));let i=setTimeout(()=>{v.delete(e),r(Error(`Relay file upload start timed out for request ${e}`))},t);v.set(e,{resolve:n,reject:r,timeout:i})}),T=new aM({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e),D.routeReadableLiveDelta(e)}}),E=new ZP({fsService:u,sessionManager:T,previewTicketService:b}),D=new BP(l,T,e.readableLiveDeltaCoalesceMs,pA),O=new JP({sessionManager:T,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>gP(e),refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e)});T.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let k=new Nh({packageName:z.packageName,currentVersion:z.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>T.getRunningRuntimeSessionCount(),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{D.shutdown(),O.close(),_?.close(),M.close(),await k.shutdown(),await T.shutdown(),await f.shutdown();for(let[e,t]of v.entries())clearTimeout(t.timeout),t.reject(Error(`Gateway shutting down`)),v.delete(e);r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{fA(null),nF=null,n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:R(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),gatewayName:e.name,machineName:lm(),gatewayIdentity:y.identity})),r.get(`/api/pairing/descriptor`,async()=>gh({gatewayId:e.gatewayId,gatewayName:e.name,machineName:lm(),relayBaseUrl:x,directBaseUrls:Sh({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),relayTransportSecurityLevel:e.relayEnabled?e.relayTransportSecurityLevel:void 0,gatewayIdentity:y.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!L(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(t,n)=>{let r=il.safeParse(t.body);if(!r.success)return n.code(400).send({error:`Invalid request`,detail:r.error.flatten()});try{let t=he(r.data.deviceName),n=await s.claimPairingCode(r.data.code,t,r.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:n.deviceId,detail:{deviceName:t}}),tP(y,{...n,gatewayName:e.name,machineName:lm()},r.data.code,r.data.deviceIdentity)}catch(e){return n.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=sl.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await XN({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}});let A=()=>Zu.parse({name:e.name,machineName:lm()}),j=async n=>{let r=Zu.pick({name:!0}).parse(n);if(!t.configPath)throw Error(`Gateway config path is unavailable`);return e.name=await wm(t.configPath,r.name),A()};r.get(`/api/gateway/settings`,async(e,t)=>{if(ne(e,t))return A()}),r.post(`/api/gateway/settings`,async(e,t)=>{if(!ne(e,t))return;let n=Zu.pick({name:!0}).safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await j(n.data)}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(ne(e,t))return{projects:await T.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(ne(e,t))try{return await k.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!ne(e,t))return;let n=e.body,r=Su.safeParse(n?.requestedBy);try{let e=await k.applyUpdate(r.success?r.data:`mobile`);return Du.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.post(`/api/codex/app-server/restart`,async(e,t)=>{if(ne(e,t))try{return gl.parse(await T.restartCodexAppServer())}catch(e){let n=cw(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/codex/accounts`,async(e,t)=>{if(ne(e,t))try{return pl.parse(await T.getCodexAccounts())}catch(e){return re(t,e)}}),r.post(`/api/codex/accounts/save`,async(e,t)=>{if(ne(e,t))try{return ml.parse(await T.saveCurrentCodexAccount())}catch(e){return re(t,e)}}),r.post(`/api/codex/accounts/switch`,async(e,t)=>{if(!ne(e,t))return;let n=e.body;if(typeof n?.accountId!=`string`||!n.accountId.trim())return t.code(400).send({error:`accountId is required and must be a non-empty string`});try{return hl.parse(await T.switchCodexAccount(n.accountId))}catch(e){return re(t,e)}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(ne(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(ne(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!ne(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return cw(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):sP(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!ne(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/workspace/directories`,async(e,t)=>{if(!ne(e,t))return;let n=e.body;if(typeof n?.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});if(typeof n.name!=`string`||!n.name.trim())return t.code(400).send({error:`name is required and must be a non-empty string`});try{return await u.createDirectoryUnrestricted(n.path,n.name,200)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/workspace/entries`,async(e,t)=>{if(!ne(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{let t=ie(e.query);return await E.listEntries(t,i)}catch(e){return re(t,e)}}),r.get(`/api/workspace/files/resolve`,async(e,t)=>{if(ne(e,t))try{let t=ae(e.query);return await E.resolveFile(t)}catch(e){return re(t,e)}}),r.get(`/api/workspace/files/text`,async(e,t)=>{if(!ne(e,t))return;let n=e.query,r=n.startLine?Number(n.startLine):void 0,i=n.maxLines?Number(n.maxLines):void 0,a=n.maxBytes?Number(n.maxBytes):void 0;try{let t=ae(e.query);return await E.readTextFile(t,{startLine:typeof r==`number`&&Number.isFinite(r)?r:void 0,maxLines:typeof i==`number`&&Number.isFinite(i)?i:void 0,maxBytes:typeof a==`number`&&Number.isFinite(a)?a:void 0})}catch(e){return re(t,e)}}),r.post(`/api/workspace/files/preview`,async(e,t)=>{let n=ne(e,t);if(!n)return;let r=e.body,i=Ou.safeParse(r?.locator);if(!i.success)return t.code(400).send({error:i.error.issues[0]?.message??`Invalid workspace file locator`});let a;if(r?.disposition!==void 0){let e=Ru.safeParse(r.disposition);if(!e.success)return t.code(400).send({error:e.error.issues[0]?.message??`Invalid preview disposition`});a=e.data}try{return await E.preparePreview(i.data,{deviceId:n.sub,disposition:a,buildPreviewUrl:t=>`${oe(e)}/api/workspace/files/content/${encodeURIComponent(t)}`})}catch(e){return re(t,e)}}),r.route({method:[`GET`,`HEAD`],url:`/api/workspace/files/content/:ticket`,handler:async(e,t)=>{let n=e.params.ticket?.trim()??``;if(!n)return t.code(400).send({error:`ticket is required`});try{let r=await E.readPreviewContent(n,{rangeHeader:typeof e.headers.range==`string`?e.headers.range:void 0,includeBody:e.method!==`HEAD`});return t.code(r.statusCode),t.header(`Content-Type`,r.headers.contentType),t.header(`Content-Disposition`,r.headers.contentDisposition),t.header(`Content-Length`,String(r.headers.contentLength)),t.header(`ETag`,r.headers.etag),t.header(`Cache-Control`,r.headers.cacheControl),r.headers.acceptRanges&&t.header(`Accept-Ranges`,r.headers.acceptRanges),r.headers.contentRange&&t.header(`Content-Range`,r.headers.contentRange),r.headers.lastModified&&t.header(`Last-Modified`,r.headers.lastModified),e.method===`HEAD`||!r.body?t.send():t.send(r.body)}catch(e){return re(t,e)}}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!ne(e,t))return;let n=le(e,t);if(n)try{return{capabilities:await T.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return cw(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!ne(e,t))return;let n=le(e,t);if(n)try{return await T.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return cw(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!ne(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await T.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!ne(e,t))return;let n=e.params;try{return await T.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=e.query,i=se(r.status,t);if(!i)return;let a=ce(r.syncExternal);try{return{sessions:await T.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return cw(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=await T.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/config`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=await T.getProjectSessionConfig(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.post(`/api/projects/:projectId/sessions/:sessionId/history-sync`,async(e,t)=>{if(!ne(e,t))return;let n=e.params;try{let e=await T.syncProjectSessionHistory(n.projectId,n.sessionId);return e.historyUpdated&&await D.refreshDetailSessionSnapshots({projectId:n.projectId,sessionId:n.sessionId,reason:`explicit_history_sync`,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}),{session:e.session,rawEventCount:e.rawEvents.length,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged,refreshMode:e.refreshMode,...e.fromRawSeq===void 0?{}:{fromRawSeq:e.fromRawSeq},...e.toRawSeq===void 0?{}:{toRawSeq:e.toRawSeq}}}catch(e){return cw(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=typeof r.fromRawSeqExclusive==`string`?Number(r.fromRawSeqExclusive):void 0,o=nc.safeParse(r.detailLevel).success?nc.parse(r.detailLevel):`full`;try{return await I(n.projectId,n.sessionId,i,typeof a==`number`&&Number.isFinite(a)?Math.max(0,Math.floor(a)):void 0,o,`http`)}catch(e){return cw(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=e.query,i=await T.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>L(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!L(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=ue(t.headers.authorization)??de(t.url);if(!n){e.close(1008,`Missing access token`);return}let i;try{i=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let a=l.addClient(i.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await P(gc(e),i.sub,a)}catch(e){await F({deviceId:i.sub,clientId:a,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,(e,t)=>{let n=l.getSubscriptions(a),o=O.getClientWatchTargets(a);r.log.info({clientId:a,deviceId:i.sub,transport:`direct`,closeCode:typeof e==`number`?e:null,closeReason:sF(t),streamSubscriptionCount:n.length,streamSubscriptions:n.map(cF),externalWatchTargetCount:o.length,externalWatchTargets:o},`gateway websocket client disconnected`),O.removeClient(a),l.removeClient(a),D.clearStatesForClient(a)})});let M=new gA({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?e.relayTransportSecurityLevel:`plaintext-relay`,gatewayIdentity:y.identity,gatewayIdentityPrivateKeyPem:y.privateKeyPem,sessionHub:l,logger:r.log,describeClientState:e=>{let t=l.getSubscriptions(e),n=O.getClientWatchTargets(e);return{streamSubscriptionCount:t.length,streamSubscriptions:t.map(cF),externalWatchTargetCount:n.length,externalWatchTargets:n}},handlePairingClaim:async t=>{let n=he(t.deviceName);return tP(y,{...await s.claimPairingCode(t.code,n,t.deviceIdentity),gatewayName:e.name,machineName:lm()},t.code,t.deviceIdentity)},handleRefresh:async t=>{let n=await XN({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return YN(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},handleFileContentRequest:async(e,t)=>{if(t.method===`GET`&&t.responseMode===`stream_upload`){let n=await E.openPreviewContentStream(t.ticket,{rangeHeader:t.rangeHeader,includeBody:!0});if(n.bodyStream&&t.uploadUrl&&t.uploadToken){let i=w(e,15e3),a=mF({uploadUrl:t.uploadUrl,uploadToken:t.uploadToken,contentLength:n.headers.contentLength,bodyStream:n.bodyStream});a.completed.catch(n=>{C(e,n),r.log.warn({err:n,requestId:e,ticket:t.ticket},`relay workspace preview upload failed`)});try{await i}catch(e){throw a.abort(e),e}}return qd.parse({status:n.statusCode,headers:n.headers,...n.bodyStream?{bodyTransport:`stream_upload`}:{}})}let n=await E.readPreviewContent(t.ticket,{rangeHeader:t.rangeHeader,includeBody:t.method===`GET`});return qd.parse({status:n.statusCode,headers:n.headers,...n.body?{bodyBase64:n.body.toString(`base64`)}:{}})},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(t,n)=>rP(t,{gatewayId:e.gatewayId,relayPreviewBaseUrl:x,authService:s,logger:r.log,sessionManager:T,projectDiscoveryService:h,fsService:u,workspaceFileService:E,updateService:k,gatewaySettings:{get:A,update:j},relayDeviceId:n.deviceId,refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e),buildRawEventsListResult:lF}),handleFileContentUploadStarted:S,sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await P(e,t,n)}catch(r){await F({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),N=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await T.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await T.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:await T.startReview(e.payload.sessionId,e.payload.config,t,{input:e.payload.input,turnConfig:e.payload.turnConfig});return;case`tool.approval.respond`:await T.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await T.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await T.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.external.watch.set`:{oF(`command.received`,{clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions},`received session.external.watch.set`);let i=O.setClientWatchTargets(n,e.payload.sessions,e.payload.replace);oF(`command.applied`,{clientId:n,deviceId:t,replace:e.payload.replace,requestedSessionCount:e.payload.sessions.length,targetCount:i.length,targets:i}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,requestedSessionCount:e.payload.sessions.length,targetCount:i.length,targets:i},`applied session.external.watch.set`),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:i.map(e=>e.sessionId)}});return}case`session.stream.subscribe`:{let t=eF(e.payload.sessions);await D.handleSessionStreamSubscribeCommand(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=T.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await T.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=T.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await T.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},P=async(e,t,n)=>{await N(e,t,n)},F=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await T.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},I=async(e,t,n=300,r,i=`full`,a=`http`)=>lF({sessionManager:T,projectId:e,sessionId:t,limit:n,fromRawSeqExclusive:r,detailLevel:i,requestSource:a}),L=t=>t.headers[`x-api-key`]===e.apiKey,R=e=>{if(e==null)return e;if(typeof e==`string`){let t=ee(e);return t===void 0?B(e,a):te(V(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=ee(t);return n===void 0?B(t,a):te(V(n))}return typeof e==`object`?te(V(e)):String(e)},ee=e=>{try{return JSON.parse(e)}catch{return}},B=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,V=e=>{if(Array.isArray(e))return e.map(e=>V(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=V(r)}return n}return e},te=e=>{let t=H(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:B(t,a)}},H=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},ne=(e,t)=>{let n=ue(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},re=(e,t)=>{let n=cw(t)?t.status:500;return cw(t)?e.code(n).send({error:String(t),code:t.code,...t.details===void 0?{}:{details:t.details}}):e.code(n).send({error:String(t)})},ie=e=>{let t=e&&typeof e==`object`?e:{},n=ku.safeParse({kind:typeof t.locatorKind==`string`?t.locatorKind:void 0,projectId:typeof t.projectId==`string`?t.projectId:void 0,path:typeof t.path==`string`?t.path:void 0});if(!n.success)throw Error(n.error.issues[0]?.message??`Invalid workspace entries locator`);return n.data},ae=e=>{let t=e&&typeof e==`object`?e:{},n=Ou.safeParse({kind:typeof t.locatorKind==`string`?t.locatorKind:void 0,sessionId:typeof t.sessionId==`string`?t.sessionId:void 0,projectId:typeof t.projectId==`string`?t.projectId:void 0,path:typeof t.path==`string`?t.path:void 0});if(!n.success)throw Error(n.error.issues[0]?.message??`Invalid workspace file locator`);return n.data},oe=t=>{let n=t.headers.host?.trim();return n?`${t.protocol}://${n}`.replace(/\/+$/,``):`${e.httpsEnabled?`https`:`http`}://${e.host}:${e.httpsEnabled?e.httpsPort:e.port}`},se=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ce=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},le=(e,t)=>{let n=e.params,r=e.query,i=Na.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},ue=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},de=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},fe=e.httpsEnabled?e.httpsPort:e.port,pe=e.httpsEnabled?`https`:`http`,me=lm(),he=e=>e?.trim()||`Craby mobile`;await r.listen({host:e.host,port:fe});let ge=r.server.address(),_e=typeof ge==`object`&&ge?ge.port:fe;if(r.log.info({host:e.host,port:_e,protocol:pe,machineName:me},pF(pe,e.host,_e)),e.relayEnabled&&(_=new AA({gatewayId:e.gatewayId,machineName:e.name,relayUrl:e.relayUrl,relayTransportSecurityLevel:e.relayTransportSecurityLevel,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>FA({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:y.identity,privateKeyPem:y.privateKeyPem}),gatewayIdentity:y.identity,directBaseUrls:Sh({protocol:pe,host:e.host,port:_e}),logger:r.log,onFrame:async e=>{await M.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await k.start(),{protocol:pe,listenPort:_e,gatewayName:e.name,machineName:me,gatewayIdentity:y.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>k.getInfo(),requestGatewayUpdate:(e=`console`)=>k.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>T.restartCodexAppServer(),startupPairingCode:g}}function dF(e,t){let n=t;if(!e.httpsEnabled)return(0,tw.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:aF}});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);let r={key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}};return(0,tw.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:aF},https:r})}function fF(e,t){let n=process.env.NODE_ENV!==`production`,r=nw.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?nw.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,nw.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function pF(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function mF(e){let t=new URL(e.uploadUrl),n=t.protocol===`https:`?S.request:t.protocol===`http:`?x.request:null;if(!n)throw Error(`Unsupported relay preview upload protocol: ${t.protocol}`);let r=null,i=e=>{};return{completed:new Promise((a,o)=>{let s=!1,c=t=>{if(s)return;if(s=!0,!t){a();return}let n=t instanceof Error?t:Error(String(t));e.bodyStream.destroy(n),r?.destroy(n),o(n)};r=n(t,{method:`PUT`,headers:{"content-type":`application/octet-stream`,"content-length":String(e.contentLength),"x-relay-upload-token":e.uploadToken}},e=>{let t=[];e.on(`data`,e=>{t.push(Buffer.isBuffer(e)?e:Buffer.from(e))}),e.on(`error`,c),e.on(`end`,()=>{let n=e.statusCode??0;if(n>=200&&n<300){c();return}c(Error(`Relay preview upload failed (${n}): ${Buffer.concat(t).toString(`utf8`)}`))})}),i=e=>{c(e??Error(`Relay preview upload aborted`))},r.on(`error`,c),(0,C.pipeline)(e.bodyStream,r).catch(c)}),abort:i}}function hF(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,b.inspect)(e,{depth:6,breakLength:120})}async function gF(e){let t=await bm({configPath:e.configPath,ensureConfigFile:!0});Tm(t.config);let n=await uF(t.config,{configPath:t.configPath,logToConsole:e.logToConsole,onUpdatePrepared:async e=>{vF({type:`worker.update.prepared`,payload:e})}});vF({type:`worker.ready`,payload:_F(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=yF(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${hF(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${hF(e)}`),i(1)});async function a(e){try{switch(e.method){case`gateway.update.apply`:{if(!n.requestGatewayUpdate)throw Error(`gateway update is unavailable`);let t=await n.requestGatewayUpdate(e.requestedBy);vF({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}case`codex.appServer.restart`:{if(!n.requestCodexAppServerRestart)throw Error(`codex app-server restart is unavailable`);let t=await n.requestCodexAppServerRestart(e.requestedBy);vF({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){vF({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function _F(e){return{protocol:e.protocol,listenPort:e.listenPort,gatewayName:e.gatewayName,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function vF(e){process.send&&process.send(e)}function yF(e){if(!bF(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:e.method,requestedBy:e.requestedBy};default:return null}}function bF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}xF(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function xF(e){let t=ee(e);switch(t.command){case`help`:EF();return;case`version`:console.log(z.version);return;case`init`:await CF(t);return;case`doctor`:await wF(t);return;case`start`:await SF(t);return;case`__worker`:await TF(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function SF(e){let t=await bm({configPath:e.configPath,ensureConfigFile:!0});Tm(t.config);let n=await Wm({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await og({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(hg(e,t.config))}Gm(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function CF(e){let t=await ym({configPath:e.configPath,overwrite:e.force});t.created?console.log(`[gateway] wrote config to ${t.configPath}`):(console.log(`[gateway] config already exists at ${t.configPath}`),console.log(`[gateway] rerun with --force to overwrite`));let n=await bm({configPath:t.configPath,ensureConfigFile:!1}),r=await Wm({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Km(r))}async function wF(e){let t=await bm({configPath:vm(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Wm({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Km(n)),Gm(n)&&(process.exitCode=1)}async function TF(e){try{await gF(e)}catch(t){let n=await bm({configPath:e.configPath,ensureConfigFile:!0});throw Error(hg(t,n.config))}}function EF(){console.log(`${z.cliName} ${z.version}`),console.log(``),console.log(`Usage:`),console.log(` ${z.cliName} [start] [--config <path>] [--log]`),console.log(` ${z.cliName} init [--config <path>] [--force]`),console.log(` ${z.cliName} doctor [--config <path>]`),console.log(` ${z.cliName} --version`)}exports.runCli=xF;
|
|
513
|
+
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},DD=3,OD=250;function kD(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function AD(e,t){let n=Math.max(1,t?.maxAttempts??DD),r=Math.max(0,t?.retryDelayMs??OD),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!kD(e)||t>=n)throw e;r>0&&await jD(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function jD(e){return new Promise(t=>{setTimeout(t,e)})}function MD(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function ND(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var PD=3e4,FD=1e3,ID=2e3,LD=1e3,RD={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},zD=class e{constructor(e,t,n,r,i,a){this.process=t,this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.logger=e.logger,this.requestTimeoutMs=n,this.closeInterruptTimeoutMs=r,this.closeGraceTimeoutMs=i,this.forceKillTimeoutMs=a,this.processExitPromise=new Promise(e=>{this.resolveProcessExit=e}),this.bindProcess()}id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;requestTimeoutMs;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;interruptRequested=!1;interruptIssuedTurnId;titleReadInFlight=!1;stdoutBuffer=``;stderrTail=``;closeInterruptTimeoutMs;closeGraceTimeoutMs;forceKillTimeoutMs;processExitPromise;resolveProcessExit=null;closePromise=null;static async create(t,n={}){let r=new e(t,n.spawnProcess?.()??BD(),n.requestTimeoutMs??PD,n.closeInterruptTimeoutMs??FD,n.closeGraceTimeoutMs??ID,n.forceKillTimeoutMs??LD);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.resetInterruptState();try{let n=t?.model??this.activeModel,r=MD(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=HD(this.activeSessionConfig.reasoningEffort),o,s=UD(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&WD(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:UD(t?.mode,n,`low`)})}let c=JE(o.turn?.id);c&&(this.activeTurnId=c),this.flushQueuedInterrupt(`turn_start_response`)}catch(e){throw this.turnInProgress=!1,this.resetInterruptState(),e}}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async interrupt(){this.ensureOpen(),this.turnInProgress&&(this.interruptRequested=!0,await this.requestActiveTurnInterrupt())}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;if(r.method===`item/commandExecution/requestApproval`||r.method===`execCommandApproval`){let e={decision:i};this.sendResponse(r.rpcId,e)}else{let e={decision:i};this.sendResponse(r.rpcId,e)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=KD(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:ND(r),inputMethod:n.method})}async bootstrap(){let e={clientInfo:RD,capabilities:{experimentalApi:!0,optOutNotificationMethods:XE}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return JE((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return JE((await AD(()=>this.sendRequest(`thread/resume`,i))).thread?.id)}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.consumeStderrChunk(String(e))}),this.process.on(`error`,e=>{this.handleProcessFailure(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.resolveProcessExit?.(),this.resolveProcessExit=null,this.closed){this.log(`info`,`codex app-server process exited during shutdown`,{exitCode:e,signal:t});return}let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.handleProcessFailure(`Codex app-server exited unexpectedly (${i})${r}`)})}async closeInternal(){if(this.closed)return;let e=Date.now(),t={threadId:this.threadId,activeTurnId:this.activeTurnId};this.log(`info`,`codex app-server shutdown starting`,{...t,turnInProgress:this.turnInProgress,pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,closeInterruptTimeoutMs:this.closeInterruptTimeoutMs,closeGraceTimeoutMs:this.closeGraceTimeoutMs,forceKillTimeoutMs:this.forceKillTimeoutMs});let n=await this.tryInterruptTurnForClose();this.log(n.result===`failed`?`warn`:`info`,`codex app-server shutdown turn interrupt completed`,{...t,interrupt:n}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.pendingApprovals.clear(),this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.endProcessStdin();let r=Date.now();if(await this.waitForProcessExit(this.closeGraceTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`graceful_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r});return}this.log(`warn`,`codex app-server shutdown grace period elapsed; sending SIGTERM`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r}),this.tryKillProcess(`SIGTERM`);let i=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigterm_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i});return}this.log(`warn`,`codex app-server shutdown SIGTERM grace elapsed; sending SIGKILL`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i}),this.tryKillProcess(`SIGKILL`);let a=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigkill_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a});return}this.log(`error`,`codex app-server shutdown did not observe process exit after SIGKILL`,{...t,result:`sigkill_timeout`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a})}async tryInterruptTurnForClose(){let e=Date.now();if(!this.threadId||!this.activeTurnId)return{attempted:!1,result:`skipped`,durationMs:Date.now()-e,reason:this.threadId?`missing_active_turn_id`:`missing_thread_id`};try{return await qD(this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:this.activeTurnId}),this.closeInterruptTimeoutMs,`Codex app-server turn/interrupt timed out during close`),{attempted:!0,result:`submitted`,durationMs:Date.now()-e}}catch(t){return{attempted:!0,result:`failed`,durationMs:Date.now()-e,error:String(t)}}}endProcessStdin(){if(!(this.process.stdin.destroyed||this.process.stdin.writableEnded))try{this.process.stdin.end()}catch{}}async waitForProcessExit(e){if(this.process.exitCode!==null)return!0;if(!Number.isFinite(e)||e<=0)return await this.processExitPromise,!0;let t;try{await Promise.race([this.processExitPromise,new Promise(n=>{t=setTimeout(n,e)})])}finally{t&&clearTimeout(t)}return this.process.exitCode!==null}tryKillProcess(e){if(this.process.exitCode===null)try{this.process.kill(e)}catch{}}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,processPid:this.process.pid??void 0,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
514
|
+
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t&&this.handleIncomingLine(t)}}consumeStderrChunk(e){this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}handleIncomingLine(e){let t;try{t=JSON.parse(e)}catch{this.emit({type:`native.raw`,source:`codex.app_server`,parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON line from codex app-server`,line:e});return}this.emit({type:`native.raw`,source:`codex.app_server`,message:t});let n=JE(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let e={method:n,id:t.id,params:t.params};this.handleServerRequest(e);return}if(n){let e={method:n,params:t.params};this.handleNotification(e);return}r&&this.handleResponse(t)}handleResponse(e){let t=YE(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=qE(e.error),r=JE(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`);return}}registerApprovalRequest(e,t,n,r){let i=`req_${ow(8)}`;this.pendingApprovals.set(i,{rpcId:e,method:t,kind:n});let a=qE(r),o=JE(a.threadId);o&&(this.threadId=o),this.emit({type:`tool.permission.requested`,requestId:i,toolName:n===`command`?`command_execution`:`file_change`,reason:JE(a.reason),threadId:o,turnId:JE(a.turnId),itemId:JE(a.itemId),approvalMethod:t,rawParams:GE(a)})}registerUserInputRequest(e,t,n){let r=`req_${ow(8)}`;this.pendingUserInputs.set(r,{rpcId:e,method:t});let i=JE(n.threadId);i&&(this.threadId=i);let a=Array.isArray(n.questions)?n.questions.map(GD).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:r,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:GE(n)})}handleNotification(e){let t=(e,t)=>{let n=qE(qE(e).turn),r=JE(n.status)??t;if(this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),r===`failed`){this.emit({type:`turn.failed`,status:r,turn:GE(n),error:GE(n.error??{})});return}this.emit({type:`turn.completed`,status:r,turn:GE(n)}),this.tryEmitTitleFromThreadRead()};if(e.method===`turn/interrupted`){t(e.params,`interrupted`);return}switch(e.method){case`thread/started`:{let t=e.params,n=JE(t.thread?.id);n&&(this.threadId=n),this.emitThreadTitleUpdated(JE(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:GE(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=JE(t.threadId);n&&(this.threadId=n),this.emitThreadTitleUpdated(JE(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params,n=JE(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.flushQueuedInterrupt(`turn_started_notification`),this.emit({type:`turn.started`,turn:GE(t.turn)});return}case`turn/completed`:t(e.params);return;case`item/started`:{let t=e.params;this.emit({type:`item.started`,thread_id:JE(t.threadId),turn_id:JE(t.turnId),item:UE(t.item)});return}case`item/completed`:{let t=e.params;this.emit({type:`item.completed`,thread_id:JE(t.threadId),turn_id:JE(t.turnId),item:UE(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;this.emit({type:`item.updated`,thread_id:JE(t.threadId),turn_id:JE(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;this.emit({type:`item.updated`,thread_id:JE(t.threadId),turn_id:JE(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;this.emit({type:`item.updated`,thread_id:JE(t.threadId),turn_id:JE(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=qE(e.params);this.emit({type:`item.updated`,thread_id:JE(t.threadId),turn_id:JE(t.turnId),item:{id:JE(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:JE(t.delta)??JE(t.text)??``,original_method:e.method,payload:GE(t)}});return}case`error`:{let t=e.params;this.emit({type:`error`,message:JE(t.error?.message)??`Codex app-server error`,error:GE(t.error),will_retry:t.willRetry===!0,thread_id:JE(t.threadId),turn_id:JE(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=YE(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen(),this.process.stdin.write(`${JSON.stringify(e)}
|
|
515
|
+
`)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=VD(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated(JE(e.thread?.name)??JE(e.thread?.preview),JE(e.thread?.name)?`codex.thread_read_name`:`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleProcessFailure(e){if(this.closed)return;let t=this.threadId,n=this.activeTurnId;this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.process`,...t?{thread_id:t}:{},...n?{turn_id:n}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}resetInterruptState(){this.interruptRequested=!1,this.interruptIssuedTurnId=void 0}flushQueuedInterrupt(e){this.interruptRequested&&this.requestActiveTurnInterrupt().catch(t=>{this.log(`warn`,`codex app-server queued interrupt failed`,{reason:e,error:t instanceof Error?t.message:String(t)})})}async requestActiveTurnInterrupt(){if(!this.turnInProgress||!this.threadId||!this.activeTurnId)return;let e=this.activeTurnId;if(this.interruptIssuedTurnId!==e){this.interruptIssuedTurnId=e;try{await this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:e})}catch(t){throw this.turnInProgress&&this.activeTurnId===e&&(this.interruptIssuedTurnId=void 0),t}}}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function BD(){let e=oD();return(0,D.spawn)(e.command,[...e.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function VD(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function HD(e){return e?e===`max`?`xhigh`:e:null}function UD(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function WD(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function GD(e){let t=qE(e),n=JE(t.id),r=JE(t.header),i=JE(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=qE(e),n=JE(t.label),r=JE(t.description)??n,i=JE(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:t.isOther===!0,isSecret:t.isSecret===!0,options:o}}function KD(e){let t={};for(let[n,r]of Object.entries(e??{}))n&&(t[n]=Array.isArray(r)?r.map(e=>String(e)):[]);return t}async function qD(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}var JD=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new HE(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await CD()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??zD.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function YD(e,t){let n=[],r=null,i=tO(t?.maxThreads),a=t?.sortKey,o=t?.updatedAfterUnixSeconds;do{let t=i===null?100:Math.max(0,i-n.length);if(t===0)break;let s=await XD({cwd:e,archived:!1,cursor:r,limit:i===null?100:Math.min(100,t),sortKey:a}),c=!1;for(let t of s.threads)if(t.cwd===e){if(o!==void 0&&t.updatedAt<o){if(a===`updated_at`){c=!0;break}continue}if(n.push(t),i!==null&&n.length>=i){c=!0;break}}if(c)break;r=s.nextCursor}while(r);return n}async function XD(e){return SD(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>eO(e)),nextCursor:n.nextCursor}})}async function ZD(e,t=!0){return SD(async n=>eO((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function QD(e){return SD(async t=>{let n=!1;try{let r=await AD(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,iO(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function $D(){let e=[],t=null;do{let n=await SD(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>rO(e))),t=n.nextCursor}while(t);return e}function eO(e){let t=JE(qE(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,status:nO(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:oO(e.source),gitInfo:e.gitInfo?qE(GE(e.gitInfo)):null,turns:e.turns.map(e=>aO(e))}}function tO(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function nO(e){let t=JE(qE(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function rO(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function iO(e){let t=sO(e.model),n=cO(e.reasoningEffort),r=lO(e.approvalPolicy),i=uO(e.sandbox),a=r!==null||i!==null;return t||n!==null||a?{model:t,sessionTurnConfig:{mode:`default`,model:t??null,reasoningEffort:n,...a?{execution:{codex:{approvalPolicy:r,sandboxMode:i}}}:{}},sessionTurnConfigUpdatedAt:new Date(e.thread.updatedAt*1e3).toISOString()}:null}function aO(e){return{id:e.id,status:e.status,error:e.error?qE(GE(e.error)):null,items:e.items.map(e=>UE(e))}}function oO(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function sO(e){return JE(e)?.trim()||void 0}function cO(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function lO(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function uO(e){let t=typeof e==`string`?e:JE(qE(e).type);return t===`read-only`||t===`readOnly`?`read-only`:t===`workspace-write`||t===`workspaceWrite`?`workspace-write`:t===`danger-full-access`||t===`dangerFullAccess`?`danger-full-access`:null}var dO=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;activeTurnTerminalEmitted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=MD(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=gO(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:ND(r),questions:mO(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{let t=null;try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=FO(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:IO(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(n){if(this.closed||this.activeQuery!==e)return;let r=n instanceof Error?n.message:String(n);this.interruptRequested?t=r:this.emit({type:`error`,message:r})}finally{if(this.closed||this.activeQuery!==e)return;if(this.interruptRequested&&!this.activeTurnTerminalEmitted){let e=this.buildInterruptedTerminalEvents(t??`Operation aborted`);for(let t of e)this.emit(t)}this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>pO(e,t)?this.requestUserInput(e,t,n):fO(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${ow(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=mO(t),i=`req_${ow(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1}captureResumeSessionId(e){let t=FO(e),n=IO(t.session_id)??IO(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${ow(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=BO(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=IO(e.tool_id)??IO(e.tool_use_id)??RO(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=IO(e.uuid);if(n)return this.activeToolItemId=n,n;let r=VO(IO(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}buildInterruptedTerminalEvents(e){return this.activeTurnTerminalEmitted=!0,[...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,status:`interrupted`,error:{message:e},turn_id:this.activeTurnId,source_event_type:`abort`}]}mapClaudeMessage(e){let t=FO(e),n=IO(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!AO(t))return[];let n=jO(FO(t.message));return n?[{type:`item.completed`,item:{id:IO(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:IO(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=kO(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=FO(t.event);if(IO(e.type)===`message_start`){let t=BO(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=MO(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||IO(t.subtype)?.startsWith(`error_`)===!0){let n=NO(t);return this.activeTurnTerminalEmitted=!0,[...e,{type:`turn.failed`,error:{message:n},usage:PO(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:PO(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=IO(t.summary)??`tool summary`,i=IO(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=IO(t.tool_name)??`tool`,i=IO(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=IO(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(IO(t.session_id)??IO(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:IO(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=IO(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=_O(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=vO(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=yO({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function fO(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function pO(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function mO(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=hO(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function hO(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function gO(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function _O(e){let t=FO(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=FO(e);if(t.type!==`tool_use`)continue;let n=IO(t.id),i=IO(t.name),a=FO(t.input);if(!(!n||!i)){if(i===`Task`){let e=IO(a.subagent_type),t=IO(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:IO(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=IO(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=IO(a.file_path);r.push({id:n,toolName:`Write`,title:wO(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function vO(e){let t=FO(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=FO(e);if(t.type!==`tool_result`)continue;let n=IO(t.tool_use_id);if(n)return{toolUseId:n}}return null}function yO(e){let t=FO(e.raw.tool_use_result),n=bO(t.content)??jO(FO(e.raw.message)),r=FO(t.usage),i=zO(t.totalTokens)??zO(r.total_tokens)??zO(r.output_tokens),a=zO(t.totalToolUseCount),o=zO(t.totalDurationMs),s=IO(t.agentId),c=IO(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=SO(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=xO(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=LO(t.content),r=CO(EO(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function bO(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=FO(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
516
|
+
`):void 0}function xO(e){return LO(FO(e.file).content)||bO(e.content)}function SO(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${DO(t)} tokens`),typeof n==`number`&&r.push(OO(n)),r.join(` · `)}function CO(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function wO(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${TO(e)})`:`Write`}function TO(e){let t=e.split(`/`);return t[t.length-1]||e}function EO(e){if(e)return e.split(`
|
|
517
|
+
`).length}function DO(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function OO(e){let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}m`:`${n}m ${r}s`}function kO(e){return jO(FO(e.message))||(LO(e.result)??``)}function AO(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=FO(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>FO(e).type===`tool_result`)}function jO(e){let t=LO(e.content);if(t)return t;let n=LO(e.text)??LO(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=FO(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
|
|
518
|
+
`)}function MO(e){let t=FO(FO(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function NO(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):IO(e.subtype)||`Claude turn failed`}function PO(e){let t=FO(e);return{input_tokens:zO(t.input_tokens)??zO(t.inputTokens)??0,cached_input_tokens:zO(t.cached_input_tokens)??zO(t.cache_read_input_tokens)??zO(t.cacheReadInputTokens)??0,output_tokens:zO(t.output_tokens)??zO(t.outputTokens)??0}}function FO(e){return typeof e==`object`&&e?e:{}}function IO(e){if(typeof e==`string`&&e.trim())return e}function LO(e){if(typeof e==`string`&&e.length>0)return e}function RO(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function zO(e){if(typeof e==`number`&&Number.isFinite(e))return e}function BO(e){let t=IO(FO(e.message).id);if(t)return t;let n=IO(FO(FO(e.event).message).id);if(n)return n}function VO(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var HO=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=UO(e);for(let e of this.listeners)e(t)};if(typeof e?.subscribe==`function`){let n=e.subscribe(e=>t(e));typeof n==`function`&&(this.unsubscribe=n);return}if(typeof e?.on==`function`){let n=e=>t(e);e.on(`event`,n),this.unsubscribe=()=>{typeof e?.off==`function`&&e.off(`event`,n)};return}throw Error(`Native session does not expose a known event subscription API`)}};function UO(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var WO=`@anthropic-ai/claude-agent-sdk`,GO=`claude-sonnet-4-6`,KO=1e4,qO=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(WO),!0}catch{return!1}}async createSession(e){if(!this.preferNative)throw Error(`Claude native provider is disabled. Set ENABLE_NATIVE_PROVIDERS=true to use Claude sessions.`);try{let t=await import(WO),n=await JO(YO(t,e),KO,`Claude native query session creation timed out`);if(n)return n;let r=await JO(XO(t,e),KO,`Claude legacy native session creation timed out`);if(r)return r;throw this.requireNative,Error(`Claude SDK loaded but no supported stable session API was found`)}catch(e){throw Error(`Claude native session creation failed: ${String(e)}`)}}};async function JO(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}async function YO(e,t){let n=ZO(e);if(!n)return null;let r=t.model??GO;return new dO(t.sessionId,r,({prompt:e,model:i,sessionConfig:a,resume:o,abortController:s,canUseTool:c})=>{let l=a?.permissionMode??t.sessionConfig?.permissionMode??`default`,u={model:i??r,includePartialMessages:!0,abortController:s,canUseTool:c,permissionMode:l},d=QO(a?.reasoningEffort??t.sessionConfig?.reasoningEffort);return d&&(u.effort=d),l===`bypassPermissions`&&(u.allowDangerouslySkipPermissions=!0),t.cwd&&(u.cwd=t.cwd),o&&(u.resume=o,u.forkSession=!1),n({prompt:e,options:u})},t.resumeSessionId,{cwd:t.cwd})}async function XO(e,t){if(typeof e?.createSession==`function`){let n=await e.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new HO(`claude`,t.sessionId,t.model,n)}if(typeof e?.ClaudeAgentClient==`function`){let n=new e.ClaudeAgentClient;if(typeof n?.createSession==`function`){let e=await n.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new HO(`claude`,t.sessionId,t.model,e)}}if(typeof e?.default?.createSession==`function`){let n=await e.default.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new HO(`claude`,t.sessionId,t.model,n)}return null}function ZO(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function QO(e){if(e){if(e===`max`)return`max`;if(e===`high`||e===`medium`||e===`low`)return e;if(e===`xhigh`)return`max`;if(e===`minimal`||e===`none`)return`low`}}function $O(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new JD(n,r):new qO(n,r)}const ek=p.default.join(`.claude`,`projects`),tk=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function nk(e){return(await(0,O.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>lk(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function rk(e,t){let n=sk(e,t?.homeDir),r=p.default.resolve(e);try{let i=await uk(e,n,r,{maxSessions:zk(t?.maxSessions),updatedAfterMs:Rk(t?.updatedAfterMs)});if(i.length>0)return i}catch{}return dk(n,{maxSessions:zk(t?.maxSessions),updatedAfterMs:Rk(t?.updatedAfterMs)})}async function ik(e){let t=await wk(e.nativeSessionId,e.projectPath),n=await Tk(e.projectPath,e.nativeSessionId,e.homeDir),r=mk(t,{createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),i=hk(r.updatedAt,n.mtimeMs);return{rawEvents:ak({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),model:r.model,updatedAt:i,status:gk(t),nativeWatchPath:ok(e.projectPath,e.nativeSessionId,e.homeDir)}}function ak(e){let t=[],n=mk(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function ok(e,t,n){return p.default.join(sk(e,n),`${t}.jsonl`)}function sk(e,t){let n=t??f.default.homedir();return p.default.join(n,ek,ck(e))}function ck(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function lk(e){let t=Pk(e.customTitle)??Pk(e.summary)??Pk(e.firstPrompt),n=Sk(e.createdAt??e.lastModified),r=Sk(e.lastModified);return{nativeSessionId:e.sessionId,cwd:xk(e.cwd),title:t,createdAt:n,updatedAt:r,status:`idle`}}async function uk(e,t,n,r){let i=Math.max(1,Math.min(r.maxSessions??100,100)),a=[],o=0,s=!1;for(;r.maxSessions===void 0||a.length<r.maxSessions;){let c=r.maxSessions===void 0?i:Math.max(1,Math.min(i,r.maxSessions-a.length)),l=await(0,O.listSessions)({dir:e,limit:c,offset:o});if(l.length===0)break;for(let e of l){let i=Rk(e.lastModified);if(r.updatedAfterMs!==void 0&&i!==void 0&&i<r.updatedAfterMs){s=!0;break}let o=lk(e);if(typeof o.cwd!=`string`||p.default.resolve(o.cwd)!==n)continue;let c=await fk(t,{nativeSessionId:o.nativeSessionId,sdkSession:o});if(c&&(a.push(c),r.maxSessions!==void 0&&a.length>=r.maxSessions))break}if(s||r.maxSessions!==void 0&&a.length>=r.maxSessions||l.length<c)break;o+=l.length}return pk(a,r)}async function dk(e,t){let n=[];try{n=await d.default.readdir(e,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}let r=[];for(let t of n){if(!t.isFile()||!t.name.endsWith(`.jsonl`))continue;let n=await fk(e,{nativeSessionId:t.name.slice(0,-6)});n&&r.push(n)}return pk(r,t)}async function fk(e,t){let n=p.default.join(e,`${t.nativeSessionId}.jsonl`),r;try{r=await Ck(n)}catch(e){if(e.code===`ENOENT`)return t.sdkSession;throw e}if(!bk(r))return;let i=await d.default.stat(n),a=t.sdkSession?.createdAt?Lk(t.sdkSession.createdAt):void 0,o=t.sdkSession?.updatedAt?Lk(t.sdkSession.updatedAt):void 0,s=mk(r,{createdAtFallbackMs:a??i.birthtimeMs,updatedAtFallbackMs:o??i.mtimeMs});return{nativeSessionId:t.nativeSessionId,model:s.model,title:t.sdkSession?.title??s.title,createdAt:s.createdAt,updatedAt:t.sdkSession?.updatedAt??s.updatedAt,status:gk(r)}}function pk(e,t){let n=e.filter(e=>{if(t.updatedAfterMs===void 0)return!0;let n=Lk(e.updatedAt);return n===void 0?!0:n>=t.updatedAfterMs}).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return t.maxSessions===void 0?n:n.slice(0,t.maxSessions)}function mk(e,t){let n,r,i,a;for(let t of e)if(t.timestampMs!==void 0&&(i=i===void 0?t.timestampMs:Math.min(i,t.timestampMs),a=a===void 0?t.timestampMs:Math.max(a,t.timestampMs)),!r&&t.type===`user`&&(r=jk(kk(Mk(t.raw.message)))),t.type===`assistant`){let e=Nk(Mk(t.raw.message).model);e&&(n=e)}let o=i??Rk(t.createdAtFallbackMs)??0,s=a??Rk(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function hk(e,t){let n=Lk(e)??0,r=Rk(t)??0;return new Date(Math.max(n,r)).toISOString()}function gk(e,t=Date.now()){let n=null;for(let t of e){let e=_k(t);e&&(n=e)}return!n?.unresolved||n.timestampMs!==void 0&&t-n.timestampMs>6e5?`idle`:`running`}function _k(e){let t=e.timestampMs??Lk(e.timestamp??``);switch(e.type){case`assistant`:case`result`:case`tool_use_summary`:return{unresolved:!1,timestampMs:t};case`stream_event`:case`tool_progress`:return{unresolved:!0,timestampMs:t};case`user`:return vk(e.raw,t);default:return null}}function vk(e,t){let n=Mk(e);if(n.isMeta===!0)return null;let r=Mk(n.message);if(Ok(r).length>0)return{unresolved:!0,timestampMs:t};let i=kk(r);return i?yk(i)?{unresolved:!1,timestampMs:t}:{unresolved:!0,timestampMs:t}:null}function yk(e){let t=e.toLowerCase();return t.includes(`<command-name>/exit</command-name>`)||t.includes(`<command-message>exit</command-message>`)||t.includes(`<local-command-stdout>catch you later!</local-command-stdout>`)}function bk(e){for(let t of e){if(t.type===`user`){let e=Mk(t.raw.message);if(kk(e)||Ok(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=Mk(t.raw.message);if(kk(e)||Dk(e).length>0||Nk(t.raw.error))return!0}return!1}function xk(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Sk(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Ck(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
|
519
|
+
`),n=[];for(let e=0;e<t.length;e+=1){let r=t[e]?.trim();if(!r)continue;let i;try{i=JSON.parse(r)}catch{continue}let a=Mk(i),o=Nk(a.timestamp),s=o?Lk(o):void 0;n.push({line:e+1,raw:a,type:Nk(a.type),timestamp:o,timestampMs:s})}return n}async function wk(e,t){let n=await(0,O.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>Ek(e,t+1))}async function Tk(e,t,n){let r=ok(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function Ek(e,t){let n=Mk(e),r=Mk(n.message),i=Nk(n.timestamp)??Nk(r.timestamp)??Nk(r.created_at)??Nk(r.createdAt);return{line:t,raw:{...n,message:r},type:Nk(n.type),timestamp:i,timestampMs:i?Lk(i):void 0}}function Dk(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=Mk(e);if(Nk(t.type)!==`tool_use`)continue;let r=Mk(t.input),i=Nk(r.command),a=Nk(t.name)??`tool`,o=Nk(r.description);n.push({id:Nk(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function Ok(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=Mk(e);if(Nk(t.type)!==`tool_result`)continue;let r=Fk(Nk(t.content)??Nk(Mk(t.toolUseResult).stdout)??Nk(Mk(t.tool_use_result).stdout)??Nk(t.text));n.push({toolUseId:Nk(t.tool_use_id)??Nk(t.toolUseId),toolName:Nk(t.tool_name)??Nk(t.toolName),text:r,isError:t.is_error===!0})}return n}function kk(e){let t=Nk(e.content);if(t)return Fk(t);let n=Nk(e.text)??Nk(e.prompt);if(n)return Fk(n);let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push(e);continue}let t=Mk(e),n=Nk(t.type);if(n&&n!==`text`)continue;let r=Nk(t.text)??Nk(t.content)??Ak(t);r&&i.push(r)}if(i.length!==0)return Fk(i.join(`
|
|
520
|
+
`))}function Ak(e){let t=Array.isArray(e.text_elements)?e.text_elements:Array.isArray(e.textElements)?e.textElements:[];if(t.length===0)return;let n=[];for(let e of t){let t=Mk(e),r=Nk(t.text)??Nk(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function jk(e,t=60){if(!e)return;let n=Ik(e).replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function Mk(e){return typeof e==`object`&&e?e:{}}function Nk(e){return typeof e==`string`&&e.trim()||void 0}function Pk(e){if(typeof e==`string`)return Fk(e)}function Fk(e){if(!e)return;let t=Ik(e).trim();return t.length>0?t:void 0}function Ik(e){return e.replace(tk,``)}function Lk(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function Rk(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.round(e)}function zk(e){if(e===void 0||!Number.isFinite(e))return;let t=Math.floor(e);return t>0?t:void 0}var Bk=class{constructor(e){this.options=e}async init(){await this.options.store.init()}async getProjects(){await this.init();let e=await this.options.store.getIndex();return e?{generatedAt:e.generatedAt,source:`cache`,providers:e.providers,projects:e.projects}:this.refreshProjects()}async refreshProjects(){await this.init();let e=new Map,[t,n]=await Promise.all([this.scanCodexSessions(e),this.scanClaudeSessions(e)]),r=new Date().toISOString(),i={codex:t.status,claude:n.status},{projects:a,projectSessions:o}=Hk(r,[t,n]);if(Uk(i)){let e=await this.options.store.getSnapshot();if(e)return await this.options.store.writeSnapshot({...e,providers:i}),{generatedAt:e.generatedAt,source:`cache`,providers:i,projects:e.projects}}return await this.options.store.writeSnapshot({generatedAt:r,providers:i,projects:a,projectSessions:o}),{generatedAt:r,source:`fresh_scan`,providers:i,projects:a}}async listProjectSessions(e){await this.init();let t=e.trim(),n=await this.options.store.getIndex(),r=!1;n||(n=Gk(await this.refreshProjects()),r=!0);let i=await Wk(n.projects,t);if(!i)throw ww(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Gk(await this.refreshProjects()),i=await Wk(n.projects,t),!i)throw ww(t);if(a=await this.options.store.getProject(i.key),!a)throw Error(`Discovery cache missing project sessions: ${i.path}`)}if(!a)throw Error(`Discovery cache missing project sessions: ${i.path}`);return{canonicalProjectPath:i.path,project:a.project,providers:a.providers,sessions:a.sessions}}async scanCodexSessions(e){let t=new Date().toISOString();try{let n=new Map;for(let e of[!1,!0]){let t=null;do{let r=await XD({archived:e,cursor:t,limit:100});for(let e of r.threads)n.set(e.id,e);t=r.nextCursor}while(t)}let r=await Vk({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>Jk(e.cwd),mapSession:e=>{let t=Yk(e.createdAt),n=Yk(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:Jk(e.name)??Jk(e.preview),model:Jk(e.model),createdAt:t,updatedAt:n}}});return{records:r.records,status:{scannedAt:t,sessionCount:r.records.length,status:r.skippedCount>0?`partial`:`ready`,...r.skippedCount>0?{error:`Skipped ${r.skippedCount} Codex session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}async scanClaudeSessions(e){let t=new Date().toISOString();try{let n=await Vk({sessions:await nk(),canonicalPathCache:e,getRawPath:e=>Jk(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:Jk(e.title),model:Jk(e.model),createdAt:Jk(e.createdAt),updatedAt:e.updatedAt})});return{records:n.records,status:{scannedAt:t,sessionCount:n.records.length,status:n.skippedCount>0?`partial`:`ready`,...n.skippedCount>0?{error:`Skipped ${n.skippedCount} Claude session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}};async function Vk(e){let t=[],n=0;for(let r of e.sessions){let i=e.getRawPath(r);if(!i){n+=1;continue}try{let n=await Kk(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Hk(e,t){let n=new Map;for(let e of t)for(let t of e.records){let e=n.get(t.canonicalProjectPath);e||(e={path:t.canonicalProjectPath,key:qk(t.canonicalProjectPath),title:p.default.basename(t.canonicalProjectPath)||t.canonicalProjectPath,providerCounts:{codex:0,claude:0},sessionsByKey:new Map},n.set(t.canonicalProjectPath,e));let r=`${t.session.provider}:${t.session.nativeSessionId}`,i=e.sessionsByKey.get(r);i||(e.providerCounts[t.session.provider]+=1);let a=Xk(i,t.session);e.sessionsByKey.set(r,a),(!e.lastSessionAt||t.session.updatedAt>e.lastSessionAt)&&(e.lastSessionAt=t.session.updatedAt)}let r=[...n.values()].map(t=>({project:{key:t.key,path:t.path,title:t.title,lastSessionAt:t.lastSessionAt,sessionCount:t.sessionsByKey.size,providerCounts:t.providerCounts,lastDiscoveryAt:e},sessions:[...t.sessionsByKey.values()].sort(Qk)})).sort((e,t)=>Zk(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function Uk(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Wk(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await CE(t);return e.find(e=>e.path===r)}function Gk(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function Kk(e,t){let n=t.get(e);return n||(n=CE(e),t.set(e,n)),n}function qk(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function Jk(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Yk(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Xk(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function Zk(e,t){let n=e.lastSessionAt??e.lastDiscoveryAt,r=t.lastSessionAt??t.lastDiscoveryAt;return n===r?e.path.localeCompare(t.path):r.localeCompare(n)}function Qk(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var $k=class{indexPath;projectsDir;ready;writeQueue=Promise.resolve();indexCache=null;projectCache=new Map;constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`discovery-index.json`),this.projectsDir=p.default.join(e,`discovery-projects`),this.ready=this.loadFromDisk()}async init(){await this.ready}async getIndex(){return await this.ready,this.indexCache?structuredClone(this.indexCache):null}async getProject(e){await this.ready;let t=this.projectCache.get(e);if(t)return structuredClone(t);let n=await eA(this.getProjectPath(e),rA);return n?(this.projectCache.set(e,n),structuredClone(n)):null}async getSnapshot(){if(await this.ready,!this.indexCache)return null;let e=[];for(let t of this.indexCache.projects){let n=await this.getProject(t.key);if(!n)return null;e.push({project:n.project,sessions:n.sessions})}return{generatedAt:this.indexCache.generatedAt,providers:structuredClone(this.indexCache.providers),projects:structuredClone(this.indexCache.projects),projectSessions:e}}async writeSnapshot(e){await this.ready;let t={v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects},n=e.projectSessions.map(t=>({v:1,projectKey:t.project.key,canonicalProjectPath:t.project.path,project:t.project,providers:e.providers,sessions:t.sessions}));await this.enqueueWrite(async()=>{await d.default.mkdir(this.projectsDir,{recursive:!0});let e=new Set(n.map(e=>e.projectKey)),r=[];try{r=await d.default.readdir(this.projectsDir,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}await Promise.all(n.map(async e=>{await tA(this.getProjectPath(e.projectKey),e)})),await Promise.all(r.map(async t=>{if(!t.isFile()||!t.name.endsWith(`.json`))return;let n=t.name.slice(0,-5);e.has(n)||(await d.default.rm(p.default.join(this.projectsDir,t.name),{force:!0}),this.projectCache.delete(n))})),await tA(this.indexPath,t),this.indexCache=t,this.projectCache.clear();for(let e of n)this.projectCache.set(e.projectKey,e)})}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0}),await d.default.mkdir(this.projectsDir,{recursive:!0}),this.indexCache=await eA(this.indexPath,nA)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function eA(e,t){try{let n=await d.default.readFile(e,`utf8`),r=JSON.parse(n);return t(r)?r:null}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function tA(e,t){let n=`${JSON.stringify(t,null,2)}\n`;try{if(await d.default.readFile(e,`utf8`)===n)return}catch(e){if(e.code!==`ENOENT`)throw e}await d.default.mkdir(p.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await d.default.writeFile(r,n,`utf8`),await d.default.rename(r,e)}function nA(e){return!iA(e)||e.v!==1||typeof e.generatedAt!=`string`||!ed.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>td.safeParse(e).success)}function rA(e){return!iA(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!td.safeParse(e.project).success||!ed.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>nd.safeParse(e).success)}function iA(e){return typeof e==`object`&&!!e}const aA=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function oA(e){let t=Rd.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=Af(Nf(uA(i.export({format:`jwk`})))),o=bf({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a}}),s=(0,l.sign)(null,Buffer.from(o,`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`);return{gatewayHello:zd.parse({version:t.version,securityLevel:t.securityLevel,cipherSuite:t.cipherSuite,gatewayId:e.gatewayId,deviceId:t.deviceId,clientNonce:t.clientNonce,gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a,signatureAlgorithm:`ed25519`,signature:s}),gatewayEphemeralPrivateKey:r}}function sA(e){let t=Rd.parse(e.clientHello),n=zd.parse(e.gatewayHello),r=Bd.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!Od.safeParse(t.cipherSuite).success||n.cipherSuite!==t.cipherSuite||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported_version`);if(r.gatewayId!==e.gatewayId||n.gatewayId!==e.gatewayId)throw Error(`transcript_invalid`);if(r.deviceId!==t.deviceId||n.deviceId!==t.deviceId||r.deviceIdentityFingerprint!==t.deviceIdentity.publicKeyFingerprint)throw Error(`identity_mismatch`);let i=(0,l.createPublicKey)({format:`der`,type:`spki`,key:Buffer.concat([aA,jf(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(xf({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,jf(r.signature)))throw Error(`transcript_invalid`)}function cA(e){let t=zd.parse(e.gatewayHello),n=Bd.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:Mf(jf(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return wf({role:`gateway`,keySchedule:Cf({gatewayId:e.gatewayId,clientHello:Rd.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function lA(e){return Jd.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function uA(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}const dA=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;let fA=null;function pA(e){fA=e}function mA(e,t){dA&&(console.log(`[session-fetch][gateway] ${e}`,t),fA?.info({event:e,...t},`session fetch debug`))}const hA=64*1024;var gA=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}sendProviderRaw(e){this.onPayload(e)}close(){this.readyState=3}},_A=class{mobileConnections=new Map;constructor(e){this.dependencies=e}async handleFrame(e){switch(e.type){case`mobile.connected`:this.addMobileConnection(e.mobileId??``,e.payload.deviceId,e.payload.deliveryMode,e.payload.gatewayAvailableAtConnect);return;case`mobile.disconnected`:this.removeMobileConnection(e.mobileId??``,`mobile.disconnected`);return;case`secure.client_hello`:await this.handleSecureClientHello(e.mobileId,e.payload);return;case`secure.client_auth`:await this.handleSecureClientAuth(e.mobileId,e.payload);return;case`from_mobile`:await this.handleFromMobile(e);return;case`rpc.request`:await this.handleRpcRequest(e);return;case`pairing.claim.forward`:await this.handlePairingClaim(e.requestId,e.payload);return;case`auth.refresh.forward`:await this.handleRefresh(e.requestId,e.payload);return;case`file.content.forward`:await this.handleFileContent(e.requestId,e.payload);return;case`file.content.upload.started`:this.dependencies.handleFileContentUploadStarted?.(e.requestId);return;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e,`bridge.close`)}addMobileConnection(e,t,n,r){if(!e)return;this.removeMobileConnection(e,`mobile.replaced`);let i={mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}};this.mobileConnections.set(e,i),this.dependencies.relayTransportSecurityLevel!==`e2ee-relay`&&this.ensureReadyMobileClient(i),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(_f.parse({type:`secure.handshake_required`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,gatewayId:this.dependencies.gatewayId,deviceId:t,reason:r?`gateway_restarted`:`gateway_available`,retryable:!0}}))}removeMobileConnection(e,t){let n=this.mobileConnections.get(e);if(!n)return;let r=n.clientId?this.dependencies.describeClientState?.(n.clientId)??{}:{};this.dependencies.logger?.info?.({mobileId:e,deviceId:n.deviceId,clientId:n.clientId??null,reason:t,hadSocket:!!n.socket,socketReadyState:n.socket?.readyState??null,...r},`relay mobile connection removed`),n.socket?.close(),n.clientId&&this.dependencies.sessionHub.removeClient(n.clientId),this.mobileConnections.delete(e)}async handleFromMobile(e){let t=e.mobileId;if(!t){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile frame requires mobileId`});return}let n=this.mobileConnections.get(t);if(!n){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${t}`});return}if(n.handshake.status===`ready`&&n.clientId){let r=n,i=r.clientId;if(!i){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let a=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>hc.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(!a)return;await this.dependencies.dispatchCommand(a,r.deviceId,i);return}if(this.dependencies.relayTransportSecurityLevel===`e2ee-relay`){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}if(this.ensureReadyMobileClient(n),!n.clientId)return;if(e.payload===void 0){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`plaintext relay payload missing`});return}let r=hc.parse(e.payload);await this.dependencies.dispatchCommand(r,n.deviceId,n.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(_f.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...CA(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(_f.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...CA(t,`auth.refresh`)})}}async handleFileContent(e,t){try{let n=await this.dependencies.handleFileContentRequest(e,t);this.dependencies.sendFrame(_f.parse({type:`file.content.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...CA(t,`file.content`)})}}async handleRpcRequest(e){let t=e.mobileId,n=e.requestId,r=this.mobileConnections.get(t);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:{...SA(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status===`ready`){let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>Yd.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(!a)return;try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(_f.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let r=Qd.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...r.success?r.data:SA(`INTERNAL`,500,String(e)),method:a.method})})}return}if(this.dependencies.relayTransportSecurityLevel===`e2ee-relay`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}if(e.payload===void 0){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:SA(`BAD_REQUEST`,400,`plaintext relay payload missing`)});return}let i=Yd.parse(e.payload);try{let e=await this.dependencies.handleRpcRequest(i,{mobileId:t,deviceId:r.deviceId});this.dependencies.sendFrame(_f.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(r,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let a=Qd.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(r,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...a.success?a.data:SA(`INTERNAL`,500,String(e)),method:i.method})})}}async handleSecureClientHello(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_hello frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status!==`awaiting_client_hello`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_hello`);return}if(t.deviceId!==n.deviceId){this.sendSecureError(e,n.deviceId,`identity_mismatch`,`deviceId does not match relay token`);return}if(t.version!==1||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`){this.sendSecureError(e,n.deviceId,`unsupported_version`,`unsupported secure handshake version`);return}let r=oA({gatewayId:this.dependencies.gatewayId,gatewayIdentity:this.dependencies.gatewayIdentity,privateKeyPem:this.dependencies.gatewayIdentityPrivateKeyPem,clientHello:t});n.handshake={status:`awaiting_client_auth`,clientHello:t,gatewayHello:r.gatewayHello,gatewayEphemeralPrivateKey:r.gatewayEphemeralPrivateKey},this.mobileConnections.set(e,n),this.dependencies.sendFrame(_f.parse({type:`secure.gateway_hello`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:r.gatewayHello}))}async handleSecureClientAuth(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_auth frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status===`ready`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_auth`);return}if(n.handshake.status!==`awaiting_client_auth`){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure.client_hello missing`);return}try{sA({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,wA(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=cA({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t,gatewayEphemeralPrivateKey:n.handshake.gatewayEphemeralPrivateKey});this.ensureReadyMobileClient(n),n.handshake={status:`ready`,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,session:i},this.mobileConnections.set(e,n),this.dependencies.sendFrame(_f.parse({type:`secure.ready`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,securityLevel:`e2ee-relay`,cipherSuite:i.cipherSuite,gatewayId:this.dependencies.gatewayId,deviceId:n.deviceId,keyEpoch:i.keyEpoch,deviceIdentityFingerprint:r.publicKeyFingerprint??n.handshake.clientHello.deviceIdentity.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus??`active`}}))}catch(t){this.sendSecureError(e,n.deviceId,EA(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new gA(t=>{try{let n=_f.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,...this.createRelayBusinessPayloadFields(e,{frameType:`to_mobile`,messageType:`event`},t)});this.dependencies.sendFrame(n)}catch(t){this.sendSecureError(e.mobileId,e.deviceId,TA(t),`relay secure payload failed: ${String(t)}`)}}),n=this.dependencies.sessionHub.addClient(e.deviceId,t);e.socket=t,e.clientId=n}sendSecureError(e,t,n,r){this.dependencies.sendFrame({type:`secure.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:lA({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`||n===`key_epoch_mismatch`})})}sendRelayError(e){this.dependencies.sendFrame({type:`relay.error`,gatewayId:this.dependencies.gatewayId,...e.mobileId?{mobileId:e.mobileId}:{},...e.requestId?{requestId:e.requestId}:{},messageType:`system`,payload:SA(e.code,e.status,e.message)})}decodeRelayBusinessPayload(e){if(e.payload!==void 0)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload must be encrypted`),null;if(!e.encryptedPayload)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload missing`),null;try{return kf({session:e.connection.handshake.session,metadata:{frameType:e.frameType,messageType:e.messageType,gatewayId:this.dependencies.gatewayId,...e.requestId?{requestId:e.requestId}:{}},encryptedPayload:e.encryptedPayload,parse:e.parse})}catch(t){return this.sendSecureError(e.mobileId,e.connection.deviceId,TA(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){let r=pd({payload:n,compressionThresholdBytes:vA(t.frameType,n)?hA:void 0});if(yA(n)){let i=bA(n),a=xA(n);mA(`relay.snapshot.chunk.outbound`,{mobileId:e.mobileId,deviceId:e.deviceId,frameType:t.frameType,messageType:t.messageType,sessionId:n.sessionId,projectId:n.projectId??null,snapshotId:i.snapshotId??a?.snapshotId??null,chunkIndex:i.chunkIndex??a?.chunkIndex??null,totalChunks:i.totalChunks??a?.totalChunks??null,snapshotFormat:n.kind===`session.readable.snapshot.chunk`?`readable`:a?`raw+readable`:`raw`,chunkEventCount:i.events.length||null,chunkTimelineItemCount:a?.timelineItems?.length??null,handshakeStatus:e.handshake.status,payloadTransport:e.handshake.status===`ready`?`encryptedPayload`:r.compression===`gzip`?`compressedPayload`:`payload`,compression:r.compression,compressionThresholdBytes:hA,uncompressedByteLength:r.uncompressedByteLength,compressedByteLength:r.compressedByteLength})}if(e.handshake.status!==`ready`){let e=md(r);return e?{compressedPayload:e}:{payload:n}}return{encryptedPayload:Of({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},preparedPayload:r})}}};function vA(e,t){return e===`to_mobile`&&yA(t)}function yA(e){return typeof e==`object`&&!!e&&`kind`in e&&(e.kind===`session.stream.snapshot.chunk`||e.kind===`session.readable.snapshot.chunk`)}function bA(e){return e.kind===`session.readable.snapshot.chunk`?{snapshotId:e.payload.readable.snapshotId,chunkIndex:e.payload.readable.chunkIndex,totalChunks:e.payload.readable.totalChunks,events:[]}:e.payload.raw}function xA(e){return e.kind===`session.readable.snapshot.chunk`||`readable`in e.payload?e.payload.readable:void 0}function SA(e,t,n){return Qd.parse({code:e,status:t,message:n})}function CA(e,t){if(cw(e))switch(e.code){case`PAIRING_CODE_INVALID`:case`PAIRING_CODE_EXPIRED`:return{code:`BAD_REQUEST`,status:e.status,message:String(e)};case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:case`PREVIEW_TICKET_INVALID`:case`PREVIEW_TICKET_EXPIRED`:return{code:`UNAUTHORIZED`,status:e.status,message:String(e)};default:return{code:e.status>=500?`INTERNAL`:`BAD_REQUEST`,status:e.status,message:String(e)}}let n=String(e),r=DA(e);return t===`pairing.claim`&&(r===`Invalid pairing code`||r===`Pairing code expired`)?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(r===`Refresh token revoked`||r===`Device revoked`||r===`Device revoked or not found`||r===`Refresh token device mismatch`||Ow(e))||t===`file.content`&&Ow(e)?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function wA(e){return OA(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function TA(e){return OA(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function EA(e){if(cw(e))switch(e.code){case`DEVICE_REVOKED`:return`device_revoked`;case`DEVICE_IDENTITY_NOT_REGISTERED`:case`DEVICE_IDENTITY_MISMATCH`:return`identity_mismatch`;default:return`transcript_invalid`}let t=DA(e);return t===`Device revoked`||t===`Device revoked or not found`?`device_revoked`:t===`Device identity mismatch`||t===`Device identity not registered`?`identity_mismatch`:`transcript_invalid`}function DA(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function OA(e,t){let n=DA(e);return t.find(e=>e===n)}function kA(e){return e?e.readyState:null}function AA(e){return(typeof e.extensions==`string`?e.extensions.trim():``)||null}var jA=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;heartbeatIntervalMs;heartbeatTimeoutMs;webSocketFactory;socket;reconnectTimer;heartbeatIntervalTimer;heartbeatTimeoutTimer;reconnectAttempt=0;connectAttemptId=0;state=`idle`;stopped=!1;constructor(e){this.options=e,this.logger=e.logger??{},this.reconnectBaseDelayMs=e.reconnectBaseDelayMs??1e3,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??15e3,this.heartbeatIntervalMs=e.heartbeatIntervalMs??15e3,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??2e4,this.webSocketFactory=e.webSocketFactory??PA}start(){this.stopped&&=!1,!(this.socket||this.reconnectTimer)&&this.connect()}close(){this.stopped=!0,this.state=`stopped`,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),void 0);let e=this.socket;if(this.socket=void 0,this.stopHeartbeat(),!e)return;let t=kA(e);try{e.close(1e3,`Gateway shutting down`)}catch(n){this.logger.error?.({err:n,readyState:t},`relay websocket close threw during shutdown`);try{e.terminate()}catch(e){this.logger.error?.({err:e,readyState:t},`relay websocket terminate threw after close failure`)}}}isConnected(){let e=this.socket;return this.state===`connected`&&!!e&&e.readyState===e.OPEN}send(e){let t=this.socket;if(!t||t.readyState!==t.OPEN)return!1;let n=_f.parse(e);return t.send(JSON.stringify(n)),!0}async connect(){if(this.stopped)return;let e=++this.connectAttemptId,t;try{t=await this.resolveGatewayAccessToken()}catch(e){this.state=`idle`,this.logger.warn?.({err:e},`failed to resolve relay gateway access token`),this.scheduleReconnect();return}if(this.stopped||e!==this.connectAttemptId)return;let n=MA(this.options.relayUrl);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.on(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,this.startHeartbeat(r),this.logger.info?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,negotiatedExtensions:AA(r)},`relay gateway websocket connected`),this.send({type:`gateway.hello`,gatewayId:this.options.gatewayId,messageType:`system`,payload:{name:this.options.machineName,relayBaseUrl:this.options.relayUrl,directBaseUrls:this.options.directBaseUrls,transportSecurityLevel:this.options.relayTransportSecurityLevel,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=_f.parse(JSON.parse(NA(e)));Promise.resolve(this.options.onFrame(t)).catch(e=>{this.logger.error?.({err:e},`failed to handle relay frame`)})}catch(e){this.logger.warn?.({err:e},`failed to parse relay frame from relay`)}}}),r.on(`error`,e=>{this.socket===r&&this.logger.warn?.({err:e},`relay websocket emitted error`)}),r.on(`pong`,()=>{this.socket===r&&this.ackHeartbeat(r)}),r.on(`close`,(e,t)=>{if(this.socket===r){if(this.socket=void 0,this.stopHeartbeat(),this.stopped){this.state=`stopped`;return}this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,closeCode:e,closeReason:t.toString(`utf8`)},`relay websocket closed`),this.state=`idle`,this.scheduleReconnect()}})}async resolveGatewayAccessToken(){let e=this.options.relayGatewayAccessToken.trim();if(e)return e;let t=this.options.resolveRelayGatewayAccessToken;if(t)return t();throw Error(`Gateway relay access token is not configured`)}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;let e=Math.min(this.reconnectMaxDelayMs,this.reconnectBaseDelayMs*Math.max(1,2**this.reconnectAttempt));this.reconnectAttempt+=1,this.logger.info?.({delayMs:e},`scheduling relay reconnect`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatIntervalTimer=setInterval(()=>{if(!(this.socket!==e||this.stopped)&&!(e.readyState!==e.OPEN||this.heartbeatTimeoutTimer)){try{e.ping()}catch(t){this.logger.warn?.({err:t},`failed to send relay websocket heartbeat ping`),e.terminate();return}this.heartbeatTimeoutTimer=setTimeout(()=>{this.heartbeatTimeoutTimer=void 0,!(this.socket!==e||this.stopped||e.readyState!==e.OPEN)&&(this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,heartbeatTimeoutMs:this.heartbeatTimeoutMs},`relay websocket heartbeat timed out`),e.terminate())},this.heartbeatTimeoutMs)}},this.heartbeatIntervalMs)}ackHeartbeat(e){this.socket===e&&(this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0))}stopHeartbeat(){this.heartbeatIntervalTimer&&=(clearInterval(this.heartbeatIntervalTimer),void 0),this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0)}};function MA(e){let t=new URL(e);return t.protocol===`http:`?t.protocol=`ws:`:t.protocol===`https:`&&(t.protocol=`wss:`),t.pathname=`/ws/gateway`,t.toString()}function NA(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):String(e)}function PA(e){return new RE(e,void 0,{perMessageDeflate:!0})}function FA(e){let t={gatewayId:e.gatewayId.trim(),gatewayIdentity:e.gatewayIdentity,requestedAt:e.requestedAt??new Date().toISOString()};if(!t.gatewayId)throw Error(`gatewayId must not be empty when requesting a guest relay gateway access token.`);return{grantType:`guest`,payload:t,signatureAlgorithm:`ed25519`,signature:(0,l.sign)(null,Buffer.from(vf(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function IA(e){let t=e.fetchImpl??globalThis.fetch;if(!t)throw Error(`fetch is not available when requesting a guest relay gateway access token.`);let n=await t(LA(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(FA({gatewayId:e.gatewayId,gatewayIdentity:e.gatewayIdentity,privateKeyPem:e.privateKeyPem}))}),r=await n.text();if(!n.ok)throw Error(`Failed to request a guest relay gateway access token (${n.status}): ${r}`);return af.parse(JSON.parse(r)).token}function LA(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=`/api/gateway-token/guest`,t.search=``,t.toString()}function RA(e){return e?.trim()||void 0}function zA(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function BA(e,t){return{modeDefault:`default`,model:RA(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function VA(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function HA(e,t){let n=VA(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function UA(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function WA(e){let t=HA(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||RA(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?GA({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function GA(e){let t=HA(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?UA(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=HA(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=RA(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??RA(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:zA(r.execution)}}}const KA=[],qA=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],JA=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],YA=Fa.options,XA=[`read-only`,`workspace-write`,`danger-full-access`],ZA=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],QA={codex:[{version:`codex-mobile-v1`,defaults:{reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]};function $A(e,t){let n=t?.trim().toLowerCase();return n?(QA[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function ej(e,t,n){return e.some(e=>e.id===t)?e.map(e=>({...e,isDefault:e.id===t})):[{id:t,label:t,isDefault:!0,...n===`codex`?{supportedReasoningEfforts:JA}:{}},...e.map(e=>({...e,isDefault:!1}))]}function tj(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function nj(e){let t=new Set;for(let n of e){let e=tj(n);e&&t.add(e)}return[...t]}function rj(e){return e?.trim()||void 0}function ij(e){let t=rj(e.runtimeModel);if(t)return t;let n=rj(e.discoveredModel);if(n)return n;let r=rj(e.existingModel),i=rj(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function aj(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,description:e.description,isDefault:e.isDefault,supportedReasoningEfforts:nj(e.supportedReasoningEfforts)}));return t.length===0?KA:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function oj(e){let t=Date.now();try{let n=aj(await $D());return e?.info?.({provider:`codex`,durationMs:Date.now()-t,modelCount:n.length},`provider capabilities codex model load completed`),n}catch(n){return e?.warn?.({provider:`codex`,durationMs:Date.now()-t,err:n},`provider capabilities codex model load failed`),null}}async function sj(e){let t=Date.now();try{let n=await import(`@anthropic-ai/claude-agent-sdk`),r=n.query??n.default?.query;if(typeof r!=`function`)return null;let i=r,a=p.default.join(_m(),`claude-capability-probe`);await d.default.mkdir(a,{recursive:!0,mode:448});let o=i({prompt:`/clear`,options:{cwd:a,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let n=await o.supportedModels(),r=[];for(let e of n){let t=typeof e.value==`string`?e.value:``;if(!t)continue;let n=Array.isArray(e.supportedEffortLevels)&&e.supportedEffortLevels.length>0,i=lj(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?nj(e.supportedEffortLevels??[]):i===`haiku`?[]:void 0;r.push({id:t,label:e.displayName||t,description:typeof e.description==`string`&&e.description.trim()?e.description.trim():void 0,isDefault:t===`default`,supportedReasoningEfforts:a})}return r.length===0?null:(r.some(e=>e.isDefault)||(r[0]={...r[0],isDefault:!0}),e?.info?.({provider:`claude`,durationMs:Date.now()-t,modelCount:r.length},`provider capabilities claude model load completed`),r)}finally{o.close()}}catch(n){return e?.warn?.({provider:`claude`,durationMs:Date.now()-t,err:n},`provider capabilities claude model load failed`),null}}function cj(e){let t=(e.find(e=>e.isDefault)??e[0])?.supportedReasoningEfforts??[];if(t.includes(`medium`))return`medium`;if(t.includes(`high`))return`high`;if(t.length>0)return t[0]}function lj(...e){for(let t of e){let e=t?.trim().toLowerCase();if(e){if(e.includes(`haiku`))return`haiku`;if(e.includes(`opus`))return`opus`;if(e.includes(`sonnet`)||e.includes(`sonnect`))return`sonnet`}}}var uj=class{cache=new Map;inFlight=new Map;constructor(e){this.options=e}async getProviderCapabilities(e,t,n){return(await this.resolveProviderCapabilities(e,t,n)).capabilities}async getAgentConfig(e,t){let n=await this.resolveProviderCapabilities(e,t?.projectId,t?.agentVersion);return{agent:{provider:e,requestedVersion:t?.agentVersion?.trim()||null,resolvedVersion:n.resolvedAgentVersion},capabilities:n.capabilities}}async warmStartupProviderCapabilities(){if(!this.options.preferNativeProviders)return;let e=QA.claude.length>0?QA.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async getProviderDefaults(e,t,n){return BA(e,await this.getProviderCapabilities(e,t,n))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw gw(t);let r=$A(e,n),i=r?.version??`default`,a=`${e}::${i}`,o={provider:e,projectId:t??null,requestedAgentVersion:n?.trim()||null,resolvedAgentVersion:i},s=Date.now(),c=this.cache.get(a);if(c){if(c.expiresAt>s)return this.options.logger?.info?.({...o,cacheStatus:`hit`,source:c.value.capabilities.source,modelCount:c.value.capabilities.models.length},`provider capabilities cache hit`),c.value;this.cache.delete(a)}let l=this.inFlight.get(a);if(l)return this.options.logger?.info?.({...o,cacheStatus:`in_flight`},`provider capabilities awaiting in-flight load`),l;let u=Date.now(),d=(async()=>{let t=$O(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=Date.now(),a=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1;this.options.logger?.info?.({...o,cacheStatus:`miss`,nativeAvailable:a,durationMs:Date.now()-n},`provider capabilities native availability checked`);let s=a?`native`:`fallback`,c=e===`codex`&&a?await oj(this.options.logger)??KA:KA,l=e===`claude`&&a?await sj(this.options.logger)??qA:qA,d=nj(l.flatMap(e=>e.supportedReasoningEfforts??[])),f=e===`codex`?{provider:e,source:s,models:c,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:JA,approvalPolicies:YA,sandboxModes:XA,permissionModes:[]},defaults:{model:c.find(e=>e.isDefault)?.id??c[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:s,models:l,support:{reasoningEffort:d.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:d,approvalPolicies:[],sandboxModes:[],permissionModes:ZA},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:cj(l),permissionMode:`default`}};if(!r){let e={capabilities:f,resolvedAgentVersion:i};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:e.capabilities.source,modelCount:e.capabilities.models.length},`provider capabilities resolved`),e}let p={...f.defaults,...r.defaults},m=p.model?.trim(),h=s===`native`?f.models:m?ej(f.models,m,e):f.models,g={capabilities:{...f,models:h,defaults:p},resolvedAgentVersion:r.version};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:g.capabilities.source,modelCount:g.capabilities.models.length},`provider capabilities resolved`),g})();this.inFlight.set(a,d);try{let e=await d;return this.cache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}catch(e){throw this.options.logger?.warn?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,err:e},`provider capabilities resolution failed`),e}finally{this.inFlight.delete(a)}}};const dj=`.meta.json`;function fj(){let e=process.env.CODEX_HOME?.trim();return e?p.default.resolve(e):p.default.join(f.default.homedir(),`.codex`)}function pj(){return p.default.join(fj(),`auth.json`)}function mj(){return p.default.join(_m(),`codex-accounts`)}var hj=class{currentAuthFilePath;snapshotsDir;readAccountMetadata;constructor(e={}){this.currentAuthFilePath=e.currentAuthFilePath??pj(),this.snapshotsDir=e.snapshotsDir??mj(),this.readAccountMetadata=e.readAccountMetadata??vj}async getAccountsOverview(){let e=await this.getCurrentAccount();return{current:e,savedAccounts:await this.listSavedAccounts(e?.accountId??null)}}async getCurrentAccount(){let e=await this.readCurrentAuthFileOrNull();if(!e)return null;let t=await this.readAccountMetadataOrNull();if(!t)return null;let n=t.accountType===`chatgpt`?await this.resolveSnapshotStatus(t.accountId,e.canonicalContent):`missing`;return{accountId:t.accountId,accountType:t.accountType,authMode:e.authMode,planType:t.planType,lastRefreshAt:e.lastRefreshAt,hasSavedSnapshot:n!==`missing`,snapshotStatus:n,rateLimits:t.rateLimits}}async saveCurrentAccount(){let e=await this.readCurrentAuthFile(),t=await this.readSnapshotSupportedAccountMetadata();return await this.writeSnapshot(t.accountId,e,t),{current:{accountId:t.accountId,accountType:t.accountType,authMode:e.authMode,planType:t.planType,lastRefreshAt:e.lastRefreshAt,hasSavedSnapshot:!0,snapshotStatus:`current`,rateLimits:t.rateLimits},savedAccounts:await this.listSavedAccounts(t.accountId)}}async applySavedAccount(e){let t=await Fj(this.currentAuthFilePath),n=await this.readSavedSnapshot(e);return await Ij(this.currentAuthFilePath,n.rawContent),{previousRawContent:t}}async restoreCurrentAuthFile(e){await Ij(this.currentAuthFilePath,e)}async listSavedAccounts(e){let t=await Pj(this.snapshotsDir);return(await Promise.all(t.filter(e=>e.isFile()&&Nj(e.name)).map(async t=>{let n=Mj(t.name);if(!n)return null;let r=p.default.join(this.snapshotsDir,t.name);try{let t=gj(await d.default.readFile(r,`utf8`),r),i=await this.readSnapshotMetadata(n),a=await d.default.stat(r);return{accountId:i?.accountId??n,accountType:i?.accountType??`unknown`,authMode:t.authMode,planType:i?.planType??null,lastRefreshAt:t.lastRefreshAt,savedAt:i?.savedAt??a.mtime.toISOString(),isCurrent:e===n,rateLimits:i?.rateLimits??null}}catch{return null}}))).filter(e=>e!==null).sort((e,t)=>e.isCurrent===t.isCurrent?t.savedAt.localeCompare(e.savedAt):e.isCurrent?-1:1)}async resolveSnapshotStatus(e,t){let n=await Fj(this.getSnapshotPath(e));if(n===null)return`missing`;try{return gj(n,this.getSnapshotPath(e)).canonicalContent===t?`current`:`stale`}catch{return`stale`}}async writeSnapshot(e,t,n){let r=new Date().toISOString();await Ij(this.getSnapshotPath(e),t.rawContent),await Ij(this.getSnapshotMetadataPath(e),JSON.stringify({accountId:n.accountId,accountType:n.accountType,planType:n.planType,rateLimits:n.rateLimits,savedAt:r},null,2))}async readSavedSnapshot(e){let t=this.getSnapshotPath(e),n=await Fj(t);if(n===null)throw Sw(e);return gj(n,t)}async readSnapshotMetadata(e){let t=await Fj(this.getSnapshotMetadataPath(e));if(t===null)return null;try{return _j(t)}catch{return null}}async readCurrentAuthFile(){let e=await this.readCurrentAuthFileOrNull();if(!e)throw Cw(`Current Codex auth.json is missing or unreadable`);return e}async readCurrentAuthFileOrNull(){let e=await Fj(this.currentAuthFilePath);if(e===null)return null;try{return gj(e,this.currentAuthFilePath)}catch{return null}}async readAccountMetadataOrNull(){try{return await this.readAccountMetadata()}catch{return null}}async readSnapshotSupportedAccountMetadata(){let e=await this.readAccountMetadataOrNull();if(!e||e.accountType!==`chatgpt`)throw Cw(`Current Codex account does not expose a ChatGPT email via account/read`);return e}getSnapshotPath(e){return p.default.join(this.snapshotsDir,`${jj(e)}.json`)}getSnapshotMetadataPath(e){return p.default.join(this.snapshotsDir,`${jj(e)}${dj}`)}};function gj(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Cw(`Codex auth file is not valid JSON: ${t}`,{error:String(e)})}if(!n||typeof n!=`object`||Array.isArray(n))throw Cw(`Codex auth file is not an object: ${t}`);let r=n;return{authMode:yj(r.auth_mode),lastRefreshAt:Cj(r.last_refresh),rawContent:e,canonicalContent:kj(n)}}function _j(e){let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`invalid snapshot metadata`);let n=t,r=xj(n.accountId);if(!r)throw Error(`missing snapshot metadata accountId`);return{accountId:r,accountType:Sj(n.accountType),planType:bj(n.planType),rateLimits:wj(n.rateLimits),savedAt:Cj(n.savedAt)??new Date(0).toISOString()}}async function vj(){return SD(async e=>{let t=Oj(await e.sendRequest(`account/read`,{refreshToken:!1}));if(!t)return null;let n=Oj(t.account);if(!n)return null;let r=null;try{let t=Oj(await e.sendRequest(`account/rateLimits/read`,void 0));r=t?wj(Oj(t.rateLimits)):null}catch{r=null}let i=Sj(n.type);if(i===`chatgpt`){let e=xj(n.email);return e?{accountId:e,accountType:i,planType:bj(n.planType)??r?.planType??null,rateLimits:r}:null}return i===`apiKey`?{accountId:`API Key`,accountType:i,planType:bj(n.planType)??r?.planType??null,rateLimits:r}:null})}function yj(e){return typeof e==`string`&&e.trim()?e.trim():`unknown`}function bj(e){return typeof e==`string`&&e.trim()?e.trim():null}function xj(e){return typeof e==`string`&&e.trim()?e.trim().toLowerCase():null}function Sj(e){return e===`chatgpt`||e===`apiKey`?e:`unknown`}function Cj(e){if(typeof e!=`string`||!e.trim())return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toISOString()}function wj(e){let t=Oj(e);if(!t)return null;let n=Tj(t.primary),r=Tj(t.secondary),i=bj(t.planType??t.plan_type),a=Oj(t.credits),o=bj(t.creditsBalance??a?.balance);return!n&&!r&&!i&&!o?null:{...n?{primary:n}:{},...r?{secondary:r}:{},...i?{planType:i}:{},...o?{creditsBalance:o}:{}}}function Tj(e){let t=Oj(e);if(!t)return null;let n=Ej(t.usedPercent??t.used_percent);return n===null?null:{usedPercent:n,windowMinutes:Dj(t.windowMinutes??t.windowDurationMins??t.window_minutes),resetsAt:Ej(t.resetsAt??t.resets_at)}}function Ej(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Dj(e){return typeof e==`number`&&Number.isFinite(e)?Math.trunc(e):null}function Oj(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function kj(e){return JSON.stringify(Aj(e))}function Aj(e){return Array.isArray(e)?e.map(e=>Aj(e)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Aj(t)])):e}function jj(e){let t=xj(e);if(!t)throw Cw(`Codex account identifier cannot be empty`);return encodeURIComponent(t)}function Mj(e){if(!Nj(e))return null;try{return xj(decodeURIComponent(e.slice(0,-5)))}catch{return null}}function Nj(e){return e.endsWith(`.json`)&&!e.endsWith(dj)}async function Pj(e){try{return await d.default.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Fj(e){try{return await d.default.readFile(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ij(e,t){let n=p.default.dirname(e),r=p.default.join(n,`.${p.default.basename(e)}.${process.pid}.${Date.now()}.tmp`);await d.default.mkdir(n,{recursive:!0,mode:448}),await d.default.writeFile(r,t,{encoding:`utf8`,mode:384}),await d.default.rename(r,e)}const Lj=[`## Code review guidelines:`,`# Review guidelines:`,``,`You are acting as a reviewer for a proposed code change made by another engineer.`,``,`Below are some default guidelines for determining whether the original author would appreciate the issue being flagged.`,``,`These are not the final word in determining whether an issue is a bug. In many cases, you will encounter other, more specific guidelines. These may be present elsewhere in a developer message, a user message, a file, or even elsewhere in this system message.`,`Those guidelines should be considered to override these general instructions.`,``,`Here are the general guidelines for determining whether something is a bug and should be flagged.`,``,`1. It meaningfully impacts the accuracy, performance, security, or maintainability of the code.`,`2. The bug is discrete and actionable (i.e. not a general issue with the codebase or a combination of multiple issues).`,`3. Fixing the bug does not demand a level of rigor that is not present in the rest of the codebase (e.g. one doesn't need very detailed comments and input validation in a repository of one-off scripts in personal projects).`,`4. The bug was introduced in the change under review (pre-existing bugs should not be flagged).`,`5. The author of the original change would likely fix the issue if they were made aware of it.`,`6. The bug does not rely on unstated assumptions about the codebase or the author's intent.`,`7. It is not enough to speculate that a change may disrupt another part of the codebase; to be considered a bug, one must identify the other parts of the code that are provably affected.`,`8. The bug is clearly not just an intentional change by the original author.`,``,`When flagging a bug, you will also provide an accompanying comment. Once again, these guidelines are not the final word on how to construct a comment; defer to any subsequent guidelines that you encounter.`,``,`1. The comment should be clear about why the issue is a bug.`,`2. The comment should appropriately communicate the severity of the issue. It should not claim that an issue is more severe than it actually is.`,`3. The comment should be brief. The body should be at most 1 paragraph. It should not introduce line breaks within the natural language flow unless it is necessary for the code fragment.`,`4. The comment should not include any chunks of code longer than 3 lines. Any code chunks should be wrapped in markdown inline code tags or a code block.`,`5. The comment should clearly and explicitly communicate the scenarios, environments, or inputs that are necessary for the bug to arise. The comment should immediately indicate that the issue's severity depends on these factors.`,`6. The comment's tone should be matter-of-fact and not accusatory or overly positive. It should read as a helpful AI assistant suggestion without sounding too much like a human reviewer.`,`7. The comment should be written such that the original author can immediately grasp the idea without close reading.`,`8. The comment should avoid excessive flattery and comments that are not helpful to the original author. The comment should avoid phrasing like "Great job ..." or "Thanks for ...".`,``,`Below are some more detailed guidelines that you should apply to this specific review.`,``,`HOW MANY FINDINGS TO RETURN:`,``,`Output all findings that the original author would fix if they knew about them. If there is no finding that a person would definitely appreciate and fix, prefer outputting no findings. Do not stop at the first qualifying finding. Continue until you have listed every qualifying finding.`,``,`GUIDELINES:`,``,`- Ignore trivial style unless it obscures meaning or violates documented standards.`,`- Use one comment per distinct issue (or a multi-line range if necessary).`,"- Use ```suggestion``` blocks only for concrete replacement code (minimal lines; no commentary inside the block).","- In every ```suggestion``` block, preserve the exact leading whitespace of the replaced lines (spaces vs tabs, number of spaces).",`- Do not introduce or remove outer indentation levels unless that is the actual fix.`,``,`The comments will be presented in the code review as inline comments. Avoid unnecessary location details in the comment body. Always keep the line range as short as possible for interpreting the issue. Avoid ranges longer than 5-10 lines; instead, choose the most suitable subrange that pinpoints the problem.`,``,`At the beginning of the finding title, tag the bug with a priority level. For example "[P1] Un-padding slices along wrong tensor dimensions".`,`- [P0]: Drop everything to fix. Blocking release, operations, or major usage. Only use this for universal issues that do not depend on assumptions about the inputs.`,`- [P1]: Urgent. Should be addressed in the next cycle.`,`- [P2]: Normal. To be fixed eventually.`,`- [P3]: Low. Nice to have.`,``,"Additionally, include a numeric priority field in the JSON output for each finding: set `priority` to 0 for P0, 1 for P1, 2 for P2, or 3 for P3. If a priority cannot be determined, omit the field or use null.",``,`At the end of your findings, output an overall correctness verdict of whether or not the patch should be considered correct.`,`Correct implies that existing code and tests will not break, and the patch is free of bugs and other blocking issues.`,`Ignore non-blocking issues such as style, formatting, typos, documentation, and other nits.`,``,`FORMATTING GUIDELINES:`,`The finding description should be one paragraph.`,``,`OUTPUT FORMAT:`,``,`## Output schema - MUST MATCH exactly`,``,"```json",`{`,` "findings": [`,` {`,` "title": "<= 80 chars, imperative",`,` "body": "<valid Markdown explaining why this is a problem; cite files/lines/functions>",`,` "confidence_score": <float 0.0-1.0>,`,` "priority": <int 0-3, optional>,`,` "code_location": {`,` "absolute_file_path": "<file path>",`,` "line_range": {"start": <int>, "end": <int>}`,` }`,` }`,` ],`,` "overall_correctness": "patch is correct" | "patch is incorrect",`,` "overall_explanation": "<1-3 sentence explanation justifying the overall_correctness verdict>",`,` "overall_confidence_score": <float 0.0-1.0>`,`}`,"```",``,`- Do not wrap the JSON in markdown fences or extra prose.`,"- The `code_location` field is required and must include `absolute_file_path` and `line_range`.",`- Line ranges must be as short as possible for interpreting the issue (avoid ranges over 5-10 lines; pick the most suitable subrange).`,"- The `code_location` should overlap with the diff under review.",`- Do not generate a fix patch.`,`- Your initial response to the user must always use the JSON schema above.`,`- After the initial response, choose the format based on the user's request:`,` - If they explicitly ask for another review (for example, "re-review" or "rerun the review"), return the findings in the exact JSON schema again.`,` - If they ask you to fix something, answer follow-up questions, or otherwise request non-review help, respond in plain text (no JSON or schema output).`,`- All review instructions apply to the overall code review conversation. Continue following the guidelines in every response, only switching between JSON and plain text as described above.`];function Rj(e,t){let n=e.provider===`codex`?e.codex:void 0;if(!n)throw Error(`Codex review config is required`);return[...Lj,``,Bj(n.target),`## My request for Codex:`,zj(e,t)].join(`
|
|
521
|
+
`)}function zj(e,t){let n=e.provider===`codex`?e.codex:void 0;if(!n)throw Error(`Codex review config is required`);let r=n.target,i=r.type===`baseBranch`?`Please review the code changes against the base branch ${r.branch}.`:r.type===`commit`?`Please review the code changes introduced by commit ${Vj(r.sha,r.title)}.`:r.type===`custom`?r.instructions:`Please review my uncommitted changes.`,a=Hj(t);return a?`${i}\n\nAdditional review instructions:\n${a}`:i}function Bj(e){return e.type===`baseBranch`?`Review the code changes against the base branch ${e.branch} and provide prioritized, actionable findings.`:e.type===`commit`?`Review the code changes introduced by commit ${Vj(e.sha,e.title)} and provide prioritized, actionable findings.`:e.type===`custom`?`Review the requested code changes and provide prioritized, actionable findings.`:`Review the current code changes (staged, unstaged, and untracked files) and provide prioritized, actionable findings.`}function Vj(e,t){let n=Hj(t);return n?`${e} (${JSON.stringify(n)})`:e}function Hj(e){return e?.trim()||void 0}const Uj=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function Wj(e){return e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt}function Gj(e,t){Uj&&(!e.startsWith(`config.get`)&&!e.startsWith(`raw-events`)&&!e.startsWith(`sync-external`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function Kj(e){return e?{sessionFound:!0,sessionId:e.id,nativeSessionId:e.nativeSessionId??null,sessionSource:e.source??null,sessionModel:e.model??null,sessionUpdatedAt:e.updatedAt,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt??null,sessionTurnConfigModel:e.sessionTurnConfig?.model??null,sessionTurnConfigReasoningEffort:e.sessionTurnConfig?.reasoningEffort??null,sessionTurnConfigApprovalPolicy:e.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,sessionTurnConfigSandboxMode:e.sessionTurnConfig?.execution?.codex?.sandboxMode??null,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null,lastHydratedExternalConfigFreshnessAt:e.lastHydratedExternalConfigFreshnessAt??null}:{sessionFound:!1}}function qj(e,t){return e?.status===`running`?{status:`running`}:t?{status:`running`,interactionLockReason:`external_turn_running`}:{status:`idle`}}function Jj(e){return e.status===`active`?!0:e.turns.some(e=>e.status===`inProgress`||e.status===`in_progress`)}function Yj(e,t){if(!t)return Jj(e);for(let n of e.turns)if(!(n.status!==`inProgress`&&n.status!==`in_progress`)&&!t.terminalTurnStatusById.has(n.id))return!0;return!1}function Xj(e){return e.startsWith(`sess_`)}function Zj(e){return e.source===`native_discovered`?!0:e.providerMode===`native`&&(e.provider===`codex`||e.provider===`claude`)}function Qj(e){return e.nativeSessionId?.trim()??``?!0:e.provider===`codex`&&!Xj(e.id)}function $j(e){return Xj(e.id)?e.nativeSessionId??e.id:e.id}function eM(e){return e.provider!==`codex`&&e.provider!==`claude`||e.providerMode!==`native`?!1:Qj(e)}function tM(e){return e instanceof Error&&/^Session .+ is closed$/i.test(e.message)}function nM(e,t){if(e.provider!==`codex`||t.type!==`error.runtime`)return!1;if(yN(t.source)?.startsWith(`codex.app_server`))return!0;let n=yN(t.message)??``;return/\bclosed\b/i.test(n)}const rM={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function iM(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function aM(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}var oM=class{sessions=new Map;providerCapabilities;codexAccounts;nextRawSeqBySession=new Map;preparingRuntimeDispatches=new Set;queuedInterruptsBeforeDispatch=new Set;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.providerCapabilities=new uj({preferNativeProviders:e.preferNativeProviders,projectStore:e.projectStore,logger:e.logger}),this.codexAccounts=e.codexAccountService??new hj,this.runtimeLifecycle={idleTtlMs:iM(e.runtimeLifecycle?.idleTtlMs,rM.idleTtlMs),sweepIntervalMs:aM(e.runtimeLifecycle?.sweepIntervalMs,rM.sweepIntervalMs),maxSessions:iM(e.runtimeLifecycle?.maxSessions,rM.maxSessions),maxCodexSessions:iM(e.runtimeLifecycle?.maxCodexSessions,rM.maxCodexSessions),maxClaudeSessions:iM(e.runtimeLifecycle?.maxClaudeSessions,rM.maxClaudeSessions)},this.runtimeLifecycle.sweepIntervalMs<=0){this.sweepTimer=null;return}this.sweepTimer=setInterval(()=>{this.sweepRuntimeSessions().catch(e=>{console.error(`[session-runtime] sweep failed: ${String(e)}`)})},this.runtimeLifecycle.sweepIntervalMs),this.sweepTimer.unref?.()}async shutdown(){this.shuttingDown=!0,this.sweepTimer&&clearInterval(this.sweepTimer);let e=[...this.sessions.keys()];this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown starting`),await Promise.allSettled(e.map(e=>this.closeRuntimeSession(e,`shutdown`))),await iD(),this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown completed`)}async listProjects(){let e=await this.options.projectStore.list(),t=this.buildProjectStatsMap();return e.map(e=>this.attachProjectStats(e,t))}async createProject(e){let t=await this.options.projectStore.upsertByPath(e.path,e.title);return this.attachProjectStats(t,this.buildProjectStatsMap())}async deleteProject(e){if(this.listProjectSessionsWithRuntime(e,`running`).length>0)throw bw(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.getRunningRuntimeSessionCount();if(e>0)throw xw(e);let t=[...this.sessions.values()].filter(e=>e.provider===`codex`).map(e=>e.id);return await Promise.allSettled(t.map(e=>this.closeRuntimeSession(e,`codex_restart`))),await aD(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.app_server.restart`,detail:{closedRuntimeSessionCount:t.length}}),{restarted:!0,closedRuntimeSessionCount:t.length}}async getCodexAccounts(){return this.codexAccounts.getAccountsOverview()}async saveCurrentCodexAccount(){let e=await this.codexAccounts.saveCurrentAccount();return await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.account.save`,detail:{currentAccountId:e.current?.accountId??null,savedAccountCount:e.savedAccounts.length}}),{saved:!0,accounts:e}}async switchCodexAccount(e){let t=await this.codexAccounts.getCurrentAccount();if(t?.accountId===e)return{switched:!0,closedRuntimeSessionCount:0,accounts:t.accountType===`chatgpt`?await this.codexAccounts.saveCurrentAccount():await this.codexAccounts.getAccountsOverview()};let n=this.getRunningRuntimeSessionCount();if(n>0)throw xw(n);let r=[...this.sessions.values()].filter(e=>e.provider===`codex`).map(e=>e.id);await Promise.allSettled(r.map(e=>this.closeRuntimeSession(e,`codex_restart`))),t?.accountType===`chatgpt`&&await this.codexAccounts.saveCurrentAccount(),await iD();let i=null;try{i=await this.codexAccounts.applySavedAccount(e),await aD()}catch(e){if(i?.previousRawContent)try{await this.codexAccounts.restoreCurrentAuthFile(i.previousRawContent),await aD()}catch{}throw e}let a=await this.codexAccounts.getAccountsOverview();return await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.account.switch`,detail:{previousAccountId:t?.accountId??null,nextAccountId:a.current?.accountId??e,closedRuntimeSessionCount:r.length}}),{switched:!0,closedRuntimeSessionCount:r.length,accounts:a}}async getProject(e){return this.options.projectStore.getById(e)}getRunningRuntimeSessionCount(){let e=0;for(let t of this.sessions.values())t.status===`running`&&(e+=1);return e}buildProjectStatsMap(){let e=new Map,t=this.listAllSessionsWithRuntime(`all`);for(let n of t){let t=e.get(n.projectId)??{runningCount:0,idleCount:0,totalCount:0,lastSessionAt:void 0};n.status===`running`?t.runningCount+=1:t.idleCount+=1,t.totalCount+=1;let r=n.updatedAt||n.createdAt;(!t.lastSessionAt||r>t.lastSessionAt)&&(t.lastSessionAt=r),e.set(n.projectId,t)}return e}attachProjectStats(e,t){let n=t.get(e.id),r=n?.idleCount??0;return{...e,lastSessionAt:n?.lastSessionAt,runningCount:n?.runningCount??0,idleCount:r,totalCount:n?.totalCount??0,endedCount:r}}async getProviderCapabilities(e,t,n){return this.providerCapabilities.getProviderCapabilities(e,t,n)}async getAgentConfig(e,t){return this.providerCapabilities.getAgentConfig(e,t)}async warmStartupProviderCapabilities(){if(!this.shuttingDown)return this.providerCapabilities.warmStartupProviderCapabilities()}async getProviderDefaults(e,t,n){return this.providerCapabilities.getProviderDefaults(e,t,n)}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw gw(e);if(n?.syncExternal){let e=Date.now(),n=this.options.historyStore.listProjectSessions(r.id,`all`).length;this.options.logger?.info?.({projectId:r.id,projectPath:r.path,requestedStatus:t,sessionCountBeforeSync:n},`project external session sync started`);let[i,a]=await Promise.all([this.syncCodexSessionsForProject(r),this.syncClaudeSessionsForProject(r)]);this.options.logger?.info?.({projectId:r.id,projectPath:r.path,requestedStatus:t,sessionCountBeforeSync:n,sessionCountAfterSync:this.options.historyStore.listProjectSessions(r.id,`all`).length,totalDurationMs:Date.now()-e,codexSync:i,claudeSync:a},`project external session sync completed`)}return this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){let n=this.options.historyStore.getProjectSession(e,t);return this.getRuntimeSessionSummary(e,t,n)||this.maybeHydrateClaudeExternalSessionSummary(n)}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(Gj(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:Kj(n),runtime:Kj(r)}),r)return Gj(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...Kj(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return Gj(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...Kj(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw gw(e);let r=this.options.historyStore.getProjectSession(e,t);if(!r&&this.options.preferNativeProviders&&(await this.syncCodexSessionsForProject(n),await this.syncClaudeSessionsForProject(n),r=this.options.historyStore.getProjectSession(e,t)),!r)throw _w(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.options.historyStore.getSessionStoredRawEvents(r.id,2**53-1),o=await this.syncExternalRawHistory(r,e,i,a),s=o.session??this.options.historyStore.getProjectSession(e,r.id)??r,c=QM(i,o.rawEvents);Gj(`sync-external.classify`,ZM({projectId:e,sessionId:t,session:s,previousEvents:i,nextEvents:o.rawEvents,classification:c}));let l=s.status!==r.status||(s.interactionLockReason??``)!==(r.interactionLockReason??``);return{session:s,rawEvents:o.rawEvents,historyUpdated:c.historyUpdated,statusChanged:l,refreshMode:c.refreshMode,fromRawSeq:c.fromRawSeq,toRawSeq:c.toRawSeq,nativeWatchPath:o.nativeWatchPath}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw gw(e);let i=0,a=0,o,s=(s,c)=>{Gj(`raw-events.read`,{projectId:e,sessionId:t,limit:n,provider:o?.provider,source:o?.source,providerMode:o?.providerMode,localReadDurationMs:i,finalCount:a,outcome:s,totalDurationMs:Date.now()-r,...c})},c=this.options.historyStore.getProjectSession(e,t);if(!c&&this.getRuntimeSessionSummary(e,t))return s(`runtime_session_empty`),[];if(!c)throw _w(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEvents(c.id,Math.max(n,300));return i=Date.now()-l,a=u.slice(-Math.max(1,n)).length,s(`local_only_cached`,{localEventCount:u.length}),u.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompacted(r.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3){let i=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsSinceSeq(i.id,n,r)}async getProjectSessionRawSeqRange(e,t){let n=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawSeqRange(n.id)}async resolveProjectSessionForRawRead(e,t){if(!await this.options.projectStore.getById(e))throw gw(e);let n=this.options.historyStore.getProjectSession(e,t);if(n||=this.getRuntimeSessionSummary(e,t),!n)throw _w(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${ow(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=$O(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?HA(e.provider,e.sessionTurnConfig):WA({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=GA({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!a&&this.preparingRuntimeDispatches.has(e))throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(i?.interactionLockReason===`external_turn_running`)throw yw(e,`an external native turn is still running`,{reason:`external_turn_running`,status:i.status,interactionLockReason:i.interactionLockReason,provider:i.provider,providerMode:i.providerMode});if(a?.status===`running`)throw yw(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&Zj(i))throw yw(e,`the native session is still running`,{reason:`persisted_running`,status:i.status,provider:i.provider,providerMode:i.providerMode,source:i.source});let o=!a,s=a,c=!1;try{if(o&&this.preparingRuntimeDispatches.add(e),s=a??await this.resumeSessionFromHistory(e),!s)throw vw(e);let i=await this.getProviderDefaults(s.provider,s.projectId),l=GA({provider:s.provider,providerDefaults:i,currentSessionTurnConfig:s.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});if(s.dispatchInFlight=!0,this.touchSession(s),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:l.model,sessionConfig:r?.sessionConfig,mode:l.mode,config:r?.config,resolvedSessionConfig:l.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(this.options.historyStore.getSession(s.id)||await this.persistSessionSnapshot(s),this.consumeQueuedInterruptBeforeDispatch(e)))throw c=!0,this.createInterruptedBeforeDispatchError(e);if(s=await this.sendInputWithRuntimeRecovery(e,s,t,{model:l.model,sessionConfig:l.sessionConfig,mode:l.mode}),!s.title){let e=_N(t);e&&this.setSessionTitle(s,e)}let u=new Date().toISOString();s.sessionTurnConfig=HA(s.provider,l.sessionTurnConfig),s.sessionTurnConfigUpdatedAt=u,l.model&&s.model!==l.model&&(s.model=l.model),s.updatedAt=u,await this.persistSessionSnapshot(s)}finally{o&&this.preparingRuntimeDispatches.delete(e),this.queuedInterruptsBeforeDispatch.delete(e);let t=!1;c&&o&&s&&(await this.closeRuntimeSession(s.id,`dispatch_cancelled`,{suppressAudit:!0}),t=!0),!t&&s&&(s.dispatchInFlight=!1,this.touchSession(s))}}async startReview(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!a&&this.preparingRuntimeDispatches.has(e))throw yw(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(i?.interactionLockReason===`external_turn_running`)throw yw(e,`an external native turn is still running`,{reason:`external_turn_running`,status:i.status,interactionLockReason:i.interactionLockReason,provider:i.provider,providerMode:i.providerMode});if(a?.status===`running`)throw yw(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&Zj(i))throw yw(e,`the native session is still running`,{reason:`persisted_running`,status:i.status,provider:i.provider,providerMode:i.providerMode,source:i.source});let o=!a,s=a,c=!1;try{if(o&&this.preparingRuntimeDispatches.add(e),s=a??await this.resumeSessionFromHistory(e),!s)throw vw(e);if(s.provider!==t.provider)throw Error(`Review provider mismatch for session ${e}`);if(t.provider!==`codex`||!t.codex)throw Error(`Only Codex review is currently supported`);let i=await this.getProviderDefaults(s.provider,s.projectId),l=GA({provider:s.provider,providerDefaults:i,currentSessionTurnConfig:s.sessionTurnConfig,config:r?.turnConfig});if(s.dispatchInFlight=!0,this.touchSession(s),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`review.start`,deviceId:n,sessionId:e,detail:{input:r?.input,config:t,turnConfig:r?.turnConfig,resolvedModel:l.model,resolvedSessionConfig:l.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(this.options.historyStore.getSession(s.id)||await this.persistSessionSnapshot(s),this.consumeQueuedInterruptBeforeDispatch(e)))throw c=!0,this.createInterruptedBeforeDispatchError(e);let u=Rj(t,r?.input);if(s=await this.sendInputWithRuntimeRecovery(e,s,u,{model:l.model,sessionConfig:l.sessionConfig}),!s.title){let e=vN(t,r?.input);e&&this.setSessionTitle(s,e)}let d=new Date().toISOString();s.sessionTurnConfig=HA(s.provider,l.sessionTurnConfig),s.sessionTurnConfigUpdatedAt=d,l.model&&s.model!==l.model&&(s.model=l.model),s.updatedAt=d,await this.persistSessionSnapshot(s)}finally{o&&this.preparingRuntimeDispatches.delete(e),this.queuedInterruptsBeforeDispatch.delete(e);let t=!1;c&&o&&s&&(await this.closeRuntimeSession(s.id,`dispatch_cancelled`,{suppressAudit:!0}),t=!0),!t&&s&&(s.dispatchInFlight=!1,this.touchSession(s))}}async sendInputWithRuntimeRecovery(e,t,n,r){try{return await t.providerSession.sendInput(n,r),t}catch(i){if(!tM(i))throw i;let a=i;this.options.logger?.warn?.({sessionId:e,runtimeSessionId:t.id,nativeSessionId:t.nativeSessionId,provider:t.provider,providerMode:t.providerMode,projectId:t.projectId,projectPath:t.projectPath,model:t.model,error:a.message},`provider runtime session sendInput hit closed session; resuming from history`),await this.closeRuntimeSession(t.id,`provider_error`,{suppressAudit:!0});let o=await this.resumeSessionFromHistory(e);if(!o)throw a;return o.dispatchInFlight=!0,this.touchSession(o),await o.providerSession.sendInput(n,r),o}}async respondToolPermission(e,t,n,r,i){let a=this.mustGetSession(e);if(!a.pendingToolApprovals.has(t))throw Error(`Unknown tool approval request: ${t}`);if(typeof a.providerSession.respondToolPermission!=`function`){a.pendingToolApprovals.delete(t),a.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(a);return}await a.providerSession.respondToolPermission(t,n,r),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`tool.approval.respond`,deviceId:i,sessionId:e,detail:{requestId:t,decision:n,reason:r}})}async respondUserInput(e,t,n,r){let i=this.mustGetSession(e);if(!i.pendingUserInputs.has(t))throw Error(`Unknown user input request: ${t}`);if(typeof i.providerSession.respondUserInput!=`function`){i.pendingUserInputs.delete(t),i.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(i);return}await i.providerSession.respondUserInput(t,n),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`user.input.respond`,deviceId:r,sessionId:e,detail:{requestId:t,answeredCount:bN(n)}})}async interruptSession(e,t){let n=this.sessions.get(e),r=this.preparingRuntimeDispatches.has(e)||!!n?.dispatchInFlight;r&&this.queuedInterruptsBeforeDispatch.add(e),n&&await n.providerSession.interrupt(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.interrupt`,deviceId:t,sessionId:e,detail:{runtimeSessionFound:!!n,queuedBeforeDispatch:r}})}async closeSession(e){throw Error(`session.close is deprecated. Use session.interrupt instead.`)}getSessionExecutionContext(e){let t=this.sessions.get(e);if(t)return{provider:t.provider,projectId:t.projectId,projectPath:t.projectPath};let n=this.options.historyStore.getSession(e);if(!n)throw vw(e);return{provider:n.provider,projectId:n.projectId,projectPath:n.projectPath}}async emitExternalEvent(e){let t=this.options.historyStore.getSession(e.sessionId),n={v:`1.0`,kind:`provider.raw`,rawSeq:await this.nextRawSeq(e.sessionId),provider:e.provider,sessionId:e.sessionId,projectId:e.projectId??t?.projectId,eventId:`raw_${ow(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:e.type,payload:{raw:{...e.raw,type:e.type}}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}async resumeSessionFromHistory(e){let t=this.options.historyStore.getSession(e);if(!t)return;let n=t.provider===`codex`&&this.options.requireNativeCodex,r=$O(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=HA(t.provider,t.sessionTurnConfig),o=GA({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`?$j(t):t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}consumeQueuedInterruptBeforeDispatch(e){return this.queuedInterruptsBeforeDispatch.delete(e)}createInterruptedBeforeDispatchError(e){return yw(e,`the pending turn was interrupted before provider dispatch started`,{reason:`interrupt_requested_before_dispatch`})}async syncCodexSessionsForProject(e){let t=Date.now();if(!this.options.preferNativeProviders)return{provider:`codex`,status:`disabled`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:0,applyDurationMs:0,totalDurationMs:Date.now()-t};let n=Date.now(),r,i=Math.floor((Date.now()-14400*60*1e3)/1e3);try{r=await YD(e.path,{maxThreads:100,sortKey:`updated_at`,updatedAfterUnixSeconds:i})}catch(r){let i={provider:`codex`,status:`error`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:Date.now()-n,applyDurationMs:0,totalDurationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)};return this.options.logger?.warn?.({projectId:e.id,projectPath:e.path,...i},`project external session sync provider failed`),i}let a=Date.now()-n,o=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),s=Date.now(),c=0;for(let t of r){if(t.cwd!==e.path)continue;let n=[...o.values()].find(e=>e.provider===`codex`&&(e.id===t.id||e.nativeSessionId===t.id)),r=n?.id??t.id,i=this.sessions.get(r)??this.sessions.get(t.id),a=xN(t.createdAt),s=xN(t.updatedAt),l=qj(i,Jj(t)),u=l.status,d=u===`running`?i?.pendingToolApprovals.size??0:0,f=u===`running`?i?.pendingUserInputs.size??0:0,p={id:r,nativeSessionId:t.id,source:n?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:i?.providerMode??n?.providerMode??`native`,model:ij({runtimeModel:i?.model,discoveredModel:t.model,existingModel:n?.model,modelProvider:t.modelProvider}),title:i?.title??_N(t.name??t.preview)??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??a,updatedAt:u===`running`?i?.updatedAt??s:s,status:u,interactionLockReason:l.interactionLockReason,pendingApprovals:d,pendingUserInputs:f,pendingActions:d+f};await this.options.historyStore.upsertSession(p),o.set(r,p),c+=1}let l={provider:`codex`,status:`ok`,discoveredCount:r.filter(t=>t.cwd===e.path).length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxThreads:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async syncClaudeSessionsForProject(e){let t=Date.now();if(!this.options.preferNativeProviders)return{provider:`claude`,status:`disabled`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:0,applyDurationMs:0,totalDurationMs:Date.now()-t};let n=Date.now(),r,i=Date.now()-14400*60*1e3;try{r=await rk(e.path,{maxSessions:100,updatedAfterMs:i})}catch(r){let i={provider:`claude`,status:`error`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:Date.now()-n,applyDurationMs:0,totalDurationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)};return this.options.logger?.warn?.({projectId:e.id,projectPath:e.path,...i},`project external session sync provider failed`),i}let a=Date.now()-n,o=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),s=Date.now(),c=0;for(let t of r){let n=[...o.values()].find(e=>e.provider===`claude`&&(e.id===t.nativeSessionId||e.nativeSessionId===t.nativeSessionId)),r=n?.id??t.nativeSessionId,i=this.sessions.get(r),a=qj(i,t.status===`running`),s=a.status,l=s===`running`?i?.pendingToolApprovals.size??0:0,u=s===`running`?i?.pendingUserInputs.size??0:0,d={id:r,nativeSessionId:t.nativeSessionId,source:n?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:i?.providerMode??n?.providerMode??`native`,model:i?.model??n?.model??t.model,title:i?.title??t.title??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??t.createdAt,updatedAt:s===`running`?i?.updatedAt??t.updatedAt:t.updatedAt,status:s,interactionLockReason:a.interactionLockReason,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),o.set(r,d),c+=1}let l={provider:`claude`,status:`ok`,discoveredCount:r.length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxSessions:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=Wj(e),n=zM([e.nativeSessionId,e.id]);for(let r of n)try{Gj(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:r,...Kj(e)});let n=await QD(r);if(!n){Gj(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:r});continue}let i={...e,model:rj(n.model)??e.model,sessionTurnConfig:n.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:n.sessionTurnConfigUpdatedAt,...t?{lastHydratedExternalConfigFreshnessAt:t}:{}};return await this.options.historyStore.upsertSession(i),Gj(`config.get.probe.result`,{projectId:e.projectId,sessionId:e.id,threadId:r,snapshotModel:n.model??null,snapshotSessionTurnConfigModel:n.sessionTurnConfig?.model??null,snapshotReasoningEffort:n.sessionTurnConfig?.reasoningEffort??null,snapshotApprovalPolicy:n.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,snapshotSandboxMode:n.sessionTurnConfig?.execution?.codex?.sandboxMode??null,snapshotUpdatedAt:n.sessionTurnConfigUpdatedAt,next:Kj(i)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??i}catch(t){Gj(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:r,error:String(t)})}return e}async maybeHydrateClaudeExternalSessionSummary(e){if(!e||e.provider!==`claude`||!Zj(e)||!Qj(e))return e;let t=VM(e);if(!t)return e;try{let n=await ik({projectPath:e.projectPath,nativeSessionId:t,provider:e.provider,sessionId:e.id,projectId:e.projectId});return this.patchObservedExternalSessionSummary(e,{updatedAt:n.updatedAt,externallyRunning:n.status===`running`,model:n.model})}catch(t){if(e.source===`native_discovered`&&BM(t))return e;throw t}}shouldHydrateCodexExternalSessionConfig(e){if(!this.options.preferNativeProviders||e.provider!==`codex`||!eM(e)||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=Wj(e),n=e.sessionTurnConfigUpdatedAt||``;if(!e.sessionTurnConfig||!rj(e.model)||!n)return!0;if(!t)return!1;let r=e.lastHydratedExternalConfigFreshnessAt;return r?t.localeCompare(r)>0:!0}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw gw(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await SN(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw gw(e);return await SN(t.path),t}return this.options.projectStore.upsertByPath(t)}async attachRuntimeSession(e){let t=this.sessions.get(e.id);t&&await this.closeRuntimeSession(t.id,`replaced`,{suppressAudit:!0});let n={...e,unsubscribe:()=>{}};return await this.initializeRawSeqCursor(n.id),n.unsubscribe=n.providerSession.onEvent(e=>{if(!n.streamReady){n.bufferedProviderEvents.push(e);return}this.handleProviderEvent(n,e)}),this.sessions.set(n.id,n),n}handleProviderEvent(e,t){let n=this.ensureProviderRequestId(t);if(this.emitRawEnvelope(e,n),this.maybePersistUpdatedNativeSessionId(e),e.updatedAt=new Date().toISOString(),this.touchSession(e),n.type===`thread.title.updated`){let t=yN(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=yN(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e),nM(e,n)&&this.closeRuntimeSession(e.id,`provider_error`,{suppressAudit:!0});return}if(n.type===`tool.permission.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingToolApprovals.add(t),this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.resolved`&&typeof n.requestId==`string`){e.pendingToolApprovals.delete(n.requestId),this.persistSessionSnapshot(e);return}if(n.type===`user.input.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingUserInputs.add(t),this.persistSessionSnapshot(e);return}if(n.type===`user.input.resolved`&&typeof n.requestId==`string`){e.pendingUserInputs.delete(n.requestId),this.persistSessionSnapshot(e);return}}emitRawEnvelope(e,t){let n={v:`1.0`,kind:`provider.raw`,rawSeq:this.nextRawSeqSync(e.id),provider:e.provider,sessionId:e.id,projectId:e.projectId,eventId:`raw_${ow(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:t.type,payload:{raw:t}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}nextRawEnvelopeTimestamp(){let e=Date.now(),t=e>this.lastRawEnvelopeTimestampMs?e:this.lastRawEnvelopeTimestampMs+1;return this.lastRawEnvelopeTimestampMs=t,new Date(t).toISOString()}async initializeRawSeqCursor(e){if(this.nextRawSeqBySession.has(e))return;let t=await this.options.historyStore.getSessionRawSeqRange(e),n=t?t.max+1:1;this.nextRawSeqBySession.set(e,n)}async nextRawSeq(e){return await this.initializeRawSeqCursor(e),this.nextRawSeqSync(e)}nextRawSeqSync(e){let t=this.nextRawSeqBySession.get(e)??1;return this.nextRawSeqBySession.set(e,t+1),t}touchSession(e){e.lastActiveAtMs=Date.now()}isSessionEvictable(e){return!(e.closing||e.status!==`idle`||e.pendingToolApprovals.size>0||e.pendingUserInputs.size>0||e.dispatchInFlight)}async closeRuntimeSession(e,t,n){let r=this.sessions.get(e);if(!r||r.closing)return!1;r.closing=!0;let i=Date.now();this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,statusBefore:r.status,projectId:r.projectId,projectPath:r.projectPath,model:r.model,pendingApprovalCount:r.pendingToolApprovals.size,pendingUserInputCount:r.pendingUserInputs.size,dispatchInFlight:r.dispatchInFlight},`provider runtime session close starting`);try{r.unsubscribe()}catch{}let a;try{await r.providerSession.close()}catch(n){a=n,console.error(`[session-runtime] failed closing session ${e}:`,n),this.options.logger?.error?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,error:String(n),err:n},`provider runtime session close failed`)}finally{r.status=`idle`,r.updatedAt=new Date().toISOString(),r.pendingToolApprovals.clear(),r.pendingUserInputs.clear();let t=this.sessions.get(e);if(!(t&&t!==r))try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}this.sessions.get(e)===r&&this.sessions.delete(e),r.dispatchInFlight=!1,r.closing=!1}if(this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,result:a?`error`:`success`,durationMs:Date.now()-i},`provider runtime session close completed`),!n?.suppressAudit)try{await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.runtime.close`,sessionId:e,detail:{reason:t,provider:r.provider}})}catch(e){console.error(`[session-runtime] failed to record runtime close audit log: ${String(e)}`)}return!0}async sweepRuntimeSessions(){if(this.shuttingDown||this.sessions.size===0)return;let e=Date.now(),t=this.runtimeLifecycle.idleTtlMs,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs);for(let r of n)e-r.lastActiveAtMs<t||await this.closeRuntimeSession(r.id,`idle_ttl`);await this.enforceProviderSessionCap(`codex`,this.runtimeLifecycle.maxCodexSessions),await this.enforceProviderSessionCap(`claude`,this.runtimeLifecycle.maxClaudeSessions),await this.enforceGlobalSessionCap(this.runtimeLifecycle.maxSessions)}async enforceProviderSessionCap(e,t){let n=[...this.sessions.values()].filter(t=>t.provider===e);if(n.length<=t)return;let r=n.length-t,i=n.filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),a=0;for(let e of i){if(a>=r)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(a+=1)}a<r&&console.warn(`[session-runtime] ${e} sessions exceed cap (${n.length}/${t}), no more idle sessions to evict`)}async enforceGlobalSessionCap(e){if(this.sessions.size<=e)return;let t=this.sessions.size-e,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),r=0;for(let e of n){if(r>=t)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(r+=1)}r<t&&console.warn(`[session-runtime] session count exceeds cap (${this.sessions.size}/${e}), no more idle sessions to evict`)}ensureProviderRequestId(e){return e.type===`tool.permission.requested`||e.type===`user.input.requested`?typeof e.requestId==`string`&&e.requestId.trim()?e:{...e,requestId:`req_${ow(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n,r){if(!r)return n;let i=await this.options.historyStore.mergeSessionRawEvents(e.id,n,{replaceMissing:!0,baseEventIds:t.map(e=>e.eventId)}),a=i[i.length-1]?.rawSeq;return typeof a==`number`&&Number.isFinite(a)&&a>0&&this.nextRawSeqBySession.set(e.id,a+1),i}async syncExternalRawHistory(e,t,n,r=n){if(e.provider===`claude`){let i=VM(e);if(!i)return{rawEvents:n};try{let a=Date.now(),o=await ik({projectPath:e.projectPath,nativeSessionId:i,provider:e.provider,sessionId:e.id,projectId:t}),s=Date.now(),c=await this.finalizeExternalRawHistorySync(e,r,o.rawEvents,o.updatedAt),l=await this.patchObservedExternalSessionSummary(e,{updatedAt:o.updatedAt,externallyRunning:o.status===`running`,model:o.model});return Gj(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,localStoredEventCount:r.length,historyEventCount:o.rawEvents.length,resultEventCount:c.length,readHistoryDurationMs:s-a,finalizeDurationMs:Date.now()-s}),{rawEvents:c,session:l,nativeWatchPath:o.nativeWatchPath}}catch(i){return e.source===`native_discovered`&&BM(i)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),Gj(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,localStoredEventCount:r.length,error:i instanceof Error?i.message:String(i)}),{rawEvents:n}}}if(e.provider!==`codex`)return{rawEvents:n};let i=vM(n,(this.sessions.get(e.id)??(e.nativeSessionId?this.sessions.get(e.nativeSessionId):void 0))?.status===`running`),a=zM([e.nativeSessionId,e.id]);for(let o of a)try{let a=Date.now(),s=await ZD(o,!0),c=Date.now(),l,u;if(e.source===`gateway`&&n.length>0)l=uN({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n,localCodexLiveTurnState:i}),u=`gateway_incremental`;else if(e.source===`native_discovered`&&n.length>0){let r=eN({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n});r?(l=r,u=`native_tail_incremental`):(l=$M({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localCodexLiveTurnState:i}),u=`full`)}else l=$M({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localCodexLiveTurnState:i}),u=`full`;let d=Date.now(),f=await this.finalizeExternalRawHistorySync(e,r,l,xN(s.updatedAt),i),p=await this.patchObservedExternalSessionSummary(e,{updatedAt:xN(s.updatedAt),externallyRunning:e.source===`gateway`?Yj(s,i):Jj(s)});return Gj(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:o,threadStatus:s.status,threadUpdatedAt:xN(s.updatedAt),threadTurnCount:s.turns.length,threadTurns:s.turns.slice(-3).map(e=>({id:e.id,status:e.status,itemCount:e.items.length,lastItemId:e.items[e.items.length-1]?.id??null,lastItemType:e.items[e.items.length-1]?.type??null})),externallyRunning:e.source===`gateway`?Yj(s,i):Jj(s),localEventCount:n.length,localStoredEventCount:r.length,historyBuildMode:u,historyEventCount:l.length,resultEventCount:f.length,readThreadDurationMs:c-a,buildHistoryDurationMs:d-c,finalizeDurationMs:Date.now()-d}),{rawEvents:f,session:p,nativeWatchPath:s.path??void 0}}catch(i){Gj(`sync-external.codex.read.error`,{projectId:t,sessionId:e.id,source:e.source,threadId:o,localEventCount:n.length,localStoredEventCount:r.length,error:i instanceof Error?i.message:String(i)})}return Gj(`sync-external.codex.read.exhausted`,{projectId:t,sessionId:e.id,source:e.source,attemptedThreadIds:a,localEventCount:n.length}),{rawEvents:n}}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt,i){let a=Date.now(),o=cM(e.provider,t,n,i),s=Date.now(),c=await this.maybePersistSyncedExternalRawEvents(e,t,o,!0);return await this.markExternalHistoryHydrated(e.id,r),Gj(`sync-external.finalize`,{sessionId:e.id,provider:e.provider,source:e.source,localEventCount:t.length,historyEventCount:n.length,mergedEventCount:o.length,persistedEventCount:c.length,hydratedExternalUpdatedAt:r,mergeDurationMs:s-a,persistDurationMs:Date.now()-s}),c}async patchObservedExternalSessionSummary(e,t){let n=this.options.historyStore.getSession(e.id)??e,r=this.sessions.get(e.id)??(e.nativeSessionId?this.sessions.get(e.nativeSessionId):void 0),i=qj(r,t.externallyRunning),a=i.status===`running`?r?.pendingToolApprovals.size??0:0,o=i.status===`running`?r?.pendingUserInputs.size??0:0,s={...n,updatedAt:i.status===`running`?r?.updatedAt??t.updatedAt:t.updatedAt,status:i.status,model:r?.model??rj(t.model)??n.model,interactionLockReason:i.interactionLockReason,pendingApprovals:a,pendingUserInputs:o,pendingActions:a+o};return await this.options.historyStore.upsertSession(s),this.options.historyStore.getSession(e.id)??s}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw vw(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,interactionLockReason:void 0,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=gN(t);!n||n===e.title||(e.title=n,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}resolveCanonicalSessionId(e,t,n){return e===`codex`&&t.getNativeSessionId?.()||n}resolveNativeSessionId(e,t,n){return e!==`codex`&&e!==`claude`?n:t.getNativeSessionId?.()||n}maybePersistUpdatedNativeSessionId(e){let t=this.resolveNativeSessionId(e.provider,e.providerSession,e.nativeSessionId);!t||t===e.nativeSessionId||this.shouldPersistNativeSessionId(e,t)&&(e.nativeSessionId=t,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}shouldPersistNativeSessionId(e,t){return e.source===`native_discovered`?!1:e.nativeSessionId?e.nativeSessionId===e.id&&e.id.startsWith(`sess_`)?t!==e.nativeSessionId:!1:!0}};const sM=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function cM(e,t,n,r){if(e===`claude`)return uM(e,xM(t,n),n);if(e!==`codex`)return uM(e,t,n);if(t.length===0)return n.slice().sort((e,t)=>e.ts.localeCompare(t.ts));let i=r??vM(t),a=lM(e,t.filter(e=>!mM(e))),o=TM(e),s=t.filter(t=>{if(_M(t,i))return!1;if(!mM(t))return!0;let n=EM(e,t,o);if(n.length===0||n.some(e=>(a.get(e)??0)<=0))return!0;for(let e of n){let t=(a.get(e)??0)-1;t>0?a.set(e,t):a.delete(e)}return!1}),c=new Map,l=new Map,u=new Set,d=TM(e),f=TM(e),p=bM(t)??bM(n)??Date.now();for(let[t,n]of s.entries()){c.set(n.eventId,n),l.set(n.eventId,t);for(let t of EM(e,n,d))u.add(t)}for(let t of n){if(_M(t,i))continue;let n=EM(e,t,f);if(!c.has(t.eventId)&&n.length>0&&n.every(e=>u.has(e)))continue;let r=c.get(t.eventId);if(r){if(!dM(r,t))continue;let e=l.get(t.eventId),n=yM(r,t);e!==void 0&&(s[e]=n),c.set(n.eventId,n)}else{p+=1;let e={...t,ts:new Date(p).toISOString()};c.set(e.eventId,e),l.set(e.eventId,s.length),s.push(e)}for(let e of n)u.add(e)}return s}function lM(e,t){let n=new Map,r=TM(e);for(let i of t)for(let t of EM(e,i,r))n.set(t,(n.get(t)??0)+1);return n}function uM(e,t,n){let r=new Map,i=new Set,a=TM(e),o=TM(e);for(let n of t){r.set(n.eventId,n);for(let t of EM(e,n,a))i.add(t)}for(let t of n){let n=EM(e,t,o);if(!(!r.has(t.eventId)&&n.length>0&&n.every(e=>i.has(e)))){r.set(t.eventId,t);for(let e of n)i.add(e)}}return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function dM(e,t){return fM(e)&&fM(t)}function fM(e){return e.type===`native.raw`?$(Q(e.payload.raw).source)===`codex.history.thread_read`:!1}function pM(e){return e===`codex.history.thread_read`||e===`codex.history.thread_read.incremental`}function mM(e){let t=Q(e.payload.raw),n=$(t.source);return t.historyReplay===!0||pM(n)}function hM(e){let t=Q(e.payload.raw),n=Q(t.item),r=Q(t.turn);if(e.type===`turn.started`||e.type===`turn.completed`||e.type===`turn.failed`)return $(t.turn_id)??$(t.turnId)??$(r.id)??$(n.turn_id)??$(n.turnId);if(e.type===`item.started`||e.type===`item.updated`||e.type===`item.completed`)return $(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId)??$(r.id);if(e.type!==`native.raw`)return;let i=$(t.source),a=Q(t.message);if(i===`codex.app_server`){let e=$(a.method),t=Q(a.params);return e===`turn/started`||e===`turn/completed`||e===`turn/failed`||e===`turn/interrupted`?$(Q(t.turn).id)??$(t.turn_id)??$(t.turnId):e===`item/started`||e===`item/updated`||e===`item/completed`?$(t.turn_id)??$(t.turnId)??$(Q(t.item).turn_id)??$(Q(t.item).turnId):void 0}if(i!==`codex.history.thread_read`)return;let o=$(a.scope);if(o===`turn`)return $(Q(a.turn).id);if(o===`item`)return $(a.turn_id)??$(Q(a.item).turn_id)}function gM(e){let t=Q(e.payload.raw);if(e.type===`turn.completed`||e.type===`turn.failed`){let n=$(t.status)??(e.type===`turn.completed`?`completed`:`failed`);return n&&mN(n)?n:void 0}if(e.type!==`native.raw`)return;let n=$(t.source),r=Q(t.message);if(n===`codex.app_server`){let e=$(r.method);if(e!==`turn/completed`&&e!==`turn/failed`&&e!==`turn/interrupted`)return;let t=$(Q(Q(r.params).turn).status)??(e===`turn/completed`?`completed`:e===`turn/interrupted`?`interrupted`:`failed`);return t&&mN(t)?t:void 0}if(n!==`codex.history.thread_read`||$(r.scope)!==`turn`)return;let i=$(Q(r.turn).status);return i&&mN(i)?i:void 0}function _M(e,t){if(!mM(e))return!1;let n=hM(e),r=gM(e);return!n||!r?!1:hN(t.terminalTurnStatusById.get(n),r)}function vM(e,t=!1){let n=new Set,r=new Map;for(let t of e){if(mM(t))continue;let e=hM(t);e&&n.add(e);let i=gM(t);e&&i&&r.set(e,i)}let i=new Set;if(t)for(let e of n)r.has(e)||i.add(e);return{activeTurnIds:i,terminalTurnStatusById:r}}function yM(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function bM(e){let t;for(let n of e){let e=Date.parse(n.ts);Number.isFinite(e)&&(t=t===void 0?e:Math.max(t,e))}return t}function xM(e,t){let n=SM(e);if(n.size===0)return e;let r=new Set(e.map(e=>e.eventId)),i=new Set;for(let e of t){if(r.has(e.eventId))continue;let t=wM(e);if(!t)continue;let a=n.get(t.text);if(!a||a.length===0)continue;let o,s=1/0;for(let e of a){if(e.consumed)continue;let n=t.tsMs-e.tsMs;if(n>3e4||n<0)continue;let r=Math.abs(n);r>=s||(o=e,s=r)}if(o){o.consumed=!0;for(let e of o.eventIds)i.add(e)}}return i.size===0?e:e.filter(e=>!i.has(e.eventId))}function SM(e){let t=new Map,n=new Map;for(let r of e){let e=CM(r);if(!e)continue;let i=t.get(e.text)??[],a=e.syntheticMessageId?`${e.text}\u0000${e.syntheticMessageId}`:``,o=a?n.get(a):void 0;if(o)o.tsMs=Math.min(o.tsMs,e.tsMs),o.eventIds.push(r.eventId);else{let t={text:e.text,tsMs:e.tsMs,eventIds:[r.eventId],consumed:!1};i.push(t),a&&n.set(a,t)}t.set(e.text,i)}return t}function CM(e){let t=Date.parse(e.ts);if(!Number.isFinite(t))return;if(e.type===`item.completed`){let n=Q(Q(e.payload.raw).item);if($(n.type)!==`user_message`||$(n.source_event_type)!==`claude.synthetic.user_input`)return;let r=LM(n);return r?{text:r,tsMs:t,syntheticMessageId:yN(n.id)??yN(n.item_id)??yN(n.itemId)}:void 0}if(e.type!==`native.raw`)return;let n=Q(e.payload.raw);if($(n.source)!==`claude.synthetic.user_input`||($(n.native_type)??$(Q(n.message).type))!==`user`)return;let r=RM(Q(Q(n.message).message));if(r)return{text:r,tsMs:t,syntheticMessageId:yN(Q(n.message).uuid)}}function wM(e){if(e.type!==`native.raw`)return;let t=Date.parse(e.ts);if(!Number.isFinite(t))return;let n=Q(e.payload.raw),r=$(n.source);if(!r||!sM.has(r))return;let i=Q(n.message);if(($(n.native_type)??$(i.type))!==`user`)return;let a=RM(Q(i.message));if(a)return{text:a,tsMs:t}}function TM(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function EM(e,t,n){return e===`codex`?DM(t,n):e===`claude`?NM(t):[]}function DM(e,t){let n=Q(e.payload.raw),r=new Set,i=PM(e.type,n);if(i){let a=OM(e.type,n);a?r.add(jM(a,t,n)):r.add(i)}if(e.type!==`native.raw`)return[...r];let a=$(n.source);if(a===`codex.app_server`){let e=Q(n.message),i=$(e.method),a=Q(e.params);if(i===`turn/started`)return r.add(FM(`turn.started`,{turn:Q(a.turn)})),[...r];if(i===`turn/completed`)return r.add(FM(`turn.completed`,{status:`completed`,turn:Q(a.turn)})),[...r];if(i===`turn/failed`||i===`turn/interrupted`)return r.add(FM(`turn.failed`,{status:i===`turn/interrupted`?`interrupted`:`failed`,turn:Q(a.turn)})),[...r];if(i===`item/started`||i===`item/updated`||i===`item/completed`){let e=i.replace(`/`,`.`),n={turn_id:$(a.turn_id)??$(a.turnId)??$(Q(a.item).turn_id),item:Q(a.item)},o=OM(e,n);return o?r.add(jM(o,t,n)):r.add(FM(e,n)),[...r]}return[...r]}if(a!==`codex.history.thread_read`)return[...r];let o=Q(n.message),s=$(o.scope);if(s===`thread`){let e=Q(o.thread),t=$(e.id);t&&r.add(FM(`thread.started`,{thread_id:t,thread:e}));let n=_N(IM(e.preview)??IM(e.name)??``);return n&&r.add(FM(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(s===`turn`){let e=Q(o.turn),t=$(e.status);return r.add(FM(`turn.started`,{turn:e})),t===`completed`?r.add(FM(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(FM(`turn.failed`,{status:t,turn:e})),[...r]}if(s===`item`){let e={turn_id:$(o.turn_id)??$(Q(o.item).turn_id),item:Q(o.item)},n=OM(`item.completed`,e);return n?r.add(jM(n,t,e)):r.add(FM(`item.completed`,e)),[...r]}return[...r]}function OM(e,t){if(!e.startsWith(`item.`))return;let n=Q(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=kM($(n.type));if(!(!r||!i))return[`codex`,e,r,i,AM(i,$(n.phase)),$(n.status)??``,YM($(n.command)),YM(LM(n))].join(`|`)}function kM(e){if(!e)return;let t=e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase();return t.length>0?t:void 0}function AM(e,t){return e===`agent_message`&&(!t||t===`final_answer`)?``:t??``}function jM(e,t,n){let r=MM(n);if(r!==void 0)return`${e}|${r}`;let i=t?.codexTurnScopedItemOccurrences;if(!i)return e;let a=(i.get(e)??0)+1;return i.set(e,a),`${e}|${a}`}function MM(e){if(!e)return;let t=e.semantic_occurrence??e.semanticOccurrence;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return t;if(typeof t==`string`){let e=Number.parseInt(t,10);if(Number.isInteger(e)&&e>0)return e}}function NM(e){let t=Q(e.payload.raw),n=PM(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!sM.has(r))return[];let i=Q(t.message),a=$(t.native_type)??$(i.type),o=Q(i.message);if(a===`user`){let e=RM(o),t=$(i.uuid);return!e||!t?[]:[FM(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=RM(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[FM(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function PM(e,t){switch(e){case`thread.started`:case`thread.title.updated`:case`turn.started`:case`turn.completed`:case`turn.failed`:case`item.started`:case`item.updated`:case`item.completed`:return FM(e,t);default:return}}function FM(e,t){let n=Q(t.item),r=Q(t.turn),i=Q(t.thread),a=$(n.id)??``,o=$(t.turn_id)??$(t.turnId)??$(r.id)??$(n.turn_id)??``,s=$(r.status)??$(t.status)??``,c=$(t.thread_id)??$(t.threadId)??$(i.id)??``,l=$(n.type)??``,u=$(n.phase)??``,d=$(n.status)??``,f=YM($(n.command)),p=YM(LM(n)),m=YM(IM(t.message)),h=YM(IM(t.title));return e.startsWith(`item.`)?[e,a,l,u,d,f,p||m].join(`|`):e.startsWith(`turn.`)?[e,o,s].join(`|`):e===`thread.title.updated`?[e,c,h].join(`|`):[e,c,o,a,l,h||m].join(`|`)}function Q(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function IM(e){if(typeof e==`string`)return e.length>0?e:void 0}function LM(e){let t=IM(e.text);if(t)return t;let n=Array.isArray(e.content)?e.content:[];if(n.length>0){let e=[];for(let t of n){let n=IM(Q(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
522
|
+
`)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>IM(e)).filter(e=>!!e);if(e.length>0)return e.join(`
|
|
523
|
+
`)}return``}function RM(e){let t=$(e.content);if(t)return t;let n=$(e.text)??$(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`){let t=e.trim();t&&i.push(t);continue}let t=Q(e),n=$(t.type);if(n&&n!==`text`)continue;let r=$(t.text)??$(t.content);r&&i.push(r)}if(i.length!==0)return i.join(`
|
|
524
|
+
`)}function zM(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function BM(e){return String(e).includes(`returned no messages from getSessionMessages`)}function VM(e){return $j(e)}function HM(e){return e?{rawSeq:e.rawSeq,type:e.type,eventId:e.eventId,ts:e.ts}:null}function UM(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(!WM(n,i))return r}return e.length===t.length?null:n}function WM(e,t){return qM(GM(e))===qM(GM(t))}function GM(e){let{ts:t,...n}=e;return n}function KM(e){if(typeof e==`string`)return JM(e);if(Array.isArray(e))return e.map(e=>KM(e));if(!e||typeof e!=`object`)return e;let t=e,n={};for(let e of Object.keys(t).sort())n[e]=KM(t[e]);return n}function qM(e){return JSON.stringify(KM(e))}function JM(e){return e.length<=4096?e:{__type:`hashed_text`,length:e.length,sha256:(0,l.createHash)(`sha256`).update(e).digest(`hex`)}}function YM(e){if(!e)return``;let t=JM(e);return typeof t==`string`?t:`sha256:${t.length}:${t.sha256}`}function XM(e,t,n,r){if(!n.historyUpdated)return`unchanged`;if(n.refreshMode===`delta`)return`append_only_delta`;if(t.length<e.length)return`history_shrunk`;let i=Math.min(e.length,t.length);return r!==null&&r<i?`prefix_rewrite`:`snapshot_fallback`}function ZM(e){let t=e.previousEvents[e.previousEvents.length-1]?.rawSeq??null,n=e.nextEvents[e.nextEvents.length-1]?.rawSeq??null,r=UM(e.previousEvents,e.nextEvents),i=r??Math.min(e.previousEvents.length,e.nextEvents.length);return{projectId:e.projectId,sessionId:e.sessionId,provider:e.session.provider,source:e.session.source,providerMode:e.session.providerMode,decision:e.classification.refreshMode,reason:XM(e.previousEvents,e.nextEvents,e.classification,r),historyUpdated:e.classification.historyUpdated,fromRawSeq:e.classification.fromRawSeq??null,toRawSeq:e.classification.toRawSeq??null,previousEventCount:e.previousEvents.length,nextEventCount:e.nextEvents.length,sharedPrefixCount:i,appendedCount:Math.max(0,e.nextEvents.length-e.previousEvents.length),firstMismatchIndex:r,previousLastRawSeq:t,nextLastRawSeq:n,previousMismatchEvent:HM(r===null?void 0:e.previousEvents[r]),nextMismatchEvent:HM(r===null?void 0:e.nextEvents[r])}}function QM(e,t){let n=e[e.length-1]?.rawSeq,r=t[t.length-1]?.rawSeq;return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&WM(e,r)})?{historyUpdated:!1,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}:t.length>e.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&WM(e,r)})?{historyUpdated:!0,refreshMode:`delta`,fromRawSeq:n??0,toRawSeq:r??n??0}:{historyUpdated:!0,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}}function $M(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,n+=1,new Date(n).toISOString()),a=(n,a)=>{let o=t.length+1;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:o,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:lN(e.sessionId,r,a),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};a({scope:`thread`,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo}},[`thread`,e.thread.id,e.thread.updatedAt]);for(let t of e.thread.turns){let n=e.localCodexLiveTurnState?e.localCodexLiveTurnState.terminalTurnStatusById.has(t.id)||e.localCodexLiveTurnState.activeTurnIds.has(t.id):!1,r=e.localCodexLiveTurnState?.terminalTurnStatusById.get(t.id);(mN(t.status)?!hN(r,t.status):!n)&&a({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}},[`turn`,t.id,t.status]);for(let n of t.items)a({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,yN(n.id)??null])}return t}function eN(e){let t=tN(e.localEvents);if(!t.hasHistoryReplay||!t.hasThreadEnvelope)return null;let n=e.thread.turns.map(e=>e.id);if(t.turnOrder.length>n.length)return null;for(let[e,r]of t.turnOrder.entries())if(n[e]!==r)return null;let r=[],i=Math.max(bM(e.localEvents)??0,e.thread.updatedAt>0?e.thread.updatedAt*1e3:Date.now()),a=0,o=()=>(a+=1,i+=1,new Date(i).toISOString()),s=(t,n)=>{r.push({v:`1.0`,kind:`provider.raw`,rawSeq:r.length+1,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:lN(e.sessionId,a,n),ts:o(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:t,historyReplay:!0,replaySynthetic:!0}}})},c=t.turnOrder.length-1;for(let[n,r]of e.thread.turns.entries()){let i=t.turnsById.get(r.id);if(!i){s({scope:`turn`,thread_id:e.thread.id,turn:{id:r.id,status:r.status,error:r.error}},[`turn`,r.id,r.status]);for(let t of r.items)s({scope:`item`,thread_id:e.thread.id,turn_id:r.id,item:t},[`item`,r.id,yN(t.id)??null]);continue}let a=n!==c,o=rN(i,r);if(!o.safe||a&&(o.appendedItems.length>0||o.statusChanged))return null;if(!a){o.statusChanged&&s({scope:`turn`,thread_id:e.thread.id,turn:{id:r.id,status:r.status,error:r.error}},[`turn`,r.id,r.status]);for(let t of o.appendedItems)s({scope:`item`,thread_id:e.thread.id,turn_id:r.id,item:t},[`item`,r.id,yN(t.id)??null])}}return r}function tN(e){let t={hasHistoryReplay:!1,hasThreadEnvelope:!1,turnOrder:[],turnsById:new Map};for(let n of e){if(n.type!==`native.raw`)continue;let e=Q(n.payload.raw);if($(e.source)!==`codex.history.thread_read`)continue;let r=Q(e.message),i=$(r.scope);if(t.hasHistoryReplay=!0,i===`thread`){t.hasThreadEnvelope=!0;continue}if(i===`turn`){let e=Q(r.turn),n=$(e.id);if(!n)continue;let i=nN(t,n),a=$(e.status);a&&(i.status=a),i.fingerprint=sN(e);continue}if(i!==`item`)continue;let a=Q(r.item),o=$(r.turn_id)??$(a.turn_id);if(!o)continue;let s=nN(t,o),c=iN(o,a,void 0,s.itemOccurrenceByBaseKey);c&&(s.itemFingerprintByKey.has(c)||s.itemOrder.push(c),s.itemFingerprintByKey.set(c,oN(a)))}return t}function nN(e,t){let n=e.turnsById.get(t);if(n)return n;let r={itemOrder:[],itemFingerprintByKey:new Map,itemOccurrenceByBaseKey:new Map};return e.turnsById.set(t,r),e.turnOrder.push(t),r}function rN(e,t){if(t.items.length<e.itemOrder.length)return{safe:!1,appendedItems:[],statusChanged:!1};let n=new Map;for(let[r,i]of e.itemOrder.entries()){let a=t.items[r];if(!a||iN(t.id,a,r,n)!==i||e.itemFingerprintByKey.get(i)!==oN(a))return{safe:!1,appendedItems:[],statusChanged:!1}}return e.fingerprint!==void 0&&e.fingerprint!==sN(t)&&(e.status??``)===t.status?{safe:!1,appendedItems:[],statusChanged:!1}:{safe:!0,appendedItems:t.items.slice(e.itemOrder.length),statusChanged:(e.status??``)!==t.status}}function iN(e,t,n,r){let i=aN(e,t,n);if(!i)return;if(!r)return i;let a=(r.get(i)??0)+1;return r.set(i,a),`${i}|${a}`}function aN(e,t,n){let r=OM(`item.completed`,{turn_id:e,item:t});if(r)return r;let i=yN(t.id);if(i)return`id:${i}`;if(n!==void 0)return`${e}::${n}`}function oN(e){let t=kM($(e.type)),n=t?AM(t,$(e.phase)):$(e.phase),r={};for(let[i,a]of Object.entries(e))if(!(i===`id`||i===`turn_id`||i===`turnId`)){if(i===`type`){t&&(r.type=t);continue}if(i===`phase`){n&&(r.phase=n);continue}r[i]=a}return t&&r.type===void 0&&(r.type=t),qM(r)}function sN(e){return qM({status:$(e.status)??null,error:Q(e.error)})}function cN(e){return String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``)}function lN(e,t,n){let r=n.map(cN).filter(e=>e.length>0);return r.length===0?`raw_hist_codex_${e}_${t.toString().padStart(6,`0`)}`:`raw_hist_codex_${e}_${r.join(`_`)}`}function uN(e){let t=e.localCodexLiveTurnState??vM(e.localEvents),n=new Set,r=dN(e.localEvents),i=new Map,a=0,o=1;for(let t of e.localEvents){let e=Date.parse(t.ts);Number.isFinite(e)&&(a=Math.max(a,e)),o=Math.max(o,t.rawSeq+1);let r=Q(t.payload.raw),s=$(r.source),c=s===`codex.history.thread_read.incremental`;if(t.type===`turn.started`){let e=$(r.turn_id)??$(Q(r.turn).id);e&&!c&&n.add(e);continue}if(t.type===`turn.completed`||t.type===`turn.failed`){let e=$(r.turn_id)??$(Q(r.turn).id);if(!e)continue;c||n.add(e);let a=$(r.status)??(t.type===`turn.completed`?`completed`:`failed`);i.set(e,a)}if(t.type!==`native.raw`||s!==`codex.history.thread_read`)continue;let l=Q(r.message);if($(l.scope)===`turn`){let e=Q(l.turn),t=$(e.id);if(!t)continue;let n=$(e.status);n&&mN(n)&&i.set(t,n);continue}}let s=Math.max(a,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),c=0,l=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),u=t=>{let n=t.map(l).filter(e=>e.length>0);return n.length===0?`raw_sync_codex_${e.sessionId}_${o.toString().padStart(6,`0`)}`:`raw_sync_codex_${e.sessionId}_${n.join(`_`)}`},d=()=>(c+=1,new Date(s+c).toISOString()),f=[],p=(t,n,r)=>{let i=d();f.push({v:`1.0`,kind:`provider.raw`,rawSeq:o,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:u(r),ts:i,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),o+=1};for(let a of e.thread.turns){let e=i.get(a.id),s=hN(e,a.status);!(n.has(a.id)||t.activeTurnIds.has(a.id))&&!s&&p(`turn.started`,{type:`turn.started`,turn:{id:a.id,status:a.status,items:[],error:a.error}},[`turn_started`,a.id]);let c=new Map;for(let e of a.items){let t=$(e.id),n=iN(a.id,e,void 0,c);if(n&&r.has(n))continue;let i=n?fN(n):void 0;p(`item.completed`,{type:`item.completed`,turn_id:a.id,item:e,...i?{semantic_occurrence:i}:{}},[`item_completed`,a.id,t??`seq_${o}`])}if(mN(a.status)&&e!==a.status){if(a.status===`completed`){p(`turn.completed`,{type:`turn.completed`,status:a.status,turn:{id:a.id,status:a.status,items:[],error:a.error}},[`turn_terminal`,a.id]);continue}p(`turn.failed`,{type:`turn.failed`,status:a.status,turn:{id:a.id,status:a.status,items:[],error:a.error},...a.error?{error:a.error}:{}},[`turn_terminal`,a.id])}}return f}function dN(e){let t=new Set,n=new Map;for(let r of e){let e=pN(r);if(!e)continue;let i=iN(e.turnId,e.item,void 0,n);i&&t.add(i)}return t}function fN(e){let t=e.lastIndexOf(`|`);if(t<0||t===e.length-1)return;let n=Number.parseInt(e.slice(t+1),10);return Number.isInteger(n)&&n>0?n:void 0}function pN(e){let t=Q(e.payload.raw);if(e.type===`item.completed`){let e=Q(t.item),n=$(t.turn_id)??$(t.turnId)??$(e.turn_id)??$(e.turnId);return!n||Object.keys(e).length===0?null:{turnId:n,item:e}}if(e.type!==`native.raw`)return null;let n=$(t.source);if(n===`codex.app_server`){let e=Q(t.message);if($(e.method)!==`item/completed`)return null;let n=Q(e.params),r=Q(n.item),i=$(n.turn_id)??$(n.turnId)??$(r.turn_id)??$(r.turnId);return!i||Object.keys(r).length===0?null:{turnId:i,item:r}}if(n===`codex.history.thread_read`){let e=Q(t.message);if($(e.scope)!==`item`)return null;let n=Q(e.item),r=$(e.turn_id)??$(n.turn_id)??$(n.turnId);return!r||Object.keys(n).length===0?null:{turnId:r,item:n}}return null}function mN(e){return e===`completed`||e===`failed`||e===`interrupted`}function hN(e,t){return e===t&&mN(t)}function gN(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function _N(e,t=60){let n=gN(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function vN(e,t){if(t){let e=_N(t);if(e)return e}if(e.provider!==`codex`||!e.codex)return _N(`代码审查`);let n=e.codex.target;return n.type===`baseBranch`?_N(`审查 ${n.branch} 分支改动`):n.type===`custom`?_N(n.instructions):n.type===`commit`?_N(n.title||`审查提交 ${n.sha.slice(0,12)}`):_N(`审查未提交更改`)}function yN(e){if(typeof e!=`string`)return;let t=gN(e);if(t)return t}function bN(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function xN(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function SN(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var CN=class{indexPath;eventsDir;sessions=new Map;rawEventsCacheBySession=new Map;compactedRawEventsCacheBySession=new Map;pendingRawMutationsBySession=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`session-index.json`),this.eventsDir=p.default.join(e,`session-events`),this.ready=this.loadFromDisk()}async init(){await this.ready}async flushRawCompactions(e){await this.ready}async shutdown(){await this.ready}async upsertSession(e){await this.ready;let t=wN(e),n=this.sessions.get(t.id);this.sessions.set(t.id,{...n,...t}),await this.enqueueWrite(async()=>{await this.persistIndex()})}async patchSession(e,t){await this.ready;let n=this.sessions.get(e);return n?(this.sessions.set(e,wN({...n,...t})),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async setSessionStatus(e,t,n){await this.ready;let r=this.sessions.get(e);r&&(this.sessions.set(e,{...r,status:t,updatedAt:n,interactionLockReason:void 0,pendingApprovals:t===`running`?r.pendingApprovals:0,pendingUserInputs:t===`running`?r.pendingUserInputs:0,pendingActions:t===`running`?r.pendingActions:0}),await this.enqueueWrite(async()=>{await this.persistIndex()}))}async removeSession(e){if(await this.ready,!this.sessions.has(e))return;this.sessions.delete(e),this.rawEventsCacheBySession.delete(e),this.compactedRawEventsCacheBySession.delete(e);let t=p.default.join(this.eventsDir,`${e}.jsonl`),n=p.default.join(this.eventsDir,`${e}.raw.jsonl`);await this.enqueueWrite(async()=>{await Promise.all([this.persistIndex(),d.default.rm(t,{force:!0}),d.default.rm(n,{force:!0})])})}hasSession(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}getProjectSession(e,t){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return n}listSessions(e=`all`){return[...this.sessions.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessions(e,t=`all`){return this.listSessions(t).filter(t=>t.projectId===e)}async appendRawEvent(e){await this.ready;let t=this.normalizeRawEventProjectIdentity(e);this.sessions.has(t.sessionId)&&(UN(t)||await this.enqueueRawSessionWrite(t.sessionId,async()=>{if(FN(t)){let e=HN([...await this.readSessionRawEventsLocked(t.sessionId),t]);await this.replaceRawEventFile(t.sessionId,e),this.rawEventsCacheBySession.set(t.sessionId,e),this.compactedRawEventsCacheBySession.set(t.sessionId,AN(e));return}await this.appendRawEventLine(t),this.appendRawEventToCache(t)}))}async mergeSessionRawEvents(e,t,n){if(await this.ready,!this.sessions.has(e))return[];let r=t.filter(t=>t.sessionId===e).map(e=>this.normalizeRawEventProjectIdentity(e)),i=[];return await this.enqueueRawSessionWrite(e,async()=>{let t=IN(await this.readSessionRawEventsLocked(e),r,n);await this.replaceRawEventFile(e,t);let a=AN(t);i=jN(a),this.rawEventsCacheBySession.set(e,t),this.compactedRawEventsCacheBySession.set(e,a)}),i}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionStoredRawEvents(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsLocked(e)).slice(-n)}),i}async getSessionRawEventsCompacted(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsCompactedFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),i}async getSessionRawEventsSinceSeq(e,t,n=2e3){if(await this.ready,!this.sessions.has(e))return[];let r=Math.max(1,n),i=this.readSessionRawEventsFromCache(e);if(i!==void 0)return Pp(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=Pp((await this.readSessionRawEventsLocked(e)).filter(e=>e.rawSeq>t)).slice(0,r)}),a}async getSessionRawSeqRange(e){if(await this.ready,!this.sessions.has(e))return null;let t=this.readSessionRawEventsFromCache(e);if(t!==void 0)return ON(t);let n=null;return await this.enqueueWrite(async()=>{n=ON(await this.readSessionRawEventsLocked(e))}),n}async loadFromDisk(){await d.default.mkdir(this.eventsDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.sessions))return;for(let e of t.sessions)if(e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath){if(e.projectId!==e.projectPath)throw Error(`Legacy session project ids are no longer supported in ${this.indexPath}; clear the session history store and restart the gateway.`);this.sessions.set(e.id,{...e,status:`idle`,interactionLockReason:void 0,pendingApprovals:0,pendingUserInputs:0,pendingActions:0})}}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,sessions:[...this.sessions.values()].sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}async enqueueRawSessionWrite(e,t){this.incrementPendingRawMutation(e);try{let e;return await this.enqueueWrite(async()=>{e=await t()}),e}finally{this.decrementPendingRawMutation(e)}}async appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${DN(e)}\n`;await d.default.appendFile(t,n,`utf8`)}async replaceRawEventFile(e,t){let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r=t.map(e=>DN(e)).join(`
|
|
525
|
+
`);await kN(n,r?`${r}\n`:``)}appendRawEventToCache(e){let t=this.rawEventsCacheBySession.get(e.sessionId),n=t?.[t.length-1];t&&t.push(e);let r=this.compactedRawEventsCacheBySession.get(e.sessionId);if(r){if(PN(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&NN(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}MN(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return jN(t);let n=AN(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),jN(n)}async readSessionRawEventsLocked(e){let t=this.rawEventsCacheBySession.get(e);if(t)return t;let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r;try{r=await d.default.readFile(n,`utf8`)}catch(t){if(t.code===`ENOENT`)return this.rawEventsCacheBySession.set(e,[]),[];throw t}let i=r.split(`
|
|
526
|
+
`).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!TN(t)||t.kind!==`provider.raw`)continue;let n=EN(t.rawSeq);a.push({value:t,...n===void 0?{}:{rawSeq:n}})}catch{}if(a.length===0)return this.rawEventsCacheBySession.set(e,[]),[];let o=a.some(e=>e.rawSeq===void 0),s=a.map((e,t)=>({...e.value,rawSeq:e.rawSeq??t+1})),c=[];for(let t of s){let n=Gc.safeParse(t);if(n.success){let t=this.normalizeRawEventProjectIdentity(n.data);if(t.projectId!==n.data.projectId)throw Error(`Legacy raw event project ids are no longer supported for session ${e}; clear the session history store and restart the gateway.`);c.push(t)}}if(o){let e=c.map(e=>DN(e)).join(`
|
|
527
|
+
`),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}normalizeRawEventProjectIdentity(e){let t=this.sessions.get(e.sessionId);return!t||!t.projectId||e.projectId===t.projectId?e:{...e,projectId:t.projectId}}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return jN(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=AN(n);return this.compactedRawEventsCacheBySession.set(e,r),jN(r)}incrementPendingRawMutation(e){this.pendingRawMutationsBySession.set(e,(this.pendingRawMutationsBySession.get(e)??0)+1)}decrementPendingRawMutation(e){let t=(this.pendingRawMutationsBySession.get(e)??0)-1;if(t>0){this.pendingRawMutationsBySession.set(e,t);return}this.pendingRawMutationsBySession.delete(e)}hasPendingRawMutation(e){return(this.pendingRawMutationsBySession.get(e)??0)>0}};function wN(e){let t=e.projectPath?.trim()||e.projectId;return t===e.projectId?e:{...e,projectId:t}}function TN(e){return typeof e==`object`&&!!e}function EN(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function DN(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n})}function ON(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function kN(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{await d.default.writeFile(n,t,`utf8`),await d.default.rename(n,e)}catch(e){try{await d.default.rm(n,{force:!0})}catch{}throw e}}function AN(e){let t=Np(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ip(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function jN(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function MN(e,t){let n=Ip(t);if(!n){e.slots.push(t),e.dense=null;return}let r=e.indexByKey.get(n.key);if(r===void 0){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let i=e.slots[r];if(!i){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let a=Lp(i,t);if(!a){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}e.slots[r]=null,e.slots.push(a),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null}function NN(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function PN(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=TN(e.payload.raw)?e.payload.raw:{},n=TN(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function FN(e){if(PN(e)||e.type===`turn.completed`||e.type===`turn.failed`)return!0;if(e.type!==`native.raw`)return!1;let t=TN(e.payload.raw)?e.payload.raw:{},n=TN(t.message)?t.message:{},r=typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``;return r===`turn/completed`||r===`turn/failed`||r===`turn/interrupted`}function IN(e,t,n){if(n?.replaceMissing)return LN(e,t,n);let r=[...e].sort(VN),i=new Map,a=1;for(let[e,t]of r.entries())i.set(t.eventId,e),a=Math.max(a,t.rawSeq+1);for(let e of t){let t=i.get(e.eventId);if(t!==void 0){let n=r[t];n&&RN(n,e)&&(r[t]=BN(n,e));continue}let n={...e,rawSeq:a};a+=1,i.set(n.eventId,r.length),r.push(n)}return HN(r.sort(VN)).sort(VN)}function LN(e,t,n){let r=new Map(e.map(e=>[e.eventId,e])),i=new Set(t.map(e=>e.eventId)),a=n?.baseEventIds?new Set(n.baseEventIds):null,o=a?e.filter(e=>!a.has(e.eventId)&&!i.has(e.eventId)):[],s=[...t,...o].sort(VN),c=1;for(let t of e)c=Math.max(c,t.rawSeq+1);return HN(s.map(e=>{let t=r.get(e.eventId);if(t)return RN(t,e)?BN(t,e):{...e,rawSeq:t.rawSeq};let n={...e,rawSeq:c};return c+=1,n})).sort(VN)}function RN(e,t){return zN(e)&&zN(t)}function zN(e){return e.type===`native.raw`?JN((TN(e.payload.raw)?e.payload.raw:{}).source)===`codex.history.thread_read`:!1}function BN(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function VN(e,t){let n=e.rawSeq-t.rawSeq;if(n!==0)return n;let r=e.ts.localeCompare(t.ts);return r===0?e.eventId.localeCompare(t.eventId):r}function HN(e){let t=Fp(e).filter(e=>!UN(e)),n=new Set;for(let e of t){let t=WN(e);t&&n.add(t)}return n.size===0?t:t.filter(e=>{let t=GN(e);return!t||!n.has(t)})}function UN(e){if(e.type!==`native.raw`)return!1;let t=TN(e.payload.raw)?e.payload.raw:{};if(JN(t.source)!==`codex.app_server`)return!1;let n=TN(t.message)?t.message:{};return JN(n.method)??JN(t.method)?!1:TN((TN(n.result)?n.result:{}).turn)}function WN(e){if(e.type===`item.completed`){let t=TN(e.payload.raw)?e.payload.raw:{},n=TN(t.item)?t.item:{};return KN(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=TN(e.payload.raw)?e.payload.raw:{},n=TN(t.message)?t.message:{},r=TN(n.params)?n.params:{};if((JN(n.method)??JN(t.method))!==`item/completed`)return null;let i=TN(r.item)?r.item:{};return KN(e.sessionId,i)}function GN(e){if(e.type===`item.updated`){let t=TN(e.payload.raw)?e.payload.raw:{},n=TN(t.item)?t.item:{},r=JN(n.original_method)??JN(n.originalMethod)??``,i=TN(n.payload)?n.payload:{};return!(typeof i.delta==`string`||typeof i.output_delta==`string`||typeof i.outputDelta==`string`||typeof n.output_delta==`string`||typeof n.outputDelta==`string`||typeof n.text==`string`)&&!qN(r)?null:KN(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=TN(e.payload.raw)?e.payload.raw:{},n=TN(t.message)?t.message:{},r=TN(n.params)?n.params:{};if(!qN(JN(n.method)??JN(t.method)??``))return null;let i=TN(r.msg)?r.msg:{},a=JN(r.itemId)??JN(r.item_id)??JN(i.itemId)??JN(i.item_id);return a?`${e.sessionId}|${a}`:null}function KN(e,t){let n=JN(t.id)??JN(t.item_id)??JN(t.itemId);return n?`${e}|${n}`:null}function qN(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function JN(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function YN(e){return!e||e.providerMode!==`native`?!1:e.interactionLockReason===`external_turn_running`?!0:e.status!==`running`}function XN(e,t){if(e&&e!==t)throw pw()}async function ZN(e){let t=QN(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:$N(t)},`auth refresh attempt`);try{let t=await e.execute(),n=QN(e.authService,e.refreshToken),r=QN(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:$N(n),nextRefreshToken:$N(r)},`auth refresh succeeded`),t}catch(t){let n=QN(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:$N(n),error:eP(t)},`auth refresh failed`),t}}function QN(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function $N(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:tP(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:tP(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function eP(e){return cw(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function tP(e){return e?e.slice(-8):null}function nP(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:rP(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:om(e.identity,e.privateKeyPem,i)}}function rP(e){return e.replace(/\s+/gu,``).toUpperCase()}async function iP(e,t){try{let n=Yd.parse(e);switch(n.method){case`auth.refresh`:{let e=await ZN({authService:t.authService,execute:()=>t.authService.refreshAccessToken(n.params.refreshToken),logger:t.logger,refreshToken:n.params.refreshToken,requestedDeviceId:n.params.deviceId??t.relayDeviceId,source:`relay_rpc`});return XN(n.params.deviceId??t.relayDeviceId,e.deviceId),Xd.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Xd.parse({method:n.method,result:{projects:e}})}case`codex.accounts.get`:{let e=await t.sessionManager.getCodexAccounts();return Xd.parse({method:n.method,result:e})}case`codex.accounts.save`:{let e=await t.sessionManager.saveCurrentCodexAccount();return Xd.parse({method:n.method,result:e})}case`codex.accounts.switch`:{let e=await t.sessionManager.switchCodexAccount(n.params.accountId);return Xd.parse({method:n.method,result:e})}case`gateway.settings.get`:return Xd.parse({method:n.method,result:t.gatewaySettings.get()});case`gateway.settings.update`:{let e=await t.gatewaySettings.update(n.params);return Xd.parse({method:n.method,result:e})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Xd.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return Xd.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Xd.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Xd.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Xd.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Xd.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw oP(n.method,`NOT_FOUND`,404,`Project not found`);return Xd.parse({method:n.method,result:{removed:!0}});case`workspace.directories.list`:{let e=await t.fsService.listDirectoriesUnrestricted(n.params.path,n.params.limit??200);return Xd.parse({method:n.method,result:e})}case`workspace.directories.create`:{let e=await t.fsService.createDirectoryUnrestricted(n.params.path,n.params.name,200);return Xd.parse({method:n.method,result:e})}case`workspace.entries.list`:{let e=await t.workspaceFileService.listEntries(n.params.locator,n.params.limit??200);return Xd.parse({method:n.method,result:e})}case`workspace.files.resolve`:{let e=await t.workspaceFileService.resolveFile(n.params.locator);return Xd.parse({method:n.method,result:e})}case`workspace.files.readText`:{let e=await t.workspaceFileService.readTextFile(n.params.locator,{startLine:n.params.startLine,maxLines:n.params.maxLines,maxBytes:n.params.maxBytes});return Xd.parse({method:n.method,result:e})}case`workspace.files.preparePreview`:{let e=t.relayPreviewBaseUrl?.trim(),r=t.gatewayId?.trim();if(!e||!r)throw oP(n.method,`BAD_REQUEST`,400,`Relay preview base url is not configured`);let i=await t.workspaceFileService.preparePreview(n.params.locator,{deviceId:t.relayDeviceId,disposition:n.params.disposition,buildPreviewUrl:t=>`${e.replace(/\/+$/,``)}/api/gateways/${encodeURIComponent(r)}/workspace/files/content/${encodeURIComponent(t)}`});return Xd.parse({method:n.method,result:i})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return Xd.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Xd.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw oP(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Xd.parse({method:n.method,result:{session:e}})}case`sessions.config.get`:{let e=await t.sessionManager.getProjectSessionConfig(n.params.projectId,n.params.sessionId);if(!e)throw oP(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Xd.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return e.historyUpdated&&await t.refreshDetailSessionSnapshots?.({projectId:n.params.projectId,sessionId:n.params.sessionId,reason:`explicit_history_sync`,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}),Xd.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged,refreshMode:e.refreshMode,...e.fromRawSeq===void 0?{}:{fromRawSeq:e.fromRawSeq},...e.toRawSeq===void 0?{}:{toRawSeq:e.toRawSeq}}})}case`sessions.rawEvents.list`:{let e=n.params.limit===`all`?2**53-1:n.params.limit,r=await t.buildRawEventsListResult({sessionManager:t.sessionManager,projectId:n.params.projectId,sessionId:n.params.sessionId,limit:e,fromRawSeqExclusive:n.params.fromRawSeqExclusive,detailLevel:n.params.detailLevel,requestSource:`rpc`});return Xd.parse({method:n.method,result:r})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),Xd.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Xd.parse({method:n.method,result:e})}case`devices.list`:return Xd.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw oP(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Xd.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw oP(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw aP(e)}}function aP(e){if(cw(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return oP(`UNAUTHORIZED`,e.status,String(e),e.details);case`PROJECT_NOT_FOUND`:case`DISCOVERED_PROJECT_NOT_FOUND`:case`PROJECT_SESSION_NOT_FOUND`:case`SESSION_NOT_FOUND`:case`CODEX_ACCOUNT_NOT_FOUND`:return oP(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return oP(`BAD_REQUEST`,e.status,String(e),e.details);default:return oP(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Qd.safeParse(e);if(t.success)return t.data;let n=Zd.safeParse(e);if(n.success)return oP(void 0,n.data.code,n.data.status,n.data.message,n.data.details);if(e&&typeof e==`object`&&`code`in e&&`status`in e&&`message`in e&&typeof e.code==`string`&&typeof e.status==`number`&&typeof e.message==`string`){let t=e;return oP(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?oP(`BAD_REQUEST`,400,r):sP(e)?oP(`UNAUTHORIZED`,401,r):cP(r)?oP(`BAD_REQUEST`,400,r):oP(`INTERNAL`,500,r)}function oP(e,t,n,r,i){let a=typeof t==`string`,o=a?e:void 0,s=a?t:e,c=a?n:t,l=a?r:n,u=a?i:r;return Qd.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function sP(e){return cw(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||Ow(e)}function cP(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}function lP(e,t){return e.length===0?[]:t===void 0?[...e]:e.filter(e=>e.rawSeq>t)}function uP(e){return{baseRawEvents:Np(e.rawEvents.filter(t=>t.rawSeq<=e.cursorRawSeq)),nextRawEvents:Np(e.rawEvents)}}function dP(e,t){return t&&`kind`in t&&t.kind===`bootstrapping`?t:{kind:`bootstrapping`,sessionId:e,previousReadyState:t??null,queuedEnvelopes:[]}}function fP(e,t){let n=e.previousReadyState;if(!n)return{previousReadyState:null,nextReadyState:null,replayedEnvelopes:[]};let r=lP(e.queuedEnvelopes,n.rawEvents[n.rawEvents.length-1]?.rawSeq),i=n;for(let e of r)i=t(i,e);return{previousReadyState:n,nextReadyState:i,replayedEnvelopes:r}}function pP(e){return{v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${ow(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}}function mP(e){return{v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events},...e.timelineItems?{readable:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,...e.timelineItems?{timelineItems:e.timelineItems}:{}}}:{}}}}function hP(e){return{v:`1.0`,kind:`session.readable.snapshot.chunk`,type:`session.readable.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`readable_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{readable:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,timelineItems:e.timelineItems,...e.pendingApprovals?{pendingApprovals:e.pendingApprovals}:{},...e.pendingUserInputs?{pendingUserInputs:e.pendingUserInputs}:{},...e.contextUsage===void 0?{}:{contextUsage:e.contextUsage}}}}}function gP(e){return{v:`1.0`,kind:`session.readable.delta`,type:`session.readable.delta`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`readable_delta_${e.sessionId}_${e.toRawSeq}`,ts:new Date().toISOString(),payload:{readable:{...e.fromRawSeq===void 0?{}:{fromRawSeq:e.fromRawSeq},toRawSeq:e.toRawSeq,timelineUpserts:e.timelineUpserts,timelineRemovals:e.timelineRemovals,...e.timelineTextDeltaPatches&&e.timelineTextDeltaPatches.length>0?{timelineTextDeltaPatches:e.timelineTextDeltaPatches}:{},...e.pendingApprovalUpserts&&e.pendingApprovalUpserts.length>0?{pendingApprovalUpserts:e.pendingApprovalUpserts}:{},...e.pendingApprovalRemovals&&e.pendingApprovalRemovals.length>0?{pendingApprovalRemovals:e.pendingApprovalRemovals}:{},...e.pendingUserInputUpserts&&e.pendingUserInputUpserts.length>0?{pendingUserInputUpserts:e.pendingUserInputUpserts}:{},...e.pendingUserInputRemovals&&e.pendingUserInputRemovals.length>0?{pendingUserInputRemovals:e.pendingUserInputRemovals}:{},...e.sessionSummary?{sessionSummary:e.sessionSummary}:{},...e.contextUsage===void 0?{}:{contextUsage:e.contextUsage}}}}}function _P(e){return{v:`1.0`,kind:`session.external.update`,type:`session.external.update`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`session_external_update_${ow(12)}`,ts:new Date().toISOString(),payload:{raw:{updatedAt:e.updatedAt,status:e.status,interactionLockReason:e.interactionLockReason,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged}}}}function vP(e,t){if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}const yP=1e3,bP=(e,t)=>`${e}::${t}`,xP=e=>e.purpose===`detail_view`&&e.bootstrapMode===`readable`,SP=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},CP=e=>({kind:`ready`,sessionId:e.target.sessionId,projectId:e.target.projectId,provider:e.target.provider,detailLevel:e.target.detailLevel,preserveIncompleteCommandOutput:e.preserveIncompleteCommandOutput??!1,rawEvents:[...e.rawEvents],projectionRawEvents:[...e.projectionRawEvents??e.rawEvents],contextUsage:e.contextUsage??null,timelineItems:[...e.timelineItems],pendingApprovals:[...e.pendingApprovals],pendingUserInputs:[...e.pendingUserInputs]}),wP=e=>typeof e==`object`&&e?e:{},TP=(e,...t)=>{for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}},EP=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=wP(n),r=TP(e,`id`),i=TP(e,`header`),a=TP(e,`question`);if(!r||!i||!a)continue;let o=Array.isArray(e.options)?e.options.map(e=>{let t=wP(e),n=TP(t,`label`);if(!n)return null;let r=TP(t,`description`)??n,i=TP(t,`markdown`);return{label:n,description:r,...i?{markdown:i}:{}}}).filter(e=>e!==null):null;t.push({id:r,header:i,question:a,multiSelect:e.multiSelect===!0,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:o})}return t},DP=e=>e.filter(e=>!(e.kind===`system`&&e.title===`Turn Usage`)),OP=(e,t)=>{let n=ep(e,t),r=new Map,i=new Map;for(let e of n){if(e.type===`tool.permission.requested`){let t=wP(e.payload.raw),n=TP(t,`requestId`,`request_id`);if(!n)continue;let i=wP(t.rawParams??t.raw_params),a=wP(i.networkApprovalContext??i.network_approval_context);r.set(n,{requestId:n,sessionId:e.sessionId,...TP(t,`toolName`,`tool_name`)?{toolName:TP(t,`toolName`,`tool_name`)}:{},...TP(t,`reason`)?{reason:TP(t,`reason`)}:{},...TP(i,`command`)?{command:TP(i,`command`)}:{},...TP(i,`cwd`)?{cwd:TP(i,`cwd`)}:{},...TP(i,`grantRoot`,`grant_root`)?{grantRoot:TP(i,`grantRoot`,`grant_root`)}:{},...TP(a,`host`)?{networkHost:TP(a,`host`)}:{},...TP(a,`protocol`)?{networkProtocol:TP(a,`protocol`)}:{},...TP(t,`itemId`,`item_id`)?{itemId:TP(t,`itemId`,`item_id`)}:{},...TP(t,`turnId`,`turn_id`)?{turnId:TP(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`tool.permission.resolved`){let t=TP(wP(e.payload.raw),`requestId`,`request_id`);t&&r.delete(t);continue}if(e.type===`user.input.requested`){let t=wP(e.payload.raw),n=TP(t,`requestId`,`request_id`);if(!n)continue;i.set(n,{requestId:n,sessionId:e.sessionId,questions:EP(t.questions),...TP(t,`itemId`,`item_id`)?{itemId:TP(t,`itemId`,`item_id`)}:{},...TP(t,`turnId`,`turn_id`)?{turnId:TP(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`user.input.resolved`){let t=TP(wP(e.payload.raw),`requestId`,`request_id`);t&&i.delete(t)}}return{pendingApprovals:[...r.values()],pendingUserInputs:[...i.values()]}},kP=e=>{let t=e.rawEventsAreDetailProjection===!0?e.rawEvents:IP({rawEvents:e.rawEvents,detailLevel:e.target.detailLevel,preserveIncompleteCommandOutput:e.preserveIncompleteCommandOutput??!1}),n=e.target.purpose===`detail_view`?Sc({provider:e.target.provider,rawEvents:t}):null,r=e.target.purpose===`detail_view`?DP(tp(e.target.sessionId,t,[])):[],i=e.target.purpose===`detail_view`?_o({rawEvents:t,messages:r}):{timelineItems:[],consumedMessageIds:[]},a=e.target.purpose===`detail_view`?OP(e.target.sessionId,t):{pendingApprovals:[],pendingUserInputs:[]};return{filteredRawEvents:t,contextUsage:n,timelineItems:i.timelineItems,pendingApprovals:a.pendingApprovals,pendingUserInputs:a.pendingUserInputs}},AP=e=>{let t=MP(e.target),n=IP({rawEvents:e.rawEvents,detailLevel:e.target.detailLevel,preserveIncompleteCommandOutput:t}),r=kP({target:e.target,rawEvents:n,rawEventsAreDetailProjection:!0});return CP({target:e.target,rawEvents:e.rawEvents,projectionRawEvents:n,preserveIncompleteCommandOutput:t,contextUsage:r.contextUsage,timelineItems:r.timelineItems,pendingApprovals:r.pendingApprovals,pendingUserInputs:r.pendingUserInputs})},jP=(e,t)=>{let n=UP(e.rawEvents,t),r=NP(e.preserveIncompleteCommandOutput,t),i=IP({rawEvents:UP(e.projectionRawEvents,t),detailLevel:e.detailLevel,preserveIncompleteCommandOutput:r}),a=kP({target:{sessionId:e.sessionId,provider:e.provider,detailLevel:e.detailLevel,purpose:`detail_view`},rawEvents:i,rawEventsAreDetailProjection:!0});return{...e,preserveIncompleteCommandOutput:r,rawEvents:n,projectionRawEvents:i,contextUsage:a.contextUsage,timelineItems:a.timelineItems,pendingApprovals:a.pendingApprovals,pendingUserInputs:a.pendingUserInputs}},MP=e=>e.status===`running`,NP=(e,t)=>PP(t)?!0:FP(t)?!1:e,PP=e=>{if(e.type===`turn.started`)return!0;if(e.type!==`native.raw`)return!1;let t=wP(e.payload.raw),n=TP(wP(t.message),`method`)??TP(t,`method`);return n===`turn/started`||n===`codex/event/task_started`},FP=e=>{if(e.type===`turn.completed`||e.type===`turn.failed`)return!0;if(e.type!==`native.raw`)return!1;let t=wP(e.payload.raw),n=TP(wP(t.message),`method`)??TP(t,`method`);return n===`turn/completed`||n===`turn/failed`||n===`codex/event/task_complete`||n===`codex/event/task_failed`},IP=e=>eE(e.rawEvents,e.detailLevel,{compactIncompleteCommandOutput:!e.preserveIncompleteCommandOutput}),LP=e=>TP(e,`id`,`itemId`,`item_id`)??null,RP=e=>{if(e.type===`item.started`||e.type===`item.updated`||e.type===`item.completed`)return LP(wP(wP(e.payload.raw).item));if(e.type!==`native.raw`)return null;let t=wP(wP(e.payload.raw).message),n=wP(t.params),r=wP(n.item),i=wP(n.msg);return LP(r)??LP(wP(t.item))??TP(n,`itemId`,`item_id`)??TP(i,`itemId`,`item_id`)??null},zP=e=>{if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=wP(e.payload.raw);return(TP(wP(t.message),`method`)??TP(t,`method`))===`item/completed`},BP=(e,t)=>t?`${e}|${t}`:null,VP=e=>BP(e.sessionId,RP(e)),HP=e=>{let t=VP(e);if(t)return`item:${t}`;let n=Ip(e);return n?`delta:${n.key}`:null},UP=(e,t)=>{let n=[...e],r=VP(t),i=HP(t),a=Ip(t),o=t;if(i&&a)for(let e=n.length-1;e>=0;--e){let r=n[e];if(!r||HP(r)!==i||!Ip(r))continue;let a=Lp(r,t);if(a){n[e]=null,o=a;break}}return n.push(o),!r||!zP(t)?n.filter(e=>e!==null):n.filter(e=>e!==null&&(e.eventId===o.eventId||VP(e)!==r||!Ip(e)))},WP=e=>{let t=GP(e);if(!t)return null;let n=LP(t),r=wP(t.payload),i=TP(t,`output_delta`,`outputDelta`)??TP(r,`output_delta`,`outputDelta`);return!n||!i?null:{itemId:n,delta:i}},GP=e=>{if(e.type===`item.updated`){let t=wP(wP(e.payload.raw).item);return KP(t)?t:null}if(e.type!==`native.raw`)return null;let t=wP(e.payload.raw),n=wP(t.message);if((TP(n,`method`)??TP(t,`method`))!==`item/updated`)return null;let r=wP(wP(n.params).item);return KP(r)?r:null},KP=e=>{let t=TP(e,`type`);return t===`commandExecution`||t===`command_execution`},qP=e=>e.includes(`[compact history preview:`),JP=(e,t)=>{let n=WP(t);if(!n)return null;let r=e.timelineItems.findIndex(e=>e.kind===`terminal_card`&&e.itemId===n.itemId&&typeof e.output==`string`);if(r<0)return null;let i=e.timelineItems[r];if(!i||i.kind!==`terminal_card`||qP(i.output))return null;let a=UP(e.rawEvents,t),o=IP({rawEvents:UP(e.projectionRawEvents,t),detailLevel:e.detailLevel,preserveIncompleteCommandOutput:!0}),s={...i,output:`${i.output}${n.delta}`},c=[...e.timelineItems];c[r]=s;let l=a[a.length-1]?.rawSeq??t.rawSeq;return{nextState:{...e,preserveIncompleteCommandOutput:!0,rawEvents:a,projectionRawEvents:o,timelineItems:c},messageInput:{provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,fromRawSeq:e.rawEvents[e.rawEvents.length-1]?.rawSeq,toRawSeq:l,timelineUpserts:[],timelineRemovals:[],timelineTextDeltaPatches:[{id:i.id,field:`output`,delta:n.delta}]}}},YP=e=>Buffer.byteLength(JSON.stringify(hP(e)),`utf8`),XP=e=>{let t=Math.max(1,Math.floor(e.maxChunkBytes??524288)),n=[],r=(t,n)=>YP({provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,snapshotId:e.snapshotId,chunkIndex:t,totalChunks:1,timelineItems:n,pendingApprovals:t===0?e.pendingApprovals:void 0,pendingUserInputs:t===0?e.pendingUserInputs:void 0,contextUsage:t===0?e.contextUsage:void 0});if(e.timelineItems.length===0)return[{timelineItems:[],estimatedByteLength:r(0,[])}];let i=[];for(let a of e.timelineItems){let e=n.length,o=[...i,a],s=r(e,o);if(i.length>0&&s>t){n.push({timelineItems:i,estimatedByteLength:r(e,i)}),i=[a];continue}i=o}return n.push({timelineItems:i,estimatedByteLength:r(n.length,i)}),n},ZP=(e,t)=>{let n=new Map(e.map(e=>[e.requestId,JSON.stringify(e)])),r=new Map(t.map(e=>[e.requestId,JSON.stringify(e)]));return{upserts:t.filter(e=>n.get(e.requestId)!==r.get(e.requestId)),removals:e.filter(e=>!r.has(e.requestId)).map(e=>e.requestId)}},QP=(e,t)=>{let n=new Map(e.map(e=>[e.requestId,JSON.stringify(e)])),r=new Map(t.map(e=>[e.requestId,JSON.stringify(e)]));return{upserts:t.filter(e=>n.get(e.requestId)!==r.get(e.requestId)),removals:e.filter(e=>!r.has(e.requestId)).map(e=>e.requestId)}},$P=(e,t,n,r)=>{let i={},a=ep(e,[t]),o=a.find(e=>e.type===`thread.title.updated`),s=a.find(e=>e.type===`turn.started`||e.type===`turn.completed`||e.type===`turn.failed`);if(o){let e=TP(wP(o.payload.raw),`title`);e&&(i.title=e)}return s&&(i.updatedAt=s.ts,i.status=s.type===`turn.started`?`running`:`idle`,i.interactionLockReason=void 0),n.pendingApprovals.length!==r.pendingApprovals.length&&(i.pendingApprovals=r.pendingApprovals.length),n.pendingUserInputs.length!==r.pendingUserInputs.length&&(i.pendingUserInputs=r.pendingUserInputs.length),n.pendingApprovals.length+n.pendingUserInputs.length!==r.pendingApprovals.length+r.pendingUserInputs.length&&(i.pendingActions=r.pendingApprovals.length+r.pendingUserInputs.length),Object.keys(i).length>0?i:void 0},eF=e=>e?{stateFound:!0,kind:e.kind,sessionId:e.sessionId,projectId:e.projectId,provider:e.provider,detailLevel:e.detailLevel,preserveIncompleteCommandOutput:e.preserveIncompleteCommandOutput,rawEventCount:e.rawEvents.length,projectionRawEventCount:e.projectionRawEvents.length,firstRawSeq:e.rawEvents[0]?.rawSeq??null,lastRawSeq:e.rawEvents[e.rawEvents.length-1]?.rawSeq??null,timelineItemCount:e.timelineItems.length,pendingApprovalCount:e.pendingApprovals.length,pendingUserInputCount:e.pendingUserInputs.length,hasContextUsage:!!e.contextUsage}:{stateFound:!1},tF=e=>e?e.kind===`ready`?eF(e):{stateFound:!0,kind:e.kind,sessionId:e.sessionId,queuedEnvelopeCount:e.queuedEnvelopes.length,previousReadyState:eF(e.previousReadyState)}:{stateFound:!1},nF=(e,t)=>{let n,r,i;try{n=Is(e.previousState.timelineItems,e.nextState.timelineItems),r=ZP(e.previousState.pendingApprovals,e.nextState.pendingApprovals),i=QP(e.previousState.pendingUserInputs,e.nextState.pendingUserInputs)}catch(n){throw t?.(`stream.readable.delta.build.error`,{sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,previousState:eF(e.previousState),nextState:eF(e.nextState),sessionSummaryKeys:e.sessionSummary?Object.keys(e.sessionSummary):[],errorMessage:n instanceof Error?n.message:String(n)}),n}let a=JSON.stringify(e.previousState.contextUsage??null)!==JSON.stringify(e.nextState.contextUsage??null);if(n.upserts.length===0&&n.removals.length===0&&n.textDeltaPatches.length===0&&r.upserts.length===0&&r.removals.length===0&&i.upserts.length===0&&i.removals.length===0&&!a&&!e.sessionSummary)return null;let o=e.nextState.rawEvents[e.nextState.rawEvents.length-1]?.rawSeq;return o===void 0?null:{provider:e.previousState.provider,sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,fromRawSeq:e.previousState.rawEvents[e.previousState.rawEvents.length-1]?.rawSeq,toRawSeq:o,timelineUpserts:n.upserts,timelineRemovals:n.removals,timelineTextDeltaPatches:n.textDeltaPatches,pendingApprovalUpserts:r.upserts,pendingApprovalRemovals:r.removals,pendingUserInputUpserts:i.upserts,pendingUserInputRemovals:i.removals,sessionSummary:e.sessionSummary,contextUsage:a?e.nextState.contextUsage:void 0}};function rF(e){return e?{sessionFound:!0,sessionId:e.id,projectId:e.projectId,nativeSessionId:e.nativeSessionId??null,provider:e.provider,providerMode:e.providerMode,source:e.source??null,status:e.status,interactionLockReason:e.interactionLockReason??null,updatedAt:e.updatedAt,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null}:{sessionFound:!1}}var iF=class{stateByClientSession=new Map;pendingDeltaByClientSession=new Map;constructor(e,t,n,r){this.sessionHub=e,this.sessionManager=t,this.readableLiveDeltaCoalesceMs=n,this.log=r}shutdown(){for(let e of this.pendingDeltaByClientSession.values())clearTimeout(e.timer);this.pendingDeltaByClientSession.clear(),this.stateByClientSession.clear()}handleSessionStreamSubscribeCommand=async(e,t,n)=>{let r=SP(t),i=new Set(r.map(e=>e.sessionId)),a=this.sessionHub.getSubscriptions(e);this.log(`stream.subscribe.received`,{clientId:e,replace:n,incomingSubscriptionCount:t.length,dedupedSubscriptionCount:r.length,subscriptions:r.map(e=>({sessionId:e.sessionId,projectId:e.projectId??null,purpose:e.purpose??null,detailLevel:e.detailLevel??null,bootstrapMode:e.bootstrapMode??null,cursorKind:e.cursor.kind,rawSeq:e.cursor.kind===`raw_seq`?e.cursor.rawSeq:null}))}),this.primeReadableBootstrapForSubscriptions(e,r);for(let t of i)this.sessionHub.pauseSession(e,t);this.sessionHub.replaceSubscriptions(e,r,n),this.syncReadableLiveProjectionSubscriptions(e,a,r,n);try{for(let t of r)try{await this.syncSessionStreamSubscription(e,t)}catch(n){throw xP(t)&&this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:e,sessionId:t.sessionId}),n}}finally{for(let t of i)this.sessionHub.resumeSession(e,t)}};clearState=(e,t)=>{let n=bP(e,t),r=this.stateByClientSession.get(n);this.stateByClientSession.delete(n);let i=this.pendingDeltaByClientSession.get(n);i&&(clearTimeout(i.timer),this.pendingDeltaByClientSession.delete(n)),(r||i)&&this.log(`readable.state.cleared`,{clientId:e,sessionId:t,hadState:!!r,previousState:tF(r),hadPendingDelta:!!i,pendingDeltaFromRawSeq:i?.previousState.rawEvents[i.previousState.rawEvents.length-1]?.rawSeq??null,pendingDeltaToRawSeq:i?.nextState.rawEvents[i.nextState.rawEvents.length-1]?.rawSeq??null})};clearStatesForClient=e=>{let t=`${e}::`;for(let e of this.stateByClientSession.keys())e.startsWith(t)&&this.stateByClientSession.delete(e);for(let[e,n]of this.pendingDeltaByClientSession)e.startsWith(t)&&(clearTimeout(n.timer),this.pendingDeltaByClientSession.delete(e))};routeReadableLiveDelta=e=>{let t=this.sessionHub.getClientSubscriptionsForSession(e.sessionId,`detail_view`);if(t.length!==0)for(let{clientId:n,subscription:r}of t){if(!xP(r))continue;let t=bP(n,e.sessionId),i=this.stateByClientSession.get(t);if(!i)continue;if(i.kind===`bootstrapping`){i.queuedEnvelopes.push(e);continue}let a=JP(i,e);if(a){this.flushPendingReadableLiveDelta(n,e.sessionId),this.stateByClientSession.set(t,a.nextState),this.sessionHub.sendSessionMessageToClient(n,e.sessionId,gP(a.messageInput)),this.log(`stream.readable.live_patch.sent`,{clientId:n,sessionId:e.sessionId,projectId:i.projectId,provider:i.provider,fromRawSeq:a.messageInput.fromRawSeq??null,toRawSeq:a.messageInput.toRawSeq,timelineTextDeltaPatchCount:a.messageInput.timelineTextDeltaPatches?.length??0});continue}let o=jP(i,e);this.stateByClientSession.set(t,o);let s=$P(e.sessionId,e,i,o);this.enqueueReadableLiveDelta({clientId:n,previousState:i,nextState:o,sessionSummary:s})}};refreshDetailSessionSnapshots=async e=>{let t=this.sessionHub.getClientSubscriptionsForSession(e.sessionId,`detail_view`);for(let{clientId:n,subscription:r}of t){let t=r.projectId?.trim()??``;if(!(t&&t!==e.projectId)){this.sessionHub.pauseSession(n,e.sessionId);try{let t=await this.resolveSessionStreamTarget(r);if(t.bootstrapMode===`readable`){let r=this.getReadableRefreshDeltaBase({clientId:n,sessionId:e.sessionId,projectId:e.projectId,detailLevel:t.detailLevel,refreshMode:e.refreshMode,reason:e.reason});if(r){this.startReadableLiveProjectionBootstrap({clientId:n,sessionId:e.sessionId,previousReadyState:r.previousReadyState}),await this.sendSessionReadableResumeDelta(n,t,r.cursor,r.reason);continue}this.startReadableLiveProjectionBootstrap({clientId:n,sessionId:e.sessionId}),await this.sendSessionReadableSnapshot(n,t,e.reason)}else await this.sendSessionSnapshot(n,t,e.reason)}catch(t){throw xP(r)&&this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:n,sessionId:e.sessionId}),t}finally{this.sessionHub.resumeSession(n,e.sessionId)}}}};sendSessionSnapshot=async(e,t,n)=>{let r=`snap_${ow(12)}`,{compactedRawEvents:i,projectionRawEvents:a,lastRawSeq:o,slimReadableProjection:s,pendingApprovals:c,pendingUserInputs:l}=await this.buildReadableSnapshotProjection(t);this.sessionHub.sendStreamMessage(e,pP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...o===void 0?{}:{toRawSeq:o}}));let u=vP(a,yP),d=t.purpose===`detail_view`?vP(s.timelineItems,yP):[],f=t.purpose===`detail_view`?`raw+readable`:`raw`,p=Math.max(u.length,d.length,1);this.log(`stream.snapshot.prepared`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,provider:t.provider,detailLevel:t.detailLevel,reason:n,snapshotId:r,snapshotFormat:f,compactedEventCount:i.length,filteredEventCount:a.length,readableTimelineItemCount:s.timelineItems.length,totalChunks:p,firstRawSeq:a[0]?.rawSeq??null,lastRawSeq:o??null});for(let n=0;n<p;n+=1){let i=u[n]??[],a=d[n]??[];this.sessionHub.sendStreamMessage(e,mP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:p,events:i,timelineItems:t.purpose===`detail_view`?a:void 0}))}};sendSessionReadableSnapshot=async(e,t,n)=>{let r=`snap_${ow(12)}`,i=this.startReadableLiveProjectionBootstrap({clientId:e,sessionId:t.sessionId});try{let{compactedRawEvents:a,projectionRawEvents:o,contextUsage:s,lastRawSeq:c,slimReadableProjection:l,pendingApprovals:u,pendingUserInputs:d}=await this.buildReadableSnapshotProjection(t),f=this.sessionHub.getSubscriptions(e).find(e=>e.sessionId===t.sessionId),p=f?.projectId?.trim()??``;if(!f||!xP(f)||p&&p!==t.projectId||(f.detailLevel??`full`)!==t.detailLevel){this.clearState(e,t.sessionId);return}let m=CP({target:t,rawEvents:a,projectionRawEvents:o,preserveIncompleteCommandOutput:MP(t),contextUsage:s,timelineItems:l.timelineItems,pendingApprovals:u,pendingUserInputs:d}),h=this.stateByClientSession.get(i),g=lP(h?.kind===`bootstrapping`?h.queuedEnvelopes:[],c);for(let e of g)m=jP(m,e);this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:m.rawEvents,projectionRawEvents:m.projectionRawEvents,preserveIncompleteCommandOutput:m.preserveIncompleteCommandOutput,contextUsage:m.contextUsage,timelineItems:m.timelineItems,pendingApprovals:m.pendingApprovals,pendingUserInputs:m.pendingUserInputs});let _=m.rawEvents[m.rawEvents.length-1]?.rawSeq;this.sessionHub.sendStreamMessage(e,pP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,..._===void 0?{}:{toRawSeq:_}}));let v=XP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,timelineItems:m.timelineItems,pendingApprovals:m.pendingApprovals,pendingUserInputs:m.pendingUserInputs,contextUsage:m.contextUsage}),y=Math.max(v.length,1);this.log(`stream.snapshot.prepared`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,provider:t.provider,detailLevel:t.detailLevel,bootstrapMode:t.bootstrapMode,reason:n,snapshotId:r,snapshotFormat:`readable`,compactedEventCount:a.length,canonicalRawEventCount:m.rawEvents.length,projectionRawEventCount:m.projectionRawEvents.length,readableTimelineItemCount:m.timelineItems.length,bufferedReadableDeltaCount:g.length,readableChunkTargetBytes:524288,readableChunkItemCounts:v.map(e=>e.timelineItems.length),readableChunkEstimatedBytes:v.map(e=>e.estimatedByteLength),totalChunks:y,firstRawSeq:m.rawEvents[0]?.rawSeq??null,lastRawSeq:_??null});for(let n=0;n<y;n+=1){let i=v[n];this.sessionHub.sendStreamMessage(e,hP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:y,timelineItems:i?.timelineItems??[],pendingApprovals:n===0?m.pendingApprovals:void 0,pendingUserInputs:n===0?m.pendingUserInputs:void 0,contextUsage:n===0?m.contextUsage:void 0}))}}catch(n){throw this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:e,sessionId:t.sessionId}),n}};sendSessionReadableResumeDelta=async(e,t,n,r)=>{let i=bP(e,t.sessionId),a=await this.sessionManager.getProjectSessionRawEvents(t.projectId,t.sessionId,2**53-1),{baseRawEvents:o,nextRawEvents:s}=uP({rawEvents:a,cursorRawSeq:n}),c=AP({target:t,rawEvents:o}),l=AP({target:t,rawEvents:s}),u=this.stateByClientSession.get(i),d=lP(u?.kind===`bootstrapping`?u.queuedEnvelopes:[],l.rawEvents[l.rawEvents.length-1]?.rawSeq);for(let e of d)l=jP(l,e);this.log(`stream.readable.resume.prepared`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,provider:t.provider,detailLevel:t.detailLevel,reason:r,cursorRawSeq:n,rawEventCount:a.length,baseRawEventCount:o.length,nextRawEventCount:s.length,bootstrapState:tF(u),bufferedEnvelopeCount:d.length,previousState:eF(c),nextState:eF(l)}),this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:l.rawEvents,contextUsage:l.contextUsage,timelineItems:l.timelineItems,pendingApprovals:l.pendingApprovals,pendingUserInputs:l.pendingUserInputs});let f=l.rawEvents[l.rawEvents.length-1]?.rawSeq??n;this.sessionHub.sendStreamMessage(e,pP({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`delta`,reason:r,fromRawSeq:n,...f===void 0?{}:{toRawSeq:f}}));let p=nF({previousState:c,nextState:l},this.log);this.log(`stream.readable.resume.delta`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,reason:r,cursorRawSeq:n,emittedDelta:!!p,deltaFromRawSeq:p?.fromRawSeq??n,deltaToRawSeq:p?.toRawSeq??f??null,timelineUpsertCount:p?.timelineUpserts.length??0,timelineRemovalCount:p?.timelineRemovals.length??0,timelineTextDeltaPatchCount:p?.timelineTextDeltaPatches.length??0,pendingApprovalUpsertCount:p?.pendingApprovalUpserts.length??0,pendingUserInputUpsertCount:p?.pendingUserInputUpserts.length??0}),this.sessionHub.sendSessionMessageToClient(e,t.sessionId,gP(p??{provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,fromRawSeq:n,toRawSeq:f,timelineUpserts:[],timelineRemovals:[]}))};syncReadableLiveProjectionSubscriptions(e,t,n,r){let i=new Set(n.filter(xP).map(e=>e.sessionId));if(r)for(let n of t)i.has(n.sessionId)||this.clearState(e,n.sessionId);for(let t of n)xP(t)||this.clearState(e,t.sessionId)}startReadableLiveProjectionBootstrap(e){let t=bP(e.clientId,e.sessionId),n=this.stateByClientSession.get(t),r=this.pendingDeltaByClientSession.get(t),i=e.previousReadyState??(n?.kind===`bootstrapping`?n.previousReadyState:this.getReadableDeliveredReadyState(e.clientId,e.sessionId)),a=this.getReadablePendingDeltaReplayEnvelopes(i,r);r&&(clearTimeout(r.timer),this.pendingDeltaByClientSession.delete(t));let o=n?.kind===`bootstrapping`?n:i,s=dP(e.sessionId,o);if(a.length>0){let e=new Set(s.queuedEnvelopes.map(e=>e.rawSeq));for(let t of a)e.has(t.rawSeq)||(s.queuedEnvelopes.push(t),e.add(t.rawSeq))}return this.stateByClientSession.set(t,s),this.log(`readable.bootstrap.started`,{clientId:e.clientId,sessionId:e.sessionId,replacedState:tF(n),clearedPendingDelta:!!r,carriedPendingEnvelopeCount:a.length}),t}getReadableDeliveredReadyState(e,t){let n=bP(e,t),r=this.pendingDeltaByClientSession.get(n);if(r)return r.previousState;let i=this.stateByClientSession.get(n);return i?.kind===`ready`?i:null}getReadablePendingDeltaReplayEnvelopes(e,t){return t?lP(t.nextState.rawEvents,e?.rawEvents[e.rawEvents.length-1]?.rawSeq):[]}getReadableRefreshDeltaBase(e){let t=this.getReadableRefreshDeltaReason(e.reason);if(!t||e.refreshMode!==`delta`)return null;let n=this.getReadableDeliveredReadyState(e.clientId,e.sessionId);if(!n||n.projectId!==e.projectId||n.detailLevel!==e.detailLevel)return null;let r=n.rawEvents[n.rawEvents.length-1]?.rawSeq;return typeof r==`number`?{cursor:r,previousReadyState:n,reason:t}:null}getReadableRefreshDeltaReason(e){return e===`external_history_updated`||e===`explicit_history_sync`?`${e}_delta`:null}seedReadableLiveProjectionState(e){let t=CP(e);this.stateByClientSession.set(bP(e.clientId,e.target.sessionId),t),this.log(`readable.state.seeded`,{clientId:e.clientId,sessionId:e.target.sessionId,projectId:e.target.projectId,provider:e.target.provider,detailLevel:e.target.detailLevel,state:eF(t)})}primeReadableBootstrapForSubscriptions(e,t){for(let n of t)xP(n)&&this.startReadableLiveProjectionBootstrap({clientId:e,sessionId:n.sessionId})}async syncSessionStreamSubscription(e,t){let n=await this.resolveSessionStreamTarget(t);if(n.bootstrapMode===`readable`){if(t.cursor.kind===`all`){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`all`,requestedRawSeq:null,decision:`snapshot`,reason:`readable_bootstrap_snapshot`}),await this.sendSessionReadableSnapshot(e,n,`readable_bootstrap_snapshot`);return}let r=await this.sessionManager.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:t.cursor.rawSeq,decision:`snapshot`,reason:`readable_empty_history_snapshot`,rangeMin:null,rangeMax:null}),await this.sendSessionReadableSnapshot(e,n,`readable_empty_history_snapshot`);return}let i=t.cursor.rawSeq,a=Math.max(0,r.min-1);if(i<a||i>r.max){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`snapshot`,reason:`readable_cursor_out_of_range_snapshot`,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a}),await this.sendSessionReadableSnapshot(e,n,`readable_cursor_out_of_range_snapshot`);return}let o=n.status===`running`?`readable_cursor_resumed_delta`:`readable_session_idle_delta`;this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`delta`,reason:o,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a}),await this.sendSessionReadableResumeDelta(e,n,i,o);return}if(t.cursor.kind===`all`){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`all`,requestedRawSeq:null,decision:`snapshot`,reason:`cursor_all`}),await this.sendSessionSnapshot(e,n,`cursor_all`);return}let r=await this.sessionManager.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:t.cursor.rawSeq,decision:`snapshot`,reason:`empty_history_snapshot`,rangeMin:null,rangeMax:null}),await this.sendSessionSnapshot(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq,a=Math.max(0,r.min-1);if(i<a||i>r.max){this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`snapshot`,reason:`cursor_out_of_range_snapshot`,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a}),await this.sendSessionSnapshot(e,n,`cursor_out_of_range_snapshot`);return}let o=await this.sessionManager.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),s=o[o.length-1]?.rawSeq??i;this.log(`stream.subscribe.decision`,{clientId:e,sessionId:n.sessionId,projectId:n.projectId,provider:n.provider,purpose:t.purpose??null,detailLevel:n.detailLevel,bootstrapMode:n.bootstrapMode,targetStatus:n.status,cursorKind:`raw_seq`,requestedRawSeq:i,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,rangeMin:r.min,rangeMax:r.max,minExpectedCursor:a,backlogCount:o.length,backlogFirstRawSeq:o[0]?.rawSeq??null,backlogLastRawSeq:s}),this.sessionHub.sendStreamMessage(e,pP({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:s}));for(let t of o)this.sessionHub.sendStreamMessage(e,t)}async resolveSessionStreamTarget(e){let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let r=await this.sessionManager.getProjectSessionSummary(n,t);if(!r)throw _w(n,t);let i={sessionId:t,projectId:n,provider:r.provider,status:r.status,detailLevel:e.detailLevel??`full`,purpose:e.purpose??null,bootstrapMode:e.bootstrapMode??`stream`};return this.log(`stream.subscribe.target.resolved`,{sessionId:t,requestedProjectId:n,resolvedProjectId:i.projectId,purpose:i.purpose,detailLevel:i.detailLevel,bootstrapMode:i.bootstrapMode,targetProvider:i.provider,targetStatus:i.status,resolvedViaExecutionContext:!1,summary:rF(r)}),i}let r=this.sessionManager.getSessionExecutionContext(t),i=await this.sessionManager.getProjectSessionSummary(r.projectId,t),a={sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`,detailLevel:e.detailLevel??`full`,purpose:e.purpose??null,bootstrapMode:e.bootstrapMode??`stream`};return this.log(`stream.subscribe.target.resolved`,{sessionId:t,requestedProjectId:null,resolvedProjectId:a.projectId,purpose:a.purpose,detailLevel:a.detailLevel,bootstrapMode:a.bootstrapMode,targetProvider:a.provider,targetStatus:a.status,resolvedViaExecutionContext:!0,executionContextProvider:r.provider,summary:rF(i)}),a}async buildReadableSnapshotProjection(e){let t=await this.sessionManager.getProjectSessionRawEventsCompacted(e.projectId,e.sessionId,2**53-1),n=MP(e),r=IP({rawEvents:t,detailLevel:e.detailLevel,preserveIncompleteCommandOutput:n}),i=kP({target:e,rawEvents:r,rawEventsAreDetailProjection:!0}),a=t[t.length-1]?.rawSeq;return{compactedRawEvents:t,projectionRawEvents:r,contextUsage:i.contextUsage,lastRawSeq:a,slimReadableProjection:{timelineItems:i.timelineItems,consumedMessageIds:[]},pendingApprovals:i.pendingApprovals,pendingUserInputs:i.pendingUserInputs}}restoreReadableLiveProjectionAfterBootstrapFailure(e){let t=bP(e.clientId,e.sessionId),n=this.stateByClientSession.get(t);if(!n||n.kind!==`bootstrapping`)return;let r=this.sessionHub.getSubscriptions(e.clientId).find(t=>t.sessionId===e.sessionId),i=r?.projectId?.trim()??``,a=fP(n,jP);if(!a.previousReadyState||!r||!xP(r)||i&&i!==a.previousReadyState.projectId||(r.detailLevel??`full`)!==a.previousReadyState.detailLevel||!a.nextReadyState){this.log(`readable.bootstrap.recovery.discarded`,{clientId:e.clientId,sessionId:e.sessionId,bootstrapState:tF(n),currentSubscriptionFound:!!r,currentSubscriptionProjectId:i||null,currentSubscriptionDetailLevel:r?.detailLevel??null,previousReadyState:eF(a.previousReadyState),nextReadyState:eF(a.nextReadyState)}),this.clearState(e.clientId,e.sessionId);return}if(this.stateByClientSession.set(t,a.nextReadyState),a.replayedEnvelopes.length===0){this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:0,nextReadyState:eF(a.nextReadyState)});return}let o,s=a.previousReadyState;for(let t of a.replayedEnvelopes){let n=jP(s,t),r=$P(e.sessionId,t,s,n);r&&(o={...o??{},...r}),s=n}let c=nF({previousState:a.previousReadyState,nextState:a.nextReadyState,sessionSummary:o},this.log);if(!c){this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:eF(a.nextReadyState),emittedDelta:!1});return}this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:eF(a.nextReadyState),emittedDelta:!0,deltaFromRawSeq:c.fromRawSeq??null,deltaToRawSeq:c.toRawSeq}),this.sessionHub.sendSessionMessageToClient(e.clientId,a.previousReadyState.sessionId,gP(c))}sendReadableLiveDeltaNow(e){let t=nF({previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary},this.log);t&&this.sessionHub.sendSessionMessageToClient(e.clientId,e.previousState.sessionId,gP(t))}flushPendingReadableLiveDelta(e,t){let n=bP(e,t),r=this.pendingDeltaByClientSession.get(n);r&&(clearTimeout(r.timer),this.pendingDeltaByClientSession.delete(n),this.sendReadableLiveDeltaNow({clientId:e,previousState:r.previousState,nextState:r.nextState,sessionSummary:r.sessionSummary}))}enqueueReadableLiveDelta(e){if(this.readableLiveDeltaCoalesceMs<=0){this.sendReadableLiveDeltaNow(e);return}let t=bP(e.clientId,e.previousState.sessionId),n=this.pendingDeltaByClientSession.get(t);if(n){let t=aF({existing:{previousState:n.previousState,nextState:n.nextState,sessionSummary:n.sessionSummary},next:{previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary}});n.previousState=t.previousState,n.nextState=t.nextState,n.sessionSummary=t.sessionSummary;return}let r=setTimeout(()=>{this.flushPendingReadableLiveDelta(e.clientId,e.previousState.sessionId)},this.readableLiveDeltaCoalesceMs);r.unref?.(),this.pendingDeltaByClientSession.set(t,{clientId:e.clientId,sessionId:e.previousState.sessionId,previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary,timer:r})}};function aF(e){let t=(e,t)=>{let n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0};return e.existing?{previousState:e.existing.previousState,nextState:e.next.nextState,sessionSummary:t(e.existing.sessionSummary,e.next.sessionSummary)}:{previousState:e.next.previousState,nextState:e.next.nextState,sessionSummary:t(void 0,e.next.sessionSummary)}}function oF(e){return e.sendProviderRaw?`relay_ws`:`direct_ws`}function sF(e){let t=performance.now(),n=JSON.stringify(e);return{payload:n,byteLength:Buffer.byteLength(n),serializeDurationMs:Number((performance.now()-t).toFixed(3))}}function cF(e){return e.kind===`session.readable.snapshot.chunk`?{snapshotId:e.payload.readable.snapshotId,chunkIndex:e.payload.readable.chunkIndex,totalChunks:e.payload.readable.totalChunks,snapshotFormat:`readable`,chunkEventCount:null,chunkTimelineItemCount:e.payload.readable.timelineItems.length}:e.kind===`session.stream.snapshot.chunk`?{snapshotId:e.payload.raw.snapshotId,chunkIndex:e.payload.raw.chunkIndex,totalChunks:e.payload.raw.totalChunks,snapshotFormat:e.payload.readable?`raw+readable`:`raw`,chunkEventCount:e.payload.raw.events.length,chunkTimelineItemCount:e.payload.readable?.timelineItems?.length??null}:null}var lF=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${ow(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}getWatchSubscriptions(e){let t=new Map;for(let n of this.clients.values())for(let r of n.subscriptionsBySessionId.values())r.purpose===e&&t.set(r.sessionId,r);return[...t.values()]}getClientSubscriptionsForSession(e,t){let n=this.clientIdsBySessionId.get(e);if(!n||n.size===0)return[];let r=[];for(let i of n){let n=this.clients.get(i),a=n?.subscriptionsBySessionId.get(e);!n||!a||t&&a.purpose!==t||r.push({clientId:i,subscription:a})}return r}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=null;for(let r of t){let t=this.clients.get(r),i=t?.subscriptionsBySessionId.get(e.sessionId);if(!t||!i||!this.shouldDeliverProviderRaw(i))continue;let a=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(a?.paused){a.queued.push({message:e});continue}if(t.socket.readyState===t.socket.OPEN){if(t.socket.sendProviderRaw){t.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),t.socket.send(n)}}}routeSessionMessage(e,t){let n=this.clientIdsBySessionId.get(e.sessionId);if(!n||n.size===0)return;let r=null;for(let i of n){let n=this.clients.get(i),a=n?.subscriptionsBySessionId.get(e.sessionId);if(!n||!a||!t(a))continue;let o=this.deliveryStateByClientSession.get(this.clientSessionKey(i,e.sessionId));if(o?.paused){o.queued.push({message:e});continue}n.socket.readyState===n.socket.OPEN&&(r=this.sendGatewayStreamMessage(n,e,r))}}sendSessionMessageToClient(e,t,n){let r=this.clients.get(e),i=r?.subscriptionsBySessionId.get(t);if(!r||!i)return;let a=this.deliveryStateByClientSession.get(this.clientSessionKey(e,t));if(a?.paused){a.queued.push({message:n});return}r.socket.readyState===r.socket.OPEN&&this.sendGatewayStreamMessage(r,n)}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued];r.queued=[];for(let e of a){if(e.message.kind===`provider.raw`&&i.socket.sendProviderRaw){i.socket.sendProviderRaw(e.message);continue}this.sendGatewayStreamMessage(i,e.message)}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||this.sendGatewayStreamMessage(n,t)}sendBroadcastMessage(e,t){let n=null;for(let r of this.clients.values())if(r.socket.readyState===r.socket.OPEN){if(t?.sessionId){let e=r.subscriptionsBySessionId.get(t.sessionId);if(!e||t.purpose&&e.purpose!==t.purpose)continue}n=this.sendGatewayStreamMessage(r,e,n)}}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}sendGatewayStreamMessage(e,t,n=null){let r=n??sF(t),i=cF(t);return i&&mA(`stream.snapshot.chunk.outbound`,{clientId:e.id,deviceId:e.deviceId,transport:oF(e.socket),provider:t.provider,sessionId:t.sessionId,projectId:t.projectId??null,messageKind:t.kind,messageType:t.type,snapshotId:i.snapshotId,chunkIndex:i.chunkIndex,totalChunks:i.totalChunks,snapshotFormat:i.snapshotFormat,chunkEventCount:i.chunkEventCount,chunkTimelineItemCount:i.chunkTimelineItemCount,serializedByteLength:r.byteLength,serializeDurationMs:r.serializeDurationMs}),e.socket.send(r.payload),r}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}shouldDeliverProviderRaw(e){return!(e.purpose===`detail_view`&&e.bootstrapMode===`readable`)}};const uF=1200,dF=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var fF=class{statesByKey=new Map;targetsByClientId=new Map;constructor(e){this.options=e}getClientWatchTargets(e){let t=this.targetsByClientId.get(e);return t?[...t.values()]:[]}setClientWatchTargets(e,t,n){let r=new Map;for(let e of t){let t=e.sessionId.trim(),n=e.projectId?.trim()??``;!t||!n||r.set(this.stateKey(n,t),{sessionId:t,projectId:n})}let i=this.targetsByClientId.get(e)??new Map,a=n?new Map:new Map(i);for(let[e,t]of r)a.set(e,t);for(let[t,n]of i)a.has(t)||this.removeClientFromState(e,n.projectId??``,n.sessionId);for(let[t,n]of a)i.get(t)||this.addClientToState(e,n.projectId??``,n.sessionId);return this.targetsByClientId.set(e,a),[...a.values()]}removeClient(e){let t=this.targetsByClientId.get(e);if(t){for(let n of t.values())this.removeClientFromState(e,n.projectId??``,n.sessionId);this.targetsByClientId.delete(e)}}close(){for(let e of this.statesByKey.values())this.disposeState(e);this.statesByKey.clear(),this.targetsByClientId.clear()}logDebug(e,t){dF&&(console.log(`[native-watch][gateway]`,e,t),this.options.logger.info?.({event:e,...t},`native session watch debug`))}addClientToState(e,t,n){if(!t||!n)return;let r=this.stateKey(t,n),i=this.statesByKey.get(r);i||(i={provider:`codex`,sessionId:n,projectId:t,ownerClientIds:new Set,fileWatcher:null,debounceTimer:null,catchupRetryTimer:null,reconcileTimer:setInterval(()=>{this.requestSync(r,`reconcile`)},25e3),syncInFlight:!1,rerunRequested:!1,stableIdleSyncCount:0,watchCatchupRetryCount:0,lastObservedRawSeq:0,lastObservedRawEventCount:0,lastTriggeredAt:0,lastSyncStartedAt:null,lastSyncCompletedAt:null},this.statesByKey.set(r,i),this.logDebug(`state.created`,{clientId:e,projectId:t,sessionId:n})),i.ownerClientIds.add(e),this.logDebug(`lease.added`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:i.ownerClientIds.size}),this.requestSync(r,`lease_added`)}removeClientFromState(e,t,n){let r=this.statesByKey.get(this.stateKey(t,n));r&&(r.ownerClientIds.delete(e),this.logDebug(`lease.removed`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:r.ownerClientIds.size}),!(r.ownerClientIds.size>0)&&(this.disposeState(r),this.statesByKey.delete(this.stateKey(t,n))))}disposeState(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null),this.clearCatchupRetry(e,{resetAttempts:!0}),clearInterval(e.reconcileTimer),e.fileWatcher?.close(),e.fileWatcher=null,this.logDebug(`state.disposed`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:e.watchedPath})}async requestSync(e,t){let n=this.statesByKey.get(e);if(n){if(n.lastTriggeredAt=Date.now(),n.syncInFlight){n.rerunRequested=!0;return}n.syncInFlight=!0,n.rerunRequested=!1,n.lastSyncStartedAt=Date.now(),this.logDebug(`sync.begin`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,ownerClientCount:n.ownerClientIds.size,watchedPath:n.watchedPath,watchedDir:n.watchedDir,watchedBaseName:n.watchedBaseName,stableIdleSyncCount:n.stableIdleSyncCount});try{let r=await this.options.sessionManager.getProjectSessionSummary(n.projectId,n.sessionId);if(!r||r.providerMode!==`native`||r.provider!==`codex`&&r.provider!==`claude`){this.logDebug(`sync.stop.unwatchable_summary`,{projectId:n.projectId,sessionId:n.sessionId,summarySource:r?.source,summaryProvider:r?.provider,summaryProviderMode:r?.providerMode,summaryStatus:r?.status}),this.stopState(e);return}if(n.provider=r.provider,!YN(r)){this.clearCatchupRetry(n,{resetAttempts:!0}),n.stableIdleSyncCount=0,this.logDebug(`sync.skip.gateway_live`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,summaryStatus:r.status,interactionLockReason:r.interactionLockReason,watchedPath:n.watchedPath,ownerClientCount:n.ownerClientIds.size});return}let i=await this.options.sessionManager.syncProjectSessionHistory(n.projectId,n.sessionId);n.lastSyncCompletedAt=Date.now(),this.applyWatchPath(n,i.nativeWatchPath);let a=n.lastObservedRawSeq,o=n.lastObservedRawEventCount,s=this.resolveObservedRawSeq(i),c=s>a||i.rawEvents.length>o;if(c?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,s),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),i.session.status!==`running`&&!i.historyUpdated?n.stableIdleSyncCount+=1:n.stableIdleSyncCount=0,this.logDebug(`sync.result`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,status:i.session.status,interactionLockReason:i.session.interactionLockReason,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,nativeWatchPath:i.nativeWatchPath,rawEventCount:i.rawEvents.length,cursorAdvanced:c,previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount}),i.historyUpdated||i.statusChanged){let e=this.options.createExternalUpdateMessage({provider:i.session.provider,sessionId:i.session.id,projectId:i.session.projectId,updatedAt:i.session.updatedAt,status:i.session.status,interactionLockReason:i.session.interactionLockReason,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e)}i.historyUpdated&&await this.options.refreshDetailSessionSnapshots?.({projectId:n.projectId,sessionId:n.sessionId,reason:`external_history_updated`,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq})}catch(e){this.options.logger.warn({err:e,projectId:n.projectId,sessionId:n.sessionId,reason:t},`native session watch sync failed`)}finally{let n=this.statesByKey.get(e);if(!n)return;n.syncInFlight=!1,n.rerunRequested&&(this.logDebug(`sync.rerun`,{projectId:n.projectId,sessionId:n.sessionId,reason:t}),n.rerunRequested=!1,this.requestSync(e,`rerun`))}}}stopState(e){let t=this.statesByKey.get(e);if(t){this.disposeState(t),this.statesByKey.delete(e);for(let t of this.targetsByClientId.values())t.delete(e)}}applyWatchPath(e,t){let n=t?.trim()??``;if(!n)return;let r=p.default.resolve(n);if(e.watchedPath===r&&e.fileWatcher)return;let i=p.default.dirname(r),a=p.default.basename(r);e.fileWatcher?.close(),e.fileWatcher=null,e.watchedPath=r,e.watchedDir=i,e.watchedBaseName=a,this.logDebug(`watch.path.applied`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,watchedDir:i,watchedBaseName:a});try{e.fileWatcher=this.createPathWatcher(r,(t,n)=>{let i=n?Buffer.isBuffer(n)?n.toString(`utf8`):n:void 0;this.logDebug(`watch.fs.event`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,eventType:t,filename:i}),this.scheduleDebouncedSync(this.stateKey(e.projectId,e.sessionId))}),e.fileWatcher.on(`error`,t=>{this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`native session watcher error`)})}catch(t){this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`failed to start native session watcher`)}}createPathWatcher(e,t){return this.options.createWatcher?this.options.createWatcher(e,t):(0,u.watch)(e,(e,n)=>{t(e,n)})}scheduleDebouncedSync(e){let t=this.statesByKey.get(e);if(!t)return;let n=!!t.debounceTimer;t.debounceTimer&&clearTimeout(t.debounceTimer),this.clearCatchupRetry(t,{resetAttempts:!0}),this.logDebug(`watch.debounce.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath,delayMs:300,replacedExistingTimer:n}),t.debounceTimer=setTimeout(()=>{t.debounceTimer=null,this.logDebug(`watch.debounce.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath}),this.requestSync(e,`watch`)},300)}resolveObservedRawSeq(e){let t=e.rawEvents[e.rawEvents.length-1],n=t&&typeof t==`object`&&t&&`rawSeq`in t&&typeof t.rawSeq==`number`?t.rawSeq:void 0;return e.toRawSeq??n??0}clearCatchupRetry(e,t){e.catchupRetryTimer&&=(clearTimeout(e.catchupRetryTimer),null),t?.resetAttempts&&(e.watchCatchupRetryCount=0)}maybeScheduleWatchCatchupRetry(e,t,n,r,i){n!==`watch`&&n!==`watch_catchup`||t.ownerClientIds.size!==0&&(t.watchCatchupRetryCount>=2||(t.catchupRetryTimer||=(t.watchCatchupRetryCount+=1,this.logDebug(`watch.catchup.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,reason:n,delayMs:uF,historyUpdated:r.historyUpdated,refreshMode:r.refreshMode,previousObservedRawSeq:i.previousObservedRawSeq,previousObservedRawEventCount:i.previousObservedRawEventCount,nextObservedRawSeq:i.nextObservedRawSeq,nextObservedRawEventCount:i.nextObservedRawEventCount,watchCatchupRetryCount:t.watchCatchupRetryCount}),setTimeout(()=>{t.catchupRetryTimer=null,this.logDebug(`watch.catchup.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchCatchupRetryCount:t.watchCatchupRetryCount}),this.requestSync(e,`watch_catchup`)},uF))))}stateKey(e,t){return JSON.stringify([e,t])}},pF=class{constructor(e){this.config=e}issue(e){let t=mF(e.sizeBytes??0),n=ZC.default.sign({sub:e.deviceId,type:`workspace_preview`,gatewayId:this.config.gatewayId,path:e.canonicalPath,disposition:e.disposition},this.config.accessSecret,{expiresIn:t}),r=ZC.default.decode(n);return{ticket:n,expiresAt:r?.exp?new Date(r.exp*1e3).toISOString():new Date().toISOString()}}getExpiresAt(e){let t=ZC.default.decode(e);return t?.exp?new Date(t.exp*1e3).toISOString():new Date().toISOString()}verify(e){let t;try{t=ZC.default.verify(e,this.config.accessSecret)}catch(e){if(e instanceof Error){if(e.name===`TokenExpiredError`)throw hw();if(e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)throw mw()}throw e}if(t.type!==`workspace_preview`||t.gatewayId!==this.config.gatewayId)throw mw();return t}};function mF(e){return e>20971520?7200:600}var hF=class{constructor(e){this.dependencies=e}async listEntries(e,t=200){if(e.kind===`absolute`)return this.dependencies.fsService.listEntriesAbsolute(e.path,t);let n=await this.requireProject(e.projectId);return this.dependencies.fsService.listEntriesProjectRelative(n.path,e.path??`.`,t)}async resolveFile(e){return{file:(await this.resolveLocator(e)).descriptor}}async readTextFile(e,t={}){let n=await this.resolveLocator(e),r=await this.dependencies.fsService.readTextFile(n.canonicalPath,t);return{file:n.descriptor,...r}}async preparePreview(e,t){let n=await this.resolveLocator(e),r=t.disposition??(n.descriptor.preferredPreviewAction===`share_sheet`||n.descriptor.preferredPreviewAction===`download`?`attachment`:`inline`),i=this.dependencies.previewTicketService.issue({canonicalPath:n.canonicalPath,deviceId:t.deviceId??``,disposition:r,sizeBytes:n.descriptor.sizeBytes}),a=i.ticket,o=i.expiresAt;return{file:n.descriptor,preview:{url:t.buildPreviewUrl(a),expiresAt:o,supportsRange:n.descriptor.capabilities.supportsRange,contentType:n.descriptor.mimeType,contentDisposition:r}}}async readPreviewContent(e,t={}){let n=this.dependencies.previewTicketService.verify(e),r=await this.dependencies.fsService.resolveAbsoluteFile(n.path),i=await this.dependencies.fsService.readFileContentRange(r.canonicalPath,{rangeHeader:t.rangeHeader,includeBody:t.includeBody});return{statusCode:i.statusCode,headers:{contentType:r.mimeType,contentDisposition:_F(n.disposition,r.displayName),contentLength:i.contentLength,etag:i.etag,...r.capabilities.supportsRange?{acceptRanges:`bytes`}:{},...i.contentRange?{contentRange:i.contentRange}:{},...i.lastModified?{lastModified:i.lastModified}:{},cacheControl:`private, max-age=300`},body:i.buffer}}async openPreviewContentStream(e,t={}){let n=this.dependencies.previewTicketService.verify(e),r=await this.dependencies.fsService.resolveAbsoluteFile(n.path),i=await this.dependencies.fsService.openFileContentRangeStream(r.canonicalPath,{rangeHeader:t.rangeHeader,includeBody:t.includeBody});return{statusCode:i.statusCode,headers:{contentType:r.mimeType,contentDisposition:_F(n.disposition,r.displayName),contentLength:i.contentLength,etag:i.etag,...r.capabilities.supportsRange?{acceptRanges:`bytes`}:{},...i.contentRange?{contentRange:i.contentRange}:{},...i.lastModified?{lastModified:i.lastModified}:{},cacheControl:`private, max-age=300`},bodyStream:i.stream}}async resolveLocator(e){if(e.kind===`absolute`){let t=await this.dependencies.fsService.resolveAbsoluteFile(e.path);return{canonicalPath:t.canonicalPath,descriptor:{locator:{kind:`absolute`,path:t.canonicalPath},canonicalPath:t.canonicalPath,displayName:t.displayName,kind:`file`,sizeBytes:t.sizeBytes,mimeType:t.mimeType,extension:t.extension,updatedAt:t.updatedAt,etag:t.etag,previewCategory:t.previewCategory,preferredPreviewAction:t.preferredPreviewAction,capabilities:t.capabilities}}}if(e.kind===`project_relative`){let t=await this.requireProject(e.projectId),n=await this.dependencies.fsService.resolveProjectRelativeFile(t.path,e.path),r=gF(p.default.relative(t.path,n.canonicalPath));return{canonicalPath:n.canonicalPath,descriptor:{locator:{kind:`project_relative`,projectId:t.id,path:r},canonicalPath:n.canonicalPath,displayName:n.displayName,projectId:t.id,relativePath:r,kind:`file`,sizeBytes:n.sizeBytes,mimeType:n.mimeType,extension:n.extension,updatedAt:n.updatedAt,etag:n.etag,previewCategory:n.previewCategory,preferredPreviewAction:n.preferredPreviewAction,capabilities:n.capabilities}}}let t=this.dependencies.sessionManager.getSessionExecutionContext(e.sessionId),n=await this.dependencies.fsService.resolveProjectRelativeFile(t.projectPath,e.path),r=gF(p.default.relative(t.projectPath,n.canonicalPath));return{canonicalPath:n.canonicalPath,descriptor:{locator:{kind:`session_relative`,sessionId:e.sessionId,path:r},canonicalPath:n.canonicalPath,displayName:n.displayName,projectId:t.projectId,relativePath:r,kind:`file`,sizeBytes:n.sizeBytes,mimeType:n.mimeType,extension:n.extension,updatedAt:n.updatedAt,etag:n.etag,previewCategory:n.previewCategory,preferredPreviewAction:n.preferredPreviewAction,capabilities:n.capabilities}}}async requireProject(e){let t=await this.dependencies.sessionManager.getProject(e);if(!t)throw gw(e);return t}};function gF(e){return e.split(p.default.sep).join(`/`)}function _F(e,t){return`${e}; filename="${t.replace(/["\\]/g,`_`)}"`}function vF(e){return e.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`},purpose:e.purpose,detailLevel:e.detailLevel,bootstrapMode:e.bootstrapMode}))}const yF=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG;let bF=null;const xF={perMessageDeflate:{threshold:1024}},SF={globalDecompression:!1,threshold:1024,customTypes:/^text\/(?!event-stream)|(?:\+|\/)json(?:;|$)|(?:\+|\/)text(?:;|$)|(?:\+|\/)xml(?:;|$)/u},CF=4096;function wF(e,t){yF&&(console.log(`[native-watch][gateway]`,e,t),bF?.info({event:e,...t},`native session watch debug`))}function TF(e){return e?typeof e==`string`?e:e.toString(`utf8`):``}function EF(e){return{sessionId:e.sessionId,projectId:e.projectId??null,purpose:e.purpose??null,detailLevel:e.detailLevel??null,bootstrapMode:e.bootstrapMode??null,cursorKind:e.cursor.kind,rawSeq:e.cursor.kind===`raw_seq`?e.cursor.rawSeq:null}}async function DF(e){let t=e.limit??300,n=e.detailLevel??`full`,r=(r,i)=>{mA(`raw-events.list`,{requestSource:e.requestSource,projectId:e.projectId,sessionId:e.sessionId,limit:t,detailLevel:n,requestedCursor:e.fromRawSeqExclusive??null,decision:r.decision,reason:r.reason,fromRawSeqExclusive:r.fromRawSeqExclusive??null,toRawSeq:r.toRawSeq??null,returnedCount:r.events.length,returnedFirstRawSeq:r.events[0]?.rawSeq??null,returnedLastRawSeq:r.events[r.events.length-1]?.rawSeq??null,...i})};if(e.fromRawSeqExclusive===void 0){let i=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),a={decision:`snapshot`,reason:i.length===0?`empty_history_snapshot`:`initial_snapshot`,toRawSeq:i[i.length-1]?.rawSeq,events:eE(i,n)};return r(a),a}let i=await e.sessionManager.getProjectSessionRawSeqRange(e.projectId,e.sessionId);if(!i){let e={decision:`snapshot`,reason:`empty_history_snapshot`,events:[]};return r(e,{rangeMin:null,rangeMax:null,minExpectedCursor:null}),e}let a=Math.max(0,i.min-1);if(e.fromRawSeqExclusive<a||e.fromRawSeqExclusive>i.max){let o=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),s={decision:`snapshot`,reason:`cursor_out_of_range`,toRawSeq:o[o.length-1]?.rawSeq,events:eE(o,n)};return r(s,{rangeMin:i.min,rangeMax:i.max,minExpectedCursor:a}),s}let o=await e.sessionManager.getProjectSessionRawEventsSinceSeq(e.projectId,e.sessionId,e.fromRawSeqExclusive,t),s={decision:`delta`,reason:`cursor_valid_delta`,fromRawSeqExclusive:e.fromRawSeqExclusive,toRawSeq:o[o.length-1]?.rawSeq??e.fromRawSeqExclusive,events:eE(o,n)};return r(s,{rangeMin:i.min,rangeMax:i.max,minExpectedCursor:a}),s}async function OF(e,t={}){await mg(e.gatewayLogPath);let n=AF(e,t),r=kF(e,n.instance);pA(r.log),bF=r.log,await r.register($C.default,{origin:!0}),await r.register(ew.default,SF),await r.register(QC.default,{options:xF});let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new kw(e);await s.init();let c=new zw(e.auditLogPath),l=new lF,u=new TT,d=new bE(e.projectStoreDir),f=new CN(e.sessionHistoryDir);await f.init();let m=new $k(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Bk({store:m});await h.init();let g,_=null,v=new Map,y=await rm(e.authStoreDir),b=new pF(e),x=e.relayEnabled?wh({relayUrl:e.relayUrl,gatewayHost:e.host}):``,S=e=>{let t=v.get(e);t&&(clearTimeout(t.timeout),v.delete(e),t.resolve())},C=(e,t)=>{let n=v.get(e);n&&(clearTimeout(n.timeout),v.delete(e),n.reject(t instanceof Error?t:Error(String(t))))},w=(e,t)=>new Promise((n,r)=>{C(e,Error(`Duplicate pending relay file upload start for request ${e}`));let i=setTimeout(()=>{v.delete(e),r(Error(`Relay file upload start timed out for request ${e}`))},t);v.set(e,{resolve:n,reject:r,timeout:i})}),T=new oM({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e),D.routeReadableLiveDelta(e)}}),E=new hF({fsService:u,sessionManager:T,previewTicketService:b}),D=new iF(l,T,e.readableLiveDeltaCoalesceMs,mA),O=new fF({sessionManager:T,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>_P(e),refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e)});T.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let k=new Nh({packageName:z.packageName,currentVersion:z.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>T.getRunningRuntimeSessionCount(),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{D.shutdown(),O.close(),_?.close(),M.close(),await k.shutdown(),await T.shutdown(),await f.shutdown();for(let[e,t]of v.entries())clearTimeout(t.timeout),t.reject(Error(`Gateway shutting down`)),v.delete(e);r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{pA(null),bF=null,n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:R(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),gatewayName:e.name,machineName:lm(),gatewayIdentity:y.identity})),r.get(`/api/pairing/descriptor`,async()=>gh({gatewayId:e.gatewayId,gatewayName:e.name,machineName:lm(),relayBaseUrl:x,directBaseUrls:Sh({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),relayTransportSecurityLevel:e.relayEnabled?e.relayTransportSecurityLevel:void 0,gatewayIdentity:y.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!L(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(t,n)=>{let r=il.safeParse(t.body);if(!r.success)return n.code(400).send({error:`Invalid request`,detail:r.error.flatten()});try{let t=he(r.data.deviceName),n=await s.claimPairingCode(r.data.code,t,r.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:n.deviceId,detail:{deviceName:t}}),nP(y,{...n,gatewayName:e.name,machineName:lm()},r.data.code,r.data.deviceIdentity)}catch(e){return n.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=sl.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await ZN({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}});let A=()=>Zu.parse({name:e.name,machineName:lm()}),j=async n=>{let r=Zu.pick({name:!0}).parse(n);if(!t.configPath)throw Error(`Gateway config path is unavailable`);return e.name=await wm(t.configPath,r.name),A()};r.get(`/api/gateway/settings`,async(e,t)=>{if(ne(e,t))return A()}),r.post(`/api/gateway/settings`,async(e,t)=>{if(!ne(e,t))return;let n=Zu.pick({name:!0}).safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await j(n.data)}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(ne(e,t))return{projects:await T.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(ne(e,t))try{return await k.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!ne(e,t))return;let n=e.body,r=Su.safeParse(n?.requestedBy);try{let e=await k.applyUpdate(r.success?r.data:`mobile`);return Du.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.post(`/api/codex/app-server/restart`,async(e,t)=>{if(ne(e,t))try{return gl.parse(await T.restartCodexAppServer())}catch(e){let n=cw(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/codex/accounts`,async(e,t)=>{if(ne(e,t))try{return pl.parse(await T.getCodexAccounts())}catch(e){return re(t,e)}}),r.post(`/api/codex/accounts/save`,async(e,t)=>{if(ne(e,t))try{return ml.parse(await T.saveCurrentCodexAccount())}catch(e){return re(t,e)}}),r.post(`/api/codex/accounts/switch`,async(e,t)=>{if(!ne(e,t))return;let n=e.body;if(typeof n?.accountId!=`string`||!n.accountId.trim())return t.code(400).send({error:`accountId is required and must be a non-empty string`});try{return hl.parse(await T.switchCodexAccount(n.accountId))}catch(e){return re(t,e)}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(ne(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(ne(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!ne(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return cw(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):cP(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!ne(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/workspace/directories`,async(e,t)=>{if(!ne(e,t))return;let n=e.body;if(typeof n?.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});if(typeof n.name!=`string`||!n.name.trim())return t.code(400).send({error:`name is required and must be a non-empty string`});try{return await u.createDirectoryUnrestricted(n.path,n.name,200)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/workspace/entries`,async(e,t)=>{if(!ne(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{let t=ie(e.query);return await E.listEntries(t,i)}catch(e){return re(t,e)}}),r.get(`/api/workspace/files/resolve`,async(e,t)=>{if(ne(e,t))try{let t=ae(e.query);return await E.resolveFile(t)}catch(e){return re(t,e)}}),r.get(`/api/workspace/files/text`,async(e,t)=>{if(!ne(e,t))return;let n=e.query,r=n.startLine?Number(n.startLine):void 0,i=n.maxLines?Number(n.maxLines):void 0,a=n.maxBytes?Number(n.maxBytes):void 0;try{let t=ae(e.query);return await E.readTextFile(t,{startLine:typeof r==`number`&&Number.isFinite(r)?r:void 0,maxLines:typeof i==`number`&&Number.isFinite(i)?i:void 0,maxBytes:typeof a==`number`&&Number.isFinite(a)?a:void 0})}catch(e){return re(t,e)}}),r.post(`/api/workspace/files/preview`,async(e,t)=>{let n=ne(e,t);if(!n)return;let r=e.body,i=Ou.safeParse(r?.locator);if(!i.success)return t.code(400).send({error:i.error.issues[0]?.message??`Invalid workspace file locator`});let a;if(r?.disposition!==void 0){let e=Ru.safeParse(r.disposition);if(!e.success)return t.code(400).send({error:e.error.issues[0]?.message??`Invalid preview disposition`});a=e.data}try{return await E.preparePreview(i.data,{deviceId:n.sub,disposition:a,buildPreviewUrl:t=>`${oe(e)}/api/workspace/files/content/${encodeURIComponent(t)}`})}catch(e){return re(t,e)}}),r.route({method:[`GET`,`HEAD`],url:`/api/workspace/files/content/:ticket`,handler:async(e,t)=>{let n=e.params.ticket?.trim()??``;if(!n)return t.code(400).send({error:`ticket is required`});try{let r=await E.readPreviewContent(n,{rangeHeader:typeof e.headers.range==`string`?e.headers.range:void 0,includeBody:e.method!==`HEAD`});return t.code(r.statusCode),t.header(`Content-Type`,r.headers.contentType),t.header(`Content-Disposition`,r.headers.contentDisposition),t.header(`Content-Length`,String(r.headers.contentLength)),t.header(`ETag`,r.headers.etag),t.header(`Cache-Control`,r.headers.cacheControl),r.headers.acceptRanges&&t.header(`Accept-Ranges`,r.headers.acceptRanges),r.headers.contentRange&&t.header(`Content-Range`,r.headers.contentRange),r.headers.lastModified&&t.header(`Last-Modified`,r.headers.lastModified),e.method===`HEAD`||!r.body?t.send():t.send(r.body)}catch(e){return re(t,e)}}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!ne(e,t))return;let n=le(e,t);if(n)try{return{capabilities:await T.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return cw(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!ne(e,t))return;let n=le(e,t);if(n)try{return await T.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return cw(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!ne(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await T.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!ne(e,t))return;let n=e.params;try{return await T.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=e.query,i=se(r.status,t);if(!i)return;let a=ce(r.syncExternal);try{return{sessions:await T.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return cw(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=await T.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/config`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=await T.getProjectSessionConfig(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.post(`/api/projects/:projectId/sessions/:sessionId/history-sync`,async(e,t)=>{if(!ne(e,t))return;let n=e.params;try{let e=await T.syncProjectSessionHistory(n.projectId,n.sessionId);return e.historyUpdated&&await D.refreshDetailSessionSnapshots({projectId:n.projectId,sessionId:n.sessionId,reason:`explicit_history_sync`,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}),{session:e.session,rawEventCount:e.rawEvents.length,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged,refreshMode:e.refreshMode,...e.fromRawSeq===void 0?{}:{fromRawSeq:e.fromRawSeq},...e.toRawSeq===void 0?{}:{toRawSeq:e.toRawSeq}}}catch(e){return cw(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=typeof r.fromRawSeqExclusive==`string`?Number(r.fromRawSeqExclusive):void 0,o=nc.safeParse(r.detailLevel).success?nc.parse(r.detailLevel):`full`;try{return await I(n.projectId,n.sessionId,i,typeof a==`number`&&Number.isFinite(a)?Math.max(0,Math.floor(a)):void 0,o,`http`)}catch(e){return cw(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=e.query,i=await T.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>L(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!L(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=ue(t.headers.authorization)??de(t.url);if(!n){e.close(1008,`Missing access token`);return}let i;try{i=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let a=l.addClient(i.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await P(gc(e),i.sub,a)}catch(e){await F({deviceId:i.sub,clientId:a,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,(e,t)=>{let n=l.getSubscriptions(a),o=O.getClientWatchTargets(a);r.log.info({clientId:a,deviceId:i.sub,transport:`direct`,closeCode:typeof e==`number`?e:null,closeReason:TF(t),streamSubscriptionCount:n.length,streamSubscriptions:n.map(EF),externalWatchTargetCount:o.length,externalWatchTargets:o},`gateway websocket client disconnected`),O.removeClient(a),l.removeClient(a),D.clearStatesForClient(a)})});let M=new _A({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?e.relayTransportSecurityLevel:`plaintext-relay`,gatewayIdentity:y.identity,gatewayIdentityPrivateKeyPem:y.privateKeyPem,sessionHub:l,logger:r.log,describeClientState:e=>{let t=l.getSubscriptions(e),n=O.getClientWatchTargets(e);return{streamSubscriptionCount:t.length,streamSubscriptions:t.map(EF),externalWatchTargetCount:n.length,externalWatchTargets:n}},handlePairingClaim:async t=>{let n=he(t.deviceName);return nP(y,{...await s.claimPairingCode(t.code,n,t.deviceIdentity),gatewayName:e.name,machineName:lm()},t.code,t.deviceIdentity)},handleRefresh:async t=>{let n=await ZN({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return XN(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},handleFileContentRequest:async(e,t)=>{if(t.method===`GET`&&t.responseMode===`stream_upload`){let n=await E.openPreviewContentStream(t.ticket,{rangeHeader:t.rangeHeader,includeBody:!0});if(n.bodyStream&&t.uploadUrl&&t.uploadToken){let i=w(e,15e3),a=MF({uploadUrl:t.uploadUrl,uploadToken:t.uploadToken,contentLength:n.headers.contentLength,bodyStream:n.bodyStream});a.completed.catch(n=>{C(e,n),r.log.warn({err:n,requestId:e,ticket:t.ticket},`relay workspace preview upload failed`)});try{await i}catch(e){throw a.abort(e),e}}return qd.parse({status:n.statusCode,headers:n.headers,...n.bodyStream?{bodyTransport:`stream_upload`}:{}})}let n=await E.readPreviewContent(t.ticket,{rangeHeader:t.rangeHeader,includeBody:t.method===`GET`});return qd.parse({status:n.statusCode,headers:n.headers,...n.body?{bodyBase64:n.body.toString(`base64`)}:{}})},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(t,n)=>iP(t,{gatewayId:e.gatewayId,relayPreviewBaseUrl:x,authService:s,logger:r.log,sessionManager:T,projectDiscoveryService:h,fsService:u,workspaceFileService:E,updateService:k,gatewaySettings:{get:A,update:j},relayDeviceId:n.deviceId,refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e),buildRawEventsListResult:DF}),handleFileContentUploadStarted:S,sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await P(e,t,n)}catch(r){await F({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),N=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await T.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await T.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:await T.startReview(e.payload.sessionId,e.payload.config,t,{input:e.payload.input,turnConfig:e.payload.turnConfig});return;case`tool.approval.respond`:await T.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await T.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await T.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.external.watch.set`:{wF(`command.received`,{clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions},`received session.external.watch.set`);let i=O.setClientWatchTargets(n,e.payload.sessions,e.payload.replace);wF(`command.applied`,{clientId:n,deviceId:t,replace:e.payload.replace,requestedSessionCount:e.payload.sessions.length,targetCount:i.length,targets:i}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,requestedSessionCount:e.payload.sessions.length,targetCount:i.length,targets:i},`applied session.external.watch.set`),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:i.map(e=>e.sessionId)}});return}case`session.stream.subscribe`:{let t=vF(e.payload.sessions);await D.handleSessionStreamSubscribeCommand(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=T.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await T.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=T.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await T.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},P=async(e,t,n)=>{await N(e,t,n)},F=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await T.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},I=async(e,t,n=300,r,i=`full`,a=`http`)=>DF({sessionManager:T,projectId:e,sessionId:t,limit:n,fromRawSeqExclusive:r,detailLevel:i,requestSource:a}),L=t=>t.headers[`x-api-key`]===e.apiKey,R=e=>{if(e==null)return e;if(typeof e==`string`){let t=ee(e);return t===void 0?B(e,a):te(V(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=ee(t);return n===void 0?B(t,a):te(V(n))}return typeof e==`object`?te(V(e)):String(e)},ee=e=>{try{return JSON.parse(e)}catch{return}},B=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,V=e=>{if(Array.isArray(e))return e.map(e=>V(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=V(r)}return n}return e},te=e=>{let t=H(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:B(t,a)}},H=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},ne=(e,t)=>{let n=ue(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},re=(e,t)=>{let n=cw(t)?t.status:500;return cw(t)?e.code(n).send({error:String(t),code:t.code,...t.details===void 0?{}:{details:t.details}}):e.code(n).send({error:String(t)})},ie=e=>{let t=e&&typeof e==`object`?e:{},n=ku.safeParse({kind:typeof t.locatorKind==`string`?t.locatorKind:void 0,projectId:typeof t.projectId==`string`?t.projectId:void 0,path:typeof t.path==`string`?t.path:void 0});if(!n.success)throw Error(n.error.issues[0]?.message??`Invalid workspace entries locator`);return n.data},ae=e=>{let t=e&&typeof e==`object`?e:{},n=Ou.safeParse({kind:typeof t.locatorKind==`string`?t.locatorKind:void 0,sessionId:typeof t.sessionId==`string`?t.sessionId:void 0,projectId:typeof t.projectId==`string`?t.projectId:void 0,path:typeof t.path==`string`?t.path:void 0});if(!n.success)throw Error(n.error.issues[0]?.message??`Invalid workspace file locator`);return n.data},oe=t=>{let n=t.headers.host?.trim();return n?`${t.protocol}://${n}`.replace(/\/+$/,``):`${e.httpsEnabled?`https`:`http`}://${e.host}:${e.httpsEnabled?e.httpsPort:e.port}`},se=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ce=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},le=(e,t)=>{let n=e.params,r=e.query,i=Na.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},ue=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},de=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},fe=e.httpsEnabled?e.httpsPort:e.port,pe=e.httpsEnabled?`https`:`http`,me=lm(),he=e=>e?.trim()||`Craby mobile`;await r.listen({host:e.host,port:fe});let ge=r.server.address(),_e=typeof ge==`object`&&ge?ge.port:fe;if(r.log.info({host:e.host,port:_e,protocol:pe,machineName:me},jF(pe,e.host,_e)),e.relayEnabled&&(_=new jA({gatewayId:e.gatewayId,machineName:e.name,relayUrl:e.relayUrl,relayTransportSecurityLevel:e.relayTransportSecurityLevel,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>IA({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:y.identity,privateKeyPem:y.privateKeyPem}),gatewayIdentity:y.identity,directBaseUrls:Sh({protocol:pe,host:e.host,port:_e}),logger:r.log,onFrame:async e=>{await M.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await k.start(),{protocol:pe,listenPort:_e,gatewayName:e.name,machineName:me,gatewayIdentity:y.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>k.getInfo(),requestGatewayUpdate:(e=`console`)=>k.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>T.restartCodexAppServer(),startupPairingCode:g}}function kF(e,t){let n=t;if(!e.httpsEnabled)return(0,tw.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:CF}});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);let r={key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}};return(0,tw.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:CF},https:r})}function AF(e,t){let n=process.env.NODE_ENV!==`production`,r=nw.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?nw.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,nw.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function jF(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function MF(e){let t=new URL(e.uploadUrl),n=t.protocol===`https:`?S.request:t.protocol===`http:`?x.request:null;if(!n)throw Error(`Unsupported relay preview upload protocol: ${t.protocol}`);let r=null,i=e=>{};return{completed:new Promise((a,o)=>{let s=!1,c=t=>{if(s)return;if(s=!0,!t){a();return}let n=t instanceof Error?t:Error(String(t));e.bodyStream.destroy(n),r?.destroy(n),o(n)};r=n(t,{method:`PUT`,headers:{"content-type":`application/octet-stream`,"content-length":String(e.contentLength),"x-relay-upload-token":e.uploadToken}},e=>{let t=[];e.on(`data`,e=>{t.push(Buffer.isBuffer(e)?e:Buffer.from(e))}),e.on(`error`,c),e.on(`end`,()=>{let n=e.statusCode??0;if(n>=200&&n<300){c();return}c(Error(`Relay preview upload failed (${n}): ${Buffer.concat(t).toString(`utf8`)}`))})}),i=e=>{c(e??Error(`Relay preview upload aborted`))},r.on(`error`,c),(0,C.pipeline)(e.bodyStream,r).catch(c)}),abort:i}}function NF(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,b.inspect)(e,{depth:6,breakLength:120})}async function PF(e){let t=await bm({configPath:e.configPath,ensureConfigFile:!0});Tm(t.config);let n=await OF(t.config,{configPath:t.configPath,logToConsole:e.logToConsole,onUpdatePrepared:async e=>{IF({type:`worker.update.prepared`,payload:e})}});IF({type:`worker.ready`,payload:FF(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=LF(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${NF(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${NF(e)}`),i(1)});async function a(e){try{switch(e.method){case`gateway.update.apply`:{if(!n.requestGatewayUpdate)throw Error(`gateway update is unavailable`);let t=await n.requestGatewayUpdate(e.requestedBy);IF({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}case`codex.appServer.restart`:{if(!n.requestCodexAppServerRestart)throw Error(`codex app-server restart is unavailable`);let t=await n.requestCodexAppServerRestart(e.requestedBy);IF({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){IF({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function FF(e){return{protocol:e.protocol,listenPort:e.listenPort,gatewayName:e.gatewayName,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function IF(e){process.send&&process.send(e)}function LF(e){if(!RF(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:e.method,requestedBy:e.requestedBy};default:return null}}function RF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}zF(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function zF(e){let t=ee(e);switch(t.command){case`help`:WF();return;case`version`:console.log(z.version);return;case`init`:await VF(t);return;case`doctor`:await HF(t);return;case`start`:await BF(t);return;case`__worker`:await UF(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function BF(e){let t=await bm({configPath:e.configPath,ensureConfigFile:!0});Tm(t.config);let n=await Wm({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await og({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(hg(e,t.config))}Gm(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function VF(e){let t=await ym({configPath:e.configPath,overwrite:e.force});t.created?console.log(`[gateway] wrote config to ${t.configPath}`):(console.log(`[gateway] config already exists at ${t.configPath}`),console.log(`[gateway] rerun with --force to overwrite`));let n=await bm({configPath:t.configPath,ensureConfigFile:!1}),r=await Wm({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Km(r))}async function HF(e){let t=await bm({configPath:vm(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Wm({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Km(n)),Gm(n)&&(process.exitCode=1)}async function UF(e){try{await PF(e)}catch(t){let n=await bm({configPath:e.configPath,ensureConfigFile:!0});throw Error(hg(t,n.config))}}function WF(){console.log(`${z.cliName} ${z.version}`),console.log(``),console.log(`Usage:`),console.log(` ${z.cliName} [start] [--config <path>] [--log]`),console.log(` ${z.cliName} init [--config <path>] [--force]`),console.log(` ${z.cliName} doctor [--config <path>]`),console.log(` ${z.cliName} --version`)}exports.runCli=zF;
|