craby-gateway 0.31.1 → 0.31.3
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 +5 -5
- 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.31.1`,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:workspace-deps":`pnpm --filter @remote-agent/contracts run build && pnpm --filter @remote-agent/provider-adapters run build`,"build:bundle":`pnpm run build:workspace-deps && 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`,"mobile:ios-ota:publish":`tsx src/mobileIosOtaInstall.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.118`,"@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.31.3`,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:workspace-deps":`pnpm --filter @remote-agent/contracts run build && pnpm --filter @remote-agent/provider-adapters run build`,"build:bundle":`pnpm run build:workspace-deps && 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`,"mobile:ios-ota:publish":`tsx src/mobileIosOtaInstall.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.118`,"@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
|
`)?`
|
|
@@ -135,7 +135,7 @@ ${a}`:a}function Zs(e,t){return Fc(e).map((e,n,r)=>n===r.length-1&&e===``?``:`${
|
|
|
135
135
|
`).trim();return t.length>0?t:void 0}function vc(e){return Do.test(e)}function yc(e){return e===`failed`?`error`:e===`streaming`?`accent`:e===`waiting_approval`||e===`waiting_input`?`warning`:`success`}function bc(e){let t=kc(e.payload.raw),n=jc(t,[`turn_id`,`turnId`]);if(n)return n;let r=jc(kc(t.item),[`turn_id`,`turnId`]);if(r)return r;let i=jc(kc(t.turn),[`id`,`turn_id`,`turnId`]);if(i)return i;let a=kc(t.message),o=jc(a,[`turn_id`,`turnId`]);if(o)return o;let s=jc(kc(a.item),[`turn_id`,`turnId`]);if(s)return s;let c=jc(kc(a.turn),[`id`,`turn_id`,`turnId`]);if(c)return c;let l=kc(a.params);return jc(l,[`turnId`,`turn_id`])??jc(kc(l.turn),[`id`,`turn_id`,`turnId`])??jc(kc(l.item),[`turn_id`,`turnId`])}function xc(e){if(e.type!==`native.raw`)return e.type;let t=kc(e.payload.raw),n=kc(t.message),r=jc(n,[`method`])??jc(t,[`method`]);if(r)return r;if(jc(n,[`scope`])===`item`)return`item.completed`}function Sc(e){let t=kc(e.payload.raw),n=kc(t.item);if(Object.keys(n).length>0)return n;let r=kc(t.message),i=kc(r.item);return Object.keys(i).length>0?i:kc(kc(r.params).item)}function Cc(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 wc(e){let t=xc(e);return t!==`item.started`&&t!==`item.completed`&&t!==`item/started`&&t!==`item/completed`?!1:Cc(jc(Sc(e),[`type`]))===`user_message`}function Tc(e){let t=xc(e);return t!==`item.started`&&t!==`item.completed`&&t!==`item/started`&&t!==`item/completed`?!1:Cc(jc(Sc(e),[`type`]))===`reasoning`}function Ec(e){if(e.type===`turn.completed`||e.type===`turn.failed`)return!0;let t=kc(e.payload.raw),n=kc(t.message),r=jc(n,[`method`])??jc(t,[`method`]);if(r===`turn/completed`||r===`turn/failed`||r===`turn/interrupted`)return!0;if(jc(n,[`scope`])!==`turn`)return!1;let i=jc(kc(n.turn),[`status`]);return i===`completed`||i===`failed`||i===`interrupted`}function Dc(e){let t=Sc(e),n=Cc(jc(t,[`type`]));if(n&&(n===`command_execution`||n===`file_change`||n===`web_search`))return t}function Oc(e){let t=Cc(jc(e,[`type`]));if(t===`file_change`)return`正在编辑`;if(t===`web_search`)return`正在搜索`;if(t===`command_execution`){let t=Array.isArray(e?.command_actions)?e.command_actions:Array.isArray(e?.commandActions)?e.commandActions:[],n=!1,r=!1;for(let e of t){let t=jc(kc(e),[`type`]);t===`read`||t===`listFiles`||t===`list_files`?n=!0:t===`search`&&(r=!0)}return r?`正在搜索`:n?`正在浏览`:`正在运行命令`}return`正在思考`}function kc(e){return typeof e==`object`&&e?e:{}}function Ac(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function jc(e,t){let n=e??{};for(let e of t){let t=n[e];if(typeof t==`string`&&t.trim())return t}}function Mc(e,t){let n=e??{};for(let e of t){let t=n[e];if(typeof t==`number`&&Number.isFinite(t))return t}}function Nc(e){let t=new Set,n=[];for(let r of e)!r||t.has(r)||(t.add(r),n.push(r));return n}function Pc(e){let t=e.replace(/\\/g,`/`).split(`/`);return t[t.length-1]??e}function Fc(e){return e?e.replace(/\r\n/g,`
|
|
136
136
|
`).split(`
|
|
137
137
|
`):[]}var Ic=Y([`text`,`output`]),Lc=q({id:G().min(1),field:Ic,delta:G()});function Rc(e,t){let n=new Map(e.map(e=>[e.id,e])),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!r.has(e.id)).map(e=>e.id),a=[],o=[];for(let e of t){let t=n.get(e.id);if(!t){a.push(e);continue}if(Uc(t)===Uc(e))continue;let r=zc(t,e);if(!r){a.push(e);continue}o.push(...r)}return{upserts:a,removals:i,textDeltaPatches:o}}function zc(e,t){if(e.kind!==t.kind)return null;let n=Bc(e);if(n.length===0||Wc(Hc(e))!==Wc(Hc(t)))return null;let r=[];for(let i of n){let n=Vc(e,i),a=Vc(t,i);if(n!==a){if(typeof n!=`string`||typeof a!=`string`||!a.startsWith(n)||a.length<=n.length)return null;r.push({id:t.id,field:i,delta:a.slice(n.length)})}}return r.length>0?r:null}function Bc(e){switch(e.kind){case`agent_commentary`:case`activity_summary`:return[`text`];case`terminal_card`:case`command_strip`:return[`output`];default:return[]}}function Vc(e,t){return t===`text`?`text`in e&&typeof e.text==`string`?e.text:void 0:`output`in e&&typeof e.output==`string`?e.output:void 0}function Hc(e){if(e.kind===`agent_commentary`||e.kind===`activity_summary`){let{text:t,...n}=e;return n}if(e.kind===`terminal_card`||e.kind===`command_strip`){let{output:t,...n}=e;return n}return e}function Uc(e){return JSON.stringify(e)}function Wc(e){return JSON.stringify(e)}var Gc=G().trim().min(1).nullable(),Kc=Y([`default`,`plan`]),qc=q({approvalPolicy:Ia.nullable(),sandboxMode:La.nullable()}),Jc=q({permissionMode:Ra.nullable()}),Yc=q({codex:qc.optional(),claude:Jc.optional()}),Xc=nr(Qn());q({modeDefault:Kc,model:G().trim().min(1).optional(),reasoningEffort:Fa.optional(),execution:Yc.optional()});var Zc=q({mode:Kc,model:Gc,reasoningEffort:Fa.nullable(),execution:Yc.optional()});q({provider:Pa,model:Gc,reasoningEffort:Fa.nullable(),execution:Yc.optional()});var Qc=q({model:Gc,reasoningEffort:Fa.nullable(),execution:Yc.optional(),context:Xc.optional()}),$c=q({target:tr(`type`,[q({type:J(`uncommittedChanges`)}),q({type:J(`baseBranch`),branch:G().trim().min(1)}),q({type:J(`commit`),sha:G().trim().min(1),title:G().trim().min(1).optional()}),q({type:J(`custom`),instructions:G().trim().min(1)})])}),el=q({preset:Y([`general`,`security`,`performance`,`style`]),scope:Y([`workingTree`,`staged`,`selection`,`custom`]).optional(),instructions:G().trim().min(1).optional()}),tl=q({provider:Pa,codex:$c.optional(),claude:el.optional()}).superRefine((e,t)=>{if(e.provider===`codex`){e.codex||t.addIssue({code:U.custom,path:[`codex`],message:`codex review config is required when provider is codex`}),e.claude&&t.addIssue({code:U.custom,path:[`claude`],message:`claude review config must be omitted when provider is codex`});return}e.claude||t.addIssue({code:U.custom,path:[`claude`],message:`claude review config is required when provider is claude`}),e.codex&&t.addIssue({code:U.custom,path:[`codex`],message:`codex review config must be omitted when provider is claude`})}),nl=q({v:J(`1.0`),provider:Pa,sessionId:G().min(1),projectId:G().min(1).optional(),eventId:G().min(1),ts:G().datetime(),type:G().min(1),payload:q({raw:Qn()}).passthrough()}).passthrough(),rl=Y([`compact`,`full`]),il=q({commandId:G().min(1).optional()}),al=il.extend({type:J(`session.start`),payload:q({provider:Pa,model:G().min(1).optional(),projectId:G().min(1).optional(),cwd:G().min(1).optional(),sessionConfig:Va.optional(),sessionTurnConfig:Zc.optional(),metadata:nr(Qn()).optional()})}),ol=il.extend({type:J(`turn.input`),payload:q({sessionId:G().min(1),text:G().optional(),attachments:$n(so).max(5).optional(),model:G().min(1).optional(),sessionConfig:Va.optional(),mode:Kc.optional(),config:Qc.optional()}).superRefine((e,t)=>{let n=typeof e.text==`string`&&e.text.trim().length>0,r=(e.attachments?.length??0)>0;!n&&!r&&t.addIssue({code:U.custom,path:[`text`],message:`turn.input requires text or at least one attachment`})})}),sl=il.extend({type:J(`review.start`),payload:q({sessionId:G().min(1),input:G().min(1).optional(),config:tl,turnConfig:Qc})}),cl=il.extend({type:J(`tool.approval.respond`),payload:q({sessionId:G().min(1),requestId:G().min(1),decision:Y([`allow`,`deny`]),reason:G().min(1).optional()})}),ll=il.extend({type:J(`user.input.respond`),payload:q({sessionId:G().min(1),requestId:G().min(1),answers:nr($n(G()))})}),ul=il.extend({type:J(`session.interrupt`),payload:q({sessionId:G().min(1)})}),dl=il.extend({type:J(`session.close`),payload:q({sessionId:G().min(1)})}),fl=tr(`kind`,[q({kind:J(`all`)}),q({kind:J(`raw_seq`),rawSeq:K().int().nonnegative()})]),pl=q({sessionId:G().min(1),projectId:G().min(1).optional(),cursor:fl,purpose:Y([`detail_view`,`live_follow`]).optional(),detailLevel:rl.optional(),bootstrapMode:Y([`stream`,`readable`]).optional()}),ml=il.extend({type:J(`session.stream.subscribe`),payload:q({replace:Zn().default(!0),sessions:$n(pl)})}),hl=q({sessionId:G().min(1),projectId:G().min(1).optional()}),gl=tr(`type`,[al,ol,sl,cl,ll,ul,dl,il.extend({type:J(`session.external.watch.set`),payload:q({replace:Zn().default(!0),sessions:$n(hl)})}),ml,il.extend({type:J(`fs.read`),payload:q({sessionId:G().min(1),path:G().min(1)})}),il.extend({type:J(`fs.diff`),payload:q({sessionId:G().min(1),path:G().min(1),baseContent:G().optional()})})]);function _l(e){let t=gl.parse(e);if(t.type===`session.start`&&!t.payload.projectId&&!t.payload.cwd)throw Error(`session.start requires at least one of projectId or cwd`);return t}function vl(e,t){if(!Array.isArray(e.content))return;let n=[];for(let r of e.content){let e=t(r);e&&n.push(e)}return n.length>0?n.join(`
|
|
138
|
-
`):void 0}var yl=q({inputTokens:K().int().nonnegative(),cachedInputTokens:K().int().nonnegative(),outputTokens:K().int().nonnegative(),reasoningOutputTokens:K().int().nonnegative(),totalTokens:K().int().nonnegative()}),bl=q({usedPercent:K(),windowMinutes:K().int().nonnegative().nullable(),resetsAt:K().nonnegative().nullable()}),xl=q({primary:bl.nullable().optional(),secondary:bl.nullable().optional(),planType:G().min(1).nullable().optional(),creditsBalance:G().min(1).nullable().optional()}),Sl=q({provider:Pa,usage:q({currentUsage:yl,latestTurnUsage:yl.nullable(),contextWindow:K().int().nonnegative().nullable(),sourceLabel:G().min(1),note:G().min(1).optional()}).nullable(),rateLimits:xl.optional()});function Cl(e){return e.provider===`claude`?Tl(e.rawEvents):wl(e.rawEvents)}function wl(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null;for(let c of Rl(e)){let e=Ul(c.payload.raw),l=c.type===`native.raw`?El(e):null;l?.usage&&((Fl(l.usage)||!t)&&(t=l.usage),Il(l.usage.latestTurnUsage)?n=l.usage.latestTurnUsage:Il(l.usage.currentUsage)&&!n&&(n=l.usage.currentUsage),r=l.usage.contextWindow??r),l?.rateLimits&&(i=l.rateLimits.primary??i,a=l.rateLimits.secondary??a,o=l.rateLimits.planType??o,s=l.rateLimits.creditsBalance??s);let u=Dl(c);if(u){let e=u.latestTurnUsage??u.currentUsage;Il(e)&&(n=e),r=u.contextWindow??r,!t&&(Fl(u)||u.contextWindow)&&(t=u)}}let c=t?{...t,latestTurnUsage:Il(n)?n:Il(t.latestTurnUsage)?t.latestTurnUsage:Il(t.currentUsage)?t.currentUsage:null,contextWindow:t.contextWindow??r}:null,l=kl({primary:i,secondary:a,planType:o,creditsBalance:s});return!c&&!l?null:{provider:`codex`,usage:c,...l?{rateLimits:l}:{}}}function Tl(e){let t=null;for(let n of Rl(e)){let e=Dl(n);e&&(t=e)}return t?{provider:`claude`,usage:t}:null}function El(e){if(e.source===`codex.history.thread_read`){let t=Ul(e.message),n=Ul(t.turn),r=Ml(n.usage??t.usage),i=Vl(n.model_context_window??t.model_context_window);return!r&&i===void 0?null:{usage:{currentUsage:r??Ll(),latestTurnUsage:r??null,contextWindow:i??null,sourceLabel:`codex.history.thread_read`,note:`当前来自 Codex history replay 快照。`}}}let t=zl(e);if(!t)return null;let n=Ul(Ul(e.message).params);if(t===`thread/tokenUsage/updated`){let e=Ul(n.tokenUsage??n.token_usage),t=Ml(e.total??e.total_token_usage);return t?{usage:{currentUsage:t,latestTurnUsage:Ml(e.last??e.last_token_usage),contextWindow:Vl(e.modelContextWindow??e.model_context_window)??null,sourceLabel:`thread/tokenUsage/updated`}}:null}if(t===`account/rateLimits/updated`){let e=Ol(n.rateLimits??n.rate_limits);return e?{rateLimits:e}:null}if(t===`codex/event/token_count`){let e=Ul(n.msg),t=Ul(e.info),r=Ml(t.total_token_usage??t.totalTokenUsage),i=Ol(e.rate_limits??e.rateLimits);return!r&&!i?null:{usage:r?{currentUsage:r,latestTurnUsage:Ml(t.last_token_usage??t.lastTokenUsage),contextWindow:Vl(t.model_context_window??t.modelContextWindow)??null,sourceLabel:`codex/event/token_count`}:void 0,...i?{rateLimits:i}:{}}}if(t===`codex/event/task_started`){let e=Ul(n.msg),t=Vl(e.model_context_window??e.modelContextWindow);return t===void 0?null:{usage:{currentUsage:Ll(),latestTurnUsage:null,contextWindow:t,sourceLabel:`codex/event/task_started`,note:`目前只拿到了 context window,尚未拿到 thread token usage 快照。`}}}return null}function Dl(e){if(e.type!==`turn.completed`&&e.type!==`turn.failed`&&e.type!==`turn.started`)return null;let t=Ul(e.payload.raw),n=jl(t.usage??Ul(t.turn).usage),r=Vl(t.model_context_window??Ul(t.turn).model_context_window);return!n&&r===void 0?null:{currentUsage:n??Ll(),latestTurnUsage:n??null,contextWindow:r??null,sourceLabel:e.type}}function Ol(e){let t=Ul(e),n=Al(t.primary),r=Al(t.secondary),i=Hl(t.plan_type??t.planType)??null,a=Hl(Ul(t.credits).balance)??null;return!n&&!r&&!i&&!a?null:{primary:n,secondary:r,planType:i,creditsBalance:a}}function kl(e){if(!(!e.primary&&!e.secondary&&!e.planType&&!e.creditsBalance))return{...e.primary?{primary:e.primary}:{},...e.secondary?{secondary:e.secondary}:{},...e.planType?{planType:e.planType}:{},...e.creditsBalance?{creditsBalance:e.creditsBalance}:{}}}function Al(e){let t=Ul(e),n=Vl(t.used_percent??t.usedPercent);return n===void 0?null:{usedPercent:n,windowMinutes:Vl(t.window_minutes??t.windowDurationMins)??null,resetsAt:Vl(t.resets_at??t.resetsAt)??null}}function jl(e){return Nl(e)}function Ml(e){return Nl(e,{totalFallback:`input_plus_output`})}function Nl(e,t){let n=Ul(e),r=Vl(n.input_tokens??n.inputTokens),i=Vl(n.cached_input_tokens??n.cachedInputTokens??n.cache_read_input_tokens??n.cacheReadInputTokens),a=Vl(n.output_tokens??n.outputTokens),o=Vl(n.reasoning_output_tokens??n.reasoningOutputTokens)??0,s=Vl(n.total_tokens??n.totalTokens)??Pl(r,i,a,o,t);return r===void 0&&i===void 0&&a===void 0&&s===void 0?null:{inputTokens:r??0,cachedInputTokens:i??0,outputTokens:a??0,reasoningOutputTokens:o,totalTokens:s??0}}function Pl(e,t,n,r,i){return i?.totalFallback===`input_plus_output`?Bl(e,n):Bl(e,t,n,r)}function Fl(e){return Il(e.latestTurnUsage)||Il(e.currentUsage)}function Il(e){return e?e.inputTokens>0||e.cachedInputTokens>0||e.outputTokens>0||e.reasoningOutputTokens>0||e.totalTokens>0:!1}function Ll(){return{inputTokens:0,cachedInputTokens:0,outputTokens:0,reasoningOutputTokens:0,totalTokens:0}}function Rl(e){return[...e].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.rawSeq-t.rawSeq:n})}function zl(e){return Hl(Ul(e.message).method)??Hl(e.method)??null}function Bl(...e){let t=e.filter(e=>typeof e==`number`);if(t.length!==0)return t.reduce((e,t)=>e+t,0)}function Vl(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`&&e.trim()){let t=Number(e);if(Number.isFinite(t))return t}}function Hl(e){return typeof e==`string`&&e.trim()?e:void 0}function Ul(e){return typeof e==`object`&&e?e:{}}var Wl=Y([`session.started`,`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`,`tool.permission.requested`,`tool.permission.resolved`,`user.input.requested`,`user.input.resolved`,`file.changed`,`file.diff.ready`,`status.progress`,`error`,`error.runtime`]),Gl=nl.extend({type:Wl}),Kl=nl.extend({kind:J(`provider.raw`),rawSeq:K().int().positive(),type:G().min(1)});Gl.extend({kind:J(`gateway.control`).optional(),derivedFrom:G().min(1).optional()});var ql=nl.extend({kind:J(`session.stream.sync`),type:J(`session.stream.sync`),payload:q({raw:q({decision:Y([`delta`,`snapshot`]),reason:G().min(1),snapshotId:G().min(1).optional(),fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional()}).passthrough()}).passthrough()}),Jl=q({updatedAt:G().datetime().optional(),status:Y([`running`,`idle`]).optional(),interactionLockReason:Y([`external_turn_running`]).optional(),model:G().min(1).nullable().optional(),sessionTurnConfig:Zc.optional(),sessionTurnConfigUpdatedAt:G().datetime().optional(),title:G().min(1).optional(),pendingApprovals:K().int().nonnegative().optional(),pendingUserInputs:K().int().nonnegative().optional(),pendingActions:K().int().nonnegative().optional()}),Yl=er([Kl,ql,nl.extend({kind:J(`session.stream.snapshot.chunk`),type:J(`session.stream.snapshot.chunk`),payload:q({raw:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),events:$n(Kl),sessionSummary:Jl.optional()}).passthrough(),readable:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),timelineItems:$n(Ho).optional(),sessionSummary:Jl.optional()}).passthrough().optional()}).passthrough()}),nl.extend({kind:J(`session.readable.snapshot.chunk`),type:J(`session.readable.snapshot.chunk`),payload:q({readable:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),timelineItems:$n(Ho),pendingApprovals:$n(Ro).optional(),pendingUserInputs:$n(Vo).optional(),contextUsage:Sl.nullable().optional(),sessionSummary:Jl.optional()}).passthrough()}).passthrough()}),nl.extend({kind:J(`session.readable.delta`),type:J(`session.readable.delta`),payload:q({readable:q({fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative(),timelineUpserts:$n(Ho),timelineRemovals:$n(G().min(1)),timelineTextDeltaPatches:$n(Lc).optional(),pendingApprovalUpserts:$n(Ro).optional(),pendingApprovalRemovals:$n(G().min(1)).optional(),pendingUserInputUpserts:$n(Vo).optional(),pendingUserInputRemovals:$n(G().min(1)).optional(),sessionSummary:Jl.optional(),contextUsage:Sl.nullable().optional()}).passthrough()}).passthrough()}),nl.extend({kind:J(`session.external.update`),type:J(`session.external.update`),payload:q({raw:q({updatedAt:G().datetime(),status:Y([`running`,`idle`]),interactionLockReason:Y([`external_turn_running`]).optional(),refreshMode:Y([`delta`,`snapshot`]),fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional(),historyUpdated:Zn(),statusChanged:Zn(),sessionSummary:Jl.optional()}).passthrough()}).passthrough()})]),Xl=q({algorithm:Y([`ed25519`]),publicKey:qa,publicKeyFingerprint:G().min(1),keyVersion:K().int().min(1),createdAt:G().datetime()});q({code:G().min(4),expiresAt:G().datetime()});var Zl=Y([`ed25519`]),Ql=Y([`active`,`revoked`,`rotating`,`unknown`]),$l=q({algorithm:Zl,publicKey:qa,publicKeyFingerprint:G().min(1)}),eu=q({pairingCode:G().min(4),signedAt:G().datetime()}),tu=q({gatewayId:G().min(1),deviceId:G().min(1),mobilePublicKey:qa,pairingContext:eu}),nu=q({algorithm:J(`ed25519`),gatewayPublicKeyFingerprint:G().min(1),payload:tu,signature:qa}),ru=q({code:G().min(4),deviceName:rr(e=>{if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:void 0},G().min(1).optional()),deviceIdentity:$l.optional()}),iu=q({accessToken:G().min(1),refreshToken:G().min(1),expiresInSeconds:K().int().positive()}),au=iu.extend({gatewayId:G().min(1),gatewayName:G().min(1).optional(),machineName:G().min(1).optional(),deviceId:G().min(1),gatewayIdentity:Xl.optional(),deviceIdentityFingerprint:G().min(1).optional(),deviceIdentityStatus:Ql.optional(),pairingConfirmation:nu.optional()}),ou=q({refreshToken:G().min(1)}),su=iu.extend({deviceId:G().min(1),deviceIdentityFingerprint:G().min(1).optional(),deviceIdentityStatus:Ql.optional()});function cu(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var lu=Y([`missing`,`current`,`stale`]),uu=q({accountId:G().min(1),accountType:Y([`chatgpt`,`apiKey`,`unknown`]),authMode:G().min(1),planType:G().min(1).nullable(),lastRefreshAt:G().datetime().nullable(),hasSavedSnapshot:Zn(),snapshotStatus:lu,rateLimits:xl.nullable()}),du=q({accountId:G().min(1),accountType:Y([`chatgpt`,`apiKey`,`unknown`]),authMode:G().min(1),planType:G().min(1).nullable(),lastRefreshAt:G().datetime().nullable(),savedAt:G().datetime(),isCurrent:Zn(),rateLimits:xl.nullable()}),fu=q({current:uu.nullable(),savedAccounts:$n(du)}),pu=q({saved:J(!0),accounts:fu}),mu=q({switched:J(!0),closedRuntimeSessionCount:K().int().nonnegative(),accounts:fu}),hu=q({deleted:J(!0),accounts:fu}),gu=q({restarted:J(!0),closedRuntimeSessionCount:K().int().nonnegative()}),_u=15e3,vu=12e4;function yu(e){return{sessionId:e,messages:new Map,itemToMessageKey:new Map,requestToMessageKey:new Map,turnToLastToolMessageKey:new Map,codexSemanticMessageKeyToMessageKeys:new Map,codexHistoryReplaySemanticOccurrenceByKey:new Map}}function bu(e,t,n=`codex`){if(t.sessionId!==e.sessionId)return;let r=`optimistic:${t.id}`;e.messages.has(r)||e.messages.set(r,{id:r,sessionId:e.sessionId,provider:n,kind:`user`,status:`completed`,ts:t.ts,updatedAt:t.ts,source:`optimistic`,title:`User`,text:t.text,details:[],debug:{eventTypes:[`optimistic.prompt`]}})}function xu(e,t){if(t.sessionId===e.sessionId){if(t.type===`item.started`||t.type===`item.updated`||t.type===`item.completed`){Tu(e,t);return}if(t.type===`tool.permission.requested`||t.type===`tool.permission.resolved`){Eu(e,t);return}if(t.type===`user.input.requested`||t.type===`user.input.resolved`){Du(e,t);return}if(t.type===`turn.completed`){Au(e,t);return}(t.type===`turn.failed`||t.type===`error`||t.type===`error.runtime`)&&ju(e,t)}}function Su(e){return[...e.messages.values()].map(jd).sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.id.localeCompare(t.id):n})}function Cu(e,t,n){let r=yu(e),i=t[0]?.provider??`codex`,a=[...n].sort((e,t)=>e.ts.localeCompare(t.ts));for(let e of a)bu(r,e,i);let o=[...t].filter(t=>t.sessionId===e).sort((e,t)=>e.ts.localeCompare(t.ts));for(let e of o)xu(r,e);return r}function wu(e,t,n){return Su(Cu(e,t,n))}function Tu(e,t){let n=gd(t.payload.raw),r=gd(n.item),i=qu(r,[`type`]),a=qu(r,[`phase`]),o=Gu(n,r),s=qu(r,[`id`]),c=cd(qu(r,[`status`])),l=Xu(r,i)??Ku(r),u=[...Ju(r),...Zu(r,i)],d=Iu(t.provider,o,i,a,l,u),f=d?Bu(n):void 0,p=Wu(n)&&d?Ru(e,d,f):void 0;if(!i){let r=Ku(n);if(!r)return;let i=Nu(t,`assistant`,o),a=Mu(e,i,{id:i,sessionId:e.sessionId,provider:t.provider,kind:`assistant`,status:`streaming`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Assistant`,details:[],turnId:o,debug:{eventTypes:[]}});t.type===`item.completed`?(a.status=`completed`,a.text=r):(a.status=`streaming`,a.text=yd(a.text,r)),kd(a,t);return}let m=Fu(i);if(m===`user`&&!l&&u.length===0)return;let h=p??(s?`item:${s}`:Nu(t,i,o)),g=Pu(m,i),_=m===`tool`?hd(r,l):void 0,v=Mu(e,h,{id:h,sessionId:e.sessionId,provider:t.provider,kind:m,status:`streaming`,ts:t.ts,updatedAt:t.ts,source:`event`,title:g,details:[],itemType:i,itemId:s,turnId:o,collapsible:m===`reasoning`,collapsedByDefault:m===`reasoning`,debug:{eventTypes:[],rawItemType:i,...a?{rawItemPhase:a}:{}}});s&&e.itemToMessageKey.set(s,h),d&&Lu(e,d,h),o&&m===`tool`&&e.turnToLastToolMessageKey.set(o,h),v.provider=t.provider,v.itemType=i,v.debug.rawItemPhase=a??v.debug.rawItemPhase,p&&v.itemId&&s&&v.itemId!==s||(v.itemId=s??v.itemId),v.turnId=o??v.turnId,v.title=_?.title??g,v.updatedAt=t.ts,v.collapsible=m===`reasoning`,v.collapsedByDefault=m===`reasoning`,_&&(v.toolCardData=_),u.length>0&&(v.attachments=ad(v.attachments,u));let y=qu(r,[`source_event_type`]);if(y&&Uu(m)&&!_&&Ed(v,`source: ${y}`),m===`tool`&&!_)for(let e of Dd(r))Ed(v,e);t.type===`item.started`?(v.status=m===`user`?`completed`:`streaming`,l&&(v.text=bd(m)?xd(v.text,l,r):yd(v.text,l))):t.type===`item.updated`?(v.status=m===`user`?`completed`:v.status===`waiting_approval`||v.status===`waiting_input`?v.status:`streaming`,l&&(v.text=bd(m)?xd(v.text,l,r):yd(v.text,l))):t.type===`item.completed`&&(v.status=m===`error`?`failed`:c??`completed`,l&&(v.text=l)),kd(v,t),d&&Wu(n)&&zu(e,d,f),m===`user`&&v.text&&Ad(e,v.text,v.ts)}function Eu(e,t){let n=gd(t.payload.raw),r=qu(n,[`requestId`,`request_id`]);if(!r)return;let i=qu(n,[`itemId`,`item_id`]),a=qu(n,[`turnId`,`turn_id`]),o=qu(n,[`toolName`,`tool_name`])??`tool`,s=qu(n,[`reason`]),c=qu(n,[`decision`]),l=gd(n.rawParams??n.raw_params),u=gd(l.networkApprovalContext??l.network_approval_context),d=qu(l,[`command`]),f=qu(l,[`cwd`]),p=qu(l,[`grantRoot`,`grant_root`]),m=qu(u,[`host`]),h=qu(u,[`protocol`]),g=Ou(e,r,`approval`),_=Mu(e,g,{id:g,sessionId:e.sessionId,provider:t.provider,kind:`tool`,status:`waiting_approval`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Tool Approval`,details:[],itemType:`tool_status`,itemId:i??void 0,turnId:a??void 0,requestId:r,debug:{eventTypes:[],rawItemType:`tool_status`}});_.provider=t.provider,_.updatedAt=t.ts,_.requestId=r,_.itemId=i??_.itemId,_.turnId=a??_.turnId,_.title=_.title||`Tool Approval`,t.type===`tool.permission.requested`?(_.status=`waiting_approval`,_.text=d?`等待命令执行审批`:`${o} \u9700\u8981\u5BA1\u6279`,Ed(_,`tool: ${o}`),s&&Ed(_,`reason: ${s}`),d&&Ed(_,`command: ${Pd(d,200)}`),f&&Ed(_,`cwd: ${Pd(f,200)}`),p&&Ed(_,`grant_root: ${Pd(p,200)}`),m&&Ed(_,`network: ${Pd(h?`${h}://${m}`:m,200)}`)):(_.status=c===`deny`?`failed`:`completed`,_.text=c===`deny`?`工具审批已拒绝`:`工具审批已通过`,c&&Ed(_,`decision: ${c}`),s&&Ed(_,`reason: ${s}`)),ku(e,g,r,i,a),kd(_,t)}function Du(e,t){let n=gd(t.payload.raw),r=qu(n,[`requestId`,`request_id`]);if(!r)return;let i=qu(n,[`itemId`,`item_id`]),a=qu(n,[`turnId`,`turn_id`]),o=qu(n,[`status`]),s=qu(n,[`reason`]),c=fd(n,[`answeredCount`,`answered_count`]),l=pd(n.questions),u=md(n.answers),d=Ou(e,r,`user-input`),f=Mu(e,d,{id:d,sessionId:e.sessionId,provider:t.provider,kind:`tool`,status:`waiting_input`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Plan Question`,details:[],itemType:`request_user_input`,itemId:i??void 0,turnId:a??void 0,requestId:r,userInputQuestions:l,debug:{eventTypes:[],rawItemType:`request_user_input`}});if(f.provider=t.provider,f.updatedAt=t.ts,f.requestId=r,f.itemId=i??f.itemId,f.turnId=a??f.turnId,f.title=`Plan Question`,t.type===`user.input.requested`)f.status=`waiting_input`,f.text=l.length>0?`\u9700\u8981\u56DE\u7B54 ${l.length} \u4E2A\u95EE\u9898`:`需要回答问题`,f.userInputQuestions=l,f.userInputAnswers=void 0,Ed(f,`request_id: ${r}`);else{f.status=ld(o);let e=c??0;f.text=ud(o,e),Ed(f,`status: ${o??`submitted`}`),Ed(f,`answered_count: ${e}`),s&&Ed(f,`reason: ${s}`),l.length>0&&(f.userInputQuestions=l),u&&(f.userInputAnswers=u)}ku(e,d,r,i,a),kd(f,t)}function Ou(e,t,n){return e.requestToMessageKey.get(t)??`${n}:${t}`}function ku(e,t,n,r,i){e.requestToMessageKey.set(n,t),r&&e.itemToMessageKey.set(r,t),i&&e.turnToLastToolMessageKey.set(i,t)}function Au(e,t){let n=gd(t.payload.raw),r=Gu(n,void 0),i=gd(n.usage),a=gd(gd(n.turn).usage),o=fd(i,[`input_tokens`]),s=fd(i,[`output_tokens`]),c=fd(a,[`input_tokens`]),l=fd(a,[`output_tokens`]),u=o??c,d=s??l;if(r)for(let n of e.messages.values())n.turnId===r&&n.status===`streaming`&&(n.status=`completed`,n.updatedAt=t.ts);if(u!==void 0||d!==void 0){let n=r?`turn-usage:${r}`:Nu(t,`turn.usage`,r),i=Mu(e,n,{id:n,sessionId:e.sessionId,provider:t.provider,kind:`system`,status:`completed`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Turn Usage`,details:[],turnId:r,debug:{eventTypes:[]}});i.provider=t.provider,i.status=`completed`,i.updatedAt=t.ts,i.text=`Token usage`,u!==void 0&&Ed(i,`input_tokens: ${u}`),d!==void 0&&Ed(i,`output_tokens: ${d}`),kd(i,t)}}function ju(e,t){let n=gd(t.payload.raw),r=Ku(gd(n.error))??Ku(n);if(!r)return;let i=Gu(n,void 0),a=i?`turn-error:${i}`:`error:${t.eventId}`,o=Mu(e,a,{id:a,sessionId:e.sessionId,provider:t.provider,kind:`error`,status:`failed`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Error`,text:r,details:[],turnId:i,debug:{eventTypes:[]}});o.provider=t.provider,o.status=`failed`,o.updatedAt=t.ts,o.text=r,o.turnId=i??o.turnId,kd(o,t)}function Mu(e,t,n){return e.messages.get(t)||(e.messages.set(t,n),n)}function Nu(e,t,n){let r=Date.parse(e.ts),i=Number.isFinite(r)?Math.floor(r/_u):Math.floor(Id(e.ts)/_u);return`fallback:${e.provider}:${n??`no_turn`}:${t}:${i}`}function Pu(e,t){return t===`plan`?`Plan`:e===`assistant`?t===`image_generation`||t===`image_view`?`Image`:`Assistant`:e===`user`?`User`:e===`tool`?t===`command_execution`?`Command`:t===`file_change`?`File Change`:t===`mcp_tool_call`?`MCP Tool`:t===`web_search`?`Web Search`:`Tool`:e===`reasoning`?t===`todo_list`?`Todo`:t===`plan`?`Plan`:`Reasoning`:e===`error`?`Error`:`System`}function Fu(e){return e===`user_message`?`user`:e===`agent_message`||e===`plan`||e===`image_generation`||e===`image_view`?`assistant`:e===`command_execution`||e===`file_change`||e===`mcp_tool_call`||e===`web_search`||e===`tool_status`||e===`collab_tool_call`?`tool`:e===`reasoning`||e===`todo_list`?`reasoning`:e===`error`?`error`:`system`}function Iu(e,t,n,r,i,a){let o=od(a);if(e!==`codex`||!t||!i&&!o)return;let s=Vu(n);if(!(s!==`user_message`&&s!==`agent_message`))return`${t}|${s}|${Hu(s,r)}|${i??``}|${o}`}function Lu(e,t,n){let r=e.codexSemanticMessageKeyToMessageKeys.get(t);if(!r){e.codexSemanticMessageKeyToMessageKeys.set(t,[n]);return}r.includes(n)||r.push(n)}function Ru(e,t,n){let r=e.codexSemanticMessageKeyToMessageKeys.get(t);if(!(!r||r.length===0))return r[n===void 0?e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0:n-1]}function zu(e,t,n){let r=n??(e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0)+1,i=e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0;e.codexHistoryReplaySemanticOccurrenceByKey.set(t,Math.max(i,r))}function Bu(e){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 Vu(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 Hu(e,t){return e===`agent_message`&&(!t||t===`final_answer`)?``:t??``}function Uu(e){return e===`tool`}function Wu(e){if(e.historyReplay===!0)return!0;let t=qu(e,[`source`]);return t===`codex.history.thread_read`||t===`codex.history.thread_read.incremental`}function Gu(e,t){return qu(e,[`turn_id`,`turnId`])??qu(gd(e.turn),[`id`,`turn_id`,`turnId`])??qu(t??{},[`turn_id`,`turnId`])}function Ku(e){return dd(gd(e.payload),[`delta`,`output_delta`,`outputDelta`])||dd(e,[`text`,`message`,`output`,`response`,`reason`,`output_delta`,`aggregated_output`])||_d(e)}function qu(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.trim())return t}}function Ju(e){return[...Yu(e.attachments),...Yu(e.content),...Yu(e.input)]}function Yu(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=gd(n),r=gd(e.remote_agent_attachment),i=qu(e,[`type`]),a=qu(e,[`kind`]),o=gd(e.source),s=gd(r.locator),c=qu(e,[`path`])??qu(o,[`path`])??qu(s,[`path`]),l=td(qu(r,[`mimeType`,`mime_type`])??qu(e,[`mimeType`,`mime_type`])??qu(o,[`media_type`,`mediaType`]));if(i!==`image`&&i!==`localImage`&&i!==`local_image`&&a!==`image`&&!c&&Object.keys(r).length===0)continue;let u=qu(r,[`id`])??qu(e,[`id`])??c??`image-${t.length+1}`;t.push({id:u,kind:`image`,...l?{mimeType:l}:{},fileName:qu(r,[`fileName`,`file_name`])??qu(e,[`fileName`,`file_name`]),width:rd(r.width??e.width),height:rd(r.height??e.height),sizeBytes:id(r.sizeBytes??r.size_bytes??e.sizeBytes??e.size_bytes),...c?{locator:{kind:`absolute`,path:c}}:{}})}return t}function Xu(e,t){let n=Qu(e,t);if(n)return`})`}function Zu(e,t){let n=Qu(e,t);if(!n)return[];let r=qu(e,[`id`])??n,i=td(qu(e,[`mime_type`,`mimeType`]))??nd(n),a=ed(n);return[{id:r,kind:`image`,...i?{mimeType:i}:{},...a?{fileName:a}:{},locator:{kind:`absolute`,path:n}}]}function Qu(e,t){let n=Vu(t);if(n===`image_generation`)return qu(e,[`saved_path`,`savedPath`,`path`]);if(n===`image_view`)return qu(e,[`path`,`saved_path`,`savedPath`])}function $u(e){let t=e.trim();return t?/[\s()<>]/.test(t)?`<${t.replace(/</g,`%3C`).replace(/>/g,`%3E`)}>`:t:``}function ed(e){let t=e.split(/[\\/]/).filter(Boolean).pop();return t&&t.trim()?t:void 0}function td(e){if(e===`image/png`||e===`image/jpeg`||e===`image/webp`)return e}function nd(e){let t=e.toLowerCase();if(t.endsWith(`.png`))return`image/png`;if(t.endsWith(`.jpg`)||t.endsWith(`.jpeg`))return`image/jpeg`;if(t.endsWith(`.webp`))return`image/webp`}function rd(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0}function id(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.round(e):void 0}function ad(e,t){let n=new Map;for(let r of[...e??[],...t])n.set(sd(r),r);return[...n.values()]}function od(e){return!e||e.length===0?``:e.map(sd).sort().join(`,`)}function sd(e){return e.locator?.kind===`absolute`?`path:${e.locator.path}`:`id:${e.id}`}function cd(e){if(e===`streaming`||e===`waiting_approval`||e===`waiting_input`||e===`completed`||e===`failed`)return e;if(e===`running`)return`streaming`}function ld(e){return!e||e===`submitted`?`completed`:`failed`}function ud(e,t){return!e||e===`submitted`?`\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:e===`interrupted`?t>0?`\u5DF2\u4E2D\u65AD\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已中断`:e===`cancelled`?t>0?`\u5DF2\u53D6\u6D88\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已取消`:e===`expired`?t>0?`\u5DF2\u8FC7\u671F\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已过期`:e===`dismissed`?t>0?`\u5DF2\u5173\u95ED\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已关闭`:t>0?`\u672A\u5B8C\u6210\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问未完成`}function dd(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function fd(e,t){for(let n of t){let t=e[n];if(typeof t==`number`&&Number.isFinite(t))return t}}function pd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=gd(n),r=qu(e,[`id`]),i=qu(e,[`header`]),a=qu(e,[`question`]);if(!r||!i||!a)continue;let o=Array.isArray(e.options)?e.options.map(e=>{let t=gd(e),n=qu(t,[`label`]),r=qu(t,[`description`])??n,i=qu(t,[`markdown`]);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).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}function md(e){let t=gd(e),n=Object.entries(t);if(n.length===0)return;let r={};for(let[e,t]of n)if(e){if(!Array.isArray(t)){r[e]=[];continue}r[e]=t.map(e=>typeof e==`string`?e:void 0).filter(e=>typeof e==`string`&&e.length>0)}return Object.keys(r).length>0?r:void 0}function hd(e,t){if(qu(e,[`display_as`])!==`tool_card`)return;let n=qu(e,[`title`])??t,r=qu(e,[`status_label`])??t;if(!n||!r)return;let i=[],a=qu(e,[`prompt`]),o=qu(e,[`response`]),s=qu(e,[`response_label`])??`Response`;a&&i.push({label:`Prompt`,body:a}),o&&i.push({label:s,body:o});let c=[],l=qu(e,[`file_path`]),u=fd(e,[`exit_code`,`exitCode`]),d=fd(e,[`total_tool_uses`]),f=fd(e,[`total_tokens`]),p=fd(e,[`duration_ms`]);return l&&c.push(l),typeof u==`number`&&c.push(`exit_code: ${u}`),typeof d==`number`&&c.push(`${d} tool uses`),typeof f==`number`&&c.push(`${Md(f)} tokens`),typeof p==`number`&&c.push(Nd(p)),{title:n,statusLabel:r,compactText:t?Fd(t):void 0,sections:i,details:c}}function gd(e){return typeof e==`object`&&e?e:{}}function _d(e){return vl(e,vd)}function vd(e){if(typeof e==`string`&&e.length>0)return e;let t=gd(e),n=dd(t,[`text`,`message`,`output`,`response`,`reason`]);if(n)return n;let r=dd(gd(t.data),[`text`,`message`,`output`,`response`,`reason`]);if(r)return r;if(!Array.isArray(t.text_elements))return;let i=[];for(let e of t.text_elements){let t=dd(gd(e),[`text`,`value`]);t&&i.push(t)}return i.length>0?i.join(``):void 0}function yd(e,t){return!e||t.startsWith(e)?t:e.endsWith(t)?e:`${e}${t}`}function bd(e){return e===`assistant`||e===`reasoning`}function xd(e,t,n){return e?t===e?e:t.startsWith(e)?t:e.endsWith(t)?e:Sd(n)?`${e}${t}`:wd(e,t)?t:`${e}${t}`:t}function Sd(e){let t=gd(e.payload);return Td(t.delta)||Td(t.output_delta)||Td(t.outputDelta)||Td(e.output_delta)||Td(e.outputDelta)?!0:Cd(qu(e,[`original_method`,`originalMethod`]))}function Cd(e){return e?e===`item/agentMessage/delta`||e===`codex/event/agent_message_content_delta`:!1}function wd(e,t){return t.length===0||t.length<24?!1:t.length>=Math.floor(e.length*.7)}function Td(e){return typeof e==`string`&&e.length>0}function Ed(e,t){t.trim()&&(e.details.includes(t)||e.details.push(t))}function Dd(e){let t=[],n=qu(e,[`command`]),r=qu(e,[`tool_name`,`tool`]),i=qu(e,[`server`]),a=qu(e,[`status`]),o=qu(e,[`query`]),s=qu(e,[`output_delta`,`aggregated_output`]),c=e.history_output_omitted===!0||e.historyOutputOmitted===!0,l=fd(e,[`history_output_byte_length`,`historyOutputByteLength`]),u=fd(e,[`exit_code`]),d=qu(gd(e.error),[`message`]);if(n&&t.push(`command: ${Pd(n,200)}`),r&&t.push(`tool: ${r}`),i&&t.push(`server: ${i}`),a&&t.push(`status: ${a}`),o&&t.push(`query: ${Pd(o,200)}`),u!==void 0&&t.push(`exit_code: ${u}`),d&&t.push(`error: ${Pd(d,200)}`),s?t.push(`output: ${Pd(s,400)}`):c&&t.push(l===void 0?`output: omitted in compact history`:`output: omitted in compact history (${l.toLocaleString(`en-US`)} bytes)`),e.type===`todo_list`){let n=Array.isArray(e.items)?e.items:[];for(let e of n){let n=gd(e),r=qu(n,[`text`])??``,i=n.completed===!0;t.push(`${i?`[x]`:`[ ]`} ${r}`)}}if(e.type===`file_change`){let n=Array.isArray(e.changes)?e.changes:[];for(let e of n){let n=gd(e),r=qu(n,[`path`])??`unknown`,i=Od(n);t.push(`${i}: ${r}`)}}return t}function Od(e){let t=qu(gd(e.kind),[`type`]),n=qu(e,[`kind`,`type`]),r=(t??n??`update`).replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase();return r===`add`||r===`create`||r===`new`?`add`:r===`delete`||r===`remove`||r===`removed`?`delete`:r===`move`||r===`rename`?`move`:`update`}function kd(e,t){e.debug.eventTypes.includes(t.type)||e.debug.eventTypes.push(t.type)}function Ad(e,t,n){let r=Fd(t),i=Date.parse(n);for(let[t,n]of e.messages.entries()){if(n.kind!==`user`||n.source!==`optimistic`||Fd(n.text??``)!==r)continue;let a=Date.parse(n.ts);if(!(Number.isFinite(i)&&Number.isFinite(a)&&Math.abs(i-a)>vu)){e.messages.delete(t);return}}}function jd(e){return{...e,attachments:e.attachments?e.attachments.map(e=>({...e,locator:e.locator?{...e.locator}:void 0})):void 0,details:[...e.details],userInputQuestions:e.userInputQuestions?e.userInputQuestions.map(e=>({...e,options:e.options?e.options.map(e=>({...e})):null})):void 0,userInputAnswers:e.userInputAnswers?Object.fromEntries(Object.entries(e.userInputAnswers).map(([e,t])=>[e,[...t]])):void 0,toolCardData:e.toolCardData?{...e.toolCardData,sections:e.toolCardData.sections.map(e=>({...e})),details:[...e.toolCardData.details]}:void 0,debug:{...e.debug,eventTypes:[...e.debug.eventTypes]}}}function Md(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function Nd(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 Pd(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function Fd(e){return e.trim().replace(/\s+/g,` `)}function Id(e){let t=0;for(let n=0;n<e.length;n+=1)t=t*31+e.charCodeAt(n)>>>0;return t}var Ld=Y([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),Rd=Y([`npm`,`pnpm`,`yarn`,`unknown`]),zd=Y([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),Bd=Y([`console`,`mobile`,`system`]),Vd=q({manager:Rd,installType:zd,packageName:G().min(1),packageRoot:G().min(1).optional(),binPath:G().min(1).optional(),canSelfUpdate:Zn(),reason:G().min(1).optional()}),Hd=q({id:G().min(1),targetVersion:G().min(1),requestedBy:Bd,requestedAt:G().datetime(),startedAt:G().datetime().optional()}),Ud=q({packageName:G().min(1),currentVersion:G().min(1),latestVersion:G().min(1).optional(),available:Zn(),canApply:Zn(),status:Ld,checkedAt:G().datetime().optional(),install:Vd,job:Hd.optional(),lastError:G().min(1).optional()}),Wd=q({type:J(`gateway.update.status`),payload:Ud}),Gd=q({started:Zn(),update:Ud}),Kd=rr(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},G().trim().min(1)),qd=q({id:G().min(1),title:G().min(1),path:G().min(1),createdAt:G().datetime(),updatedAt:G().datetime(),lastSessionAt:G().datetime().optional(),runningCount:K().int().nonnegative(),idleCount:K().int().nonnegative().optional(),totalCount:K().int().nonnegative().optional(),endedCount:K().int().nonnegative()}),Jd=q({name:G().min(1),path:G().min(1)}),Yd=q({kind:Y([`home`,`desktop`,`documents`,`downloads`,`root`]),path:G().min(1)}),Xd=q({rootPath:G().min(1),currentPath:G().min(1),parentPath:G().min(1).nullable(),shortcuts:$n(Yd).default([]),directories:$n(Jd)}),Zd=Y([`running`,`idle`]),Qd=Y([`running`,`idle`,`all`]),$d=Y([`external_turn_running`]),ef=Y([`delta`,`snapshot`]),tf=q({id:G().min(1),nativeSessionId:G().min(1).optional(),source:Y([`gateway`,`native_discovered`]).optional(),projectId:G().min(1),projectPath:G().min(1),provider:Pa,providerMode:Y([`native`,`mock`]).optional(),model:G().min(1).optional(),title:G().min(1).optional(),sessionTurnConfig:Zc.optional(),sessionTurnConfigUpdatedAt:G().datetime().optional(),createdAt:G().datetime(),updatedAt:G().datetime(),status:Zd,interactionLockReason:$d.optional(),pendingApprovals:K().int().nonnegative(),pendingUserInputs:K().int().nonnegative(),pendingActions:K().int().nonnegative()}),nf=q({id:G().min(1),name:G().min(1),createdAt:G().datetime(),revokedAt:G().datetime().optional(),identityAlgorithm:Y([`ed25519`]).optional(),publicKeyFingerprint:G().min(1).optional(),identityStatus:Ql.optional(),lastVerifiedAt:G().datetime().optional()}),rf=q({name:Kd,machineName:G().min(1)}),af=q({agent:q({provider:Pa,requestedVersion:G().min(1).nullable(),resolvedVersion:G().min(1)}),capabilities:Wa}),of=q({scannedAt:G().datetime(),sessionCount:K().int().nonnegative(),status:Y([`ready`,`partial`,`failed`]),error:G().min(1).optional()}),sf=q({codex:of.optional(),claude:of.optional()}),cf=q({key:G().min(1),path:G().min(1),title:G().min(1),lastSessionAt:G().datetime().optional(),sessionCount:K().int().nonnegative(),providerCounts:q({codex:K().int().nonnegative(),claude:K().int().nonnegative()}),lastDiscoveryAt:G().datetime()}),lf=q({provider:Pa,nativeSessionId:G().min(1),title:G().min(1).optional(),model:G().min(1).optional(),createdAt:G().datetime().optional(),updatedAt:G().datetime()}),uf=q({generatedAt:G().datetime(),source:Y([`cache`,`fresh_scan`]),providers:sf,projects:$n(cf)}),df=q({canonicalProjectPath:G().min(1),project:cf,providers:sf,sessions:$n(lf)}),ff=Y(`auth.refresh,codex.accounts.get,codex.accounts.save,codex.accounts.switch,codex.accounts.delete,codex.appServer.restart,gateway.settings.get,gateway.settings.update,gateway.update.get,gateway.update.apply,projects.list,projects.discovery.get,projects.discovery.refresh,projects.create,projects.delete,workspace.directories.list,workspace.directories.create,workspace.entries.list,workspace.files.resolve,workspace.files.readText,workspace.files.preparePreview,sessions.list,sessions.discovery.list,sessions.get,sessions.config.get,sessions.history.sync,sessions.rawEvents.list,sessions.readableItem.get,providers.capabilities.get,providers.execution.update,agents.config.get,devices.list,devices.revoke`.split(`,`)),pf=q({}).strict(),mf=tr(`method`,[q({method:J(`auth.refresh`),params:ou.extend({deviceId:G().min(1).optional()})}),q({method:J(`codex.accounts.get`),params:pf}),q({method:J(`codex.accounts.save`),params:pf}),q({method:J(`codex.accounts.switch`),params:q({accountId:G().min(1)})}),q({method:J(`codex.accounts.delete`),params:q({accountId:G().min(1)})}),q({method:J(`codex.appServer.restart`),params:q({requestedBy:Bd.optional()})}),q({method:J(`gateway.settings.get`),params:pf}),q({method:J(`gateway.settings.update`),params:q({name:Kd})}),q({method:J(`gateway.update.get`),params:pf}),q({method:J(`gateway.update.apply`),params:q({requestedBy:Bd.optional()})}),q({method:J(`projects.list`),params:pf}),q({method:J(`projects.discovery.get`),params:pf}),q({method:J(`projects.discovery.refresh`),params:pf}),q({method:J(`projects.create`),params:q({path:Kd,title:G().min(1).optional()})}),q({method:J(`projects.delete`),params:q({projectId:G().min(1)})}),q({method:J(`workspace.directories.list`),params:q({path:G().min(1).optional(),limit:K().int().positive().max(500).optional()})}),q({method:J(`workspace.directories.create`),params:q({path:Kd,name:Kd})}),q({method:J(`workspace.entries.list`),params:q({locator:Ya,limit:K().int().positive().max(500).optional()})}),q({method:J(`workspace.files.resolve`),params:q({locator:Ja})}),q({method:J(`workspace.files.readText`),params:q({locator:Ja,encoding:J(`utf8`).optional(),startLine:K().int().positive().optional(),maxLines:K().int().positive().max(5e3).optional(),maxBytes:K().int().positive().max(1024*1024).optional()})}),q({method:J(`workspace.files.preparePreview`),params:q({locator:Ja,disposition:io.optional()})}),q({method:J(`sessions.list`),params:q({projectId:G().min(1),status:Qd.optional(),syncExternal:Zn().optional()})}),q({method:J(`sessions.discovery.list`),params:q({projectPath:Kd})}),q({method:J(`sessions.get`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.config.get`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.history.sync`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.rawEvents.list`),params:q({projectId:G().min(1),sessionId:G().min(1),limit:er([K().int().positive().max(2e3),J(`all`)]).optional(),fromRawSeqExclusive:K().int().nonnegative().optional(),detailLevel:rl.optional()})}),q({method:J(`sessions.readableItem.get`),params:q({projectId:G().min(1),sessionId:G().min(1),itemId:G().min(1)})}),q({method:J(`providers.capabilities.get`),params:q({provider:Pa,projectId:G().min(1).optional(),agentVersion:G().min(1).optional()})}),q({method:J(`providers.execution.update`),params:Ha}),q({method:J(`agents.config.get`),params:q({provider:Pa,projectId:G().min(1).optional(),agentVersion:G().min(1).optional()})}),q({method:J(`devices.list`),params:pf}),q({method:J(`devices.revoke`),params:q({deviceId:G().min(1)})})]),hf=tr(`method`,[q({method:J(`auth.refresh`),result:su.extend({relayToken:G().min(1).optional()})}),q({method:J(`codex.accounts.get`),result:fu}),q({method:J(`codex.accounts.save`),result:pu}),q({method:J(`codex.accounts.switch`),result:mu}),q({method:J(`codex.accounts.delete`),result:hu}),q({method:J(`codex.appServer.restart`),result:gu}),q({method:J(`gateway.settings.get`),result:rf}),q({method:J(`gateway.settings.update`),result:rf}),q({method:J(`gateway.update.get`),result:Ud}),q({method:J(`gateway.update.apply`),result:Gd}),q({method:J(`projects.list`),result:q({projects:$n(qd)})}),q({method:J(`projects.discovery.get`),result:uf}),q({method:J(`projects.discovery.refresh`),result:uf}),q({method:J(`projects.create`),result:q({project:qd})}),q({method:J(`projects.delete`),result:q({removed:J(!0)})}),q({method:J(`workspace.directories.list`),result:Xd}),q({method:J(`workspace.directories.create`),result:Xd}),q({method:J(`workspace.entries.list`),result:to}),q({method:J(`workspace.files.resolve`),result:no}),q({method:J(`workspace.files.readText`),result:ro}),q({method:J(`workspace.files.preparePreview`),result:ao}),q({method:J(`sessions.list`),result:q({sessions:$n(tf)})}),q({method:J(`sessions.discovery.list`),result:df}),q({method:J(`sessions.get`),result:q({session:tf})}),q({method:J(`sessions.config.get`),result:q({session:tf})}),q({method:J(`sessions.history.sync`),result:q({session:tf,rawEventCount:K().int().nonnegative(),historyUpdated:Zn(),statusChanged:Zn(),refreshMode:ef,fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional()})}),q({method:J(`sessions.rawEvents.list`),result:tr(`decision`,[q({decision:J(`delta`),reason:Y([`cursor_valid_delta`]),fromRawSeqExclusive:K().int().nonnegative(),toRawSeq:K().int().nonnegative(),events:$n(Qn())}),q({decision:J(`snapshot`),reason:Y([`cursor_out_of_range`,`initial_snapshot`,`empty_history_snapshot`]),toRawSeq:K().int().nonnegative().optional(),events:$n(Qn())})])}),q({method:J(`sessions.readableItem.get`),result:q({item:Ho})}),q({method:J(`providers.capabilities.get`),result:q({capabilities:Wa})}),q({method:J(`providers.execution.update`),result:q({defaults:Ha})}),q({method:J(`agents.config.get`),result:af}),q({method:J(`devices.list`),result:q({devices:$n(nf)})}),q({method:J(`devices.revoke`),result:q({revoked:J(!0)})})]),gf=`json-utf8`,_f=Y([gf]),vf=Y([`identity`,`gzip`]),yf=q({version:J(1),compression:J(`gzip`),payloadEncoding:_f.default(gf),uncompressedByteLength:K().int().positive(),compressedByteLength:K().int().positive(),data:qa});function bf(e){let t=Cf(e.payload),n=t.byteLength;if(n<(e.compressionThresholdBytes??1/0))return{payloadEncoding:gf,compression:`identity`,payloadBytes:t,uncompressedByteLength:n,compressedByteLength:n};let r=ni(t);return r.byteLength>=n?{payloadEncoding:gf,compression:`identity`,payloadBytes:t,uncompressedByteLength:n,compressedByteLength:n}:{payloadEncoding:gf,compression:`gzip`,payloadBytes:r,uncompressedByteLength:n,compressedByteLength:r.byteLength}}function xf(e){return e.compression===`gzip`?yf.parse({version:1,compression:`gzip`,payloadEncoding:e.payloadEncoding,uncompressedByteLength:e.uncompressedByteLength,compressedByteLength:e.compressedByteLength,data:Ef(e.payloadBytes)}):null}function Sf(e){let t=vf.parse(e.compression??`identity`),n=e.payloadBytes;if(t===`gzip`)try{n=ri(e.payloadBytes)}catch{throw Error(`compressed_payload_invalid`)}if(typeof e.expectedUncompressedByteLength==`number`&&n.byteLength!==e.expectedUncompressedByteLength)throw Error(`compressed_payload_size_mismatch`);let r;try{r=JSON.parse(Tf(n))}catch{throw Error(`compressed_payload_invalid`)}return e.parse(r)}function Cf(e){return wf(JSON.stringify(e))}function wf(e){return new TextEncoder().encode(e)}function Tf(e){return new TextDecoder().decode(e)}function Ef(e){let t=globalThis.Buffer;if(t)return t.from(e).toString(`base64`);let n=``;for(let t of e)n+=String.fromCharCode(t);if(typeof btoa!=`function`)throw Error(`base64 encoder unavailable`);return btoa(n)}var Df=G().url(),Of=er([Df,J(``)]),kf=G().min(1).regex(/^[A-Za-z0-9_-]+$/u),Af=Y([`plaintext-relay`,`e2ee-relay`]),jf=Y([`plain`,`crypt`]);function Mf(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function Nf(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=Mf(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function Pf(e){return e.trim()}var Ff=Y([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),If=K().int().positive(),Lf=K().int().min(0).max(2**53-1),Rf=Y([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`counter_gap_too_large`,`key_epoch_mismatch`,`decrypt_failed`,`unsupported_version`]),zf=Y([`guest`,`account`,`self_hosted`]);q({type:J(`relay.gateway`),grantType:zf,gatewayId:G().min(1),subjectId:G().min(1),gatewayIdentityFingerprint:G().min(1).optional(),jti:G().min(1),iss:G().min(1),aud:G().min(1),iat:K().int().nonnegative(),exp:K().int().positive()}),q({type:J(`relay.mobile`),gatewayId:G().min(1),deviceId:G().min(1),iat:K().int().nonnegative(),exp:K().int().positive()});var Bf=q({v:J(1),gw:G().min(1),name:G().min(1),machineName:G().min(1).optional(),relay:Of.optional(),direct:$n(Df).default([]),pc:G().min(1),tsl:jf.optional(),gatewayIdentity:Xl.optional()});rr(Nf,Bf);var Vf=rr(Nf,Bf.omit({pc:!0}));rr(Nf,q({v:J(1),gw:G().min(1),relay:Of.optional(),direct:Of.optional(),pc:G().min(1),tsl:jf.optional(),gatewayIdentity:Xl.optional()}));var Hf=rr(Nf,q({v:J(1),gw:G().min(1),relay:Of.optional(),direct:Df,pc:G().min(1),pkf:kf,tsl:jf.optional()})),Uf=q({name:G().min(1),relayBaseUrl:Of.optional(),directBaseUrls:$n(Df).default([]),transportSecurityLevel:Af.default(`e2ee-relay`),gatewayIdentity:Xl.optional(),gatewayAccessToken:G().min(1).optional(),connectedAt:G().datetime().optional()}),Wf=q({gatewayId:G().min(1),deviceId:G().min(1),connectedAt:G().datetime().optional()}),Gf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Ff,deviceId:G().min(1),deviceIdentity:$l,clientNonce:qa}),Kf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Ff,gatewayId:G().min(1),deviceId:G().min(1),clientNonce:qa,gatewayNonce:qa,gatewayPublicKeyFingerprint:G().min(1),gatewayEphemeralPublicKey:qa,signatureAlgorithm:J(`ed25519`),signature:qa}),qf=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1),deviceIdentityFingerprint:G().min(1),clientEphemeralPublicKey:qa,signatureAlgorithm:J(`ed25519`),signature:qa}),Jf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Ff,gatewayId:G().min(1),deviceId:G().min(1),keyEpoch:If,deviceIdentityFingerprint:G().min(1),deviceIdentityStatus:Ql}),Yf=Y([`gateway_restarted`,`gateway_available`]),Xf=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1),reason:Yf,retryable:J(!0)}),Zf=q({ticket:G().min(1),method:Y([`GET`,`HEAD`]),rangeHeader:G().min(1).optional(),responseMode:Y([`inline_base64`,`stream_upload`]).optional(),uploadUrl:G().url().optional(),uploadToken:G().min(1).optional()}).superRefine((e,t)=>{e.responseMode===`stream_upload`&&(e.uploadUrl||t.addIssue({code:U.custom,path:[`uploadUrl`],message:`uploadUrl is required when responseMode is stream_upload`}),e.uploadToken||t.addIssue({code:U.custom,path:[`uploadToken`],message:`uploadToken is required when responseMode is stream_upload`}))}),Qf=q({status:er([J(200),J(206),J(416)]),headers:q({contentType:G().min(1),contentDisposition:G().min(1),contentLength:K().int().nonnegative(),etag:G().min(1),acceptRanges:J(`bytes`).optional(),contentRange:G().min(1).optional(),lastModified:G().min(1).optional(),cacheControl:G().min(1)}),bodyTransport:Y([`inline_base64`,`stream_upload`]).optional(),bodyBase64:qa.optional()}),$f=q({}),ep=Qf,tp=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1).optional(),code:Rf,message:G().min(1),retryable:Zn().optional()}),np=mf,rp=hf,ip=q({code:Y([`BAD_REQUEST`,`NOT_FOUND`,`UNAUTHORIZED`,`TIMEOUT`,`INTERNAL`,`GATEWAY_OFFLINE`,`TOKEN_INVALID`,`TOKEN_EXPIRED`,`GATEWAY_MISMATCH`,`GATEWAY_REVOKED`]),message:G().min(1),status:K().int().min(400).max(599),details:Qn().optional()}),ap=ip.extend({method:ff.optional()}),op=ru.extend({gatewayId:G().min(1)}),sp=au.extend({relayToken:G().min(1).optional()}),cp=ou.extend({gatewayId:G().min(1),deviceId:G().min(1).optional()}),lp=su.extend({gatewayId:G().min(1),relayToken:G().min(1).optional()}),up=q({gatewayId:G().min(1),gatewayIdentity:Xl,requestedAt:G().datetime()});q({grantType:J(`guest`),payload:up,signatureAlgorithm:J(`ed25519`),signature:qa});var dp=q({grantType:zf,token:G().min(1),expiresInSeconds:K().int().positive()}),fp=Y([`rpc`,`command`,`event`,`system`]),pp=gf,mp=_f,hp=q({version:J(1),keyEpoch:If,counter:Lf,iv:qa,ciphertext:qa,authTag:qa,plaintextEncoding:mp.default(pp),compression:vf.default(`identity`),uncompressedByteLength:K().int().positive().optional(),compressedByteLength:K().int().positive().optional()});Y([`from_mobile`,`to_mobile`,`rpc.request`,`rpc.response`,`rpc.error`]);function gp(e){return{payload:e.optional(),encryptedPayload:hp.optional()}}function _p(e){return{payload:e.optional(),compressedPayload:yf.optional(),encryptedPayload:hp.optional()}}var vp=q({gatewayId:G().min(1),mobileId:G().min(1).optional(),messageType:fp,requestId:G().min(1).optional()}),yp=Y([`fresh_connect`,`gateway_replay`]),bp=q({deviceId:G().min(1),deliveryMode:yp,gatewayAvailableAtConnect:Zn()}),xp=q({deviceId:G().min(1)}),Sp=er([Yl,Wd,q({type:J(`command.ack`),commandType:G().min(1),commandId:G().min(1).optional(),payload:Qn().optional()}),q({type:J(`command.error`),commandType:G().min(1).optional(),commandId:G().min(1).optional(),message:G().min(1)}),q({type:J(`relay.error`),error:ip})]),Cp=tr(`type`,[vp.extend({type:J(`gateway.hello`),messageType:J(`system`),payload:Uf}),vp.extend({type:J(`mobile.hello`),messageType:J(`system`),payload:Wf}),vp.extend({type:J(`secure.client_hello`),messageType:J(`system`),payload:Gf}),vp.extend({type:J(`secure.gateway_hello`),mobileId:G().min(1),messageType:J(`system`),payload:Kf}),vp.extend({type:J(`secure.client_auth`),messageType:J(`system`),payload:qf}),vp.extend({type:J(`secure.ready`),mobileId:G().min(1),messageType:J(`system`),payload:Jf}),vp.extend({type:J(`secure.handshake_required`),mobileId:G().min(1),messageType:J(`system`),payload:Xf}),vp.extend({type:J(`secure.error`),mobileId:G().min(1),messageType:J(`system`),payload:tp}),vp.extend({type:J(`mobile.connected`),messageType:J(`system`),payload:bp}),vp.extend({type:J(`mobile.disconnected`),messageType:J(`system`),payload:xp}),vp.extend({type:J(`from_mobile`),messageType:J(`command`),mobileId:G().min(1),...gp(gl)}),vp.extend({type:J(`to_mobile`),messageType:J(`event`),mobileId:G().min(1),..._p(Sp)}),vp.extend({type:J(`rpc.request`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),...gp(np)}),vp.extend({type:J(`rpc.response`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),..._p(rp)}),vp.extend({type:J(`rpc.error`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),..._p(ap)}),vp.extend({type:J(`broadcast`),messageType:J(`event`),payload:Yl}),vp.extend({type:J(`pairing.claim.forward`),messageType:J(`system`),requestId:G().min(1),payload:op}),vp.extend({type:J(`pairing.claim.result`),messageType:J(`system`),requestId:G().min(1),payload:sp}),vp.extend({type:J(`auth.refresh.forward`),messageType:J(`system`),requestId:G().min(1),payload:cp}),vp.extend({type:J(`auth.refresh.result`),messageType:J(`system`),requestId:G().min(1),payload:lp}),vp.extend({type:J(`file.content.forward`),messageType:J(`system`),requestId:G().min(1),payload:Zf}),vp.extend({type:J(`file.content.result`),messageType:J(`system`),requestId:G().min(1),payload:Qf}),vp.extend({type:J(`file.content.upload.started`),messageType:J(`system`),requestId:G().min(1),payload:$f}),vp.extend({type:J(`relay.error`),messageType:J(`system`),payload:ip})]);function wp(e){return JSON.stringify([`relay-gateway-guest-token-v1`,e.gatewayId,e.gatewayIdentity.algorithm,e.gatewayIdentity.publicKey,e.gatewayIdentity.publicKeyFingerprint,e.gatewayIdentity.keyVersion,e.gatewayIdentity.createdAt,e.requestedAt])}function Tp(e){return JSON.stringify([e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey])}function Ep(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,Tp(e)])}function Dp(e){return JSON.stringify([`relay-secure-client-auth-v1`,Tp(e),e.clientAuth.clientEphemeralPublicKey])}function Op(e){let t=If.parse(e.keyEpoch??1);return JSON.stringify([`relay-secure-session-v1`,e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey,e.clientAuth.clientEphemeralPublicKey,t])}function kp(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=If.parse(e.keyEpoch??1),r=Vp(Wp(Op({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=Vp(Up(Wp(`relay-secure-hkdf-salt-v1`),r)),a=Wp(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=Bp(e.sharedSecret,i,a,72);return{keyEpoch:n,cipherSuite:t,transcriptHash:r,clientToGatewayKey:o.slice(0,32),gatewayToClientKey:o.slice(32,64),clientToGatewayNoncePrefix:o.slice(64,68),gatewayToClientNoncePrefix:o.slice(68,72)}}function Ap(e){return e.role===`client`?{role:`client`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.clientToGatewayKey,inboundKey:e.keySchedule.gatewayToClientKey,outboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,inboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,outboundCounter:0,highestInboundCounter:null}:{role:`gateway`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.gatewayToClientKey,inboundKey:e.keySchedule.clientToGatewayKey,outboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,inboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,outboundCounter:0,highestInboundCounter:null}}function jp(e,t){let n=Lf.parse(t);if(e.length!==4)throw Error(`nonce prefix must be 4 bytes`);let r=new Uint8Array(12);return r.set(e,0),r.set(Kp(n),4),r}function Mp(e,t){let n=Lf.parse(t);if(e===null)return;let r=Lf.parse(e);if(n<=r)throw Error(`counter_replay`);if(n-r>1e3)throw Error(`counter_gap_too_large`)}function Np(e){return JSON.stringify([`relay-secure-business-payload-v1`,e.metadata.frameType,e.metadata.messageType,e.metadata.gatewayId,e.metadata.requestId??``,e.encryptedPayload.version,e.encryptedPayload.keyEpoch,e.encryptedPayload.counter])}function Pp(e){Hp(e.session.cipherSuite);let t=e.session.outboundCounter,n=jp(e.session.outboundNoncePrefix,t),r=e.preparedPayload.payloadBytes,i=Wp(Np({metadata:e.metadata,encryptedPayload:{version:1,keyEpoch:e.session.keyEpoch,counter:t}})),a=qi(e.session.outboundKey,n,i).encrypt(r),o=a.subarray(0,a.length-16),s=a.subarray(a.length-16);return e.session.outboundCounter=t+1,hp.parse({version:1,keyEpoch:e.session.keyEpoch,counter:t,iv:Ip(n),ciphertext:Ip(o),authTag:Ip(s),plaintextEncoding:pp,compression:e.preparedPayload.compression,...e.preparedPayload.compression===`gzip`?{uncompressedByteLength:e.preparedPayload.uncompressedByteLength,compressedByteLength:e.preparedPayload.compressedByteLength}:{}})}function Fp(e){Hp(e.session.cipherSuite);let t=hp.parse(e.encryptedPayload);if(t.keyEpoch!==e.session.keyEpoch)throw Error(`key_epoch_mismatch`);Mp(e.session.highestInboundCounter,t.counter);let n=jp(e.session.inboundNoncePrefix,t.counter),r=Lp(t.iv);if(!Gp(r,n))throw Error(`decrypt_failed`);let i=Wp(Np({metadata:e.metadata,encryptedPayload:t})),a=Up(Lp(t.ciphertext),Lp(t.authTag)),o;try{o=qi(e.session.inboundKey,r,i).decrypt(a)}catch{throw Error(`decrypt_failed`)}e.session.highestInboundCounter=t.counter;try{return Sf({payloadBytes:o,compression:t.compression,expectedUncompressedByteLength:t.uncompressedByteLength,parse:e.parse})}catch{throw Error(`decrypt_failed`)}}function Ip(e){let t=globalThis.Buffer;if(t)return t.from(e).toString(`base64`);let n=``;for(let t of e)n+=String.fromCharCode(t);if(typeof btoa!=`function`)throw Error(`base64 encoder unavailable`);return btoa(n)}function Lp(e){let t=globalThis.Buffer;if(t)return new Uint8Array(t.from(e,`base64`));if(typeof atob!=`function`)throw Error(`base64 decoder unavailable`);let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}function Rp(e){return Ip(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function zp(e){return Lp(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function Bp(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(ya(Na,e,t.length>0?t:new Uint8Array(32),n,r))}function Vp(e){return new Uint8Array(Na(e))}function Hp(e){if(e!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${e}`)}function Up(...e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Wp(e){return new TextEncoder().encode(e)}function Gp(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Kp(e){if(!Number.isSafeInteger(e))throw Error(`counter must be a safe integer`);let t=Math.floor(e/4294967296),n=e>>>0,r=new Uint8Array(8),i=new DataView(r.buffer);return i.setUint32(0,t),i.setUint32(4,n),r}function qp(e){return Rp(Na(Lp(e)).subarray(0,16))}function Jp(e){if(e.type!==`native.raw`)return null;let t=em(e.payload.raw),n=em(t.message),r=em(n.params),i=em(r.msg),a=tm(n.method)??tm(t.method);if(!a)return null;let o=tm(i.type)??``;if(!Qp(a)&&!$p(o))return null;let s=Zp(t);if(!s||!s.delta)return null;let c=tm(r.conversationId)??tm(r.conversation_id)??``,l=tm(i.thread_id)??tm(i.threadId)??tm(r.threadId)??tm(r.thread_id)??``,u=tm(i.turn_id)??tm(i.turnId)??tm(r.turnId)??tm(r.turn_id)??``,d=tm(i.item_id)??tm(i.itemId)??tm(r.itemId)??tm(r.item_id)??``,f=tm(t.source)??``,p=nm(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=nm(i.contentIndex??i.content_index??r.contentIndex??r.content_index);return{key:[e.sessionId,f,a,c,l,u,d,o,p,m].join(`|`),delta:s.delta,method:a}}function Yp(e,t){let n=Jp(e),r=Jp(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=em(t.payload.raw),o=Zp(a)?.location??Zp(em(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Xp(a,o,i)}}:null}function Xp(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=em(e.message),i=em(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=em(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Zp(e){let t=em(em(e.message).params),n=em(t.msg);return typeof n.delta==`string`?{delta:n.delta,location:`msg.delta`}:typeof t.delta==`string`?{delta:t.delta,location:`params.delta`}:typeof e.delta==`string`?{delta:e.delta,location:`raw.delta`}:null}function Qp(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function $p(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function em(e){return typeof e==`object`&&e?e:{}}function tm(e){return typeof e==`string`&&e.trim()||void 0}function nm(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():tm(e)??``}var rm=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]),im=/\u001B\[[0-?]*[ -/]*[@-~]/g,am={"thread.started":0,"thread.title.updated":1,"turn.started":2,"item.started":3,"item.updated":4,"item.completed":5,"turn.completed":6,"turn.failed":6,"tool.permission.requested":7,"user.input.requested":7};function om(e,t){let n=[],r=0,i=[...t].filter(t=>t.sessionId===e).sort((e,t)=>e.ts.localeCompare(t.ts)),a=[],o=()=>(r+=1,`raw_proj_item_${e}_${r}`);for(let e of i){let t=Wl.safeParse(e.type);if(t.success){n.push(dm(e,t.data,bm(e.payload.raw),e.eventId));continue}if(e.type!==`native.raw`)continue;let r=bm(e.payload.raw),i=cm(e,r);if(i.length>0&&n.push(...i),r.historyReplay!==!0)continue;let o=X(r.source);if(o?.startsWith(`codex.history.thread_read`)){n.push(...lm(e,r));continue}o&&rm.has(o)&&a.push(e)}a.length>0&&n.push(...um(a,o));let s=new Map,c=new Map;for(let e of n){let t=hm(e);if(!t){s.set(e.eventId,e);continue}let n=gm(e.payload.raw),r=c.get(t);(!r||n>r.richness)&&c.set(t,{event:e,richness:n})}for(let{event:e}of c.values())s.set(e.eventId,e);return[...s.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);if(n!==0)return n;let r=Vm(e.type)-Vm(t.type);return r===0?e.eventId.localeCompare(t.eventId):r})}function sm(e,t,n){return wu(e,om(e,t),n)}function cm(e,t){if(e.type!==`native.raw`||X(t.source)!==`codex.app_server`)return[];let n=bm(t.message),r=bm(n.params),i=X(n.method)??X(t.method);if(!i)return[];if(i===`turn/started`||i===`turn/completed`||i===`turn/failed`||i===`turn/interrupted`){let t=pm(bm(r.turn),r);if(Object.keys(t).length===0)return[];let n=i===`turn/started`?`turn.started`:i===`turn/failed`?`turn.failed`:`turn.completed`,a=X(t.status)??(i===`turn/completed`?`completed`:i===`turn/interrupted`?`interrupted`:`failed`),o=bm(t.error);return[dm(e,n,{turn:t,status:a,turn_id:X(t.id),source_event_type:`codex.app_server`,...n===`turn.failed`?{error:o}:{}},`${e.eventId}:${n.replace(`.`,`_`)}`)]}if(i===`item/started`||i===`item/completed`){let t=fm(bm(r.item));if(Object.keys(t).length===0)return[];let n=X(r.turn_id)??X(r.turnId)??X(bm(r.turn).id)??X(t.turn_id)??X(t.turnId);return[dm(e,i===`item/started`?`item.started`:`item.completed`,{turn_id:n,item:t,source_event_type:`codex.app_server`},`${e.eventId}:${i===`item/started`?`item_started`:`item_completed`}`)]}return[]}function lm(e,t){let n=[],r=bm(t.message),i=X(r.scope);if(i===`thread`){let t=bm(r.thread),i=X(t.id);n.push(dm(e,`thread.started`,{thread_id:i,thread:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:thread_started`));let a=Sm(X(t.preview));return a&&n.push(dm(e,`thread.title.updated`,{title:a,source:`codex.history.thread_read`,thread_id:i},`${e.eventId}:thread_title_updated`)),n}if(i===`turn`){let t=bm(r.turn),i=X(t.status);return n.push(dm(e,`turn.started`,{turn:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_started`)),i===`completed`||i===`interrupted`?n.push(dm(e,`turn.completed`,{status:i,turn:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_completed`)):i===`failed`&&n.push(dm(e,`turn.failed`,{status:i,turn:t,error:bm(t.error),source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_failed`)),n}if(i===`item`){let t=fm(bm(r.item)),i=X(r.turn_id)??X(r.turnId)??X(t.turn_id);n.push(dm(e,`item.completed`,{turn_id:i,item:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:item_completed`))}return n}function um(e,t){let n=[],r=e[0];if(!r)return n;let i=bm(r.payload.raw),a=bm(i.message),o=X(i.native_session_id)??X(a.session_id)??r.sessionId,s=new Map,c=!1,l=0,u;n.push(dm(r,`thread.started`,{thread_id:o,source:`claude.history.getSessionMessages`},`${r.eventId}:thread_started`));let d=(e,t,r)=>u||(l+=1,u={id:`claude_hist_turn_${l}`,terminal:!1},n.push(dm(e,`turn.started`,{turn_id:u.id,source_event_type:t,source_line:r},`${e.eventId}:turn_started:${u.id}`)),u),f=(e,t,r)=>{if(!u||u.terminal){u=void 0;return}u.terminal=!0,n.push(dm(e,`turn.completed`,{turn_id:u.id,source_event_type:t,source_line:r},`${e.eventId}:turn_completed:${u.id}`)),u=void 0},p=(e,t,r,i)=>{let a=d(e,t,r);a.terminal||(a.terminal=!0,n.push(dm(e,`turn.failed`,{turn_id:a.id,source_event_type:t,source_line:r,error:{message:i}},`${e.eventId}:turn_failed:${a.id}`)),u=void 0)};for(let r of e){let e=bm(r.payload.raw),i=bm(e.message),a=X(e.native_type)??X(i.type),l=bm(i.message),u=X(e.source)??`claude.history.getSessionMessages`,m=Bm(e.source_line);if(a===`user`){let e=Cm(l),a=wm(l),p=Em(l);if(e||a.length>0){if(e&&!c){let t=Sm(e);t&&(n.push(dm(r,`thread.title.updated`,{title:t,source:`claude.history.first_user_message`,thread_id:o},`${r.eventId}:thread_title_updated`)),c=!0)}f(r,u,m);let s=d(r,u,m);n.push(dm(r,`item.completed`,{item:{id:X(i.uuid)??t(),type:`user_message`,...e?{text:e}:{},...a.length>0?{attachments:a}:{},turn_id:s.id,source_event_type:u},source_line:m},`${r.eventId}:item_completed_user`))}p.forEach((e,i)=>{let a=e.toolUseId?s.get(e.toolUseId):void 0;if(e.toolUseId&&s.delete(e.toolUseId),a?.skipReplay)return;let o=d(r,u,m);n.push(dm(r,`item.completed`,{item:km(a,e,o.id,t),source_line:m},`${r.eventId}:item_completed_tool_result_${i+1}`))});continue}if(a!==`assistant`)continue;let h=d(r,u,m);Tm(l).forEach((e,i)=>{e.id&&s.set(e.id,e),!e.skipReplay&&n.push(dm(r,`item.started`,{item:{id:e.id??t(),type:`tool_status`,status:`running`,tool_name:e.name,title:e.title,text:e.title,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,file_path:e.filePath,turn_id:h.id,source_event_type:u},source_line:m},`${r.eventId}:item_started_tool_use_${i+1}`))});let g=Cm(l);g&&n.push(dm(r,`item.completed`,{item:{id:X(l.id)??X(i.uuid)??t(),type:`agent_message`,text:g,turn_id:h.id,source_event_type:u},source_line:m},`${r.eventId}:item_completed_assistant`));let _=zm(X(i.error));_&&p(r,u,m,_)}let m=e[e.length-1];if(m){let e=bm(m.payload.raw);f(m,X(e.source)??`claude.history.getSessionMessages`,Bm(e.source_line))}return n}function dm(e,t,n,r){return{v:e.v,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:r,ts:e.ts,type:t,payload:{raw:n}}}function fm(e){let t=_m(e),n=X(e.type);return n&&(t.type=mm(n)),t}function pm(e,t){let n=_m(e),r=X(e.id)??X(t.turn_id)??X(t.turnId);return r&&(n.id=r),n}function mm(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`webSearch`:return`web_search`;case`mcpToolCall`:return`mcp_tool_call`;case`todoList`:return`todo_list`;case`contextCompaction`:return`context_compaction`;default:return ym(e)}}function hm(e){if(e.type!==`item.started`&&e.type!==`item.completed`)return;let t=bm(e.payload.raw),n=bm(t.item),r=X(n.id)??X(n.item_id)??X(n.itemId);if(!r)return;let i=X(t.turn_id)??X(t.turnId)??X(n.turn_id)??X(n.turnId)??``;return[e.type,e.sessionId,i,r].join(`|`)}function gm(e){return Array.isArray(e)?e.reduce((e,t)=>e+gm(t),0):e&&typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>e+t.length+gm(n),1):typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?1:0}function _m(e){let t={};for(let[n,r]of Object.entries(e))t[ym(n)]=vm(r);return t}function vm(e){return Array.isArray(e)?e.map(e=>vm(e)):typeof e==`object`&&e?_m(e):e}function ym(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toLowerCase()}function bm(e){return typeof e==`object`&&e?e:{}}function X(e){return typeof e==`string`&&e.trim()||void 0}function xm(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function Sm(e,t=60){if(!e)return;let n=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 Cm(e){let t=X(e.content);if(t)return zm(t);let n=X(e.text)??X(e.prompt);if(n)return zm(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=bm(e),n=X(t.type);if(n&&n!==`text`)continue;let r=X(t.text)??X(t.content)??Rm(t);r&&i.push(r)}if(i.length!==0)return zm(i.join(`
|
|
138
|
+
`):void 0}var yl=q({inputTokens:K().int().nonnegative(),cachedInputTokens:K().int().nonnegative(),outputTokens:K().int().nonnegative(),reasoningOutputTokens:K().int().nonnegative(),totalTokens:K().int().nonnegative()}),bl=q({usedPercent:K(),windowMinutes:K().int().nonnegative().nullable(),resetsAt:K().nonnegative().nullable()}),xl=q({primary:bl.nullable().optional(),secondary:bl.nullable().optional(),planType:G().min(1).nullable().optional(),creditsBalance:G().min(1).nullable().optional()}),Sl=q({provider:Pa,usage:q({currentUsage:yl,latestTurnUsage:yl.nullable(),contextWindow:K().int().nonnegative().nullable(),sourceLabel:G().min(1),note:G().min(1).optional()}).nullable(),rateLimits:xl.optional()});function Cl(e){return e.provider===`claude`?Tl(e.rawEvents):wl(e.rawEvents)}function wl(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null;for(let c of Rl(e)){let e=Ul(c.payload.raw),l=c.type===`native.raw`?El(e):null;l?.usage&&((Fl(l.usage)||!t)&&(t=l.usage),Il(l.usage.latestTurnUsage)?n=l.usage.latestTurnUsage:Il(l.usage.currentUsage)&&!n&&(n=l.usage.currentUsage),r=l.usage.contextWindow??r),l?.rateLimits&&(i=l.rateLimits.primary??i,a=l.rateLimits.secondary??a,o=l.rateLimits.planType??o,s=l.rateLimits.creditsBalance??s);let u=Dl(c);if(u){let e=u.latestTurnUsage??u.currentUsage;Il(e)&&(n=e),r=u.contextWindow??r,!t&&(Fl(u)||u.contextWindow)&&(t=u)}}let c=t?{...t,latestTurnUsage:Il(n)?n:Il(t.latestTurnUsage)?t.latestTurnUsage:Il(t.currentUsage)?t.currentUsage:null,contextWindow:t.contextWindow??r}:null,l=kl({primary:i,secondary:a,planType:o,creditsBalance:s});return!c&&!l?null:{provider:`codex`,usage:c,...l?{rateLimits:l}:{}}}function Tl(e){let t=null;for(let n of Rl(e)){let e=Dl(n);e&&(t=e)}return t?{provider:`claude`,usage:t}:null}function El(e){if(e.source===`codex.history.thread_read`){let t=Ul(e.message),n=Ul(t.turn),r=Ml(n.usage??t.usage),i=Vl(n.model_context_window??t.model_context_window);return!r&&i===void 0?null:{usage:{currentUsage:r??Ll(),latestTurnUsage:r??null,contextWindow:i??null,sourceLabel:`codex.history.thread_read`,note:`当前来自 Codex history replay 快照。`}}}let t=zl(e);if(!t)return null;let n=Ul(Ul(e.message).params);if(t===`thread/tokenUsage/updated`){let e=Ul(n.tokenUsage??n.token_usage),t=Ml(e.total??e.total_token_usage);return t?{usage:{currentUsage:t,latestTurnUsage:Ml(e.last??e.last_token_usage),contextWindow:Vl(e.modelContextWindow??e.model_context_window)??null,sourceLabel:`thread/tokenUsage/updated`}}:null}if(t===`account/rateLimits/updated`){let e=Ol(n.rateLimits??n.rate_limits);return e?{rateLimits:e}:null}if(t===`codex/event/token_count`){let e=Ul(n.msg),t=Ul(e.info),r=Ml(t.total_token_usage??t.totalTokenUsage),i=Ol(e.rate_limits??e.rateLimits);return!r&&!i?null:{usage:r?{currentUsage:r,latestTurnUsage:Ml(t.last_token_usage??t.lastTokenUsage),contextWindow:Vl(t.model_context_window??t.modelContextWindow)??null,sourceLabel:`codex/event/token_count`}:void 0,...i?{rateLimits:i}:{}}}if(t===`codex/event/task_started`){let e=Ul(n.msg),t=Vl(e.model_context_window??e.modelContextWindow);return t===void 0?null:{usage:{currentUsage:Ll(),latestTurnUsage:null,contextWindow:t,sourceLabel:`codex/event/task_started`,note:`目前只拿到了 context window,尚未拿到 thread token usage 快照。`}}}return null}function Dl(e){if(e.type!==`turn.completed`&&e.type!==`turn.failed`&&e.type!==`turn.started`)return null;let t=Ul(e.payload.raw),n=jl(t.usage??Ul(t.turn).usage),r=Vl(t.model_context_window??Ul(t.turn).model_context_window);return!n&&r===void 0?null:{currentUsage:n??Ll(),latestTurnUsage:n??null,contextWindow:r??null,sourceLabel:e.type}}function Ol(e){let t=Ul(e),n=Al(t.primary),r=Al(t.secondary),i=Hl(t.plan_type??t.planType)??null,a=Hl(Ul(t.credits).balance)??null;return!n&&!r&&!i&&!a?null:{primary:n,secondary:r,planType:i,creditsBalance:a}}function kl(e){if(!(!e.primary&&!e.secondary&&!e.planType&&!e.creditsBalance))return{...e.primary?{primary:e.primary}:{},...e.secondary?{secondary:e.secondary}:{},...e.planType?{planType:e.planType}:{},...e.creditsBalance?{creditsBalance:e.creditsBalance}:{}}}function Al(e){let t=Ul(e),n=Vl(t.used_percent??t.usedPercent);return n===void 0?null:{usedPercent:n,windowMinutes:Vl(t.window_minutes??t.windowDurationMins)??null,resetsAt:Vl(t.resets_at??t.resetsAt)??null}}function jl(e){return Nl(e)}function Ml(e){return Nl(e,{totalFallback:`input_plus_output`})}function Nl(e,t){let n=Ul(e),r=Vl(n.input_tokens??n.inputTokens),i=Vl(n.cached_input_tokens??n.cachedInputTokens??n.cache_read_input_tokens??n.cacheReadInputTokens),a=Vl(n.output_tokens??n.outputTokens),o=Vl(n.reasoning_output_tokens??n.reasoningOutputTokens)??0,s=Vl(n.total_tokens??n.totalTokens)??Pl(r,i,a,o,t);return r===void 0&&i===void 0&&a===void 0&&s===void 0?null:{inputTokens:r??0,cachedInputTokens:i??0,outputTokens:a??0,reasoningOutputTokens:o,totalTokens:s??0}}function Pl(e,t,n,r,i){return i?.totalFallback===`input_plus_output`?Bl(e,n):Bl(e,t,n,r)}function Fl(e){return Il(e.latestTurnUsage)||Il(e.currentUsage)}function Il(e){return e?e.inputTokens>0||e.cachedInputTokens>0||e.outputTokens>0||e.reasoningOutputTokens>0||e.totalTokens>0:!1}function Ll(){return{inputTokens:0,cachedInputTokens:0,outputTokens:0,reasoningOutputTokens:0,totalTokens:0}}function Rl(e){return[...e].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.rawSeq-t.rawSeq:n})}function zl(e){return Hl(Ul(e.message).method)??Hl(e.method)??null}function Bl(...e){let t=e.filter(e=>typeof e==`number`);if(t.length!==0)return t.reduce((e,t)=>e+t,0)}function Vl(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`&&e.trim()){let t=Number(e);if(Number.isFinite(t))return t}}function Hl(e){return typeof e==`string`&&e.trim()?e:void 0}function Ul(e){return typeof e==`object`&&e?e:{}}var Wl=Y([`session.started`,`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`,`tool.permission.requested`,`tool.permission.resolved`,`user.input.requested`,`user.input.resolved`,`file.changed`,`file.diff.ready`,`status.progress`,`error`,`error.runtime`]),Gl=nl.extend({type:Wl}),Kl=nl.extend({kind:J(`provider.raw`),rawSeq:K().int().positive(),type:G().min(1)});Gl.extend({kind:J(`gateway.control`).optional(),derivedFrom:G().min(1).optional()});var ql=nl.extend({kind:J(`session.stream.sync`),type:J(`session.stream.sync`),payload:q({raw:q({decision:Y([`delta`,`snapshot`]),reason:G().min(1),snapshotId:G().min(1).optional(),fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional()}).passthrough()}).passthrough()}),Jl=q({updatedAt:G().datetime().optional(),activeStartedAt:G().datetime().optional(),status:Y([`running`,`idle`]).optional(),interactionLockReason:Y([`external_turn_running`]).optional(),model:G().min(1).nullable().optional(),sessionTurnConfig:Zc.optional(),sessionTurnConfigUpdatedAt:G().datetime().optional(),title:G().min(1).optional(),pendingApprovals:K().int().nonnegative().optional(),pendingUserInputs:K().int().nonnegative().optional(),pendingActions:K().int().nonnegative().optional()}),Yl=er([Kl,ql,nl.extend({kind:J(`session.stream.snapshot.chunk`),type:J(`session.stream.snapshot.chunk`),payload:q({raw:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),events:$n(Kl),sessionSummary:Jl.optional()}).passthrough(),readable:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),timelineItems:$n(Ho).optional(),sessionSummary:Jl.optional()}).passthrough().optional()}).passthrough()}),nl.extend({kind:J(`session.readable.snapshot.chunk`),type:J(`session.readable.snapshot.chunk`),payload:q({readable:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),timelineItems:$n(Ho),pendingApprovals:$n(Ro).optional(),pendingUserInputs:$n(Vo).optional(),contextUsage:Sl.nullable().optional(),sessionSummary:Jl.optional()}).passthrough()}).passthrough()}),nl.extend({kind:J(`session.readable.delta`),type:J(`session.readable.delta`),payload:q({readable:q({fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative(),timelineUpserts:$n(Ho),timelineRemovals:$n(G().min(1)),timelineTextDeltaPatches:$n(Lc).optional(),pendingApprovalUpserts:$n(Ro).optional(),pendingApprovalRemovals:$n(G().min(1)).optional(),pendingUserInputUpserts:$n(Vo).optional(),pendingUserInputRemovals:$n(G().min(1)).optional(),sessionSummary:Jl.optional(),contextUsage:Sl.nullable().optional()}).passthrough()}).passthrough()}),nl.extend({kind:J(`session.external.update`),type:J(`session.external.update`),payload:q({raw:q({updatedAt:G().datetime(),status:Y([`running`,`idle`]),interactionLockReason:Y([`external_turn_running`]).optional(),refreshMode:Y([`delta`,`snapshot`]),fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional(),historyUpdated:Zn(),statusChanged:Zn(),sessionSummary:Jl.optional()}).passthrough()}).passthrough()})]),Xl=q({algorithm:Y([`ed25519`]),publicKey:qa,publicKeyFingerprint:G().min(1),keyVersion:K().int().min(1),createdAt:G().datetime()});q({code:G().min(4),expiresAt:G().datetime()});var Zl=Y([`ed25519`]),Ql=Y([`active`,`revoked`,`rotating`,`unknown`]),$l=q({algorithm:Zl,publicKey:qa,publicKeyFingerprint:G().min(1)}),eu=q({pairingCode:G().min(4),signedAt:G().datetime()}),tu=q({gatewayId:G().min(1),deviceId:G().min(1),mobilePublicKey:qa,pairingContext:eu}),nu=q({algorithm:J(`ed25519`),gatewayPublicKeyFingerprint:G().min(1),payload:tu,signature:qa}),ru=q({code:G().min(4),deviceName:rr(e=>{if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:void 0},G().min(1).optional()),deviceIdentity:$l.optional()}),iu=q({accessToken:G().min(1),refreshToken:G().min(1),expiresInSeconds:K().int().positive()}),au=iu.extend({gatewayId:G().min(1),gatewayName:G().min(1).optional(),machineName:G().min(1).optional(),deviceId:G().min(1),gatewayIdentity:Xl.optional(),deviceIdentityFingerprint:G().min(1).optional(),deviceIdentityStatus:Ql.optional(),pairingConfirmation:nu.optional()}),ou=q({refreshToken:G().min(1)}),su=iu.extend({deviceId:G().min(1),deviceIdentityFingerprint:G().min(1).optional(),deviceIdentityStatus:Ql.optional()});function cu(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var lu=Y([`missing`,`current`,`stale`]),uu=q({accountId:G().min(1),accountType:Y([`chatgpt`,`apiKey`,`unknown`]),authMode:G().min(1),planType:G().min(1).nullable(),lastRefreshAt:G().datetime().nullable(),hasSavedSnapshot:Zn(),snapshotStatus:lu,rateLimits:xl.nullable()}),du=q({accountId:G().min(1),accountType:Y([`chatgpt`,`apiKey`,`unknown`]),authMode:G().min(1),planType:G().min(1).nullable(),lastRefreshAt:G().datetime().nullable(),savedAt:G().datetime(),isCurrent:Zn(),rateLimits:xl.nullable()}),fu=q({current:uu.nullable(),savedAccounts:$n(du)}),pu=q({saved:J(!0),accounts:fu}),mu=q({switched:J(!0),closedRuntimeSessionCount:K().int().nonnegative(),accounts:fu}),hu=q({deleted:J(!0),accounts:fu}),gu=q({restarted:J(!0),closedRuntimeSessionCount:K().int().nonnegative()}),_u=15e3,vu=12e4;function yu(e){return{sessionId:e,messages:new Map,itemToMessageKey:new Map,requestToMessageKey:new Map,turnToLastToolMessageKey:new Map,codexSemanticMessageKeyToMessageKeys:new Map,codexHistoryReplaySemanticOccurrenceByKey:new Map}}function bu(e,t,n=`codex`){if(t.sessionId!==e.sessionId)return;let r=`optimistic:${t.id}`;e.messages.has(r)||e.messages.set(r,{id:r,sessionId:e.sessionId,provider:n,kind:`user`,status:`completed`,ts:t.ts,updatedAt:t.ts,source:`optimistic`,title:`User`,text:t.text,details:[],debug:{eventTypes:[`optimistic.prompt`]}})}function xu(e,t){if(t.sessionId===e.sessionId){if(t.type===`item.started`||t.type===`item.updated`||t.type===`item.completed`){Tu(e,t);return}if(t.type===`tool.permission.requested`||t.type===`tool.permission.resolved`){Eu(e,t);return}if(t.type===`user.input.requested`||t.type===`user.input.resolved`){Du(e,t);return}if(t.type===`turn.completed`){Au(e,t);return}(t.type===`turn.failed`||t.type===`error`||t.type===`error.runtime`)&&ju(e,t)}}function Su(e){return[...e.messages.values()].map(jd).sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.id.localeCompare(t.id):n})}function Cu(e,t,n){let r=yu(e),i=t[0]?.provider??`codex`,a=[...n].sort((e,t)=>e.ts.localeCompare(t.ts));for(let e of a)bu(r,e,i);let o=[...t].filter(t=>t.sessionId===e).sort((e,t)=>e.ts.localeCompare(t.ts));for(let e of o)xu(r,e);return r}function wu(e,t,n){return Su(Cu(e,t,n))}function Tu(e,t){let n=gd(t.payload.raw),r=gd(n.item),i=qu(r,[`type`]),a=qu(r,[`phase`]),o=Gu(n,r),s=qu(r,[`id`]),c=cd(qu(r,[`status`])),l=Xu(r,i)??Ku(r),u=[...Ju(r),...Zu(r,i)],d=Iu(t.provider,o,i,a,l,u),f=d?Bu(n):void 0,p=Wu(n)&&d?Ru(e,d,f):void 0;if(!i){let r=Ku(n);if(!r)return;let i=Nu(t,`assistant`,o),a=Mu(e,i,{id:i,sessionId:e.sessionId,provider:t.provider,kind:`assistant`,status:`streaming`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Assistant`,details:[],turnId:o,debug:{eventTypes:[]}});t.type===`item.completed`?(a.status=`completed`,a.text=r):(a.status=`streaming`,a.text=yd(a.text,r)),kd(a,t);return}let m=Fu(i);if(m===`user`&&!l&&u.length===0)return;let h=p??(s?`item:${s}`:Nu(t,i,o)),g=Pu(m,i),_=m===`tool`?hd(r,l):void 0,v=Mu(e,h,{id:h,sessionId:e.sessionId,provider:t.provider,kind:m,status:`streaming`,ts:t.ts,updatedAt:t.ts,source:`event`,title:g,details:[],itemType:i,itemId:s,turnId:o,collapsible:m===`reasoning`,collapsedByDefault:m===`reasoning`,debug:{eventTypes:[],rawItemType:i,...a?{rawItemPhase:a}:{}}});s&&e.itemToMessageKey.set(s,h),d&&Lu(e,d,h),o&&m===`tool`&&e.turnToLastToolMessageKey.set(o,h),v.provider=t.provider,v.itemType=i,v.debug.rawItemPhase=a??v.debug.rawItemPhase,p&&v.itemId&&s&&v.itemId!==s||(v.itemId=s??v.itemId),v.turnId=o??v.turnId,v.title=_?.title??g,v.updatedAt=t.ts,v.collapsible=m===`reasoning`,v.collapsedByDefault=m===`reasoning`,_&&(v.toolCardData=_),u.length>0&&(v.attachments=ad(v.attachments,u));let y=qu(r,[`source_event_type`]);if(y&&Uu(m)&&!_&&Ed(v,`source: ${y}`),m===`tool`&&!_)for(let e of Dd(r))Ed(v,e);t.type===`item.started`?(v.status=m===`user`?`completed`:`streaming`,l&&(v.text=bd(m)?xd(v.text,l,r):yd(v.text,l))):t.type===`item.updated`?(v.status=m===`user`?`completed`:v.status===`waiting_approval`||v.status===`waiting_input`?v.status:`streaming`,l&&(v.text=bd(m)?xd(v.text,l,r):yd(v.text,l))):t.type===`item.completed`&&(v.status=m===`error`?`failed`:c??`completed`,l&&(v.text=l)),kd(v,t),d&&Wu(n)&&zu(e,d,f),m===`user`&&v.text&&Ad(e,v.text,v.ts)}function Eu(e,t){let n=gd(t.payload.raw),r=qu(n,[`requestId`,`request_id`]);if(!r)return;let i=qu(n,[`itemId`,`item_id`]),a=qu(n,[`turnId`,`turn_id`]),o=qu(n,[`toolName`,`tool_name`])??`tool`,s=qu(n,[`reason`]),c=qu(n,[`decision`]),l=gd(n.rawParams??n.raw_params),u=gd(l.networkApprovalContext??l.network_approval_context),d=qu(l,[`command`]),f=qu(l,[`cwd`]),p=qu(l,[`grantRoot`,`grant_root`]),m=qu(u,[`host`]),h=qu(u,[`protocol`]),g=Ou(e,r,`approval`),_=Mu(e,g,{id:g,sessionId:e.sessionId,provider:t.provider,kind:`tool`,status:`waiting_approval`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Tool Approval`,details:[],itemType:`tool_status`,itemId:i??void 0,turnId:a??void 0,requestId:r,debug:{eventTypes:[],rawItemType:`tool_status`}});_.provider=t.provider,_.updatedAt=t.ts,_.requestId=r,_.itemId=i??_.itemId,_.turnId=a??_.turnId,_.title=_.title||`Tool Approval`,t.type===`tool.permission.requested`?(_.status=`waiting_approval`,_.text=d?`等待命令执行审批`:`${o} \u9700\u8981\u5BA1\u6279`,Ed(_,`tool: ${o}`),s&&Ed(_,`reason: ${s}`),d&&Ed(_,`command: ${Pd(d,200)}`),f&&Ed(_,`cwd: ${Pd(f,200)}`),p&&Ed(_,`grant_root: ${Pd(p,200)}`),m&&Ed(_,`network: ${Pd(h?`${h}://${m}`:m,200)}`)):(_.status=c===`deny`?`failed`:`completed`,_.text=c===`deny`?`工具审批已拒绝`:`工具审批已通过`,c&&Ed(_,`decision: ${c}`),s&&Ed(_,`reason: ${s}`)),ku(e,g,r,i,a),kd(_,t)}function Du(e,t){let n=gd(t.payload.raw),r=qu(n,[`requestId`,`request_id`]);if(!r)return;let i=qu(n,[`itemId`,`item_id`]),a=qu(n,[`turnId`,`turn_id`]),o=qu(n,[`status`]),s=qu(n,[`reason`]),c=fd(n,[`answeredCount`,`answered_count`]),l=pd(n.questions),u=md(n.answers),d=Ou(e,r,`user-input`),f=Mu(e,d,{id:d,sessionId:e.sessionId,provider:t.provider,kind:`tool`,status:`waiting_input`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Plan Question`,details:[],itemType:`request_user_input`,itemId:i??void 0,turnId:a??void 0,requestId:r,userInputQuestions:l,debug:{eventTypes:[],rawItemType:`request_user_input`}});if(f.provider=t.provider,f.updatedAt=t.ts,f.requestId=r,f.itemId=i??f.itemId,f.turnId=a??f.turnId,f.title=`Plan Question`,t.type===`user.input.requested`)f.status=`waiting_input`,f.text=l.length>0?`\u9700\u8981\u56DE\u7B54 ${l.length} \u4E2A\u95EE\u9898`:`需要回答问题`,f.userInputQuestions=l,f.userInputAnswers=void 0,Ed(f,`request_id: ${r}`);else{f.status=ld(o);let e=c??0;f.text=ud(o,e),Ed(f,`status: ${o??`submitted`}`),Ed(f,`answered_count: ${e}`),s&&Ed(f,`reason: ${s}`),l.length>0&&(f.userInputQuestions=l),u&&(f.userInputAnswers=u)}ku(e,d,r,i,a),kd(f,t)}function Ou(e,t,n){return e.requestToMessageKey.get(t)??`${n}:${t}`}function ku(e,t,n,r,i){e.requestToMessageKey.set(n,t),r&&e.itemToMessageKey.set(r,t),i&&e.turnToLastToolMessageKey.set(i,t)}function Au(e,t){let n=gd(t.payload.raw),r=Gu(n,void 0),i=gd(n.usage),a=gd(gd(n.turn).usage),o=fd(i,[`input_tokens`]),s=fd(i,[`output_tokens`]),c=fd(a,[`input_tokens`]),l=fd(a,[`output_tokens`]),u=o??c,d=s??l;if(r)for(let n of e.messages.values())n.turnId===r&&n.status===`streaming`&&(n.status=`completed`,n.updatedAt=t.ts);if(u!==void 0||d!==void 0){let n=r?`turn-usage:${r}`:Nu(t,`turn.usage`,r),i=Mu(e,n,{id:n,sessionId:e.sessionId,provider:t.provider,kind:`system`,status:`completed`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Turn Usage`,details:[],turnId:r,debug:{eventTypes:[]}});i.provider=t.provider,i.status=`completed`,i.updatedAt=t.ts,i.text=`Token usage`,u!==void 0&&Ed(i,`input_tokens: ${u}`),d!==void 0&&Ed(i,`output_tokens: ${d}`),kd(i,t)}}function ju(e,t){let n=gd(t.payload.raw),r=Ku(gd(n.error))??Ku(n);if(!r)return;let i=Gu(n,void 0),a=i?`turn-error:${i}`:`error:${t.eventId}`,o=Mu(e,a,{id:a,sessionId:e.sessionId,provider:t.provider,kind:`error`,status:`failed`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Error`,text:r,details:[],turnId:i,debug:{eventTypes:[]}});o.provider=t.provider,o.status=`failed`,o.updatedAt=t.ts,o.text=r,o.turnId=i??o.turnId,kd(o,t)}function Mu(e,t,n){return e.messages.get(t)||(e.messages.set(t,n),n)}function Nu(e,t,n){let r=Date.parse(e.ts),i=Number.isFinite(r)?Math.floor(r/_u):Math.floor(Id(e.ts)/_u);return`fallback:${e.provider}:${n??`no_turn`}:${t}:${i}`}function Pu(e,t){return t===`plan`?`Plan`:e===`assistant`?t===`image_generation`||t===`image_view`?`Image`:`Assistant`:e===`user`?`User`:e===`tool`?t===`command_execution`?`Command`:t===`file_change`?`File Change`:t===`mcp_tool_call`?`MCP Tool`:t===`web_search`?`Web Search`:`Tool`:e===`reasoning`?t===`todo_list`?`Todo`:t===`plan`?`Plan`:`Reasoning`:e===`error`?`Error`:`System`}function Fu(e){return e===`user_message`?`user`:e===`agent_message`||e===`plan`||e===`image_generation`||e===`image_view`?`assistant`:e===`command_execution`||e===`file_change`||e===`mcp_tool_call`||e===`web_search`||e===`tool_status`||e===`collab_tool_call`?`tool`:e===`reasoning`||e===`todo_list`?`reasoning`:e===`error`?`error`:`system`}function Iu(e,t,n,r,i,a){let o=od(a);if(e!==`codex`||!t||!i&&!o)return;let s=Vu(n);if(!(s!==`user_message`&&s!==`agent_message`))return`${t}|${s}|${Hu(s,r)}|${i??``}|${o}`}function Lu(e,t,n){let r=e.codexSemanticMessageKeyToMessageKeys.get(t);if(!r){e.codexSemanticMessageKeyToMessageKeys.set(t,[n]);return}r.includes(n)||r.push(n)}function Ru(e,t,n){let r=e.codexSemanticMessageKeyToMessageKeys.get(t);if(!(!r||r.length===0))return r[n===void 0?e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0:n-1]}function zu(e,t,n){let r=n??(e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0)+1,i=e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0;e.codexHistoryReplaySemanticOccurrenceByKey.set(t,Math.max(i,r))}function Bu(e){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 Vu(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 Hu(e,t){return e===`agent_message`&&(!t||t===`final_answer`)?``:t??``}function Uu(e){return e===`tool`}function Wu(e){if(e.historyReplay===!0)return!0;let t=qu(e,[`source`]);return t===`codex.history.thread_read`||t===`codex.history.thread_read.incremental`}function Gu(e,t){return qu(e,[`turn_id`,`turnId`])??qu(gd(e.turn),[`id`,`turn_id`,`turnId`])??qu(t??{},[`turn_id`,`turnId`])}function Ku(e){return dd(gd(e.payload),[`delta`,`output_delta`,`outputDelta`])||dd(e,[`text`,`message`,`output`,`response`,`reason`,`output_delta`,`aggregated_output`])||_d(e)}function qu(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.trim())return t}}function Ju(e){return[...Yu(e.attachments),...Yu(e.content),...Yu(e.input)]}function Yu(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=gd(n),r=gd(e.remote_agent_attachment),i=qu(e,[`type`]),a=qu(e,[`kind`]),o=gd(e.source),s=gd(r.locator),c=qu(e,[`path`])??qu(o,[`path`])??qu(s,[`path`]),l=td(qu(r,[`mimeType`,`mime_type`])??qu(e,[`mimeType`,`mime_type`])??qu(o,[`media_type`,`mediaType`]));if(i!==`image`&&i!==`localImage`&&i!==`local_image`&&a!==`image`&&!c&&Object.keys(r).length===0)continue;let u=qu(r,[`id`])??qu(e,[`id`])??c??`image-${t.length+1}`;t.push({id:u,kind:`image`,...l?{mimeType:l}:{},fileName:qu(r,[`fileName`,`file_name`])??qu(e,[`fileName`,`file_name`]),width:rd(r.width??e.width),height:rd(r.height??e.height),sizeBytes:id(r.sizeBytes??r.size_bytes??e.sizeBytes??e.size_bytes),...c?{locator:{kind:`absolute`,path:c}}:{}})}return t}function Xu(e,t){let n=Qu(e,t);if(n)return`})`}function Zu(e,t){let n=Qu(e,t);if(!n)return[];let r=qu(e,[`id`])??n,i=td(qu(e,[`mime_type`,`mimeType`]))??nd(n),a=ed(n);return[{id:r,kind:`image`,...i?{mimeType:i}:{},...a?{fileName:a}:{},locator:{kind:`absolute`,path:n}}]}function Qu(e,t){let n=Vu(t);if(n===`image_generation`)return qu(e,[`saved_path`,`savedPath`,`path`]);if(n===`image_view`)return qu(e,[`path`,`saved_path`,`savedPath`])}function $u(e){let t=e.trim();return t?/[\s()<>]/.test(t)?`<${t.replace(/</g,`%3C`).replace(/>/g,`%3E`)}>`:t:``}function ed(e){let t=e.split(/[\\/]/).filter(Boolean).pop();return t&&t.trim()?t:void 0}function td(e){if(e===`image/png`||e===`image/jpeg`||e===`image/webp`)return e}function nd(e){let t=e.toLowerCase();if(t.endsWith(`.png`))return`image/png`;if(t.endsWith(`.jpg`)||t.endsWith(`.jpeg`))return`image/jpeg`;if(t.endsWith(`.webp`))return`image/webp`}function rd(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0}function id(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.round(e):void 0}function ad(e,t){let n=new Map;for(let r of[...e??[],...t])n.set(sd(r),r);return[...n.values()]}function od(e){return!e||e.length===0?``:e.map(sd).sort().join(`,`)}function sd(e){return e.locator?.kind===`absolute`?`path:${e.locator.path}`:`id:${e.id}`}function cd(e){if(e===`streaming`||e===`waiting_approval`||e===`waiting_input`||e===`completed`||e===`failed`)return e;if(e===`running`)return`streaming`}function ld(e){return!e||e===`submitted`?`completed`:`failed`}function ud(e,t){return!e||e===`submitted`?`\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:e===`interrupted`?t>0?`\u5DF2\u4E2D\u65AD\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已中断`:e===`cancelled`?t>0?`\u5DF2\u53D6\u6D88\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已取消`:e===`expired`?t>0?`\u5DF2\u8FC7\u671F\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已过期`:e===`dismissed`?t>0?`\u5DF2\u5173\u95ED\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已关闭`:t>0?`\u672A\u5B8C\u6210\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问未完成`}function dd(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function fd(e,t){for(let n of t){let t=e[n];if(typeof t==`number`&&Number.isFinite(t))return t}}function pd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=gd(n),r=qu(e,[`id`]),i=qu(e,[`header`]),a=qu(e,[`question`]);if(!r||!i||!a)continue;let o=Array.isArray(e.options)?e.options.map(e=>{let t=gd(e),n=qu(t,[`label`]),r=qu(t,[`description`])??n,i=qu(t,[`markdown`]);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).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}function md(e){let t=gd(e),n=Object.entries(t);if(n.length===0)return;let r={};for(let[e,t]of n)if(e){if(!Array.isArray(t)){r[e]=[];continue}r[e]=t.map(e=>typeof e==`string`?e:void 0).filter(e=>typeof e==`string`&&e.length>0)}return Object.keys(r).length>0?r:void 0}function hd(e,t){if(qu(e,[`display_as`])!==`tool_card`)return;let n=qu(e,[`title`])??t,r=qu(e,[`status_label`])??t;if(!n||!r)return;let i=[],a=qu(e,[`prompt`]),o=qu(e,[`response`]),s=qu(e,[`response_label`])??`Response`;a&&i.push({label:`Prompt`,body:a}),o&&i.push({label:s,body:o});let c=[],l=qu(e,[`file_path`]),u=fd(e,[`exit_code`,`exitCode`]),d=fd(e,[`total_tool_uses`]),f=fd(e,[`total_tokens`]),p=fd(e,[`duration_ms`]);return l&&c.push(l),typeof u==`number`&&c.push(`exit_code: ${u}`),typeof d==`number`&&c.push(`${d} tool uses`),typeof f==`number`&&c.push(`${Md(f)} tokens`),typeof p==`number`&&c.push(Nd(p)),{title:n,statusLabel:r,compactText:t?Fd(t):void 0,sections:i,details:c}}function gd(e){return typeof e==`object`&&e?e:{}}function _d(e){return vl(e,vd)}function vd(e){if(typeof e==`string`&&e.length>0)return e;let t=gd(e),n=dd(t,[`text`,`message`,`output`,`response`,`reason`]);if(n)return n;let r=dd(gd(t.data),[`text`,`message`,`output`,`response`,`reason`]);if(r)return r;if(!Array.isArray(t.text_elements))return;let i=[];for(let e of t.text_elements){let t=dd(gd(e),[`text`,`value`]);t&&i.push(t)}return i.length>0?i.join(``):void 0}function yd(e,t){return!e||t.startsWith(e)?t:e.endsWith(t)?e:`${e}${t}`}function bd(e){return e===`assistant`||e===`reasoning`}function xd(e,t,n){return e?t===e?e:t.startsWith(e)?t:e.endsWith(t)?e:Sd(n)?`${e}${t}`:wd(e,t)?t:`${e}${t}`:t}function Sd(e){let t=gd(e.payload);return Td(t.delta)||Td(t.output_delta)||Td(t.outputDelta)||Td(e.output_delta)||Td(e.outputDelta)?!0:Cd(qu(e,[`original_method`,`originalMethod`]))}function Cd(e){return e?e===`item/agentMessage/delta`||e===`codex/event/agent_message_content_delta`:!1}function wd(e,t){return t.length===0||t.length<24?!1:t.length>=Math.floor(e.length*.7)}function Td(e){return typeof e==`string`&&e.length>0}function Ed(e,t){t.trim()&&(e.details.includes(t)||e.details.push(t))}function Dd(e){let t=[],n=qu(e,[`command`]),r=qu(e,[`tool_name`,`tool`]),i=qu(e,[`server`]),a=qu(e,[`status`]),o=qu(e,[`query`]),s=qu(e,[`output_delta`,`aggregated_output`]),c=e.history_output_omitted===!0||e.historyOutputOmitted===!0,l=fd(e,[`history_output_byte_length`,`historyOutputByteLength`]),u=fd(e,[`exit_code`]),d=qu(gd(e.error),[`message`]);if(n&&t.push(`command: ${Pd(n,200)}`),r&&t.push(`tool: ${r}`),i&&t.push(`server: ${i}`),a&&t.push(`status: ${a}`),o&&t.push(`query: ${Pd(o,200)}`),u!==void 0&&t.push(`exit_code: ${u}`),d&&t.push(`error: ${Pd(d,200)}`),s?t.push(`output: ${Pd(s,400)}`):c&&t.push(l===void 0?`output: omitted in compact history`:`output: omitted in compact history (${l.toLocaleString(`en-US`)} bytes)`),e.type===`todo_list`){let n=Array.isArray(e.items)?e.items:[];for(let e of n){let n=gd(e),r=qu(n,[`text`])??``,i=n.completed===!0;t.push(`${i?`[x]`:`[ ]`} ${r}`)}}if(e.type===`file_change`){let n=Array.isArray(e.changes)?e.changes:[];for(let e of n){let n=gd(e),r=qu(n,[`path`])??`unknown`,i=Od(n);t.push(`${i}: ${r}`)}}return t}function Od(e){let t=qu(gd(e.kind),[`type`]),n=qu(e,[`kind`,`type`]),r=(t??n??`update`).replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase();return r===`add`||r===`create`||r===`new`?`add`:r===`delete`||r===`remove`||r===`removed`?`delete`:r===`move`||r===`rename`?`move`:`update`}function kd(e,t){e.debug.eventTypes.includes(t.type)||e.debug.eventTypes.push(t.type)}function Ad(e,t,n){let r=Fd(t),i=Date.parse(n);for(let[t,n]of e.messages.entries()){if(n.kind!==`user`||n.source!==`optimistic`||Fd(n.text??``)!==r)continue;let a=Date.parse(n.ts);if(!(Number.isFinite(i)&&Number.isFinite(a)&&Math.abs(i-a)>vu)){e.messages.delete(t);return}}}function jd(e){return{...e,attachments:e.attachments?e.attachments.map(e=>({...e,locator:e.locator?{...e.locator}:void 0})):void 0,details:[...e.details],userInputQuestions:e.userInputQuestions?e.userInputQuestions.map(e=>({...e,options:e.options?e.options.map(e=>({...e})):null})):void 0,userInputAnswers:e.userInputAnswers?Object.fromEntries(Object.entries(e.userInputAnswers).map(([e,t])=>[e,[...t]])):void 0,toolCardData:e.toolCardData?{...e.toolCardData,sections:e.toolCardData.sections.map(e=>({...e})),details:[...e.toolCardData.details]}:void 0,debug:{...e.debug,eventTypes:[...e.debug.eventTypes]}}}function Md(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function Nd(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 Pd(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function Fd(e){return e.trim().replace(/\s+/g,` `)}function Id(e){let t=0;for(let n=0;n<e.length;n+=1)t=t*31+e.charCodeAt(n)>>>0;return t}var Ld=Y([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),Rd=Y([`npm`,`pnpm`,`yarn`,`unknown`]),zd=Y([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),Bd=Y([`console`,`mobile`,`system`]),Vd=q({manager:Rd,installType:zd,packageName:G().min(1),packageRoot:G().min(1).optional(),binPath:G().min(1).optional(),canSelfUpdate:Zn(),reason:G().min(1).optional()}),Hd=q({id:G().min(1),targetVersion:G().min(1),requestedBy:Bd,requestedAt:G().datetime(),startedAt:G().datetime().optional()}),Ud=q({packageName:G().min(1),currentVersion:G().min(1),latestVersion:G().min(1).optional(),available:Zn(),canApply:Zn(),status:Ld,checkedAt:G().datetime().optional(),install:Vd,job:Hd.optional(),lastError:G().min(1).optional()}),Wd=q({type:J(`gateway.update.status`),payload:Ud}),Gd=q({started:Zn(),update:Ud}),Kd=rr(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},G().trim().min(1)),qd=q({id:G().min(1),title:G().min(1),path:G().min(1),createdAt:G().datetime(),updatedAt:G().datetime(),lastSessionAt:G().datetime().optional(),runningCount:K().int().nonnegative(),idleCount:K().int().nonnegative().optional(),totalCount:K().int().nonnegative().optional(),endedCount:K().int().nonnegative()}),Jd=q({name:G().min(1),path:G().min(1)}),Yd=q({kind:Y([`home`,`desktop`,`documents`,`downloads`,`root`]),path:G().min(1)}),Xd=q({rootPath:G().min(1),currentPath:G().min(1),parentPath:G().min(1).nullable(),shortcuts:$n(Yd).default([]),directories:$n(Jd)}),Zd=Y([`running`,`idle`]),Qd=Y([`running`,`idle`,`all`]),$d=Y([`external_turn_running`]),ef=Y([`delta`,`snapshot`]),tf=q({id:G().min(1),nativeSessionId:G().min(1).optional(),source:Y([`gateway`,`native_discovered`]).optional(),projectId:G().min(1),projectPath:G().min(1),provider:Pa,providerMode:Y([`native`,`mock`]).optional(),model:G().min(1).optional(),title:G().min(1).optional(),sessionTurnConfig:Zc.optional(),sessionTurnConfigUpdatedAt:G().datetime().optional(),createdAt:G().datetime(),updatedAt:G().datetime(),activeStartedAt:G().datetime().optional(),status:Zd,interactionLockReason:$d.optional(),pendingApprovals:K().int().nonnegative(),pendingUserInputs:K().int().nonnegative(),pendingActions:K().int().nonnegative()}),nf=q({id:G().min(1),name:G().min(1),createdAt:G().datetime(),revokedAt:G().datetime().optional(),identityAlgorithm:Y([`ed25519`]).optional(),publicKeyFingerprint:G().min(1).optional(),identityStatus:Ql.optional(),lastVerifiedAt:G().datetime().optional()}),rf=q({name:Kd,machineName:G().min(1)}),af=q({agent:q({provider:Pa,requestedVersion:G().min(1).nullable(),resolvedVersion:G().min(1)}),capabilities:Wa}),of=q({scannedAt:G().datetime(),sessionCount:K().int().nonnegative(),status:Y([`ready`,`partial`,`failed`]),error:G().min(1).optional()}),sf=q({codex:of.optional(),claude:of.optional()}),cf=q({key:G().min(1),path:G().min(1),title:G().min(1),lastSessionAt:G().datetime().optional(),sessionCount:K().int().nonnegative(),providerCounts:q({codex:K().int().nonnegative(),claude:K().int().nonnegative()}),lastDiscoveryAt:G().datetime()}),lf=q({provider:Pa,nativeSessionId:G().min(1),title:G().min(1).optional(),model:G().min(1).optional(),createdAt:G().datetime().optional(),updatedAt:G().datetime()}),uf=q({generatedAt:G().datetime(),source:Y([`cache`,`fresh_scan`]),providers:sf,projects:$n(cf)}),df=q({canonicalProjectPath:G().min(1),project:cf,providers:sf,sessions:$n(lf)}),ff=Y(`auth.refresh,codex.accounts.get,codex.accounts.save,codex.accounts.switch,codex.accounts.delete,codex.appServer.restart,gateway.settings.get,gateway.settings.update,gateway.update.get,gateway.update.check,gateway.update.apply,projects.list,projects.discovery.get,projects.discovery.refresh,projects.create,projects.delete,workspace.directories.list,workspace.directories.create,workspace.entries.list,workspace.files.resolve,workspace.files.readText,workspace.files.preparePreview,sessions.list,sessions.discovery.list,sessions.get,sessions.config.get,sessions.history.sync,sessions.rawEvents.list,sessions.readableItem.get,providers.capabilities.get,providers.execution.update,agents.config.get,devices.list,devices.revoke`.split(`,`)),pf=q({}).strict(),mf=tr(`method`,[q({method:J(`auth.refresh`),params:ou.extend({deviceId:G().min(1).optional()})}),q({method:J(`codex.accounts.get`),params:pf}),q({method:J(`codex.accounts.save`),params:pf}),q({method:J(`codex.accounts.switch`),params:q({accountId:G().min(1)})}),q({method:J(`codex.accounts.delete`),params:q({accountId:G().min(1)})}),q({method:J(`codex.appServer.restart`),params:q({requestedBy:Bd.optional()})}),q({method:J(`gateway.settings.get`),params:pf}),q({method:J(`gateway.settings.update`),params:q({name:Kd})}),q({method:J(`gateway.update.get`),params:pf}),q({method:J(`gateway.update.check`),params:q({requestedBy:Bd.optional()})}),q({method:J(`gateway.update.apply`),params:q({requestedBy:Bd.optional()})}),q({method:J(`projects.list`),params:pf}),q({method:J(`projects.discovery.get`),params:pf}),q({method:J(`projects.discovery.refresh`),params:pf}),q({method:J(`projects.create`),params:q({path:Kd,title:G().min(1).optional()})}),q({method:J(`projects.delete`),params:q({projectId:G().min(1)})}),q({method:J(`workspace.directories.list`),params:q({path:G().min(1).optional(),limit:K().int().positive().max(500).optional()})}),q({method:J(`workspace.directories.create`),params:q({path:Kd,name:Kd})}),q({method:J(`workspace.entries.list`),params:q({locator:Ya,limit:K().int().positive().max(500).optional()})}),q({method:J(`workspace.files.resolve`),params:q({locator:Ja})}),q({method:J(`workspace.files.readText`),params:q({locator:Ja,encoding:J(`utf8`).optional(),startLine:K().int().positive().optional(),maxLines:K().int().positive().max(5e3).optional(),maxBytes:K().int().positive().max(1024*1024).optional()})}),q({method:J(`workspace.files.preparePreview`),params:q({locator:Ja,disposition:io.optional()})}),q({method:J(`sessions.list`),params:q({projectId:G().min(1),status:Qd.optional(),syncExternal:Zn().optional()})}),q({method:J(`sessions.discovery.list`),params:q({projectPath:Kd})}),q({method:J(`sessions.get`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.config.get`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.history.sync`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.rawEvents.list`),params:q({projectId:G().min(1),sessionId:G().min(1),limit:er([K().int().positive().max(2e3),J(`all`)]).optional(),fromRawSeqExclusive:K().int().nonnegative().optional(),detailLevel:rl.optional()})}),q({method:J(`sessions.readableItem.get`),params:q({projectId:G().min(1),sessionId:G().min(1),itemId:G().min(1)})}),q({method:J(`providers.capabilities.get`),params:q({provider:Pa,projectId:G().min(1).optional(),agentVersion:G().min(1).optional()})}),q({method:J(`providers.execution.update`),params:Ha}),q({method:J(`agents.config.get`),params:q({provider:Pa,projectId:G().min(1).optional(),agentVersion:G().min(1).optional()})}),q({method:J(`devices.list`),params:pf}),q({method:J(`devices.revoke`),params:q({deviceId:G().min(1)})})]),hf=tr(`method`,[q({method:J(`auth.refresh`),result:su.extend({relayToken:G().min(1).optional()})}),q({method:J(`codex.accounts.get`),result:fu}),q({method:J(`codex.accounts.save`),result:pu}),q({method:J(`codex.accounts.switch`),result:mu}),q({method:J(`codex.accounts.delete`),result:hu}),q({method:J(`codex.appServer.restart`),result:gu}),q({method:J(`gateway.settings.get`),result:rf}),q({method:J(`gateway.settings.update`),result:rf}),q({method:J(`gateway.update.get`),result:Ud}),q({method:J(`gateway.update.check`),result:Ud}),q({method:J(`gateway.update.apply`),result:Gd}),q({method:J(`projects.list`),result:q({projects:$n(qd)})}),q({method:J(`projects.discovery.get`),result:uf}),q({method:J(`projects.discovery.refresh`),result:uf}),q({method:J(`projects.create`),result:q({project:qd})}),q({method:J(`projects.delete`),result:q({removed:J(!0)})}),q({method:J(`workspace.directories.list`),result:Xd}),q({method:J(`workspace.directories.create`),result:Xd}),q({method:J(`workspace.entries.list`),result:to}),q({method:J(`workspace.files.resolve`),result:no}),q({method:J(`workspace.files.readText`),result:ro}),q({method:J(`workspace.files.preparePreview`),result:ao}),q({method:J(`sessions.list`),result:q({sessions:$n(tf)})}),q({method:J(`sessions.discovery.list`),result:df}),q({method:J(`sessions.get`),result:q({session:tf})}),q({method:J(`sessions.config.get`),result:q({session:tf})}),q({method:J(`sessions.history.sync`),result:q({session:tf,rawEventCount:K().int().nonnegative(),historyUpdated:Zn(),statusChanged:Zn(),refreshMode:ef,fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional()})}),q({method:J(`sessions.rawEvents.list`),result:tr(`decision`,[q({decision:J(`delta`),reason:Y([`cursor_valid_delta`]),fromRawSeqExclusive:K().int().nonnegative(),toRawSeq:K().int().nonnegative(),events:$n(Qn())}),q({decision:J(`snapshot`),reason:Y([`cursor_out_of_range`,`initial_snapshot`,`empty_history_snapshot`]),toRawSeq:K().int().nonnegative().optional(),events:$n(Qn())})])}),q({method:J(`sessions.readableItem.get`),result:q({item:Ho})}),q({method:J(`providers.capabilities.get`),result:q({capabilities:Wa})}),q({method:J(`providers.execution.update`),result:q({defaults:Ha})}),q({method:J(`agents.config.get`),result:af}),q({method:J(`devices.list`),result:q({devices:$n(nf)})}),q({method:J(`devices.revoke`),result:q({revoked:J(!0)})})]),gf=`json-utf8`,_f=Y([gf]),vf=Y([`identity`,`gzip`]),yf=q({version:J(1),compression:J(`gzip`),payloadEncoding:_f.default(gf),uncompressedByteLength:K().int().positive(),compressedByteLength:K().int().positive(),data:qa});function bf(e){let t=Cf(e.payload),n=t.byteLength;if(n<(e.compressionThresholdBytes??1/0))return{payloadEncoding:gf,compression:`identity`,payloadBytes:t,uncompressedByteLength:n,compressedByteLength:n};let r=ni(t);return r.byteLength>=n?{payloadEncoding:gf,compression:`identity`,payloadBytes:t,uncompressedByteLength:n,compressedByteLength:n}:{payloadEncoding:gf,compression:`gzip`,payloadBytes:r,uncompressedByteLength:n,compressedByteLength:r.byteLength}}function xf(e){return e.compression===`gzip`?yf.parse({version:1,compression:`gzip`,payloadEncoding:e.payloadEncoding,uncompressedByteLength:e.uncompressedByteLength,compressedByteLength:e.compressedByteLength,data:Ef(e.payloadBytes)}):null}function Sf(e){let t=vf.parse(e.compression??`identity`),n=e.payloadBytes;if(t===`gzip`)try{n=ri(e.payloadBytes)}catch{throw Error(`compressed_payload_invalid`)}if(typeof e.expectedUncompressedByteLength==`number`&&n.byteLength!==e.expectedUncompressedByteLength)throw Error(`compressed_payload_size_mismatch`);let r;try{r=JSON.parse(Tf(n))}catch{throw Error(`compressed_payload_invalid`)}return e.parse(r)}function Cf(e){return wf(JSON.stringify(e))}function wf(e){return new TextEncoder().encode(e)}function Tf(e){return new TextDecoder().decode(e)}function Ef(e){let t=globalThis.Buffer;if(t)return t.from(e).toString(`base64`);let n=``;for(let t of e)n+=String.fromCharCode(t);if(typeof btoa!=`function`)throw Error(`base64 encoder unavailable`);return btoa(n)}var Df=G().url(),Of=er([Df,J(``)]),kf=G().min(1).regex(/^[A-Za-z0-9_-]+$/u),Af=Y([`plaintext-relay`,`e2ee-relay`]),jf=Y([`plain`,`crypt`]);function Mf(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function Nf(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=Mf(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function Pf(e){return e.trim()}var Ff=Y([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),If=K().int().positive(),Lf=K().int().min(0).max(2**53-1),Rf=Y([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`counter_gap_too_large`,`key_epoch_mismatch`,`decrypt_failed`,`unsupported_version`]),zf=Y([`guest`,`account`,`self_hosted`]);q({type:J(`relay.gateway`),grantType:zf,gatewayId:G().min(1),subjectId:G().min(1),gatewayIdentityFingerprint:G().min(1).optional(),jti:G().min(1),iss:G().min(1),aud:G().min(1),iat:K().int().nonnegative(),exp:K().int().positive()}),q({type:J(`relay.mobile`),gatewayId:G().min(1),deviceId:G().min(1),iat:K().int().nonnegative(),exp:K().int().positive()});var Bf=q({v:J(1),gw:G().min(1),name:G().min(1),machineName:G().min(1).optional(),relay:Of.optional(),direct:$n(Df).default([]),pc:G().min(1),tsl:jf.optional(),gatewayIdentity:Xl.optional()});rr(Nf,Bf);var Vf=rr(Nf,Bf.omit({pc:!0}));rr(Nf,q({v:J(1),gw:G().min(1),relay:Of.optional(),direct:Of.optional(),pc:G().min(1),tsl:jf.optional(),gatewayIdentity:Xl.optional()}));var Hf=rr(Nf,q({v:J(1),gw:G().min(1),relay:Of.optional(),direct:Df,pc:G().min(1),pkf:kf,tsl:jf.optional()})),Uf=q({name:G().min(1),relayBaseUrl:Of.optional(),directBaseUrls:$n(Df).default([]),transportSecurityLevel:Af.default(`e2ee-relay`),gatewayIdentity:Xl.optional(),gatewayAccessToken:G().min(1).optional(),connectedAt:G().datetime().optional()}),Wf=q({gatewayId:G().min(1),deviceId:G().min(1),connectedAt:G().datetime().optional()}),Gf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Ff,deviceId:G().min(1),deviceIdentity:$l,clientNonce:qa}),Kf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Ff,gatewayId:G().min(1),deviceId:G().min(1),clientNonce:qa,gatewayNonce:qa,gatewayPublicKeyFingerprint:G().min(1),gatewayEphemeralPublicKey:qa,signatureAlgorithm:J(`ed25519`),signature:qa}),qf=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1),deviceIdentityFingerprint:G().min(1),clientEphemeralPublicKey:qa,signatureAlgorithm:J(`ed25519`),signature:qa}),Jf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Ff,gatewayId:G().min(1),deviceId:G().min(1),keyEpoch:If,deviceIdentityFingerprint:G().min(1),deviceIdentityStatus:Ql}),Yf=Y([`gateway_restarted`,`gateway_available`]),Xf=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1),reason:Yf,retryable:J(!0)}),Zf=q({ticket:G().min(1),method:Y([`GET`,`HEAD`]),rangeHeader:G().min(1).optional(),responseMode:Y([`inline_base64`,`stream_upload`]).optional(),uploadUrl:G().url().optional(),uploadToken:G().min(1).optional()}).superRefine((e,t)=>{e.responseMode===`stream_upload`&&(e.uploadUrl||t.addIssue({code:U.custom,path:[`uploadUrl`],message:`uploadUrl is required when responseMode is stream_upload`}),e.uploadToken||t.addIssue({code:U.custom,path:[`uploadToken`],message:`uploadToken is required when responseMode is stream_upload`}))}),Qf=q({status:er([J(200),J(206),J(416)]),headers:q({contentType:G().min(1),contentDisposition:G().min(1),contentLength:K().int().nonnegative(),etag:G().min(1),acceptRanges:J(`bytes`).optional(),contentRange:G().min(1).optional(),lastModified:G().min(1).optional(),cacheControl:G().min(1)}),bodyTransport:Y([`inline_base64`,`stream_upload`]).optional(),bodyBase64:qa.optional()}),$f=q({}),ep=Qf,tp=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1).optional(),code:Rf,message:G().min(1),retryable:Zn().optional()}),np=mf,rp=hf,ip=q({code:Y([`BAD_REQUEST`,`NOT_FOUND`,`UNAUTHORIZED`,`TIMEOUT`,`INTERNAL`,`GATEWAY_OFFLINE`,`TOKEN_INVALID`,`TOKEN_EXPIRED`,`GATEWAY_MISMATCH`,`GATEWAY_REVOKED`]),message:G().min(1),status:K().int().min(400).max(599),details:Qn().optional()}),ap=ip.extend({method:ff.optional()}),op=ru.extend({gatewayId:G().min(1)}),sp=au.extend({relayToken:G().min(1).optional()}),cp=ou.extend({gatewayId:G().min(1),deviceId:G().min(1).optional()}),lp=su.extend({gatewayId:G().min(1),relayToken:G().min(1).optional()}),up=q({gatewayId:G().min(1),gatewayIdentity:Xl,requestedAt:G().datetime()});q({grantType:J(`guest`),payload:up,signatureAlgorithm:J(`ed25519`),signature:qa});var dp=q({grantType:zf,token:G().min(1),expiresInSeconds:K().int().positive()}),fp=Y([`rpc`,`command`,`event`,`system`]),pp=gf,mp=_f,hp=q({version:J(1),keyEpoch:If,counter:Lf,iv:qa,ciphertext:qa,authTag:qa,plaintextEncoding:mp.default(pp),compression:vf.default(`identity`),uncompressedByteLength:K().int().positive().optional(),compressedByteLength:K().int().positive().optional()});Y([`from_mobile`,`to_mobile`,`rpc.request`,`rpc.response`,`rpc.error`]);function gp(e){return{payload:e.optional(),encryptedPayload:hp.optional()}}function _p(e){return{payload:e.optional(),compressedPayload:yf.optional(),encryptedPayload:hp.optional()}}var vp=q({gatewayId:G().min(1),mobileId:G().min(1).optional(),messageType:fp,requestId:G().min(1).optional()}),yp=Y([`fresh_connect`,`gateway_replay`]),bp=q({deviceId:G().min(1),deliveryMode:yp,gatewayAvailableAtConnect:Zn()}),xp=q({deviceId:G().min(1)}),Sp=er([Yl,Wd,q({type:J(`command.ack`),commandType:G().min(1),commandId:G().min(1).optional(),payload:Qn().optional()}),q({type:J(`command.error`),commandType:G().min(1).optional(),commandId:G().min(1).optional(),message:G().min(1)}),q({type:J(`relay.error`),error:ip})]),Cp=tr(`type`,[vp.extend({type:J(`gateway.hello`),messageType:J(`system`),payload:Uf}),vp.extend({type:J(`mobile.hello`),messageType:J(`system`),payload:Wf}),vp.extend({type:J(`secure.client_hello`),messageType:J(`system`),payload:Gf}),vp.extend({type:J(`secure.gateway_hello`),mobileId:G().min(1),messageType:J(`system`),payload:Kf}),vp.extend({type:J(`secure.client_auth`),messageType:J(`system`),payload:qf}),vp.extend({type:J(`secure.ready`),mobileId:G().min(1),messageType:J(`system`),payload:Jf}),vp.extend({type:J(`secure.handshake_required`),mobileId:G().min(1),messageType:J(`system`),payload:Xf}),vp.extend({type:J(`secure.error`),mobileId:G().min(1),messageType:J(`system`),payload:tp}),vp.extend({type:J(`mobile.connected`),messageType:J(`system`),payload:bp}),vp.extend({type:J(`mobile.disconnected`),messageType:J(`system`),payload:xp}),vp.extend({type:J(`from_mobile`),messageType:J(`command`),mobileId:G().min(1),...gp(gl)}),vp.extend({type:J(`to_mobile`),messageType:J(`event`),mobileId:G().min(1),..._p(Sp)}),vp.extend({type:J(`rpc.request`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),...gp(np)}),vp.extend({type:J(`rpc.response`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),..._p(rp)}),vp.extend({type:J(`rpc.error`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),..._p(ap)}),vp.extend({type:J(`broadcast`),messageType:J(`event`),payload:Yl}),vp.extend({type:J(`pairing.claim.forward`),messageType:J(`system`),requestId:G().min(1),payload:op}),vp.extend({type:J(`pairing.claim.result`),messageType:J(`system`),requestId:G().min(1),payload:sp}),vp.extend({type:J(`auth.refresh.forward`),messageType:J(`system`),requestId:G().min(1),payload:cp}),vp.extend({type:J(`auth.refresh.result`),messageType:J(`system`),requestId:G().min(1),payload:lp}),vp.extend({type:J(`file.content.forward`),messageType:J(`system`),requestId:G().min(1),payload:Zf}),vp.extend({type:J(`file.content.result`),messageType:J(`system`),requestId:G().min(1),payload:Qf}),vp.extend({type:J(`file.content.upload.started`),messageType:J(`system`),requestId:G().min(1),payload:$f}),vp.extend({type:J(`relay.error`),messageType:J(`system`),payload:ip})]);function wp(e){return JSON.stringify([`relay-gateway-guest-token-v1`,e.gatewayId,e.gatewayIdentity.algorithm,e.gatewayIdentity.publicKey,e.gatewayIdentity.publicKeyFingerprint,e.gatewayIdentity.keyVersion,e.gatewayIdentity.createdAt,e.requestedAt])}function Tp(e){return JSON.stringify([e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey])}function Ep(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,Tp(e)])}function Dp(e){return JSON.stringify([`relay-secure-client-auth-v1`,Tp(e),e.clientAuth.clientEphemeralPublicKey])}function Op(e){let t=If.parse(e.keyEpoch??1);return JSON.stringify([`relay-secure-session-v1`,e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey,e.clientAuth.clientEphemeralPublicKey,t])}function kp(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=If.parse(e.keyEpoch??1),r=Vp(Wp(Op({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=Vp(Up(Wp(`relay-secure-hkdf-salt-v1`),r)),a=Wp(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=Bp(e.sharedSecret,i,a,72);return{keyEpoch:n,cipherSuite:t,transcriptHash:r,clientToGatewayKey:o.slice(0,32),gatewayToClientKey:o.slice(32,64),clientToGatewayNoncePrefix:o.slice(64,68),gatewayToClientNoncePrefix:o.slice(68,72)}}function Ap(e){return e.role===`client`?{role:`client`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.clientToGatewayKey,inboundKey:e.keySchedule.gatewayToClientKey,outboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,inboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,outboundCounter:0,highestInboundCounter:null}:{role:`gateway`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.gatewayToClientKey,inboundKey:e.keySchedule.clientToGatewayKey,outboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,inboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,outboundCounter:0,highestInboundCounter:null}}function jp(e,t){let n=Lf.parse(t);if(e.length!==4)throw Error(`nonce prefix must be 4 bytes`);let r=new Uint8Array(12);return r.set(e,0),r.set(Kp(n),4),r}function Mp(e,t){let n=Lf.parse(t);if(e===null)return;let r=Lf.parse(e);if(n<=r)throw Error(`counter_replay`);if(n-r>1e3)throw Error(`counter_gap_too_large`)}function Np(e){return JSON.stringify([`relay-secure-business-payload-v1`,e.metadata.frameType,e.metadata.messageType,e.metadata.gatewayId,e.metadata.requestId??``,e.encryptedPayload.version,e.encryptedPayload.keyEpoch,e.encryptedPayload.counter])}function Pp(e){Hp(e.session.cipherSuite);let t=e.session.outboundCounter,n=jp(e.session.outboundNoncePrefix,t),r=e.preparedPayload.payloadBytes,i=Wp(Np({metadata:e.metadata,encryptedPayload:{version:1,keyEpoch:e.session.keyEpoch,counter:t}})),a=qi(e.session.outboundKey,n,i).encrypt(r),o=a.subarray(0,a.length-16),s=a.subarray(a.length-16);return e.session.outboundCounter=t+1,hp.parse({version:1,keyEpoch:e.session.keyEpoch,counter:t,iv:Ip(n),ciphertext:Ip(o),authTag:Ip(s),plaintextEncoding:pp,compression:e.preparedPayload.compression,...e.preparedPayload.compression===`gzip`?{uncompressedByteLength:e.preparedPayload.uncompressedByteLength,compressedByteLength:e.preparedPayload.compressedByteLength}:{}})}function Fp(e){Hp(e.session.cipherSuite);let t=hp.parse(e.encryptedPayload);if(t.keyEpoch!==e.session.keyEpoch)throw Error(`key_epoch_mismatch`);Mp(e.session.highestInboundCounter,t.counter);let n=jp(e.session.inboundNoncePrefix,t.counter),r=Lp(t.iv);if(!Gp(r,n))throw Error(`decrypt_failed`);let i=Wp(Np({metadata:e.metadata,encryptedPayload:t})),a=Up(Lp(t.ciphertext),Lp(t.authTag)),o;try{o=qi(e.session.inboundKey,r,i).decrypt(a)}catch{throw Error(`decrypt_failed`)}e.session.highestInboundCounter=t.counter;try{return Sf({payloadBytes:o,compression:t.compression,expectedUncompressedByteLength:t.uncompressedByteLength,parse:e.parse})}catch{throw Error(`decrypt_failed`)}}function Ip(e){let t=globalThis.Buffer;if(t)return t.from(e).toString(`base64`);let n=``;for(let t of e)n+=String.fromCharCode(t);if(typeof btoa!=`function`)throw Error(`base64 encoder unavailable`);return btoa(n)}function Lp(e){let t=globalThis.Buffer;if(t)return new Uint8Array(t.from(e,`base64`));if(typeof atob!=`function`)throw Error(`base64 decoder unavailable`);let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}function Rp(e){return Ip(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function zp(e){return Lp(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function Bp(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(ya(Na,e,t.length>0?t:new Uint8Array(32),n,r))}function Vp(e){return new Uint8Array(Na(e))}function Hp(e){if(e!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${e}`)}function Up(...e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Wp(e){return new TextEncoder().encode(e)}function Gp(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Kp(e){if(!Number.isSafeInteger(e))throw Error(`counter must be a safe integer`);let t=Math.floor(e/4294967296),n=e>>>0,r=new Uint8Array(8),i=new DataView(r.buffer);return i.setUint32(0,t),i.setUint32(4,n),r}function qp(e){return Rp(Na(Lp(e)).subarray(0,16))}function Jp(e){if(e.type!==`native.raw`)return null;let t=em(e.payload.raw),n=em(t.message),r=em(n.params),i=em(r.msg),a=tm(n.method)??tm(t.method);if(!a)return null;let o=tm(i.type)??``;if(!Qp(a)&&!$p(o))return null;let s=Zp(t);if(!s||!s.delta)return null;let c=tm(r.conversationId)??tm(r.conversation_id)??``,l=tm(i.thread_id)??tm(i.threadId)??tm(r.threadId)??tm(r.thread_id)??``,u=tm(i.turn_id)??tm(i.turnId)??tm(r.turnId)??tm(r.turn_id)??``,d=tm(i.item_id)??tm(i.itemId)??tm(r.itemId)??tm(r.item_id)??``,f=tm(t.source)??``,p=nm(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=nm(i.contentIndex??i.content_index??r.contentIndex??r.content_index);return{key:[e.sessionId,f,a,c,l,u,d,o,p,m].join(`|`),delta:s.delta,method:a}}function Yp(e,t){let n=Jp(e),r=Jp(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=em(t.payload.raw),o=Zp(a)?.location??Zp(em(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Xp(a,o,i)}}:null}function Xp(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=em(e.message),i=em(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=em(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Zp(e){let t=em(em(e.message).params),n=em(t.msg);return typeof n.delta==`string`?{delta:n.delta,location:`msg.delta`}:typeof t.delta==`string`?{delta:t.delta,location:`params.delta`}:typeof e.delta==`string`?{delta:e.delta,location:`raw.delta`}:null}function Qp(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function $p(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function em(e){return typeof e==`object`&&e?e:{}}function tm(e){return typeof e==`string`&&e.trim()||void 0}function nm(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():tm(e)??``}var rm=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]),im=/\u001B\[[0-?]*[ -/]*[@-~]/g,am={"thread.started":0,"thread.title.updated":1,"turn.started":2,"item.started":3,"item.updated":4,"item.completed":5,"turn.completed":6,"turn.failed":6,"tool.permission.requested":7,"user.input.requested":7};function om(e,t){let n=[],r=0,i=[...t].filter(t=>t.sessionId===e).sort((e,t)=>e.ts.localeCompare(t.ts)),a=[],o=()=>(r+=1,`raw_proj_item_${e}_${r}`);for(let e of i){let t=Wl.safeParse(e.type);if(t.success){n.push(dm(e,t.data,bm(e.payload.raw),e.eventId));continue}if(e.type!==`native.raw`)continue;let r=bm(e.payload.raw),i=cm(e,r);if(i.length>0&&n.push(...i),r.historyReplay!==!0)continue;let o=X(r.source);if(o?.startsWith(`codex.history.thread_read`)){n.push(...lm(e,r));continue}o&&rm.has(o)&&a.push(e)}a.length>0&&n.push(...um(a,o));let s=new Map,c=new Map;for(let e of n){let t=hm(e);if(!t){s.set(e.eventId,e);continue}let n=gm(e.payload.raw),r=c.get(t);(!r||n>r.richness)&&c.set(t,{event:e,richness:n})}for(let{event:e}of c.values())s.set(e.eventId,e);return[...s.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);if(n!==0)return n;let r=Vm(e.type)-Vm(t.type);return r===0?e.eventId.localeCompare(t.eventId):r})}function sm(e,t,n){return wu(e,om(e,t),n)}function cm(e,t){if(e.type!==`native.raw`||X(t.source)!==`codex.app_server`)return[];let n=bm(t.message),r=bm(n.params),i=X(n.method)??X(t.method);if(!i)return[];if(i===`turn/started`||i===`turn/completed`||i===`turn/failed`||i===`turn/interrupted`){let t=pm(bm(r.turn),r);if(Object.keys(t).length===0)return[];let n=i===`turn/started`?`turn.started`:i===`turn/failed`?`turn.failed`:`turn.completed`,a=X(t.status)??(i===`turn/completed`?`completed`:i===`turn/interrupted`?`interrupted`:`failed`),o=bm(t.error);return[dm(e,n,{turn:t,status:a,turn_id:X(t.id),source_event_type:`codex.app_server`,...n===`turn.failed`?{error:o}:{}},`${e.eventId}:${n.replace(`.`,`_`)}`)]}if(i===`item/started`||i===`item/completed`){let t=fm(bm(r.item));if(Object.keys(t).length===0)return[];let n=X(r.turn_id)??X(r.turnId)??X(bm(r.turn).id)??X(t.turn_id)??X(t.turnId);return[dm(e,i===`item/started`?`item.started`:`item.completed`,{turn_id:n,item:t,source_event_type:`codex.app_server`},`${e.eventId}:${i===`item/started`?`item_started`:`item_completed`}`)]}return[]}function lm(e,t){let n=[],r=bm(t.message),i=X(r.scope);if(i===`thread`){let t=bm(r.thread),i=X(t.id);n.push(dm(e,`thread.started`,{thread_id:i,thread:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:thread_started`));let a=Sm(X(t.preview));return a&&n.push(dm(e,`thread.title.updated`,{title:a,source:`codex.history.thread_read`,thread_id:i},`${e.eventId}:thread_title_updated`)),n}if(i===`turn`){let t=bm(r.turn),i=X(t.status);return n.push(dm(e,`turn.started`,{turn:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_started`)),i===`completed`||i===`interrupted`?n.push(dm(e,`turn.completed`,{status:i,turn:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_completed`)):i===`failed`&&n.push(dm(e,`turn.failed`,{status:i,turn:t,error:bm(t.error),source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_failed`)),n}if(i===`item`){let t=fm(bm(r.item)),i=X(r.turn_id)??X(r.turnId)??X(t.turn_id);n.push(dm(e,`item.completed`,{turn_id:i,item:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:item_completed`))}return n}function um(e,t){let n=[],r=e[0];if(!r)return n;let i=bm(r.payload.raw),a=bm(i.message),o=X(i.native_session_id)??X(a.session_id)??r.sessionId,s=new Map,c=!1,l=0,u;n.push(dm(r,`thread.started`,{thread_id:o,source:`claude.history.getSessionMessages`},`${r.eventId}:thread_started`));let d=(e,t,r)=>u||(l+=1,u={id:`claude_hist_turn_${l}`,terminal:!1},n.push(dm(e,`turn.started`,{turn_id:u.id,source_event_type:t,source_line:r},`${e.eventId}:turn_started:${u.id}`)),u),f=(e,t,r)=>{if(!u||u.terminal){u=void 0;return}u.terminal=!0,n.push(dm(e,`turn.completed`,{turn_id:u.id,source_event_type:t,source_line:r},`${e.eventId}:turn_completed:${u.id}`)),u=void 0},p=(e,t,r,i)=>{let a=d(e,t,r);a.terminal||(a.terminal=!0,n.push(dm(e,`turn.failed`,{turn_id:a.id,source_event_type:t,source_line:r,error:{message:i}},`${e.eventId}:turn_failed:${a.id}`)),u=void 0)};for(let r of e){let e=bm(r.payload.raw),i=bm(e.message),a=X(e.native_type)??X(i.type),l=bm(i.message),u=X(e.source)??`claude.history.getSessionMessages`,m=Bm(e.source_line);if(a===`user`){let e=Cm(l),a=wm(l),p=Em(l);if(e||a.length>0){if(e&&!c){let t=Sm(e);t&&(n.push(dm(r,`thread.title.updated`,{title:t,source:`claude.history.first_user_message`,thread_id:o},`${r.eventId}:thread_title_updated`)),c=!0)}f(r,u,m);let s=d(r,u,m);n.push(dm(r,`item.completed`,{item:{id:X(i.uuid)??t(),type:`user_message`,...e?{text:e}:{},...a.length>0?{attachments:a}:{},turn_id:s.id,source_event_type:u},source_line:m},`${r.eventId}:item_completed_user`))}p.forEach((e,i)=>{let a=e.toolUseId?s.get(e.toolUseId):void 0;if(e.toolUseId&&s.delete(e.toolUseId),a?.skipReplay)return;let o=d(r,u,m);n.push(dm(r,`item.completed`,{item:km(a,e,o.id,t),source_line:m},`${r.eventId}:item_completed_tool_result_${i+1}`))});continue}if(a!==`assistant`)continue;let h=d(r,u,m);Tm(l).forEach((e,i)=>{e.id&&s.set(e.id,e),!e.skipReplay&&n.push(dm(r,`item.started`,{item:{id:e.id??t(),type:`tool_status`,status:`running`,tool_name:e.name,title:e.title,text:e.title,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,file_path:e.filePath,turn_id:h.id,source_event_type:u},source_line:m},`${r.eventId}:item_started_tool_use_${i+1}`))});let g=Cm(l);g&&n.push(dm(r,`item.completed`,{item:{id:X(l.id)??X(i.uuid)??t(),type:`agent_message`,text:g,turn_id:h.id,source_event_type:u},source_line:m},`${r.eventId}:item_completed_assistant`));let _=zm(X(i.error));_&&p(r,u,m,_)}let m=e[e.length-1];if(m){let e=bm(m.payload.raw);f(m,X(e.source)??`claude.history.getSessionMessages`,Bm(e.source_line))}return n}function dm(e,t,n,r){return{v:e.v,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:r,ts:e.ts,type:t,payload:{raw:n}}}function fm(e){let t=_m(e),n=X(e.type);return n&&(t.type=mm(n)),t}function pm(e,t){let n=_m(e),r=X(e.id)??X(t.turn_id)??X(t.turnId);return r&&(n.id=r),n}function mm(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`webSearch`:return`web_search`;case`mcpToolCall`:return`mcp_tool_call`;case`todoList`:return`todo_list`;case`contextCompaction`:return`context_compaction`;default:return ym(e)}}function hm(e){if(e.type!==`item.started`&&e.type!==`item.completed`)return;let t=bm(e.payload.raw),n=bm(t.item),r=X(n.id)??X(n.item_id)??X(n.itemId);if(!r)return;let i=X(t.turn_id)??X(t.turnId)??X(n.turn_id)??X(n.turnId)??``;return[e.type,e.sessionId,i,r].join(`|`)}function gm(e){return Array.isArray(e)?e.reduce((e,t)=>e+gm(t),0):e&&typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>e+t.length+gm(n),1):typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?1:0}function _m(e){let t={};for(let[n,r]of Object.entries(e))t[ym(n)]=vm(r);return t}function vm(e){return Array.isArray(e)?e.map(e=>vm(e)):typeof e==`object`&&e?_m(e):e}function ym(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toLowerCase()}function bm(e){return typeof e==`object`&&e?e:{}}function X(e){return typeof e==`string`&&e.trim()||void 0}function xm(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function Sm(e,t=60){if(!e)return;let n=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 Cm(e){let t=X(e.content);if(t)return zm(t);let n=X(e.text)??X(e.prompt);if(n)return zm(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=bm(e),n=X(t.type);if(n&&n!==`text`)continue;let r=X(t.text)??X(t.content)??Rm(t);r&&i.push(r)}if(i.length!==0)return zm(i.join(`
|
|
139
139
|
`))}function wm(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=bm(e);if(X(t.type)!==`image`)continue;let r=bm(t.remote_agent_attachment);if(Object.keys(r).length>0){n.push(r);continue}let i=bm(t.source),a=X(i.path),o=X(i.media_type)??X(i.mediaType);n.push({id:X(t.id)??a??`claude_image_${n.length+1}`,kind:`image`,...o?{mimeType:o}:{},...a?{locator:{kind:`absolute`,path:a}}:{}})}return n}function Tm(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=bm(e);if(X(t.type)!==`tool_use`)continue;let r=bm(t.input),i=X(t.name)??`tool`;n.push({id:X(t.id),name:i,...Dm(i,r)})}return n}function Em(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=bm(e);X(t.type)===`tool_result`&&n.push({toolUseId:X(t.tool_use_id)??X(t.toolUseId),toolName:X(t.tool_name)??X(t.toolName),text:Nm(t),isError:t.is_error===!0})}return n}function Dm(e,t){if(e===`Task`){let e=X(t.subagent_type),n=X(t.description)??e??`任务`;return{title:`${e??`Task`}(${n})`,pendingStatusLabel:`运行中`,responseLabel:`Response`,prompt:X(t.prompt)}}if(e===`Read`)return{title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:X(t.file_path)};if(e===`Write`){let e=X(t.file_path);return{title:Pm(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e,writeContent:xm(t,[`content`])}}if(e===`Edit`){let e=X(t.file_path);return{title:e?`Update(${e})`:`Edit`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e,skipReplay:!0}}return{title:e,pendingStatusLabel:`运行中`,responseLabel:`Response`,prompt:Om(t),filePath:X(t.file_path)}}function Om(e){let t=X(e.command);if(t)return t;let n=X(e.prompt);if(n)return n;let r=X(e.query);if(r)return r;let i=X(e.pattern),a=X(e.glob);return i&&a?`pattern: ${i}
|
|
140
140
|
glob: ${a}`:i||zm(X(e.description))}function km(e,t,n,r){let i=e?.name??t.toolName??`tool`,a=e?.name===`Write`?e.writeContent:t.text,o=jm(i,a),s=o!==void 0,c=Am(e,t,a,s);return{id:t.toolUseId??r(),type:`tool_status`,turn_id:n,tool_name:i,title:e?.title??i,text:c,status:t.isError&&!s?`failed`:`completed`,status_label:c,display_as:`tool_card`,response:a,response_label:e?.responseLabel??`Response`,prompt:e?.prompt,file_path:e?.filePath,...o===void 0?{}:{exit_code:o},source_event_type:`claude.history.tool_result`}}function Am(e,t,n,r=!1){return t.isError&&!r?`Failed`:e?.name===`Write`?Fm(Lm(n),e.filePath):`Done`}function jm(e,t){if(!(!Mm(e)||!t))return vo(t)}function Mm(e){let t=e.trim().toLowerCase();return t===`bash`||t===`shell`}function Nm(e){let t=zm(X(e.content)??X(bm(e.toolUseResult).stdout)??X(bm(e.tool_use_result).stdout)??X(e.text));if(t)return t;let n=Array.isArray(e.content)?e.content:[];if(n.length===0)return;let r=[];for(let e of n){if(typeof e==`string`&&e.trim().length>0){r.push(e.trim());continue}let t=bm(e),n=zm(X(t.text)??X(t.content)??X(t.value)??X(t.tool_name)??X(t.toolName));n&&r.push(n)}if(r.length!==0)return r.join(`
|
|
141
141
|
`)}function Pm(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${Im(e)})`:`Write`}function Fm(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function Im(e){let t=e.split(`/`);return t[t.length-1]||e}function Lm(e){if(e)return e.split(`
|
|
@@ -144,7 +144,7 @@ glob: ${a}`:i||zm(X(e.description))}function km(e,t,n,r){let i=e?.name??t.toolNa
|
|
|
144
144
|
`)}const ng={readInstalledPackageVersion:ig,readSystemToolVersion:ag};function rg(e,t){let n=e.minimumVersion,r=e.dependencyName?t.readInstalledPackageVersion(e.dependencyName):null,i=t.readSystemToolVersion(e.systemCommand,e.versionArgs),a=e.dependencyName?`ok`:null,o=`ok`,s=[];return e.dependencyName&&(r?n&&!P(r,n)&&(a=`fail`,s.push(`Bundled dependency ${r} is below required ${n}.`)):(a=`fail`,s.push(`Bundled dependency ${e.dependencyName} could not be resolved.`))),i?n&&!P(i,n)&&(o=e.systemCommandRequired?`fail`:`warn`,s.push(`System ${e.displayName} version ${i} is below required ${n}.`)):(o=e.systemCommandRequired?`fail`:`warn`,s.push(`System command \`${e.systemCommand}\` is not available.`)),{id:e.id,displayName:e.displayName,dependencyName:e.dependencyName,dependencyRange:e.dependencyRange,minimumVersion:n,bundledDependencyVersion:r,systemCommand:e.systemCommand,systemToolVersion:i,bundledStatus:a,systemStatus:o,notes:s}}function ig(e){try{let t=sg(e);if(!t)return null;let n=u.default.readFileSync(t,`utf8`),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}function ag(e,t){try{let n=(0,h.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0});if(n.error)return null;let r=`${n.stdout??``}\n${n.stderr??``}`.trim();return r?j(r):null}catch{return null}}function og(e){return e??`missing`}function sg(e){try{return Zh.resolve(`${e}/package.json`)}catch{}try{let t=Zh.resolve(e),n=u.default.statSync(t).isDirectory()?t:u.default.realpathSync(p.default.dirname(t));for(;;){let t=p.default.join(n,`package.json`);if(u.default.existsSync(t)){let n=u.default.readFileSync(t,`utf8`);if(JSON.parse(n).name===e)return t}let r=p.default.dirname(n);if(r===n)return null;n=r}}catch{}for(let t of[p.default.dirname(Qh),process.cwd()]){let n=cg(t,e);if(n)return n}return null}function cg(e,t){let n=e,r=t.split(`/`);for(;;){let e=p.default.join(n,`node_modules`,...r,`package.json`);if(u.default.existsSync(e))return e;let t=p.default.dirname(n);if(t===n)return null;n=t}}function lg(e,t){let n=[e];return t.configPath&&n.push(`--config`,t.configPath),t.logToConsole&&n.push(`--log`),n}function ug(e,t,n){let r=lg(t,n);return e.scriptPath?{command:e.execPath,args:[...e.execArgv,e.scriptPath,...r],cwd:e.cwd}:{command:e.execPath,args:r,cwd:e.cwd}}function dg(e,t,n,r){if(!e.binPath)throw Error(`gateway launch command is unavailable`);return{command:e.binPath,args:lg(t,n),cwd:r}}var fg=o(((e,t)=>{t.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}})),pg=o(((e,t)=>{var n=fg();function r(e){this.mode=n.MODE_8BIT_BYTE,this.data=e}r.prototype={getLength:function(){return this.data.length},write:function(e){for(var t=0;t<this.data.length;t++)e.put(this.data.charCodeAt(t),8)}},t.exports=r})),mg=o(((e,t)=>{for(var n={glog:function(e){if(e<1)throw Error(`glog(`+e+`)`);return n.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return n.EXP_TABLE[e]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)},r=0;r<8;r++)n.EXP_TABLE[r]=1<<r;for(var r=8;r<256;r++)n.EXP_TABLE[r]=n.EXP_TABLE[r-4]^n.EXP_TABLE[r-5]^n.EXP_TABLE[r-6]^n.EXP_TABLE[r-8];for(var r=0;r<255;r++)n.LOG_TABLE[n.EXP_TABLE[r]]=r;t.exports=n})),hg=o(((e,t)=>{var n=mg();function r(e,t){if(e.length===void 0)throw Error(e.length+`/`+t);for(var n=0;n<e.length&&e[n]===0;)n++;this.num=Array(e.length-n+t);for(var r=0;r<e.length-n;r++)this.num[r]=e[r+n]}r.prototype={get:function(e){return this.num[e]},getLength:function(){return this.num.length},multiply:function(e){for(var t=Array(this.getLength()+e.getLength()-1),i=0;i<this.getLength();i++)for(var a=0;a<e.getLength();a++)t[i+a]^=n.gexp(n.glog(this.get(i))+n.glog(e.get(a)));return new r(t,0)},mod:function(e){if(this.getLength()-e.getLength()<0)return this;for(var t=n.glog(this.get(0))-n.glog(e.get(0)),i=Array(this.getLength()),a=0;a<this.getLength();a++)i[a]=this.get(a);for(var o=0;o<e.getLength();o++)i[o]^=n.gexp(n.glog(e.get(o))+t);return new r(i,0).mod(e)}},t.exports=r})),gg=o(((e,t)=>{t.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}})),_g=o(((e,t)=>{var n=fg(),r=hg(),i=mg(),a=gg(),o={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(e){for(var t=e<<10;o.getBCHDigit(t)-o.getBCHDigit(o.G15)>=0;)t^=o.G15<<o.getBCHDigit(t)-o.getBCHDigit(o.G15);return(e<<10|t)^o.G15_MASK},getBCHTypeNumber:function(e){for(var t=e<<12;o.getBCHDigit(t)-o.getBCHDigit(o.G18)>=0;)t^=o.G18<<o.getBCHDigit(t)-o.getBCHDigit(o.G18);return e<<12|t},getBCHDigit:function(e){for(var t=0;e!==0;)t++,e>>>=1;return t},getPatternPosition:function(e){return o.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case a.PATTERN000:return(t+n)%2==0;case a.PATTERN001:return t%2==0;case a.PATTERN010:return n%3==0;case a.PATTERN011:return(t+n)%3==0;case a.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case a.PATTERN101:return t*n%2+t*n%3==0;case a.PATTERN110:return(t*n%2+t*n%3)%2==0;case a.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw Error(`bad maskPattern:`+e)}},getErrorCorrectPolynomial:function(e){for(var t=new r([1],0),n=0;n<e;n++)t=t.multiply(new r([1,i.gexp(n)],0));return t},getLengthInBits:function(e,t){if(1<=t&&t<10)switch(e){case n.MODE_NUMBER:return 10;case n.MODE_ALPHA_NUM:return 9;case n.MODE_8BIT_BYTE:return 8;case n.MODE_KANJI:return 8;default:throw Error(`mode:`+e)}else if(t<27)switch(e){case n.MODE_NUMBER:return 12;case n.MODE_ALPHA_NUM:return 11;case n.MODE_8BIT_BYTE:return 16;case n.MODE_KANJI:return 10;default:throw Error(`mode:`+e)}else if(t<41)switch(e){case n.MODE_NUMBER:return 14;case n.MODE_ALPHA_NUM:return 13;case n.MODE_8BIT_BYTE:return 16;case n.MODE_KANJI:return 12;default:throw Error(`mode:`+e)}else throw Error(`type:`+t)},getLostPoint:function(e){var t=e.getModuleCount(),n=0,r=0,i=0;for(r=0;r<t;r++)for(i=0;i<t;i++){for(var a=0,o=e.isDark(r,i),s=-1;s<=1;s++)if(!(r+s<0||t<=r+s))for(var c=-1;c<=1;c++)i+c<0||t<=i+c||s===0&&c===0||o===e.isDark(r+s,i+c)&&a++;a>5&&(n+=3+a-5)}for(r=0;r<t-1;r++)for(i=0;i<t-1;i++){var l=0;e.isDark(r,i)&&l++,e.isDark(r+1,i)&&l++,e.isDark(r,i+1)&&l++,e.isDark(r+1,i+1)&&l++,(l===0||l===4)&&(n+=3)}for(r=0;r<t;r++)for(i=0;i<t-6;i++)e.isDark(r,i)&&!e.isDark(r,i+1)&&e.isDark(r,i+2)&&e.isDark(r,i+3)&&e.isDark(r,i+4)&&!e.isDark(r,i+5)&&e.isDark(r,i+6)&&(n+=40);for(i=0;i<t;i++)for(r=0;r<t-6;r++)e.isDark(r,i)&&!e.isDark(r+1,i)&&e.isDark(r+2,i)&&e.isDark(r+3,i)&&e.isDark(r+4,i)&&!e.isDark(r+5,i)&&e.isDark(r+6,i)&&(n+=40);var u=0;for(i=0;i<t;i++)for(r=0;r<t;r++)e.isDark(r,i)&&u++;var d=Math.abs(100*u/t/t-50)/5;return n+=d*10,n}};t.exports=o})),vg=o(((e,t)=>{t.exports={L:1,M:0,Q:3,H:2}})),yg=o(((e,t)=>{var n=vg();function r(e,t){this.totalCount=e,this.dataCount=t}r.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],r.getRSBlocks=function(e,t){var n=r.getRsBlockTable(e,t);if(n===void 0)throw Error(`bad rs block @ typeNumber:`+e+`/errorCorrectLevel:`+t);for(var i=n.length/3,a=[],o=0;o<i;o++)for(var s=n[o*3+0],c=n[o*3+1],l=n[o*3+2],u=0;u<s;u++)a.push(new r(c,l));return a},r.getRsBlockTable=function(e,t){switch(t){case n.L:return r.RS_BLOCK_TABLE[(e-1)*4+0];case n.M:return r.RS_BLOCK_TABLE[(e-1)*4+1];case n.Q:return r.RS_BLOCK_TABLE[(e-1)*4+2];case n.H:return r.RS_BLOCK_TABLE[(e-1)*4+3];default:return}},t.exports=r})),bg=o(((e,t)=>{function n(){this.buffer=[],this.length=0}n.prototype={get:function(e){var t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)==1},put:function(e,t){for(var n=0;n<t;n++)this.putBit((e>>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},t.exports=n})),xg=c(o(((e,t)=>{var n=pg(),r=_g(),i=hg(),a=yg(),o=bg();function s(e,t){this.typeNumber=e,this.errorCorrectLevel=t,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}s.prototype={addData:function(e){var t=new n(e);this.dataList.push(t),this.dataCache=null},isDark:function(e,t){if(e<0||this.moduleCount<=e||t<0||this.moduleCount<=t)throw Error(e+`,`+t);return this.modules[e][t]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var e=1;for(e=1;e<40;e++){for(var t=a.getRSBlocks(e,this.errorCorrectLevel),n=new o,i=0,s=0;s<t.length;s++)i+=t[s].dataCount;for(var c=0;c<this.dataList.length;c++){var l=this.dataList[c];n.put(l.mode,4),n.put(l.getLength(),r.getLengthInBits(l.mode,e)),l.write(n)}if(n.getLengthInBits()<=i*8)break}this.typeNumber=e}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(e,t){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var n=0;n<this.moduleCount;n++){this.modules[n]=Array(this.moduleCount);for(var r=0;r<this.moduleCount;r++)this.modules[n][r]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(e,t),this.typeNumber>=7&&this.setupTypeNumber(e),this.dataCache===null&&(this.dataCache=s.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)},setupPositionProbePattern:function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r===0||r===6)||0<=r&&r<=6&&(n===0||n===6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)},getBestMaskPattern:function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var i=r.getLostPoint(this);(n===0||e>i)&&(e=i,t=n)}return t},createMovieClip:function(e,t,n){var r=e.createEmptyMovieClip(t,n),i=1;this.make();for(var a=0;a<this.modules.length;a++)for(var o=a*i,s=0;s<this.modules[a].length;s++){var c=s*i;this.modules[a][s]&&(r.beginFill(0,100),r.moveTo(c,o),r.lineTo(c+i,o),r.lineTo(c+i,o+i),r.lineTo(c,o+i),r.endFill())}return r},setupTimingPattern:function(){for(var e=8;e<this.moduleCount-8;e++)this.modules[e][6]===null&&(this.modules[e][6]=e%2==0);for(var t=8;t<this.moduleCount-8;t++)this.modules[6][t]===null&&(this.modules[6][t]=t%2==0)},setupPositionAdjustPattern:function(){for(var e=r.getPatternPosition(this.typeNumber),t=0;t<e.length;t++)for(var n=0;n<e.length;n++){var i=e[t],a=e[n];if(this.modules[i][a]===null)for(var o=-2;o<=2;o++)for(var s=-2;s<=2;s++)Math.abs(o)===2||Math.abs(s)===2||o===0&&s===0?this.modules[i+o][a+s]=!0:this.modules[i+o][a+s]=!1}},setupTypeNumber:function(e){for(var t=r.getBCHTypeNumber(this.typeNumber),n,i=0;i<18;i++)n=!e&&(t>>i&1)==1,this.modules[Math.floor(i/3)][i%3+this.moduleCount-8-3]=n;for(var a=0;a<18;a++)n=!e&&(t>>a&1)==1,this.modules[a%3+this.moduleCount-8-3][Math.floor(a/3)]=n},setupTypeInfo:function(e,t){for(var n=this.errorCorrectLevel<<3|t,i=r.getBCHTypeInfo(n),a,o=0;o<15;o++)a=!e&&(i>>o&1)==1,o<6?this.modules[o][8]=a:o<8?this.modules[o+1][8]=a:this.modules[this.moduleCount-15+o][8]=a;for(var s=0;s<15;s++)a=!e&&(i>>s&1)==1,s<8?this.modules[8][this.moduleCount-s-1]=a:s<9?this.modules[8][15-s-1+1]=a:this.modules[8][15-s-1]=a;this.modules[this.moduleCount-8][8]=!e},mapData:function(e,t){for(var n=-1,i=this.moduleCount-1,a=7,o=0,s=this.moduleCount-1;s>0;s-=2)for(s===6&&s--;;){for(var c=0;c<2;c++)if(this.modules[i][s-c]===null){var l=!1;o<e.length&&(l=(e[o]>>>a&1)==1),r.getMask(t,i,s-c)&&(l=!l),this.modules[i][s-c]=l,a--,a===-1&&(o++,a=7)}if(i+=n,i<0||this.moduleCount<=i){i-=n,n=-n;break}}}},s.PAD0=236,s.PAD1=17,s.createData=function(e,t,n){for(var i=a.getRSBlocks(e,t),c=new o,l=0;l<n.length;l++){var u=n[l];c.put(u.mode,4),c.put(u.getLength(),r.getLengthInBits(u.mode,e)),u.write(c)}for(var d=0,f=0;f<i.length;f++)d+=i[f].dataCount;if(c.getLengthInBits()>d*8)throw Error(`code length overflow. (`+c.getLengthInBits()+`>`+d*8+`)`);for(c.getLengthInBits()+4<=d*8&&c.put(0,4);c.getLengthInBits()%8!=0;)c.putBit(!1);for(;!(c.getLengthInBits()>=d*8||(c.put(s.PAD0,8),c.getLengthInBits()>=d*8));)c.put(s.PAD1,8);return s.createBytes(c,i)},s.createBytes=function(e,t){for(var n=0,a=0,o=0,s=Array(t.length),c=Array(t.length),l=0;l<t.length;l++){var u=t[l].dataCount,d=t[l].totalCount-u;a=Math.max(a,u),o=Math.max(o,d),s[l]=Array(u);for(var f=0;f<s[l].length;f++)s[l][f]=255&e.buffer[f+n];n+=u;var p=r.getErrorCorrectPolynomial(d),m=new i(s[l],p.getLength()-1).mod(p);c[l]=Array(p.getLength()-1);for(var h=0;h<c[l].length;h++){var g=h+m.getLength()-c[l].length;c[l][h]=g>=0?m.get(g):0}}for(var _=0,v=0;v<t.length;v++)_+=t[v].totalCount;for(var y=Array(_),b=0,x=0;x<a;x++)for(var S=0;S<t.length;S++)x<s[S].length&&(y[b++]=s[S][x]);for(var C=0;C<o;C++)for(var w=0;w<t.length;w++)C<c[w].length&&(y[b++]=c[w][C]);return y},t.exports=s}))(),1),Sg=c(vg(),1);const Cg={renderQr:Dg};function wg(e){return Hf.parse({v:1,gw:Pf(e.gatewayId),relay:e.relayBaseUrl,direct:e.bootstrapDirectBaseUrl,pc:e.pairingCode,pkf:qp(e.gatewayIdentityPublicKey),tsl:e.relayTransportSecurityLevel})}function Tg(e){return Vf.parse({v:1,gw:Pf(e.gatewayId),name:e.gatewayName,machineName:e.machineName,relay:e.relayBaseUrl,direct:e.directBaseUrls,tsl:e.relayTransportSecurityLevel,gatewayIdentity:e.gatewayIdentity})}function Eg(e,t=Cg){let n=JSON.stringify(e.descriptor),r=Buffer.from(n,`utf8`).toString(`base64`),i=t.renderQr(n);return[`[gateway] pairing code ${e.descriptor.pc} (expires ${e.expiresAt})`,`[gateway] connection descriptor bundle:`,`[gateway] this descriptor is short-lived; refresh it after pairing succeeds or when it expires.`,`[gateway] raw descriptor JSON:`,n,`[gateway] descriptor base64:`,r,`[gateway] scan this QR from the mobile app:`,i,`[gateway] fallback: if scanning fails, paste the raw descriptor JSON or descriptor base64 into mobile pairing.`].join(`
|
|
145
145
|
`)}function Dg(e){let t=new xg.default(-1,Sg.default.L);t.addData(e),t.make();let n=t.getModuleCount(),r=t.modules.slice(),i=[];for(let e=-2;e<n+2;e+=2){let t=``;for(let i=-2;i<n+2;i+=1){let a=Og(r,n,e,i,!0,!1),o=Og(r,n,e+1,i,!0,!1);t+=kg(a,o)}i.push(t)}return i.join(`
|
|
146
146
|
`)}function Og(e,t,n,r,i,a){return n<0||n>=t||r<0||r>=t?a:e[n]?.[r]===i}function kg(e,t){return`\u001b[${e?30:37};${t?40:47}m\u2580\u001b[0m`}const Ag={listGatewayListenHosts:bh,renderQr:Dg};function jg(e,t=Ag){return t.listGatewayListenHosts(e.host).map(t=>`${e.protocol}://${Ig(t)}:${e.port}`)}function Mg(e){return e.find(e=>!Lg(e))??e[0]??``}function Ng(e,t=Ag){let n=e.relayUrl.trim();if(!n)return``;let r;try{r=new URL(n)}catch{return n}if(!Rg(r.hostname))return n;let i=t.listGatewayListenHosts(e.gatewayHost).find(e=>!Rg(e));return i?(r.hostname=i,r.toString().replace(/\/$/,``)):n}function Pg(e,t=Ag){let n=[];e.createdDefaultConfig&&n.push(`[gateway] created default config at ${e.configPath}`),n.push(`[gateway] log file ${e.config.gatewayLogPath}${e.logToConsole?` (console logging enabled)`:``}`),n.push(`[gateway] gatewayId ${e.config.gatewayId}`),n.push(`[gateway] name ${e.startedServer.gatewayName}`),n.push(`[gateway] machine ${e.startedServer.machineName}`),n.push(e.config.relayEnabled?`[gateway] relay enabled: ${Ng({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t)}`:`[gateway] relay disabled`),n.push(`[gateway] available URLs:`);let r=jg({protocol:e.startedServer.protocol,host:e.config.host,port:e.startedServer.listenPort},t);for(let e of r)n.push(` ${e}`);return e.startedServer.startupPairingCode&&n.push(Eg({descriptor:wg({gatewayId:e.config.gatewayId,bootstrapDirectBaseUrl:Mg(r),pairingCode:e.startedServer.startupPairingCode.code,gatewayIdentityPublicKey:e.startedServer.gatewayIdentity.publicKey,relayBaseUrl:e.config.relayEnabled?Ng({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t):void 0,relayTransportSecurityLevel:e.config.relayEnabled?e.config.relayTransportSecurityLevel:void 0}),expiresAt:e.startedServer.startupPairingCode.expiresAt},{renderQr:t.renderQr??Dg})),n.push(...Fg(e.doctorReport)),n.join(`
|
|
147
|
-
`)}function Fg(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function Ig(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function Lg(e){try{let t=new URL(e).hostname;return Rg(t)}catch{return!1}}function Rg(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const zg={platform:y.default.platform,now:()=>new Date,currentContext:()=>({pid:y.default.pid,cwd:y.default.cwd(),argv:y.default.argv.slice(2),execArgv:[...y.default.execArgv],execPath:y.default.execPath,scriptPath:y.default.argv[1]??null}),runCommand:(e,t,n={})=>{let r=(0,h.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0,...n});return{status:r.status,stdout:typeof r.stdout==`string`?r.stdout:r.stdout?.toString(`utf8`)??``,stderr:typeof r.stderr==`string`?r.stderr:r.stderr?.toString(`utf8`)??``,...r.error?{error:r.error}:{}}}};function Bg(){return p.default.join(Eh(),`update-state.json`)}function Vg(e){return Wd.parse({type:`gateway.update.status`,payload:e})}var Hg=class{packageName;currentVersion;sessionHub;logger;consoleWrite;getRunningSessionCount;requestPreparedUpdate;stateFilePath;checkIntervalMs;runtime;state;scheduledCheckTimer=null;recurringCheckTimer=null;checkPromise=null;applyPromise=null;constructor(e){this.packageName=e.packageName,this.currentVersion=e.currentVersion,this.sessionHub=e.sessionHub,this.logger=e.logger,this.consoleWrite=e.consoleWrite,this.getRunningSessionCount=e.getRunningSessionCount,this.requestPreparedUpdate=e.requestPreparedUpdate,this.stateFilePath=e.stateFilePath??Bg(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??zg,this.state=Ud.parse({packageName:this.packageName,currentVersion:this.currentVersion,available:!1,canApply:!1,status:`unknown`,install:{manager:`unknown`,installType:`unknown`,packageName:this.packageName,canSelfUpdate:!1}})}async start(){await this.reconcilePersistedState(),this.scheduledCheckTimer=setTimeout(()=>{this.checkForUpdates(`system`),this.scheduleRecurringChecks()},5e3)}async shutdown(){this.scheduledCheckTimer&&=(clearTimeout(this.scheduledCheckTimer),null),this.recurringCheckTimer&&=(clearInterval(this.recurringCheckTimer),null)}getInfo(){return Ud.parse(this.state)}async getOrCheckInfo(e){if(this.checkPromise)return this.checkPromise;let t=this.getInfo();return t.status===`unknown`||t.status===`failed`?this.checkForUpdates(e):t}async checkForUpdates(e){return this.checkPromise||=(async()=>{let t=this.runtime.now().toISOString(),n=Kg({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=Gg(this.packageName,this.runtime);if(!r)return this.patchState({status:`failed`,available:!1,canApply:!1,latestVersion:void 0,checkedAt:t,install:n,lastError:`failed to query latest published gateway version`}),this.getInfo();let i=N(r,this.currentVersion)>0,a=i&&n.canSelfUpdate,o=i?a?`available`:`unsupported_install`:`up_to_date`;if(this.patchState({status:o,latestVersion:r,available:i,canApply:a,checkedAt:t,install:n,job:void 0,lastError:void 0}),i&&e!==`mobile`){let e=a?`[gateway] update available ${this.currentVersion} -> ${r}. Type update and press Enter to install and restart.`:`[gateway] update available ${this.currentVersion} -> ${r}, but this installation cannot self-update (${n.reason??`unsupported install`}).`;this.consoleWrite?.(e)}else e===`console`&&this.consoleWrite?.(`[gateway] already up to date at ${this.currentVersion}`);return this.getInfo()})().finally(()=>{this.checkPromise=null}),this.checkPromise}async applyUpdate(e){return this.applyPromise||=(async()=>{let t=await this.checkForUpdates(e);if(!t.available)throw Error(`gateway is already up to date`);if(!t.canApply||t.install.manager===`unknown`)throw Error(t.install.reason??`gateway installation does not support self-update`);if(t.status===`updating`||t.status===`restarting`)return Gd.parse({started:!1,update:t});let n=await this.getRunningSessionCount();if(n>0)throw Error(`gateway update requires idle runtime, found ${n} running session${n===1?``:`s`}`);let r=t.latestVersion;if(!r)throw Error(`latest gateway version is unknown`);let i=this.runtime.currentContext(),a={id:`gwupd_${Date.now()}`,targetVersion:r,requestedBy:e,requestedAt:this.runtime.now().toISOString(),startedAt:this.runtime.now().toISOString()},o={version:1,update:{...t,status:`updating`,job:a,lastError:void 0},helper:{manager:t.install.manager,packageName:this.packageName,targetVersion:r,originalPid:i.pid,restart:t_(t.install,{cwd:i.cwd,argv:[...i.argv]}),requestedBy:e,requestedAt:a.requestedAt}},s=o.helper;if(!s)throw Error(`gateway update helper state was not prepared`);await r_(this.stateFilePath,o),this.patchState({status:`updating`,job:a,lastError:void 0}),this.consoleWrite?.(`[gateway] updating ${this.packageName} to ${r} via ${t.install.manager}; gateway will restart automatically.`),this.patchState({status:`restarting`,job:a}),this.logger.info?.({job:a,stateFilePath:this.stateFilePath,originalPid:i.pid,install:t.install,restart:s.restart},`gateway update handoff prepared`);try{await this.requestPreparedUpdate?.({stateFilePath:this.stateFilePath,targetVersion:r,requestedBy:e})}catch(e){let t=Ud.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await r_(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(Vg(t)),e}return Gd.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=Ud.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(Vg(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await n_(this.stateFilePath);if(!e)return;let t=Kg({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime}),n=e.helper?.targetVersion??e.update.job?.targetVersion;if((e.update.status===`updating`||e.update.status===`restarting`)&&n){let r=N(this.currentVersion,n)>=0,i=Ud.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,latestVersion:r?this.currentVersion:n,available:!r,canApply:!r&&t.canSelfUpdate,status:r?`up_to_date`:`failed`,checkedAt:this.runtime.now().toISOString(),install:t,job:void 0,...r?{lastError:void 0}:{lastError:e.update.lastError??`gateway restarted before update completed`}});await r_(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=Ud.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Ug(e,t={}){let n=t.runtime??zg,r=t.waitForProcessExit??i_,i=t.logger,a=await n_(e);if(!a?.helper)throw Error(`gateway update helper state is missing`);i?.info?.({stateFilePath:e,originalPid:a.helper.originalPid,packageName:a.helper.packageName,targetVersion:a.helper.targetVersion,manager:a.helper.manager,cwd:a.helper.restart.cwd},`gateway update apply starting`);let o=Date.now();await r(a.helper.originalPid);let s=Date.now()-o,c=a_(a.helper.originalPid);i?.[c?`warn`:`info`]?.({stateFilePath:e,originalPid:a.helper.originalPid,waitDurationMs:s,processStillRunning:c},c?`gateway update original process still running after wait window`:`gateway update original process exited`);let l=Wg(a.helper.manager,a.helper.packageName,a.helper.targetVersion);i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd},`gateway update install starting`);let u=Date.now(),d=n.runCommand(l.command,l.args,{cwd:a.helper.restart.cwd}),f=Date.now()-u;if(d.status!==0){let t={...a,update:{...a.update,status:`failed`,lastError:s_(l.command,l.args,d)},helper:void 0};return await r_(e,t),i?.error?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status,error:d.error?.message,stderr:d.stderr.trim()||void 0,stdout:d.stdout.trim()||void 0},`gateway update install failed`),{updated:!1,update:Ud.parse(t.update)}}i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status},`gateway update install completed`);let p={...a,update:{...a.update,status:`restarting`,lastError:void 0},helper:void 0};return await r_(e,p),i?.info?.({stateFilePath:e,targetVersion:a.helper.targetVersion},`gateway update apply completed; worker restart may proceed`),{updated:!0,update:Ud.parse(p.update)}}function Wg(e,t,n){switch(e){case`npm`:return{command:`npm`,args:[`install`,`-g`,`${t}@${n}`]};case`pnpm`:return{command:`pnpm`,args:[`add`,`-g`,`${t}@${n}`]};case`yarn`:return{command:`yarn`,args:[`global`,`add`,`${t}@${n}`]}}}function Gg(e,t){let n=t.runCommand(`npm`,[`view`,e,`version`,`--json`]);if(n.error||n.status!==0)return null;let r=n.stdout.trim();if(!r)return null;try{let e=JSON.parse(r);return typeof e==`string`&&e.trim()?e.trim():null}catch{return r.replace(/^"+|"+$/g,``)}}function Kg(e){let t=Xg(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?Vd.parse({manager:`unknown`,installType:`dev_workspace`,packageName:e.packageName,packageRoot:t.packageRoot,canSelfUpdate:!1,reason:`workspace/development runtime does not support self-update`}):e.currentScriptPath?qg(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Jg(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Yg(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Vd.parse({manager:`unknown`,installType:t.packageName===e.packageName?`unknown`:`standalone_binary`,packageName:e.packageName,...t.packageRoot?{packageRoot:t.packageRoot}:{},canSelfUpdate:!1,reason:t.packageName===e.packageName?`unable to determine global package manager installation`:`gateway is not running from a supported package-manager installation`}):Vd.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function qg(e,t,n,r){let i=r.runCommand(`npm`,[`root`,`-g`]),a=r.runCommand(`npm`,[`prefix`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=Qg(c);if(!Zg(l,t,n))return null;let d=Qg(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),e_(r.platform)),m=$g(l,d)?`global_registry`:`global_file`;return Vd.parse({manager:`npm`,installType:m,packageName:e,packageRoot:l,binPath:f,canSelfUpdate:m===`global_registry`,...m===`global_registry`?{}:{reason:`npm file-linked global install is not supported`}})}function Jg(e,t,n,r){let i=r.runCommand(`pnpm`,[`root`,`-g`]),a=r.runCommand(`pnpm`,[`bin`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=Qg(c);if(!Zg(l,t,n))return null;let d=$g(l,Qg(p.default.dirname(o)))?`global_registry`:`global_file`;return Vd.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,e_(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Yg(e,t,n,r){let i=r.runCommand(`yarn`,[`global`,`dir`]),a=r.runCommand(`yarn`,[`global`,`bin`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,`node_modules`,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=Qg(c);return Zg(l,t,n)?Vd.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,e_(r.platform)),canSelfUpdate:!0}):null}function Xg(e){if(!e)return{packageRoot:null,packageName:null};let t=p.default.dirname(e);for(;;){let e=p.default.join(t,`package.json`);if(u.default.existsSync(e))try{let n=JSON.parse(u.default.readFileSync(e,`utf8`));if(typeof n.name==`string`)return{packageRoot:t,packageName:n.name}}catch{return{packageRoot:t,packageName:null}}let n=p.default.dirname(t);if(n===t)return{packageRoot:null,packageName:null};t=n}}function Zg(e,t,n){let r=Qg(e),i=t?Qg(t):null,a=Qg(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function Qg(e){try{return u.default.realpathSync(e)}catch{return e}}function $g(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function e_(e=y.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function t_(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function n_(e){try{let t=await d.default.readFile(e,`utf8`);return c_(JSON.parse(t))}catch{return null}}async function r_(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0}),await d.default.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}async function i_(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!a_(e))return;await o_(500)}}function a_(e){try{return y.default.kill(e,0),!0}catch{return!1}}function o_(e){return new Promise(t=>setTimeout(t,e))}function s_(e,t,n){let r=n.stderr.trim(),i=n.stdout.trim(),a=r||i||n.error?.message||`exit code ${String(n.status)}`;return`${e} ${t.join(` `)} failed: ${a}`}function c_(e){if(!d_(e)||e.version!==1)return null;let t=Ud.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=l_(e.helper);return n?{version:1,update:t.data,helper:n}:null}function l_(e){if(!d_(e))return null;let t=Rd.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=Bd.safeParse(e.requestedBy);if(!n.success||!f_(e.packageName)||!f_(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!p_(e.requestedAt))return null;let r=u_(e.restart);return r?{manager:t.data,packageName:e.packageName,targetVersion:e.targetVersion,originalPid:e.originalPid,restart:r,requestedBy:n.data,requestedAt:e.requestedAt}:null}function u_(e){return!d_(e)||!f_(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!f_(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function d_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function f_(e){return typeof e==`string`&&e.trim().length>0}function p_(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}const m_=3e4;async function h_(e){let t=__(),n=b_(e.loaded.config.gatewayLogPath),r=new Map,i=0,a=null,o=!1,s=null,c=null,l=!1,u=null,d=null,f=null,p=null,m=null,g=0,_=0,v=!1,b=ug(t,`__worker`,e.args),x=new Promise((e,t)=>{s=e,c=t}),S=()=>{f&&=(clearTimeout(f),null)},C=()=>{p&&=(clearTimeout(p),null)},w=()=>{m&&=(clearTimeout(m),null)},T=()=>{d&&=(clearTimeout(d),null)},E=g_({enabled:y.default.stdin.isTTY&&y.default.stdout.isTTY,onUpdate:async()=>{if(!(!a||l))try{let e=await L(`console`);if(e.started){console.log(`[gateway] update accepted; restarting into ${e.update.job?.targetVersion??`latest`}...`);return}console.log(`[gateway] update already ${e.update.status}`)}catch(e){console.error(`[gateway] update failed: ${String(e)}`)}},onRestartCodex:async()=>{if(!(!a||l))try{let e=await R(`console`);console.log(`[gateway] codex app-server restarted; closed ${e.closedRuntimeSessionCount} runtime session${e.closedRuntimeSessionCount===1?``:`s`}.`)}catch(e){console.error(`[gateway] codex app-server restart failed: ${String(e)}`)}}}),D=e=>{for(let t of r.values())t.reject(e);r.clear()},O=e=>{w(),T(),S(),C(),E(),D(Error(`gateway supervisor shutting down`)),n.close(),y.default.exit(e)},k=e=>{e.stdout&&e.stdout.unpipe(y.default.stdout),e.stderr&&e.stderr.unpipe(y.default.stderr)},A=()=>{if(o||v)return;v=!0,w(),T(),S(),C();let e=Error(`Gateway worker did not report ready within ${m_}ms after ${_} launch attempt${_===1?``:`s`}.`);n.error({error:e,workerPid:a?.pid??void 0,workerLaunchCount:_,workerRestartAttempt:g,invocation:b},`gateway supervisor initial worker ready timed out`),console.error(`[gateway] ${e.message}`);let t=a;if(a=null,t){k(t),t.removeAllListeners();try{t.kill(`SIGTERM`)}catch{}}c?.(e),s=null,c=null},j=(e,t)=>{if(l||v||u||p)return;g+=1;let r=Math.min(g-1,4),i=Math.min(15e3,1e3*2**r);n.warn({...t,reason:e,delayMs:i,restartAttempt:g,invocation:b,initialReadyReceived:o},`gateway supervisor scheduling worker restart`),console.error(`[gateway] worker exited unexpectedly; restarting in ${i}ms (attempt ${g}).`),p=setTimeout(()=>{p=null,I(b)},i)},M=e=>{if(a){n.info({reason:e,workerPid:a.pid??void 0,preparedUpdate:u},`gateway supervisor requested worker shutdown`);try{a.send?.({type:`supervisor.shutdown`,reason:e})}catch(t){n.warn({reason:e,workerPid:a.pid??void 0,error:t},`gateway supervisor failed to send graceful shutdown message; sending SIGTERM`),a.kill(`SIGTERM`)}S(),f=setTimeout(()=>{a?.kill(`SIGTERM`)},1e4)}},N=async r=>{n.info(r,`gateway supervisor continuing prepared update`),console.log(`[gateway] applying update to ${r.targetVersion}...`);let i=await Ug(r.stateFilePath,{logger:n}),a=i.updated&&i.update.install.binPath?dg(i.update.install,`__worker`,e.args,t.cwd):ug(t,`__worker`,e.args);n.info({updated:i.updated,update:i.update,nextInvocation:a},`gateway supervisor prepared next worker invocation`),!i.updated&&i.update.lastError&&console.error(`[gateway] update failed: ${i.update.lastError}`),i.updated?console.log(`[gateway] update installed; restarting worker...`):console.log(`[gateway] relaunching current worker after failed update.`),u=null,b=a,I(a)},P=(e,t)=>{if(S(),T(),n.info({workerPid:a?.pid??void 0,code:e,signal:t,preparedUpdate:u,shuttingDown:l},`gateway supervisor observed worker exit`),a=null,u){D(Error(`gateway worker restarting for update`)),N(u).catch(e=>{n.error({error:e,preparedUpdate:u},`gateway update handoff failed`),console.error(`[gateway] update handoff failed: ${String(e)}`),O(1)});return}if(l){O(0);return}D(Error(`gateway worker exited`)),t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),j(`worker_exit`,{code:e,signal:t})},F=t=>{switch(t.type){case`worker.ready`:if(g=0,C(),!o){o=!0,w(),n.info(t.payload,`gateway supervisor received initial worker ready`),console.log(Pg({configPath:e.loaded.configPath,createdDefaultConfig:e.loaded.createdDefaultConfig,config:e.loaded.config,doctorReport:e.doctorReport,startedServer:t.payload,logToConsole:e.args.logToConsole})),s?.(),s=null,c=null;return}n.info(t.payload,`gateway supervisor received worker ready after update`),console.log(`[gateway] worker ready after update.`);return;case`worker.response`:{let e=r.get(t.id);if(!e)return;r.delete(t.id),t.ok?e.resolve(t.result):e.reject(Error(t.error));return}case`worker.update.prepared`:if(u)return;u=t.payload,n.info(t.payload,`gateway supervisor received worker update prepared`),T(),d=setTimeout(()=>{M(`update`)},250);return}},I=e=>{b=e,C(),_+=1,n.info(e,`gateway supervisor spawning worker`);let t=(0,h.spawn)(e.command,e.args,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0});a=t,n.info({workerPid:t.pid??void 0,invocation:e},`gateway supervisor spawned worker`),t.stdout&&t.stdout.pipe(y.default.stdout),t.stderr&&t.stderr.pipe(y.default.stderr),t.on(`message`,e=>{let t=v_(e);t&&F(t)}),t.on(`exit`,(e,n)=>{a===t&&(k(t),P(e,n))}),t.on(`error`,r=>{a===t&&(k(t),a=null,n.error({error:r,invocation:e},`gateway supervisor failed to launch worker`),console.error(`[gateway] failed to launch worker: ${String(r)}`),j(`worker_launch_error`,{error:r}))})},L=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`gateway.update.apply`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},R=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`codex.appServer.restart`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},z=e=>{if(!l){if(l=!0,n.info({signal:e},`gateway supervisor received shutdown signal`),console.log(`[gateway] received ${e}; shutting down...`),!a){O(0);return}M(`signal`)}};y.default.on(`SIGINT`,z),y.default.on(`SIGTERM`,z),m=setTimeout(()=>{A()},m_),I(b);try{await x}catch(e){throw y.default.removeListener(`SIGINT`,z),y.default.removeListener(`SIGTERM`,z),w(),T(),S(),C(),D(Error(`gateway supervisor failed to start`)),E(),n.close(),e}}function g_(e){if(!e.enabled)return()=>{};let t=v.default.createInterface({input:y.default.stdin,output:y.default.stdout,terminal:!0});return t.on(`line`,t=>{let n=t.trim().toLowerCase();if(n===`update`){e.onUpdate();return}if(n===`restart codex`||n===`codex restart`){e.onRestartCodex();return}}),()=>{t.close()}}function __(){return{pid:y.default.pid,cwd:y.default.cwd(),argv:y.default.argv.slice(2),execArgv:[...y.default.execArgv],execPath:y.default.execPath,scriptPath:y.default.argv[1]??null}}function v_(e){if(!y_(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return y_(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||typeof e.ok!=`boolean`?null:e.ok?(e.method,{type:`worker.response`,id:e.id,method:e.method,ok:!0,result:e.result}):typeof e.error==`string`?{type:`worker.response`,id:e.id,method:e.method,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!y_(e.payload)||typeof e.payload.stateFilePath!=`string`||typeof e.payload.targetVersion!=`string`||e.payload.requestedBy!==`console`&&e.payload.requestedBy!==`mobile`&&e.payload.requestedBy!==`system`?null:{type:`worker.update.prepared`,payload:{stateFilePath:e.payload.stateFilePath,targetVersion:e.payload.targetVersion,requestedBy:e.payload.requestedBy}};default:return null}}function y_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function b_(e){let t=f.default.hostname();u.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=(n,r,i)=>{let a={level:n,time:Date.now(),pid:y.default.pid,hostname:t,...x_(r),msg:i??``};try{u.default.appendFileSync(e,`${JSON.stringify(a,S_)}\n`,`utf8`)}catch{}};return{info:(e,t)=>{n(30,e,t)},warn:(e,t)=>{n(40,e,t)},error:(e,t)=>{n(50,e,t)},close:()=>{}}}function x_(e){return y_(e)?e:{detail:e}}function S_(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t==`bigint`?t.toString():t}async function C_(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function w_(e,t){let n=t.httpsEnabled?t.httpsPort:t.port,r=t.httpsEnabled?`https`:`http`,i=e;return i?.code===`EADDRINUSE`?`[gateway] failed to start: ${r.toUpperCase()} ${t.host}:${n} is already in use.`:i?.code===`EACCES`?`[gateway] failed to start: permission denied for ${r.toUpperCase()} ${t.host}:${n}.`:i?.code===`ENOENT`||i?.code===`EISDIR`?`[gateway] failed to start: log path is invalid or unavailable: ${t.gatewayLogPath}`:i instanceof Error?`[gateway] failed to start: ${i.message}`:`[gateway] failed to start: ${String(e)}`}var T_=o(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),E_=o(((e,t)=>{var n=T_();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:w,abort:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(){var e=s;for(s=null,c=null;e;){var t=e.next,n=e.callback,r=e.errorHandler,a=e.value,o=e.context;e.value=null,e.callback=i,e.errorHandler=null,r&&r(Error(`abort`),a),n.call(o,Error(`abort`)),e.release(e),e=t}d.drain=i}function w(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),D_=o(((e,t)=>{let{format:n}=require(`node:util`);function r(){return`${this.name} [${this.code}]: ${this.message}`}let i=Symbol.for(`fastify-error-generic`);function a(e,t,o=500,s=Error,c=a.captureStackTrace){let l=e===i;if(l&&(e=`FST_ERR`),!e)throw Error(`Fastify error code must not be empty`);if(!t)throw Error(`Fastify error message must not be empty`);e=e.toUpperCase(),!o&&(o=void 0);let u=Symbol.for(`fastify-error ${e}`);function d(...r){if(!new.target)return new d(...r);this.code=e,this.name=`FastifyError`,this.statusCode=o;let i=r.length-1;i!==-1&&r[i]&&typeof r[i]==`object`&&`cause`in r[i]&&(this.cause=r.pop().cause),this.message=n(t,...r),Error.stackTraceLimit&&c&&Error.captureStackTrace(this,d)}return d.prototype=Object.create(s.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0},[i]:{value:!0,enumerable:!1,writable:!1,configurable:!1},[u]:{value:!0,enumerable:!1,writable:!1,configurable:!1}}),l?Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[i]},configurable:!1,writable:!1,enumerable:!1}):Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[u]},configurable:!1,writable:!1,enumerable:!1}),d.prototype[Symbol.toStringTag]=`Error`,d.prototype.toString=r,d}a.captureStackTrace=!0;let o=a(i,`Fastify Error`,500,Error);t.exports=a,t.exports.FastifyError=o,t.exports.default=a,t.exports.createError=a})),O_=o(((e,t)=>{let{createError:n}=D_();t.exports={AVV_ERR_EXPOSE_ALREADY_DEFINED:n(`AVV_ERR_EXPOSE_ALREADY_DEFINED`,`'%s' is already defined, specify an expose option for '%s'`),AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:n(`AVV_ERR_ATTRIBUTE_ALREADY_DEFINED`,`'%s' is already defined`),AVV_ERR_CALLBACK_NOT_FN:n(`AVV_ERR_CALLBACK_NOT_FN`,`Callback for '%s' hook is not a function. Received: '%s'`),AVV_ERR_PLUGIN_NOT_VALID:n(`AVV_ERR_PLUGIN_NOT_VALID`,`Plugin must be a function or a promise. Received: '%s'`),AVV_ERR_ROOT_PLG_BOOTED:n(`AVV_ERR_ROOT_PLG_BOOTED`,`Root plugin has already booted`),AVV_ERR_PARENT_PLG_LOADED:n(`AVV_ERR_PARENT_PLG_LOADED`,`Impossible to load '%s' plugin because the parent '%s' was already loaded`),AVV_ERR_READY_TIMEOUT:n(`AVV_ERR_READY_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`),AVV_ERR_PLUGIN_EXEC_TIMEOUT:n(`AVV_ERR_PLUGIN_EXEC_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`)}})),k_=o(((e,t)=>{t.exports={kAvvio:Symbol(`avvio.Boot`),kIsOnCloseHandler:Symbol(`isOnCloseHandler`),kThenifyDoNotWrap:Symbol(`avvio.ThenifyDoNotWrap`),kUntrackNode:Symbol(`avvio.TimeTree.untrackNode`),kTrackNode:Symbol(`avvio.TimeTree.trackNode`),kGetParent:Symbol(`avvio.TimeTree.getParent`),kGetNode:Symbol(`avvio.TimeTree.getNode`),kAddNode:Symbol(`avvio.TimeTree.addNode`),kPluginMeta:Symbol.for(`plugin-meta`)}})),A_=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=k_();var s=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[r](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[n](e){this.tableId.delete(e.id);let t=this.tableLabel.get(e.label);t.pop(),t.length===0&&this.tableLabel.delete(e.label)}[i](e){if(e===null)return null;if(this.tableLabel.has(e)){let t=this.tableLabel.get(e);return t[t.length-1]}else return null}[a](e){return this.tableId.get(e)}[o](e,t,n){let a=this[i](e);if(a===null)return this.root={parent:null,id:`root`,label:t,nodes:[],start:n,stop:null,diff:-1},this[r](this.root),this.root.id;let o=`${t}-${Math.random()}`,s={parent:e,id:o,label:t,nodes:[],start:n,stop:null,diff:-1};return a.nodes.push(s),this[r](s),o}start(e,t,n=Date.now()){return this[o](e,t,n)}stop(e,t=Date.now()){let r=this[a](e);r&&(r.stop=t,r.diff=r.stop-r.start||0,this[n](r))}toJSON(){return Object.assign({},this.root)}prettyPrint(){return c(this.toJSON())}};function c(e,t=``){let n=t,r=e.nodes.length,i=r-1;n+=`${e.label} ${e.diff} ms\n`;for(let a=0;a<r;++a){let r=e.nodes[a],o=t+(a===i?` `:`│ `);n+=t,n+=a===i?`└─`:`├─`,n+=r.nodes.length===0?`─ `:`┬ `,n+=c(r,o).slice(t.length+2)}return n}t.exports={TimeTree:s}})),j_=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),M_=o(((e,t)=>{function n(){let e={resolve:null,reject:null,promise:null};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}t.exports={createPromise:n}})),N_=o(((e,t)=>{let{kPluginMeta:n}=k_();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
|
|
147
|
+
`)}function Fg(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function Ig(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function Lg(e){try{let t=new URL(e).hostname;return Rg(t)}catch{return!1}}function Rg(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const zg={platform:y.default.platform,now:()=>new Date,currentContext:()=>({pid:y.default.pid,cwd:y.default.cwd(),argv:y.default.argv.slice(2),execArgv:[...y.default.execArgv],execPath:y.default.execPath,scriptPath:y.default.argv[1]??null}),runCommand:(e,t,n={})=>{let r=(0,h.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0,...n});return{status:r.status,stdout:typeof r.stdout==`string`?r.stdout:r.stdout?.toString(`utf8`)??``,stderr:typeof r.stderr==`string`?r.stderr:r.stderr?.toString(`utf8`)??``,...r.error?{error:r.error}:{}}}};function Bg(){return p.default.join(Eh(),`update-state.json`)}function Vg(e){return Wd.parse({type:`gateway.update.status`,payload:e})}var Hg=class{packageName;currentVersion;sessionHub;logger;consoleWrite;getRunningSessionCount;requestPreparedUpdate;stateFilePath;checkIntervalMs;runtime;state;scheduledCheckTimer=null;recurringCheckTimer=null;checkPromise=null;applyPromise=null;constructor(e){this.packageName=e.packageName,this.currentVersion=e.currentVersion,this.sessionHub=e.sessionHub,this.logger=e.logger,this.consoleWrite=e.consoleWrite,this.getRunningSessionCount=e.getRunningSessionCount,this.requestPreparedUpdate=e.requestPreparedUpdate,this.stateFilePath=e.stateFilePath??Bg(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??zg,this.state=Ud.parse({packageName:this.packageName,currentVersion:this.currentVersion,available:!1,canApply:!1,status:`unknown`,install:{manager:`unknown`,installType:`unknown`,packageName:this.packageName,canSelfUpdate:!1}})}async start(){await this.reconcilePersistedState(),this.scheduledCheckTimer=setTimeout(()=>{this.checkForUpdates(`system`),this.scheduleRecurringChecks()},5e3)}async shutdown(){this.scheduledCheckTimer&&=(clearTimeout(this.scheduledCheckTimer),null),this.recurringCheckTimer&&=(clearInterval(this.recurringCheckTimer),null)}getInfo(){return Ud.parse(this.state)}async getOrCheckInfo(e){if(this.checkPromise)return this.checkPromise;let t=this.getInfo();return t.status===`unknown`||t.status===`failed`?this.checkForUpdates(e):t}async checkForUpdates(e){if(this.checkPromise)return this.checkPromise;let t=this.getInfo();return t.status===`updating`||t.status===`restarting`?t:(this.checkPromise=(async()=>{let t=this.runtime.now().toISOString(),n=Kg({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=Gg(this.packageName,this.runtime);if(!r)return this.patchState({status:`failed`,available:!1,canApply:!1,latestVersion:void 0,checkedAt:t,install:n,lastError:`failed to query latest published gateway version`}),this.getInfo();let i=N(r,this.currentVersion)>0,a=i&&n.canSelfUpdate,o=i?a?`available`:`unsupported_install`:`up_to_date`;if(this.patchState({status:o,latestVersion:r,available:i,canApply:a,checkedAt:t,install:n,job:void 0,lastError:void 0}),i&&e!==`mobile`){let e=a?`[gateway] update available ${this.currentVersion} -> ${r}. Type update and press Enter to install and restart.`:`[gateway] update available ${this.currentVersion} -> ${r}, but this installation cannot self-update (${n.reason??`unsupported install`}).`;this.consoleWrite?.(e)}else e===`console`&&this.consoleWrite?.(`[gateway] already up to date at ${this.currentVersion}`);return this.getInfo()})().finally(()=>{this.checkPromise=null}),this.checkPromise)}async applyUpdate(e){return this.applyPromise||=(async()=>{let t=await this.checkForUpdates(e);if(!t.available)throw Error(`gateway is already up to date`);if(!t.canApply||t.install.manager===`unknown`)throw Error(t.install.reason??`gateway installation does not support self-update`);if(t.status===`updating`||t.status===`restarting`)return Gd.parse({started:!1,update:t});let n=await this.getRunningSessionCount();if(n>0)throw Error(`gateway update requires idle runtime, found ${n} running session${n===1?``:`s`}`);let r=t.latestVersion;if(!r)throw Error(`latest gateway version is unknown`);let i=this.runtime.currentContext(),a={id:`gwupd_${Date.now()}`,targetVersion:r,requestedBy:e,requestedAt:this.runtime.now().toISOString(),startedAt:this.runtime.now().toISOString()},o={version:1,update:{...t,status:`updating`,job:a,lastError:void 0},helper:{manager:t.install.manager,packageName:this.packageName,targetVersion:r,originalPid:i.pid,restart:t_(t.install,{cwd:i.cwd,argv:[...i.argv]}),requestedBy:e,requestedAt:a.requestedAt}},s=o.helper;if(!s)throw Error(`gateway update helper state was not prepared`);await r_(this.stateFilePath,o),this.patchState({status:`updating`,job:a,lastError:void 0}),this.consoleWrite?.(`[gateway] updating ${this.packageName} to ${r} via ${t.install.manager}; gateway will restart automatically.`),this.patchState({status:`restarting`,job:a}),this.logger.info?.({job:a,stateFilePath:this.stateFilePath,originalPid:i.pid,install:t.install,restart:s.restart},`gateway update handoff prepared`);try{await this.requestPreparedUpdate?.({stateFilePath:this.stateFilePath,targetVersion:r,requestedBy:e})}catch(e){let t=Ud.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await r_(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(Vg(t)),e}return Gd.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=Ud.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(Vg(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await n_(this.stateFilePath);if(!e)return;let t=Kg({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime}),n=e.helper?.targetVersion??e.update.job?.targetVersion;if((e.update.status===`updating`||e.update.status===`restarting`)&&n){let r=N(this.currentVersion,n)>=0,i=Ud.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,latestVersion:r?this.currentVersion:n,available:!r,canApply:!r&&t.canSelfUpdate,status:r?`up_to_date`:`failed`,checkedAt:this.runtime.now().toISOString(),install:t,job:void 0,...r?{lastError:void 0}:{lastError:e.update.lastError??`gateway restarted before update completed`}});await r_(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=Ud.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Ug(e,t={}){let n=t.runtime??zg,r=t.waitForProcessExit??i_,i=t.logger,a=await n_(e);if(!a?.helper)throw Error(`gateway update helper state is missing`);i?.info?.({stateFilePath:e,originalPid:a.helper.originalPid,packageName:a.helper.packageName,targetVersion:a.helper.targetVersion,manager:a.helper.manager,cwd:a.helper.restart.cwd},`gateway update apply starting`);let o=Date.now();await r(a.helper.originalPid);let s=Date.now()-o,c=a_(a.helper.originalPid);i?.[c?`warn`:`info`]?.({stateFilePath:e,originalPid:a.helper.originalPid,waitDurationMs:s,processStillRunning:c},c?`gateway update original process still running after wait window`:`gateway update original process exited`);let l=Wg(a.helper.manager,a.helper.packageName,a.helper.targetVersion);i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd},`gateway update install starting`);let u=Date.now(),d=n.runCommand(l.command,l.args,{cwd:a.helper.restart.cwd}),f=Date.now()-u;if(d.status!==0){let t={...a,update:{...a.update,status:`failed`,lastError:s_(l.command,l.args,d)},helper:void 0};return await r_(e,t),i?.error?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status,error:d.error?.message,stderr:d.stderr.trim()||void 0,stdout:d.stdout.trim()||void 0},`gateway update install failed`),{updated:!1,update:Ud.parse(t.update)}}i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status},`gateway update install completed`);let p={...a,update:{...a.update,status:`restarting`,lastError:void 0},helper:void 0};return await r_(e,p),i?.info?.({stateFilePath:e,targetVersion:a.helper.targetVersion},`gateway update apply completed; worker restart may proceed`),{updated:!0,update:Ud.parse(p.update)}}function Wg(e,t,n){switch(e){case`npm`:return{command:`npm`,args:[`install`,`-g`,`${t}@${n}`]};case`pnpm`:return{command:`pnpm`,args:[`add`,`-g`,`${t}@${n}`]};case`yarn`:return{command:`yarn`,args:[`global`,`add`,`${t}@${n}`]}}}function Gg(e,t){let n=t.runCommand(`npm`,[`view`,e,`version`,`--json`]);if(n.error||n.status!==0)return null;let r=n.stdout.trim();if(!r)return null;try{let e=JSON.parse(r);return typeof e==`string`&&e.trim()?e.trim():null}catch{return r.replace(/^"+|"+$/g,``)}}function Kg(e){let t=Xg(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?Vd.parse({manager:`unknown`,installType:`dev_workspace`,packageName:e.packageName,packageRoot:t.packageRoot,canSelfUpdate:!1,reason:`workspace/development runtime does not support self-update`}):e.currentScriptPath?qg(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Jg(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Yg(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Vd.parse({manager:`unknown`,installType:t.packageName===e.packageName?`unknown`:`standalone_binary`,packageName:e.packageName,...t.packageRoot?{packageRoot:t.packageRoot}:{},canSelfUpdate:!1,reason:t.packageName===e.packageName?`unable to determine global package manager installation`:`gateway is not running from a supported package-manager installation`}):Vd.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function qg(e,t,n,r){let i=r.runCommand(`npm`,[`root`,`-g`]),a=r.runCommand(`npm`,[`prefix`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=Qg(c);if(!Zg(l,t,n))return null;let d=Qg(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),e_(r.platform)),m=$g(l,d)?`global_registry`:`global_file`;return Vd.parse({manager:`npm`,installType:m,packageName:e,packageRoot:l,binPath:f,canSelfUpdate:m===`global_registry`,...m===`global_registry`?{}:{reason:`npm file-linked global install is not supported`}})}function Jg(e,t,n,r){let i=r.runCommand(`pnpm`,[`root`,`-g`]),a=r.runCommand(`pnpm`,[`bin`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=Qg(c);if(!Zg(l,t,n))return null;let d=$g(l,Qg(p.default.dirname(o)))?`global_registry`:`global_file`;return Vd.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,e_(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Yg(e,t,n,r){let i=r.runCommand(`yarn`,[`global`,`dir`]),a=r.runCommand(`yarn`,[`global`,`bin`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,`node_modules`,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=Qg(c);return Zg(l,t,n)?Vd.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,e_(r.platform)),canSelfUpdate:!0}):null}function Xg(e){if(!e)return{packageRoot:null,packageName:null};let t=p.default.dirname(e);for(;;){let e=p.default.join(t,`package.json`);if(u.default.existsSync(e))try{let n=JSON.parse(u.default.readFileSync(e,`utf8`));if(typeof n.name==`string`)return{packageRoot:t,packageName:n.name}}catch{return{packageRoot:t,packageName:null}}let n=p.default.dirname(t);if(n===t)return{packageRoot:null,packageName:null};t=n}}function Zg(e,t,n){let r=Qg(e),i=t?Qg(t):null,a=Qg(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function Qg(e){try{return u.default.realpathSync(e)}catch{return e}}function $g(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function e_(e=y.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function t_(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function n_(e){try{let t=await d.default.readFile(e,`utf8`);return c_(JSON.parse(t))}catch{return null}}async function r_(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0}),await d.default.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}async function i_(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!a_(e))return;await o_(500)}}function a_(e){try{return y.default.kill(e,0),!0}catch{return!1}}function o_(e){return new Promise(t=>setTimeout(t,e))}function s_(e,t,n){let r=n.stderr.trim(),i=n.stdout.trim(),a=r||i||n.error?.message||`exit code ${String(n.status)}`;return`${e} ${t.join(` `)} failed: ${a}`}function c_(e){if(!d_(e)||e.version!==1)return null;let t=Ud.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=l_(e.helper);return n?{version:1,update:t.data,helper:n}:null}function l_(e){if(!d_(e))return null;let t=Rd.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=Bd.safeParse(e.requestedBy);if(!n.success||!f_(e.packageName)||!f_(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!p_(e.requestedAt))return null;let r=u_(e.restart);return r?{manager:t.data,packageName:e.packageName,targetVersion:e.targetVersion,originalPid:e.originalPid,restart:r,requestedBy:n.data,requestedAt:e.requestedAt}:null}function u_(e){return!d_(e)||!f_(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!f_(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function d_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function f_(e){return typeof e==`string`&&e.trim().length>0}function p_(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}const m_=3e4;async function h_(e){let t=__(),n=b_(e.loaded.config.gatewayLogPath),r=new Map,i=0,a=null,o=!1,s=null,c=null,l=!1,u=null,d=null,f=null,p=null,m=null,g=0,_=0,v=!1,b=ug(t,`__worker`,e.args),x=new Promise((e,t)=>{s=e,c=t}),S=()=>{f&&=(clearTimeout(f),null)},C=()=>{p&&=(clearTimeout(p),null)},w=()=>{m&&=(clearTimeout(m),null)},T=()=>{d&&=(clearTimeout(d),null)},E=g_({enabled:y.default.stdin.isTTY&&y.default.stdout.isTTY,onUpdate:async()=>{if(!(!a||l))try{let e=await L(`console`);if(e.started){console.log(`[gateway] update accepted; restarting into ${e.update.job?.targetVersion??`latest`}...`);return}console.log(`[gateway] update already ${e.update.status}`)}catch(e){console.error(`[gateway] update failed: ${String(e)}`)}},onRestartCodex:async()=>{if(!(!a||l))try{let e=await R(`console`);console.log(`[gateway] codex app-server restarted; closed ${e.closedRuntimeSessionCount} runtime session${e.closedRuntimeSessionCount===1?``:`s`}.`)}catch(e){console.error(`[gateway] codex app-server restart failed: ${String(e)}`)}}}),D=e=>{for(let t of r.values())t.reject(e);r.clear()},O=e=>{w(),T(),S(),C(),E(),D(Error(`gateway supervisor shutting down`)),n.close(),y.default.exit(e)},k=e=>{e.stdout&&e.stdout.unpipe(y.default.stdout),e.stderr&&e.stderr.unpipe(y.default.stderr)},A=()=>{if(o||v)return;v=!0,w(),T(),S(),C();let e=Error(`Gateway worker did not report ready within ${m_}ms after ${_} launch attempt${_===1?``:`s`}.`);n.error({error:e,workerPid:a?.pid??void 0,workerLaunchCount:_,workerRestartAttempt:g,invocation:b},`gateway supervisor initial worker ready timed out`),console.error(`[gateway] ${e.message}`);let t=a;if(a=null,t){k(t),t.removeAllListeners();try{t.kill(`SIGTERM`)}catch{}}c?.(e),s=null,c=null},j=(e,t)=>{if(l||v||u||p)return;g+=1;let r=Math.min(g-1,4),i=Math.min(15e3,1e3*2**r);n.warn({...t,reason:e,delayMs:i,restartAttempt:g,invocation:b,initialReadyReceived:o},`gateway supervisor scheduling worker restart`),console.error(`[gateway] worker exited unexpectedly; restarting in ${i}ms (attempt ${g}).`),p=setTimeout(()=>{p=null,I(b)},i)},M=e=>{if(a){n.info({reason:e,workerPid:a.pid??void 0,preparedUpdate:u},`gateway supervisor requested worker shutdown`);try{a.send?.({type:`supervisor.shutdown`,reason:e})}catch(t){n.warn({reason:e,workerPid:a.pid??void 0,error:t},`gateway supervisor failed to send graceful shutdown message; sending SIGTERM`),a.kill(`SIGTERM`)}S(),f=setTimeout(()=>{a?.kill(`SIGTERM`)},1e4)}},N=async r=>{n.info(r,`gateway supervisor continuing prepared update`),console.log(`[gateway] applying update to ${r.targetVersion}...`);let i=await Ug(r.stateFilePath,{logger:n}),a=i.updated&&i.update.install.binPath?dg(i.update.install,`__worker`,e.args,t.cwd):ug(t,`__worker`,e.args);n.info({updated:i.updated,update:i.update,nextInvocation:a},`gateway supervisor prepared next worker invocation`),!i.updated&&i.update.lastError&&console.error(`[gateway] update failed: ${i.update.lastError}`),i.updated?console.log(`[gateway] update installed; restarting worker...`):console.log(`[gateway] relaunching current worker after failed update.`),u=null,b=a,I(a)},P=(e,t)=>{if(S(),T(),n.info({workerPid:a?.pid??void 0,code:e,signal:t,preparedUpdate:u,shuttingDown:l},`gateway supervisor observed worker exit`),a=null,u){D(Error(`gateway worker restarting for update`)),N(u).catch(e=>{n.error({error:e,preparedUpdate:u},`gateway update handoff failed`),console.error(`[gateway] update handoff failed: ${String(e)}`),O(1)});return}if(l){O(0);return}D(Error(`gateway worker exited`)),t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),j(`worker_exit`,{code:e,signal:t})},F=t=>{switch(t.type){case`worker.ready`:if(g=0,C(),!o){o=!0,w(),n.info(t.payload,`gateway supervisor received initial worker ready`),console.log(Pg({configPath:e.loaded.configPath,createdDefaultConfig:e.loaded.createdDefaultConfig,config:e.loaded.config,doctorReport:e.doctorReport,startedServer:t.payload,logToConsole:e.args.logToConsole})),s?.(),s=null,c=null;return}n.info(t.payload,`gateway supervisor received worker ready after update`),console.log(`[gateway] worker ready after update.`);return;case`worker.response`:{let e=r.get(t.id);if(!e)return;r.delete(t.id),t.ok?e.resolve(t.result):e.reject(Error(t.error));return}case`worker.update.prepared`:if(u)return;u=t.payload,n.info(t.payload,`gateway supervisor received worker update prepared`),T(),d=setTimeout(()=>{M(`update`)},250);return}},I=e=>{b=e,C(),_+=1,n.info(e,`gateway supervisor spawning worker`);let t=(0,h.spawn)(e.command,e.args,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0});a=t,n.info({workerPid:t.pid??void 0,invocation:e},`gateway supervisor spawned worker`),t.stdout&&t.stdout.pipe(y.default.stdout),t.stderr&&t.stderr.pipe(y.default.stderr),t.on(`message`,e=>{let t=v_(e);t&&F(t)}),t.on(`exit`,(e,n)=>{a===t&&(k(t),P(e,n))}),t.on(`error`,r=>{a===t&&(k(t),a=null,n.error({error:r,invocation:e},`gateway supervisor failed to launch worker`),console.error(`[gateway] failed to launch worker: ${String(r)}`),j(`worker_launch_error`,{error:r}))})},L=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`gateway.update.apply`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},R=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`codex.appServer.restart`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},z=e=>{if(!l){if(l=!0,n.info({signal:e},`gateway supervisor received shutdown signal`),console.log(`[gateway] received ${e}; shutting down...`),!a){O(0);return}M(`signal`)}};y.default.on(`SIGINT`,z),y.default.on(`SIGTERM`,z),m=setTimeout(()=>{A()},m_),I(b);try{await x}catch(e){throw y.default.removeListener(`SIGINT`,z),y.default.removeListener(`SIGTERM`,z),w(),T(),S(),C(),D(Error(`gateway supervisor failed to start`)),E(),n.close(),e}}function g_(e){if(!e.enabled)return()=>{};let t=v.default.createInterface({input:y.default.stdin,output:y.default.stdout,terminal:!0});return t.on(`line`,t=>{let n=t.trim().toLowerCase();if(n===`update`){e.onUpdate();return}if(n===`restart codex`||n===`codex restart`){e.onRestartCodex();return}}),()=>{t.close()}}function __(){return{pid:y.default.pid,cwd:y.default.cwd(),argv:y.default.argv.slice(2),execArgv:[...y.default.execArgv],execPath:y.default.execPath,scriptPath:y.default.argv[1]??null}}function v_(e){if(!y_(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return y_(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||typeof e.ok!=`boolean`?null:e.ok?(e.method,{type:`worker.response`,id:e.id,method:e.method,ok:!0,result:e.result}):typeof e.error==`string`?{type:`worker.response`,id:e.id,method:e.method,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!y_(e.payload)||typeof e.payload.stateFilePath!=`string`||typeof e.payload.targetVersion!=`string`||e.payload.requestedBy!==`console`&&e.payload.requestedBy!==`mobile`&&e.payload.requestedBy!==`system`?null:{type:`worker.update.prepared`,payload:{stateFilePath:e.payload.stateFilePath,targetVersion:e.payload.targetVersion,requestedBy:e.payload.requestedBy}};default:return null}}function y_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function b_(e){let t=f.default.hostname();u.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=(n,r,i)=>{let a={level:n,time:Date.now(),pid:y.default.pid,hostname:t,...x_(r),msg:i??``};try{u.default.appendFileSync(e,`${JSON.stringify(a,S_)}\n`,`utf8`)}catch{}};return{info:(e,t)=>{n(30,e,t)},warn:(e,t)=>{n(40,e,t)},error:(e,t)=>{n(50,e,t)},close:()=>{}}}function x_(e){return y_(e)?e:{detail:e}}function S_(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t==`bigint`?t.toString():t}async function C_(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function w_(e,t){let n=t.httpsEnabled?t.httpsPort:t.port,r=t.httpsEnabled?`https`:`http`,i=e;return i?.code===`EADDRINUSE`?`[gateway] failed to start: ${r.toUpperCase()} ${t.host}:${n} is already in use.`:i?.code===`EACCES`?`[gateway] failed to start: permission denied for ${r.toUpperCase()} ${t.host}:${n}.`:i?.code===`ENOENT`||i?.code===`EISDIR`?`[gateway] failed to start: log path is invalid or unavailable: ${t.gatewayLogPath}`:i instanceof Error?`[gateway] failed to start: ${i.message}`:`[gateway] failed to start: ${String(e)}`}var T_=o(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),E_=o(((e,t)=>{var n=T_();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:w,abort:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(){var e=s;for(s=null,c=null;e;){var t=e.next,n=e.callback,r=e.errorHandler,a=e.value,o=e.context;e.value=null,e.callback=i,e.errorHandler=null,r&&r(Error(`abort`),a),n.call(o,Error(`abort`)),e.release(e),e=t}d.drain=i}function w(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),D_=o(((e,t)=>{let{format:n}=require(`node:util`);function r(){return`${this.name} [${this.code}]: ${this.message}`}let i=Symbol.for(`fastify-error-generic`);function a(e,t,o=500,s=Error,c=a.captureStackTrace){let l=e===i;if(l&&(e=`FST_ERR`),!e)throw Error(`Fastify error code must not be empty`);if(!t)throw Error(`Fastify error message must not be empty`);e=e.toUpperCase(),!o&&(o=void 0);let u=Symbol.for(`fastify-error ${e}`);function d(...r){if(!new.target)return new d(...r);this.code=e,this.name=`FastifyError`,this.statusCode=o;let i=r.length-1;i!==-1&&r[i]&&typeof r[i]==`object`&&`cause`in r[i]&&(this.cause=r.pop().cause),this.message=n(t,...r),Error.stackTraceLimit&&c&&Error.captureStackTrace(this,d)}return d.prototype=Object.create(s.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0},[i]:{value:!0,enumerable:!1,writable:!1,configurable:!1},[u]:{value:!0,enumerable:!1,writable:!1,configurable:!1}}),l?Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[i]},configurable:!1,writable:!1,enumerable:!1}):Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[u]},configurable:!1,writable:!1,enumerable:!1}),d.prototype[Symbol.toStringTag]=`Error`,d.prototype.toString=r,d}a.captureStackTrace=!0;let o=a(i,`Fastify Error`,500,Error);t.exports=a,t.exports.FastifyError=o,t.exports.default=a,t.exports.createError=a})),O_=o(((e,t)=>{let{createError:n}=D_();t.exports={AVV_ERR_EXPOSE_ALREADY_DEFINED:n(`AVV_ERR_EXPOSE_ALREADY_DEFINED`,`'%s' is already defined, specify an expose option for '%s'`),AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:n(`AVV_ERR_ATTRIBUTE_ALREADY_DEFINED`,`'%s' is already defined`),AVV_ERR_CALLBACK_NOT_FN:n(`AVV_ERR_CALLBACK_NOT_FN`,`Callback for '%s' hook is not a function. Received: '%s'`),AVV_ERR_PLUGIN_NOT_VALID:n(`AVV_ERR_PLUGIN_NOT_VALID`,`Plugin must be a function or a promise. Received: '%s'`),AVV_ERR_ROOT_PLG_BOOTED:n(`AVV_ERR_ROOT_PLG_BOOTED`,`Root plugin has already booted`),AVV_ERR_PARENT_PLG_LOADED:n(`AVV_ERR_PARENT_PLG_LOADED`,`Impossible to load '%s' plugin because the parent '%s' was already loaded`),AVV_ERR_READY_TIMEOUT:n(`AVV_ERR_READY_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`),AVV_ERR_PLUGIN_EXEC_TIMEOUT:n(`AVV_ERR_PLUGIN_EXEC_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`)}})),k_=o(((e,t)=>{t.exports={kAvvio:Symbol(`avvio.Boot`),kIsOnCloseHandler:Symbol(`isOnCloseHandler`),kThenifyDoNotWrap:Symbol(`avvio.ThenifyDoNotWrap`),kUntrackNode:Symbol(`avvio.TimeTree.untrackNode`),kTrackNode:Symbol(`avvio.TimeTree.trackNode`),kGetParent:Symbol(`avvio.TimeTree.getParent`),kGetNode:Symbol(`avvio.TimeTree.getNode`),kAddNode:Symbol(`avvio.TimeTree.addNode`),kPluginMeta:Symbol.for(`plugin-meta`)}})),A_=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=k_();var s=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[r](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[n](e){this.tableId.delete(e.id);let t=this.tableLabel.get(e.label);t.pop(),t.length===0&&this.tableLabel.delete(e.label)}[i](e){if(e===null)return null;if(this.tableLabel.has(e)){let t=this.tableLabel.get(e);return t[t.length-1]}else return null}[a](e){return this.tableId.get(e)}[o](e,t,n){let a=this[i](e);if(a===null)return this.root={parent:null,id:`root`,label:t,nodes:[],start:n,stop:null,diff:-1},this[r](this.root),this.root.id;let o=`${t}-${Math.random()}`,s={parent:e,id:o,label:t,nodes:[],start:n,stop:null,diff:-1};return a.nodes.push(s),this[r](s),o}start(e,t,n=Date.now()){return this[o](e,t,n)}stop(e,t=Date.now()){let r=this[a](e);r&&(r.stop=t,r.diff=r.stop-r.start||0,this[n](r))}toJSON(){return Object.assign({},this.root)}prettyPrint(){return c(this.toJSON())}};function c(e,t=``){let n=t,r=e.nodes.length,i=r-1;n+=`${e.label} ${e.diff} ms\n`;for(let a=0;a<r;++a){let r=e.nodes[a],o=t+(a===i?` `:`│ `);n+=t,n+=a===i?`└─`:`├─`,n+=r.nodes.length===0?`─ `:`┬ `,n+=c(r,o).slice(t.length+2)}return n}t.exports={TimeTree:s}})),j_=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),M_=o(((e,t)=>{function n(){let e={resolve:null,reject:null,promise:null};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}t.exports={createPromise:n}})),N_=o(((e,t)=>{let{kPluginMeta:n}=k_();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
|
|
148
148
|
`).slice(0,2).map(e=>e.trim()).join(` -- `)}t.exports={getPluginName:r}})),P_=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}t.exports={isPromiseLike:n}})),F_=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{inherits:r}=require(`node:util`),{debug:i}=j_(),{createPromise:a}=M_(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:o}=O_(),{getPluginName:s}=N_(),{isPromiseLike:c}=P_();function l(e,t,n,r,i){this.queue=e,this.func=t,this.options=n,this.isAfter=r,this.timeout=i,this.started=!1,this.name=s(t,n),this.queue.pause(),this._error=null,this.loaded=!1,this._promise=null,this.startTime=null}r(l,n),l.prototype.exec=function(e,t){i(`exec`,this.name),this.server=e;let n=this.func,r=this.name,a=!1;this.options=typeof this.options==`function`?this.options(this.server):this.options;let s=null,l=e=>{if(a){i(`loading complete`,r);return}this._error=e,i(e?`exec errored`:`exec completed`,r),a=!0,s&&clearTimeout(s),t(e)};this.timeout>0&&(i(`setting up timeout`,r,this.timeout),s=setTimeout(function(){i(`timed out`,r),s=null;let e=new o(r);e.fn=n,l(e)},this.timeout)),this.started=!0,this.startTime=Date.now(),this.emit(`start`,this.server?this.server.name:null,this.name,Date.now());let u=n(this.server,this.options,l);c(u)?(i(`exec: resolving promise`,r),u.then(()=>process.nextTick(l),e=>process.nextTick(l,e))):n.length<3&&l()},l.prototype.loadedSoFar=function(){if(i(`loadedSoFar`,this.name),this.loaded)return Promise.resolve();let e=()=>{this.server.after((e,t)=>{this._error=e,this.queue.pause(),this._promise&&=(e?(i(`rejecting promise`,this.name,e),this._promise.reject(e)):(i(`resolving promise`,this.name),this._promise.resolve()),null),process.nextTick(t,e)}),this.queue.resume()},t;return this._promise?t=Promise.resolve():(this._promise=a(),t=this._promise.promise,this.server?e():this.on(`start`,e)),t},l.prototype.enqueue=function(e,t){i(`enqueue`,this.name,e.name),this.emit(`enqueue`,this.server?this.server.name:null,this.name,Date.now()),this.queue.push(e,t)},l.prototype.finish=function(e,t){i(`finish`,this.name,e);let n=()=>{this.loaded||(i(`loaded`,this.name),this.emit(`loaded`,this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,t(e))};if(e){this._promise&&=(this._promise.reject(e),null),n();return}let r=()=>{if(i(`check`,this.name,this.queue.length(),this.queue.running(),this._promise),this.queue.length()===0&&this.queue.running()===0)if(this._promise){let e=()=>{i(`wrap`),queueMicrotask(r)};this._promise.resolve(),this._promise.promise.then(e,e),this._promise=null}else n();else i(`delayed`,this.name),this.queue.drain=()=>{i(`drain`,this.name),this.queue.drain=u,queueMicrotask(r)}};queueMicrotask(r),this.queue.resume()};function u(){}t.exports={Plugin:l}})),I_=o(((e,t)=>{let{AVV_ERR_PLUGIN_NOT_VALID:n}=O_();function r(e){if(!(e&&(typeof e==`function`||typeof e.then==`function`)))throw Array.isArray(e)?new n(`array`):e===null?new n(`null`):new n(typeof e)}t.exports={validatePlugin:r}})),L_=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.default==`function`}t.exports={isBundledOrTypescriptPlugin:n}})),R_=o(((e,t)=>{let{debug:n}=j_(),{kThenifyDoNotWrap:r}=k_();function i(){if(this.booted){n(`thenify returning undefined because we are already booted`);return}if(this[r]){this[r]=!1;return}return n(`thenify`),(e,t)=>this._loadRegistered().then(()=>(this[r]=!0,e(this._server)),t)}t.exports={thenify:i}})),z_=o(((e,t)=>{let{isPromiseLike:n}=P_(),{kAvvio:r}=k_();function i(e,t,i){let a;try{a=e.apply(e,t)}catch(e){i&&process.nextTick(i,e);return}n(a)&&!a[r]?a.then(()=>process.nextTick(i),e=>process.nextTick(i,e)):i&&process.nextTick(i)}t.exports={executeWithThenable:i}})),B_=o(((e,t)=>{let n=E_(),r=require(`node:events`).EventEmitter,i=require(`node:util`).inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:a,AVV_ERR_CALLBACK_NOT_FN:o,AVV_ERR_ROOT_PLG_BOOTED:s,AVV_ERR_READY_TIMEOUT:c,AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:l}=O_(),{kAvvio:u,kIsOnCloseHandler:d}=k_(),{TimeTree:f}=A_(),{Plugin:p}=F_(),{debug:m}=j_(),{validatePlugin:h}=I_(),{isBundledOrTypescriptPlugin:g}=L_(),{isPromiseLike:_}=P_(),{thenify:v}=R_(),{executeWithThenable:y}=z_();function b(e,t,r){if(typeof e==`function`&&arguments.length===1&&(r=e,t={},e=null),typeof t==`function`&&(r=t,t={}),t||={},t.autostart=t.autostart!==!1,t.timeout=Number(t.timeout)||0,t.expose=t.expose||{},!new.target)return new b(e,t,r);this._server=e||this,this._opts=t,e&&this._expose(),this._current=[],this._error=null,this._lastUsed=null,this.setMaxListeners(0),r&&this.once(`start`,r),this.started=!1,this.booted=!1,this.pluginTree=new f,this._readyQ=n(this,S,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit(`start`),this._readyQ.drain=x},this._closeQ=n(this,w,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit(`close`),this._closeQ.drain=x},this._doStart=null;let i=this;this._root=new p(n(this,this._loadPluginNextTick,1),function(e,t,n){i._doStart=n,t.autostart&&i.start()},t,!1,0),this._trackPluginLoading(this._root),this._loadPlugin(this._root,e=>{m(`root plugin ready`);try{this.emit(`preReady`),this._root=null}catch(t){e=e||this._error||t}if(e){if(this._error=e,this._readyQ.length()===0)throw e}else this.booted=!0;this._readyQ.resume()})}i(b,r),`asyncDispose`in Symbol&&(b.prototype[Symbol.asyncDispose]=function(){return new Promise((e,t)=>{this.close(n=>{if(n)return t(n);e()})})}),b.prototype.start=function(){return this.started=!0,process.nextTick(this._doStart),this},b.prototype.override=function(e,t,n){return e},b.prototype[u]=!0,b.prototype.use=function(e,t){return this._lastUsed=this._addPlugin(e,t,!1),this},b.prototype._loadRegistered=function(){let e=this._current[0];return!this.started&&!this.booted&&process.nextTick(()=>this._root.queue.resume()),e?e.loadedSoFar():Promise.resolve()},Object.defineProperty(b.prototype,`then`,{get:v}),b.prototype._addPlugin=function(e,t,r){if(g(e)&&(e=e.default),h(e),t||={},this.booted)throw new s;let i=this._current[0],a=this._opts.timeout;if(!i.loaded&&i.timeout>0){let e=Date.now()-i.startTime;a=i.timeout-(e+3)}let o=new p(n(this,this._loadPluginNextTick,1),e,t,r,a);if(this._trackPluginLoading(o),i.loaded)throw Error(o.name,i.name);return i.enqueue(o,e=>{e&&(this._error=e)}),o},b.prototype._expose=function(){let e=this,t=e._server,{use:n=`use`,after:r=`after`,ready:i=`ready`,onClose:s=`onClose`,close:c=`close`}=this._opts.expose;if(t[n])throw new a(n,`use`);if(t[n]=function(t,n){return e.use(t,n),this},t[r])throw new a(r,`after`);if(t[r]=function(t){return typeof t==`function`?(e.after(E(t,this)),this):e._loadRegistered()},t[i])throw new a(i,`ready`);if(t[i]=function(t){if(t&&typeof t!=`function`)throw new o(i,typeof t);return e.ready(t?E(t,this):void 0)},t[s])throw new a(s,`onClose`);if(t[s]=function(t){if(typeof t!=`function`)throw new o(s,typeof t);return e.onClose(T(t,this)),this},t[c])throw new a(c,`close`);if(t[c]=function(t){if(t&&typeof t!=`function`)throw new o(c,typeof t);return t?(e.close(E(t,this)),this):e.close()},t.then)throw new l(`then`);Object.defineProperty(t,`then`,{get:v.bind(e)}),t[u]=!0},b.prototype.after=function(e){if(!e)return this._loadRegistered();this._addPlugin(t.bind(this),{},!0);function t(t,n,r){S.call(this,e,r)}return this},b.prototype.onClose=function(e){if(typeof e!=`function`)throw new o(`onClose`,typeof e);return e[d]=!0,this._closeQ.unshift(e,e=>{e&&(this._error=e)}),this},b.prototype.close=function(e){let t;if(e){if(typeof e!=`function`)throw new o(`close`,typeof e)}else t=new Promise(function(t,n){e=function(e){if(e)return n(e);t()}});return this.ready(()=>{this._error=null,this._closeQ.push(e),process.nextTick(this._closeQ.resume.bind(this._closeQ))}),t},b.prototype.ready=function(e){if(e){if(typeof e!=`function`)throw new o(`ready`,typeof e);this._readyQ.push(e),queueMicrotask(this.start.bind(this));return}return new Promise((e,t)=>{this._readyQ.push(r),this.start();let n=this._current[0].server;function r(r,i,a){r?t(r):e(n),process.nextTick(a)}})},b.prototype._trackPluginLoading=function(e){let t=this._current[0]?.name||null;e.once(`start`,(n,r,i)=>{let a=this.pluginTree.start(t||null,r,i);e.once(`loaded`,(e,t,n)=>{this.pluginTree.stop(a,n)})})},b.prototype.prettyPrint=function(){return this.pluginTree.prettyPrint()},b.prototype.toJSON=function(){return this.pluginTree.toJSON()},b.prototype._loadPlugin=function(e,t){let n=this;if(_(e.func)){e.func.then(n=>{typeof n.default==`function`&&(n=n.default),e.func=n,this._loadPlugin(e,t)},t);return}let r=n._current[0];if(n._current.unshift(e),n._error&&!e.isAfter){m(`skipping loading of plugin as instance errored and it is not an after`,e.name),process.nextTick(a);return}let i=r?.server||n._server;if(!e.isAfter)try{i=n.override(i,e.func,e.options)}catch(t){return m(`override errored`,e.name),a(t)}e.exec(i,a);function a(r){e.finish(r,e=>{n._current.shift(),t(e)})}},b.prototype._loadPluginNextTick=function(e,t){process.nextTick(this._loadPlugin.bind(this),e,t)};function x(){}function S(e,t){let n=this._server,r=this._error;if(this._error=null,e.length===0)this._error=r,y(e,[],t);else if(e.length===1)y(e,[r],t);else if(this._opts.timeout===0){let i=e=>{this._error=e,t(this._error)};e.length===2?e(r,i):e(r,n,i)}else C.call(this,e,r,n,t)}function C(e,t,n,r){let i=e.unwrappedName??e.name;m(`setting up ready timeout`,i,this._opts.timeout);let a=setTimeout(()=>{m(`timed out`,i),a=null;let t=new c(i);t.fn=e,this._error=t,r(t)},this._opts.timeout);e.length===2?e(t,o.bind(this)):e(t,n,o.bind(this));function o(e){a&&(clearTimeout(a),this._error=e,r(this._error))}}function w(e,t){let n=this._server,r=e[d];if(e.length===0||e.length===1){let i;i=e(r?n:this._error),i&&typeof i.then==`function`?(m(`resolving close/onClose promise`),i.then(()=>process.nextTick(t),e=>process.nextTick(t,e))):process.nextTick(t)}else e.length===2?e(r?n:this._error,t):r?e(n,t):e(this._error,n,t)}function T(e,t){return n.bind(t);function n(t,n){let r;e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===1?(r=e(this),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e(this,n)}}function E(e,t){let n=r.bind(t);return n.unwrappedName=e.name,n;function r(t,n){let r;e?e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n,t)},n):process.nextTick(n,t)):e.length===1?(r=e(t),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===2?e(t,n):e(t,this,n):process.nextTick(n)}}t.exports=b})),V_=o(((e,t)=>{t.exports={kAvvioBoot:Symbol(`fastify.avvioBoot`),kChildren:Symbol(`fastify.children`),kServerBindings:Symbol(`fastify.serverBindings`),kBodyLimit:Symbol(`fastify.bodyLimit`),kSupportedHTTPMethods:Symbol(`fastify.acceptedHTTPMethods`),kRoutePrefix:Symbol(`fastify.routePrefix`),kLogLevel:Symbol(`fastify.logLevel`),kLogSerializers:Symbol(`fastify.logSerializers`),kHooks:Symbol(`fastify.hooks`),kContentTypeParser:Symbol(`fastify.contentTypeParser`),kState:Symbol(`fastify.state`),kOptions:Symbol(`fastify.options`),kDisableRequestLogging:Symbol(`fastify.disableRequestLogging`),kPluginNameChain:Symbol(`fastify.pluginNameChain`),kRouteContext:Symbol(`fastify.context`),kGenReqId:Symbol(`fastify.genReqId`),kHttp2ServerSessions:Symbol(`fastify.http2ServerSessions`),kSchemaController:Symbol(`fastify.schemaController`),kSchemaHeaders:Symbol(`headers-schema`),kSchemaParams:Symbol(`params-schema`),kSchemaQuerystring:Symbol(`querystring-schema`),kSchemaBody:Symbol(`body-schema`),kSchemaResponse:Symbol(`response-schema`),kSchemaErrorFormatter:Symbol(`fastify.schemaErrorFormatter`),kSchemaVisited:Symbol(`fastify.schemas.visited`),kRequest:Symbol(`fastify.Request`),kRequestPayloadStream:Symbol(`fastify.RequestPayloadStream`),kRequestAcceptVersion:Symbol(`fastify.RequestAcceptVersion`),kRequestCacheValidateFns:Symbol(`fastify.request.cache.validateFns`),kRequestOriginalUrl:Symbol(`fastify.request.originalUrl`),kFourOhFour:Symbol(`fastify.404`),kCanSetNotFoundHandler:Symbol(`fastify.canSetNotFoundHandler`),kFourOhFourLevelInstance:Symbol(`fastify.404LogLevelInstance`),kFourOhFourContext:Symbol(`fastify.404ContextKey`),kDefaultJsonParse:Symbol(`fastify.defaultJSONParse`),kReply:Symbol(`fastify.Reply`),kReplySerializer:Symbol(`fastify.reply.serializer`),kReplyIsError:Symbol(`fastify.reply.isError`),kReplyHeaders:Symbol(`fastify.reply.headers`),kReplyTrailers:Symbol(`fastify.reply.trailers`),kReplyHasStatusCode:Symbol(`fastify.reply.hasStatusCode`),kReplyHijacked:Symbol(`fastify.reply.hijacked`),kReplyStartTime:Symbol(`fastify.reply.startTime`),kReplyNextErrorHandler:Symbol(`fastify.reply.nextErrorHandler`),kReplyEndTime:Symbol(`fastify.reply.endTime`),kReplyErrorHandlerCalled:Symbol(`fastify.reply.errorHandlerCalled`),kReplyIsRunningOnErrorHook:Symbol(`fastify.reply.isRunningOnErrorHook`),kReplySerializerDefault:Symbol(`fastify.replySerializerDefault`),kReplyCacheSerializeFns:Symbol(`fastify.reply.cache.serializeFns`),kTestInternals:Symbol(`fastify.testInternals`),kErrorHandler:Symbol(`fastify.errorHandler`),kErrorHandlerAlreadySet:Symbol(`fastify.errorHandlerAlreadySet`),kChildLoggerFactory:Symbol(`fastify.childLoggerFactory`),kHasBeenDecorated:Symbol(`fastify.hasBeenDecorated`),kKeepAliveConnections:Symbol(`fastify.keepAliveConnections`),kRouteByFastify:Symbol(`fastify.routeByFastify`)}})),H_=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),U_=o(((e,t)=>{let{createWarning:n}=H_();t.exports={FSTWRN001:n({name:`FastifyWarning`,code:`FSTWRN001`,message:`The %s schema for %s: %s is missing. This may indicate the schema is not well specified.`,unlimited:!0}),FSTWRN003:n({name:`FastifyWarning`,code:`FSTWRN003`,message:`The %s mixes async and callback styles that may lead to unhandled rejections. Please use only one of them.`,unlimited:!0}),FSTWRN004:n({name:`FastifyWarning`,code:`FSTWRN004`,message:`It seems that you are overriding an errorHandler in the same scope, which can lead to subtle bugs.`,unlimited:!0}),FSTSEC001:n({name:`FastifySecurity`,code:`FSTSEC001`,message:`You are using /%s/ Content-Type which may be vulnerable to CORS attack. Please make sure your RegExp start with "^" or include ";?" to proper detection of the essence MIME type.`,unlimited:!0}),FSTDEP022:n({name:`FastifyWarning`,code:`FSTDEP022`,message:'The router options for %s property access is deprecated. Please use "options.routerOptions" instead for accessing router options. The router options will be removed in `fastify@6`.',unlimited:!0})}})),W_=o(((e,t)=>{let n=D_(),r={FST_ERR_NOT_FOUND:n(`FST_ERR_NOT_FOUND`,`Not Found`,404),FST_ERR_OPTIONS_NOT_OBJ:n(`FST_ERR_OPTIONS_NOT_OBJ`,`Options must be an object`,500,TypeError),FST_ERR_QSP_NOT_FN:n(`FST_ERR_QSP_NOT_FN`,`querystringParser option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:n(`FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN`,`schemaController.bucket option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:n(`FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN`,`schemaErrorFormatter option should be a non async function. Instead got '%s'.`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ`,`ajv.customOptions option should be an object, instead got '%s'`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR`,`ajv.plugins option should be an array, instead got '%s'`,500,TypeError),FST_ERR_VALIDATION:n(`FST_ERR_VALIDATION`,`%s`,400),FST_ERR_LISTEN_OPTIONS_INVALID:n(`FST_ERR_LISTEN_OPTIONS_INVALID`,`Invalid listen options: '%s'`,500,TypeError),FST_ERR_ERROR_HANDLER_NOT_FN:n(`FST_ERR_ERROR_HANDLER_NOT_FN`,`Error Handler must be a function`,500,TypeError),FST_ERR_ERROR_HANDLER_ALREADY_SET:n(`FST_ERR_ERROR_HANDLER_ALREADY_SET`,`Error Handler already set in this scope. Set 'allowErrorHandlerOverride: true' to allow overriding.`,500,TypeError),FST_ERR_CTP_ALREADY_PRESENT:n(`FST_ERR_CTP_ALREADY_PRESENT`,`Content type parser '%s' already present.`),FST_ERR_CTP_INVALID_TYPE:n(`FST_ERR_CTP_INVALID_TYPE`,`The content type should be a string or a RegExp`,500,TypeError),FST_ERR_CTP_EMPTY_TYPE:n(`FST_ERR_CTP_EMPTY_TYPE`,`The content type cannot be an empty string`,500,TypeError),FST_ERR_CTP_INVALID_HANDLER:n(`FST_ERR_CTP_INVALID_HANDLER`,`The content type handler should be a function`,500,TypeError),FST_ERR_CTP_INVALID_PARSE_TYPE:n(`FST_ERR_CTP_INVALID_PARSE_TYPE`,`The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.`,500,TypeError),FST_ERR_CTP_BODY_TOO_LARGE:n(`FST_ERR_CTP_BODY_TOO_LARGE`,`Request body is too large`,413,RangeError),FST_ERR_CTP_INVALID_MEDIA_TYPE:n(`FST_ERR_CTP_INVALID_MEDIA_TYPE`,`Unsupported Media Type: %s`,415),FST_ERR_CTP_INVALID_CONTENT_LENGTH:n(`FST_ERR_CTP_INVALID_CONTENT_LENGTH`,`Request body size did not match Content-Length`,400,RangeError),FST_ERR_CTP_EMPTY_JSON_BODY:n(`FST_ERR_CTP_EMPTY_JSON_BODY`,`Body cannot be empty when content-type is set to 'application/json'`,400),FST_ERR_CTP_INVALID_JSON_BODY:n(`FST_ERR_CTP_INVALID_JSON_BODY`,`Body is not valid JSON but content-type is set to 'application/json'`,400),FST_ERR_CTP_INSTANCE_ALREADY_STARTED:n(`FST_ERR_CTP_INSTANCE_ALREADY_STARTED`,`Cannot call "%s" when fastify instance is already started!`,400),FST_ERR_DEC_ALREADY_PRESENT:n(`FST_ERR_DEC_ALREADY_PRESENT`,`The decorator '%s' has already been added!`),FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:n(`FST_ERR_DEC_DEPENDENCY_INVALID_TYPE`,`The dependencies of decorator '%s' must be of type Array.`,500,TypeError),FST_ERR_DEC_MISSING_DEPENDENCY:n(`FST_ERR_DEC_MISSING_DEPENDENCY`,`The decorator is missing dependency '%s'.`),FST_ERR_DEC_AFTER_START:n(`FST_ERR_DEC_AFTER_START`,`The decorator '%s' has been added after start!`),FST_ERR_DEC_REFERENCE_TYPE:n(`FST_ERR_DEC_REFERENCE_TYPE`,`The decorator '%s' of type '%s' is a reference type. Use the { getter, setter } interface instead.`),FST_ERR_DEC_UNDECLARED:n(`FST_ERR_DEC_UNDECLARED`,`No decorator '%s' has been declared on %s.`),FST_ERR_HOOK_INVALID_TYPE:n(`FST_ERR_HOOK_INVALID_TYPE`,`The hook name must be a string`,500,TypeError),FST_ERR_HOOK_INVALID_HANDLER:n(`FST_ERR_HOOK_INVALID_HANDLER`,`%s hook should be a function, instead got %s`,500,TypeError),FST_ERR_HOOK_INVALID_ASYNC_HANDLER:n(`FST_ERR_HOOK_INVALID_ASYNC_HANDLER`,`Async function has too many arguments. Async hooks should not use the 'done' argument.`,500,TypeError),FST_ERR_HOOK_NOT_SUPPORTED:n(`FST_ERR_HOOK_NOT_SUPPORTED`,`%s hook not supported!`,500,TypeError),FST_ERR_MISSING_MIDDLEWARE:n(`FST_ERR_MISSING_MIDDLEWARE`,`You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.`,500),FST_ERR_HOOK_TIMEOUT:n(`FST_ERR_HOOK_TIMEOUT`,`A callback for '%s' hook%s timed out. You may have forgotten to call 'done' function or to resolve a Promise`),FST_ERR_LOG_INVALID_DESTINATION:n(`FST_ERR_LOG_INVALID_DESTINATION`,`Cannot specify both logger.stream and logger.file options`),FST_ERR_LOG_INVALID_LOGGER:n(`FST_ERR_LOG_INVALID_LOGGER`,`Invalid logger object provided. The logger instance should have these functions(s): '%s'.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_INSTANCE:n(`FST_ERR_LOG_INVALID_LOGGER_INSTANCE`,`loggerInstance only accepts a logger instance.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_CONFIG:n(`FST_ERR_LOG_INVALID_LOGGER_CONFIG`,`logger options only accepts a configuration object.`,500,TypeError),FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:n(`FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED`,`You cannot provide both logger and loggerInstance. Please provide only one.`,500,TypeError),FST_ERR_REP_INVALID_PAYLOAD_TYPE:n(`FST_ERR_REP_INVALID_PAYLOAD_TYPE`,`Attempted to send payload of invalid type '%s'. Expected a string or Buffer.`,500,TypeError),FST_ERR_REP_RESPONSE_BODY_CONSUMED:n(`FST_ERR_REP_RESPONSE_BODY_CONSUMED`,`Response.body is already consumed.`),FST_ERR_REP_READABLE_STREAM_LOCKED:n(`FST_ERR_REP_READABLE_STREAM_LOCKED`,`ReadableStream was locked. You should call releaseLock() method on reader before sending.`),FST_ERR_REP_ALREADY_SENT:n(`FST_ERR_REP_ALREADY_SENT`,`Reply was already sent, did you forget to "return reply" in "%s" (%s)?`),FST_ERR_REP_SENT_VALUE:n(`FST_ERR_REP_SENT_VALUE`,`The only possible value for reply.sent is true.`,500,TypeError),FST_ERR_SEND_INSIDE_ONERR:n(`FST_ERR_SEND_INSIDE_ONERR`,"You cannot use `send` inside the `onError` hook"),FST_ERR_SEND_UNDEFINED_ERR:n(`FST_ERR_SEND_UNDEFINED_ERR`,`Undefined error has occurred`),FST_ERR_BAD_STATUS_CODE:n(`FST_ERR_BAD_STATUS_CODE`,`Called reply with an invalid status code: %s`),FST_ERR_BAD_TRAILER_NAME:n(`FST_ERR_BAD_TRAILER_NAME`,`Called reply.trailer with an invalid header name: %s`),FST_ERR_BAD_TRAILER_VALUE:n(`FST_ERR_BAD_TRAILER_VALUE`,`Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function.`),FST_ERR_FAILED_ERROR_SERIALIZATION:n(`FST_ERR_FAILED_ERROR_SERIALIZATION`,`Failed to serialize an error. Error: %s. Original error: %s`),FST_ERR_MISSING_SERIALIZATION_FN:n(`FST_ERR_MISSING_SERIALIZATION_FN`,`Missing serialization function. Key "%s"`),FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:n(`FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN`,`Missing serialization function. Key "%s:%s"`),FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:n(`FST_ERR_REQ_INVALID_VALIDATION_INVOCATION`,`Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.`),FST_ERR_SCH_MISSING_ID:n(`FST_ERR_SCH_MISSING_ID`,`Missing schema $id property`),FST_ERR_SCH_ALREADY_PRESENT:n(`FST_ERR_SCH_ALREADY_PRESENT`,`Schema with id '%s' already declared!`),FST_ERR_SCH_CONTENT_MISSING_SCHEMA:n(`FST_ERR_SCH_CONTENT_MISSING_SCHEMA`,`Schema is missing for the content type '%s'`),FST_ERR_SCH_DUPLICATE:n(`FST_ERR_SCH_DUPLICATE`,`Schema with '%s' already present!`),FST_ERR_SCH_VALIDATION_BUILD:n(`FST_ERR_SCH_VALIDATION_BUILD`,`Failed building the validation schema for %s: %s, due to error %s`),FST_ERR_SCH_SERIALIZATION_BUILD:n(`FST_ERR_SCH_SERIALIZATION_BUILD`,`Failed building the serialization schema for %s: %s, due to error %s`),FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:n(`FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX`,`response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }`),FST_ERR_INIT_OPTS_INVALID:n(`FST_ERR_INIT_OPTS_INVALID`,`Invalid initialization options: '%s'`),FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:n(`FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE`,`Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method`),FST_ERR_DUPLICATED_ROUTE:n(`FST_ERR_DUPLICATED_ROUTE`,`Method '%s' already declared for route '%s'`),FST_ERR_BAD_URL:n(`FST_ERR_BAD_URL`,`'%s' is not a valid url component`,400,URIError),FST_ERR_ASYNC_CONSTRAINT:n(`FST_ERR_ASYNC_CONSTRAINT`,`Unexpected error from async constraint`,500),FST_ERR_INVALID_URL:n(`FST_ERR_INVALID_URL`,`URL must be a string. Received '%s'`,400,TypeError),FST_ERR_ROUTE_OPTIONS_NOT_OBJ:n(`FST_ERR_ROUTE_OPTIONS_NOT_OBJ`,`Options for "%s:%s" route must be an object`,500,TypeError),FST_ERR_ROUTE_DUPLICATED_HANDLER:n(`FST_ERR_ROUTE_DUPLICATED_HANDLER`,`Duplicate handler for "%s:%s" route is not allowed!`,500),FST_ERR_ROUTE_HANDLER_NOT_FN:n(`FST_ERR_ROUTE_HANDLER_NOT_FN`,`Error Handler for %s:%s route, if defined, must be a function`,500,TypeError),FST_ERR_ROUTE_MISSING_HANDLER:n(`FST_ERR_ROUTE_MISSING_HANDLER`,`Missing handler function for "%s:%s" route.`,500),FST_ERR_ROUTE_METHOD_INVALID:n(`FST_ERR_ROUTE_METHOD_INVALID`,`Provided method is invalid!`,500,TypeError),FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:n(`FST_ERR_ROUTE_METHOD_NOT_SUPPORTED`,`%s method is not supported.`,500),FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:n(`FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED`,`Body validation schema for %s:%s route is not supported!`,500),FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:n(`FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT`,`'bodyLimit' option must be an integer > 0. Got '%s'`,500,TypeError),FST_ERR_ROUTE_REWRITE_NOT_STR:n(`FST_ERR_ROUTE_REWRITE_NOT_STR`,`Rewrite url for "%s" needs to be of type "string" but received "%s"`,500,TypeError),FST_ERR_REOPENED_CLOSE_SERVER:n(`FST_ERR_REOPENED_CLOSE_SERVER`,`Fastify has already been closed and cannot be reopened`),FST_ERR_REOPENED_SERVER:n(`FST_ERR_REOPENED_SERVER`,`Fastify is already listening`),FST_ERR_INSTANCE_ALREADY_LISTENING:n(`FST_ERR_INSTANCE_ALREADY_LISTENING`,`Fastify instance is already listening. %s`),FST_ERR_PLUGIN_VERSION_MISMATCH:n(`FST_ERR_PLUGIN_VERSION_MISMATCH`,`fastify-plugin: %s - expected '%s' fastify version, '%s' is installed`),FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:n(`FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE`,`The decorator '%s'%s is not present in %s`),FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:n(`FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER`,`The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.`,500,TypeError),FST_ERR_PLUGIN_CALLBACK_NOT_FN:n(`FST_ERR_PLUGIN_CALLBACK_NOT_FN`,`fastify-plugin: %s`,500,TypeError),FST_ERR_PLUGIN_NOT_VALID:n(`FST_ERR_PLUGIN_NOT_VALID`,`fastify-plugin: %s`),FST_ERR_ROOT_PLG_BOOTED:n(`FST_ERR_ROOT_PLG_BOOTED`,`fastify-plugin: %s`),FST_ERR_PARENT_PLUGIN_BOOTED:n(`FST_ERR_PARENT_PLUGIN_BOOTED`,`fastify-plugin: %s`),FST_ERR_PLUGIN_TIMEOUT:n(`FST_ERR_PLUGIN_TIMEOUT`,`fastify-plugin: %s`)};function i(e,t){return t.cause=e,t}t.exports=r,t.exports.appendStackTrace=i,t.exports.AVVIO_ERRORS_MAP={AVV_ERR_CALLBACK_NOT_FN:r.FST_ERR_PLUGIN_CALLBACK_NOT_FN,AVV_ERR_PLUGIN_NOT_VALID:r.FST_ERR_PLUGIN_NOT_VALID,AVV_ERR_ROOT_PLG_BOOTED:r.FST_ERR_ROOT_PLG_BOOTED,AVV_ERR_PARENT_PLG_LOADED:r.FST_ERR_PARENT_PLUGIN_BOOTED,AVV_ERR_READY_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT,AVV_ERR_PLUGIN_EXEC_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT}})),G_=o(((e,t)=>{let n=[`onRoute`,`onRegister`,`onReady`,`onListen`,`preClose`,`onClose`],r=[`onTimeout`,`onRequest`,`preParsing`,`preValidation`,`preSerialization`,`preHandler`,`onSend`,`onResponse`,`onError`,`onRequestAbort`],i=r.concat(n),{FST_ERR_HOOK_INVALID_TYPE:a,FST_ERR_HOOK_INVALID_HANDLER:o,FST_ERR_SEND_UNDEFINED_ERR:s,FST_ERR_HOOK_TIMEOUT:c,FST_ERR_HOOK_NOT_SUPPORTED:l,AVVIO_ERRORS_MAP:u,appendStackTrace:d}=W_(),{kChildren:f,kHooks:p,kRequestPayloadStream:m}=V_();function h(){this.onRequest=[],this.preParsing=[],this.preValidation=[],this.preSerialization=[],this.preHandler=[],this.onResponse=[],this.onSend=[],this.onError=[],this.onRoute=[],this.onRegister=[],this.onReady=[],this.onListen=[],this.onTimeout=[],this.onRequestAbort=[],this.preClose=[]}h.prototype=Object.create(null),h.prototype.validate=function(e,t){if(typeof e!=`string`)throw new a;if(Array.isArray(this[e])===!1)throw new l(e);if(typeof t!=`function`)throw new o(e,Object.prototype.toString.call(t))},h.prototype.add=function(e,t){this.validate(e,t),this[e].push(t)};function g(e){let t=new h;return t.onRequest=e.onRequest.slice(),t.preParsing=e.preParsing.slice(),t.preValidation=e.preValidation.slice(),t.preSerialization=e.preSerialization.slice(),t.preHandler=e.preHandler.slice(),t.onSend=e.onSend.slice(),t.onResponse=e.onResponse.slice(),t.onError=e.onError.slice(),t.onRoute=e.onRoute.slice(),t.onRegister=e.onRegister.slice(),t.onTimeout=e.onTimeout.slice(),t.onRequestAbort=e.onRequestAbort.slice(),t.onReady=[],t.onListen=[],t.preClose=[],t}function _(e,t,n,r){let i=n[p][e],a=0,o=0;l();function s(t){let n=i[a-1]?.name,o=n?` "${n}"`:``;if(t){t=t.code===`AVV_ERR_READY_TIMEOUT`?d(t,new c(e,o)):u[t.code]==null?t:d(t,new u[t.code](t.message)),r(t);return}r()}function l(r){if(r){s(r);return}if(a===i.length&&o===n[f].length){a===0&&o===0?s():t(function(e,t){s(e),t(e)});return}if(a===i.length&&o<n[f].length){let r=n[f][o++];_(e,t,r,l);return}t(m(i[a++],n)),l()}function m(e,t){return function(n,r){if(n){r(n);return}if(e.length===1){try{e.call(t,r)}catch(e){r(e)}return}try{let n=e.call(t);if(n&&typeof n.then==`function`){n.then(r,r);return}}catch(e){n=e}r(n)}}}function v(e){let t=e[p].onListen,n=t.length,r=0,i=0;a();function a(s){if(s&&e.log.error(s),r===n){for(;i<e[f].length;){let t=e[f][i++];v(t)}return}o(t[r++],e,a)}async function o(e,t,n){if(e.length===1){try{e.call(t,n)}catch(e){n(e)}return}try{let r=e.call(t);if(r&&typeof r.then==`function`){r.then(n,n);return}n()}catch(e){n(e)}}}function y(e){return function(t,n,r,i){let a=0;function o(s){if(s||a===t.length){i(s,n,r);return}let u;try{u=e(t[a++],n,r,o)}catch(e){i(e,n,r);return}u&&typeof u.then==`function`&&u.then(c,l)}function c(){o()}function l(e){e||=new s,i(e,n,r)}o()}}function b(e,t,n,r){return e(t,n,r)}let x=y(b),S=y(A),C=y(A),w=y(A),T=y(A);function E(e,t,n,r,i){let a=0;function o(s,u){if(s){i(s,t,n,r);return}if(u!==void 0&&(r=u),a===e.length){i(null,t,n,r);return}let d;try{d=e[a++](t,n,r,o)}catch(e){i(e,t,n);return}d&&typeof d.then==`function`&&d.then(c,l)}function c(e){o(null,e)}function l(e){e||=new s,i(e,t,n,r)}o()}let D=E;function O(e,t,n,r){let i=0;function a(s,l){if(n.sent)return;if(l!==void 0&&(t[m]=l),s||i===e.length){r(s,t,n);return}let u;try{u=e[i++](t,n,t[m],a)}catch(e){r(e,t,n);return}u&&typeof u.then==`function`&&u.then(o,c)}function o(e){a(null,e)}function c(e){e||=new s,r(e,t,n)}a()}function k(e,t,n){let r=0;function i(s){if(s||r===e.length){n(s,t);return}let c;try{c=e[r++](t,i)}catch(e){n(e,t);return}c&&typeof c.then==`function`&&c.then(a,o)}function a(){i()}function o(e){e||=new s,n(e,t)}i()}function A(e,t,n,r){if(n.sent!==!0)return e(t,n,r)}t.exports={Hooks:h,buildHooks:g,hookRunnerGenerator:y,preParsingHookRunner:O,onResponseHookRunner:x,onSendHookRunner:E,preSerializationHookRunner:D,onRequestAbortHookRunner:k,hookIterator:A,hookRunnerApplication:_,onListenHookRunner:v,preHandlerHookRunner:C,preValidationHookRunner:S,onRequestHookRunner:T,onTimeoutHookRunner:w,lifecycleHooks:r,supportedHooks:i}})),K_=o(((e,t)=>{t.exports=function(){return{[Symbol.iterator]:function*(){},add(){},delete(){},has(){return!0}}}})),q_=o(((e,t)=>{let{kTestInternals:n}=V_();function r(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}t.exports={withResolvers:typeof Promise.withResolvers==`function`?Promise.withResolvers.bind(Promise):r,[n]:{withResolvers:r}}})),J_=o(((e,t)=>{let n=require(`node:http`),r=require(`node:https`),i=require(`node:http2`),a=require(`node:dns`),o=require(`node:os`),{kState:s,kOptions:c,kServerBindings:l,kHttp2ServerSessions:u}=V_(),{FSTWRN003:d}=U_(),{onListenHookRunner:f}=G_(),{FST_ERR_REOPENED_CLOSE_SERVER:p,FST_ERR_REOPENED_SERVER:m,FST_ERR_LISTEN_OPTIONS_INVALID:h,FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:g}=W_(),_=K_(),v=q_();t.exports.createServer=b;function y(e){return`Server listening at ${e}`}function b(e,t){let n=w(e,t);function r(r={port:0,host:`localhost`},i=void 0){if(typeof i==`function`&&(i.constructor.name===`AsyncFunction`&&d(`listen method`),r.cb=i),r.signal){if(typeof r.signal.on!=`function`&&typeof r.signal.addEventListener!=`function`)throw new h(`Invalid options.signal`);if(this[s].aborted=r.signal.aborted,this[s].aborted)return this.close();r.signal.addEventListener(`abort`,()=>{this[s].aborted=!0,this.close()},{once:!0})}let a;if(a=r.path==null?r.host??`localhost`:r.host,(!Object.hasOwn(r,`host`)||r.host==null)&&(r.host=a),a===`localhost`?r.cb=(a,o)=>{if(a){i(a,o);return}x.call(this,n,t,e,r,()=>{this[s].listening=!0,i(null,o),f(this)})}:r.cb=(e,t)=>{if(e){i(e,t);return}this[s].listening=!0,i(null,t),f(this)},i===void 0)return C.call(this,n,r).then(i=>{let{promise:o,resolve:c}=v.withResolvers();return a===`localhost`?x.call(this,n,t,e,r,()=>{this[s].listening=!0,c(i),f(this)}):(c(i),f(this)),o});this.ready(S.call(this,n,r))}let i=typeof n.closeAllConnections==`function`,a=typeof n.closeIdleConnections==`function`,o=typeof n.closeHttp2Sessions==`function`,c=e.forceCloseConnections;if(c===`idle`&&!a)throw new g;typeof c!=`boolean`&&(c=a?`idle`:!1);let l=!i&&c===!0?new Set:_();return{server:n,listen:r,forceCloseConnections:c,serverHasCloseAllConnections:i,serverHasCloseHttp2Sessions:o,keepAliveConnections:l}}function x(e,t,n,r,i){this[s].listening=!1,a.lookup(r.host,{all:!0},(a,o)=>{if(a||this[s].aborted){i();return}let c=e.listening&&n.serverFactory,u=0,d=0;if(!c){let a=e.address();for(let c of o)if(c.address!==a.address){u++;let o=Object.assign({},r,{host:c.address,port:a.port,cb:e=>{d++,e||this[l].push(f),d===u&&i()}}),f=w(n,t),p=()=>{f.close(()=>{}),typeof f.closeAllConnections==`function`&&n.forceCloseConnections===!0&&f.closeAllConnections(),typeof f.closeHttp2Sessions==`function`&&f.closeHttp2Sessions()};f.on(`upgrade`,e.emit.bind(e,`upgrade`)),e.on(`unref`,p),e.on(`close`,p),e.on(`error`,p),this[s].listening=!1,S.call(this,f,o)()}}if(u===0){i();return}let f=e.unref;e.unref=function(){f.call(e),e.emit(`unref`)}})}function S(e,t){let n=r=>{if(e.removeListener(`error`,n),e.removeListener(`listening`,n),r)this[s].listening=!1,t.cb(r,null);else{let n=E.call(this,e,t.listenTextResolver||y);t.cb(null,n)}};return r=>{if(r!=null)return t.cb(r);if(this[s].listening&&this[s].closing)return t.cb(new p,null);if(this[s].listening)return t.cb(new m,null);e.once(`error`,n),this[s].closing||(e.once(`listening`,n),e.listen(t),this[s].listening=!0)}}function C(e,t){return this[s].listening&&this[s].closing?Promise.reject(new p):this[s].listening?Promise.reject(new m):this.ready().then(()=>{if(this[s].aborted)return;let{promise:n,resolve:r,reject:i}=v.withResolvers(),a=e=>{c(),this[s].listening=!1,i(e)},o=()=>{c(),this[s].listening=!0,r(E.call(this,e,t.listenTextResolver||y))};function c(){e.removeListener(`error`,a),e.removeListener(`listening`,o)}return e.once(`error`,a),e.once(`listening`,o),e.listen(t),n})}function w(e,t){if(e.serverFactory)return e.serverFactory(t,e);let a=e.https===!0?{}:e.https;if(e.http2){let n=typeof a==`object`?i.createSecureServer(a,t):i.createServer(e.http,t);return n.on(`session`,t=>t.setTimeout(e.http2SessionTimeout,()=>{t.close()})),e.forceCloseConnections===!0&&(n.closeHttp2Sessions=D(n)),n.setTimeout(e.connectionTimeout),n}let o=a?r.createServer(a,t):n.createServer(e.http,t);return o.keepAliveTimeout=e.keepAliveTimeout,o.requestTimeout=e.requestTimeout,o.setTimeout(e.connectionTimeout),e.maxRequestsPerSocket>0&&(o.maxRequestsPerSocket=e.maxRequestsPerSocket),o}function T(e){return e.address===`0.0.0.0`?Object.values(o.networkInterfaces()).flatMap(e=>e.filter(e=>e.family===`IPv4`)).sort(e=>e.internal?-1:1).map(e=>e.address):[e.address]}function E(e,t){let n;typeof e.address()==`string`?n=[e.address()]:(n=e.address().address.indexOf(`:`)===-1?T(e.address()).map(t=>t+`:`+e.address().port):[`[`+e.address().address+`]:`+e.address().port],n=n.map(e=>`http`+(this[c].https?`s`:``)+`://`+e));for(let e of n)this.log.info(t(e));return n[0]}function D(e){return e[u]=new Set,e.on(`session`,function(t){t.once(`connect`,function(){e[u].add(t)}),t.once(`close`,function(){e[u].delete(t)}),t.once(`frameError`,function(n,r,i){i===0&&e[u].delete(t)}),t.once(`goaway`,function(){e[u].delete(t)})}),function(){if(e[u].size!==0)for(let t of e[u])t.close()}}})),Y_=o(((e,t)=>{let n=/([\w!#$%&'*+.^`|~-]+)=([^;]*)/gm,r=/^[\w!#$%&'*+.^`|~-]+$/,i=/^[\w!#$%&'*+.^`|~-]+\s*/;t.exports=class{#e=!1;#t=!0;#n=``;#r=``;#i=new Map;#a;constructor(e){if(e==null||e===``||e===`undefined`)return;let t=e.indexOf(`;`);if(t===-1){if(t=e.indexOf(`/`),t===-1)return;let n=e.slice(0,t).trimStart().toLowerCase(),a=e.slice(t+1).trimEnd().toLowerCase();r.test(n)===!0&&i.test(a)===!0&&(this.#e=!0,this.#t=!1,this.#n=n,this.#r=a);return}let a=e.slice(0,t).toLowerCase(),o=e.slice(t+1).trim();if(t=a.indexOf(`/`),t===-1)return;let s=a.slice(0,t).trimStart(),c=a.slice(t+1).trimEnd();if(r.test(s)===!1||i.test(c)===!1)return;this.#n=s,this.#r=c,this.#e=!0,this.#t=!1;let l=n.exec(o);for(;l;){let e=l[1],t=l[2];if(t[0]===`"`){if(t.at(-1)!==`"`){this.#i.set(e,`invalid quoted string`),l=n.exec(o);continue}this.#i.set(e,t.slice(1,t.length-1))}else this.#i.set(e,t);l=n.exec(o)}}get[Symbol.toStringTag](){return`ContentType`}get isEmpty(){return this.#t}get isValid(){return this.#e}get mediaType(){return`${this.#n}/${this.#r}`}get type(){return this.#n}get subtype(){return this.#r}get parameters(){return this.#i}toString(){if(this.#a)return this.#a;let e=[];for(let[t,n]of this.#i.entries())e.push(`${t}="${n}"`);let t=[this.#n,`/`,this.#r];return e.length>0&&(t.push(`; `),t.push(e.join(`; `))),this.#a=t.join(``),this.#a}}})),X_=o(((e,t)=>{let{kReplyHasStatusCode:n}=V_();function r(e,t){if(!e[n]||e.statusCode===200){let n=t&&(t.statusCode||t.status);e.code(n>=400?n:500)}}t.exports={setErrorStatusCode:r}})),Z_=o(((e,t)=>{let{kReplyIsError:n,kReplyHijacked:r}=V_(),{setErrorStatusCode:i}=X_(),a=require(`node:diagnostics_channel`).tracingChannel(`fastify.request.handler`);function o(e,t,o){o&&(o.async=!0),e.then(function(e){if(t[r]!==!0){o&&a.asyncStart.publish(o);try{if(e!==void 0||t.sent===!1&&t.raw.headersSent===!1&&t.request.raw.aborted===!1&&t.request.socket&&!t.request.socket.destroyed)try{t.send(e)}catch(e){t[n]=!0,t.send(e)}}finally{o&&a.asyncEnd.publish(o)}}},function(e){o&&(o.error=e,i(t,e),a.error.publish(o),a.asyncStart.publish(o));try{if(t.sent===!0){t.log.error({err:e},`Promise errored, but reply.sent = true was set`);return}t[n]=!0,t.send(e)}catch(e){t.send(e)}finally{o&&a.asyncEnd.publish(o)}})}t.exports=o})),Q_=o(((e,t)=>{let{kSchemaHeaders:n,kSchemaParams:r,kSchemaQuerystring:i,kSchemaBody:a,kSchemaResponse:o}=V_(),s=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:c}=W_(),{FSTWRN001:l}=U_();function u(e,t){if(!e.schema||!e.schema.response)return;let{method:n,url:r}=e.config||{};e[o]=Object.keys(e.schema.response).reduce(function(i,a){let o=e.schema.response[a];if(a=a.toLowerCase(),!s.test(a))throw new c;if(o.content){let e={};for(let i of Object.keys(o.content)){let s=o.content[i].schema;e[i]=t({schema:s,url:r,method:n,httpStatus:a,contentType:i})}i[a]=e}else i[a]=t({schema:o,url:r,method:n,httpStatus:a});return i},{})}function d(e,t,o){let{schema:s}=e;if(!s)return;let{method:c,url:u}=e.config||{},d=s.headers;if(d&&(o||Object.getPrototypeOf(d)!==Object.prototype))e[n]=t({schema:d,method:c,url:u,httpPart:`headers`});else if(d){let r={};Object.keys(d).forEach(e=>{r[e]=d[e]}),r.required instanceof Array&&(r.required=r.required.map(e=>e.toLowerCase())),d.properties&&(r.properties={},Object.keys(d.properties).forEach(e=>{r.properties[e.toLowerCase()]=d.properties[e]})),e[n]=t({schema:r,method:c,url:u,httpPart:`headers`})}else Object.hasOwn(s,`headers`)&&l(`headers`,c,u);if(s.body){let n=s.body.content;if(n){let r={};for(let e of Object.keys(n)){let i=n[e].schema;r[e]=t({schema:i,method:c,url:u,httpPart:`body`,contentType:e})}e[a]=r}else e[a]=t({schema:s.body,method:c,url:u,httpPart:`body`})}else Object.hasOwn(s,`body`)&&l(`body`,c,u);s.querystring?e[i]=t({schema:s.querystring,method:c,url:u,httpPart:`querystring`}):Object.hasOwn(s,`querystring`)&&l(`querystring`,c,u),s.params?e[r]=t({schema:s.params,method:c,url:u,httpPart:`params`}):Object.hasOwn(s,`params`)&&l(`params`,c,u)}function f(e,t,n){let r=t[n]===void 0,i;try{i=e?.(r?null:t[n])}catch(e){return e.statusCode=500,e}if(i&&typeof i.then==`function`)return i.then(e=>a(e)).catch(e=>e);return a(i);function a(r){return r===!1?e.errors:r&&r.error?r.error:(r&&r.value&&(t[n]=r.value),!1)}}function p(e,t,o){let s=o===void 0;if(s||!o.skipParams){let n=f(e[r],t,`params`);if(n)return typeof n.then==`function`?m(n,e,t):v(n,`params`,e.schemaErrorFormatter)}if(s||!o.skipBody){let n=null;if(typeof e[a]==`function`)n=e[a];else if(e[a]){let r=y(t.headers[`content-type`]),i=e[a][r];i&&(n=i)}let r=f(n,t,`body`);if(r)return typeof r.then==`function`?h(r,e,t):v(r,`body`,e.schemaErrorFormatter)}if(s||!o.skipQuery){let n=f(e[i],t,`query`);if(n)return typeof n.then==`function`?g(n,e,t):v(n,`querystring`,e.schemaErrorFormatter)}let c=f(e[n],t,`headers`);return c?typeof c.then==`function`?_(c,e,t):v(c,`headers`,e.schemaErrorFormatter):!1}function m(e,t,n){return e.then(e=>e?v(e,`params`,t.schemaErrorFormatter):p(t,n,{skipParams:!0}))}function h(e,t,n){return e.then(e=>e?v(e,`body`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0}))}function g(e,t,n){return e.then(e=>e?v(e,`querystring`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0,skipQuery:!0}))}function _(e,t,n){return e.then(e=>e?v(e,`headers`,t.schemaErrorFormatter):!1)}function v(e,t,n){if(e instanceof Error)return e.statusCode=e.statusCode||400,e.code=e.code||`FST_ERR_VALIDATION`,e.validationContext=e.validationContext||t,e;let r=n(e,t);return r.statusCode=r.statusCode||400,r.code=r.code||`FST_ERR_VALIDATION`,r.validation=e,r.validationContext=t,r}function y(e){return e?e.split(/[ ;]/,1)[0].trim().toLowerCase():``}t.exports={symbols:{bodySchema:a,querystringSchema:i,responseSchema:o,paramsSchema:r,headersSchema:n},compileSchemasForValidation:d,compileSchemasForSerialization:u,validate:p}})),$_=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Y_(),i=Z_(),{validate:a}=Q_(),{preValidationHookRunner:o,preHandlerHookRunner:s}=G_(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:c}=W_(),{setErrorStatusCode:l}=X_(),{kReplyIsError:u,kRouteContext:d,kFourOhFourContext:f,kSupportedHTTPMethods:p}=V_(),m=n.tracingChannel(`fastify.request.handler`);function h(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let i=t.method;if(this[p].bodyless.has(i)){g(t,n);return}if(this[p].bodywith.has(i)){let e=t.headers,i=e[`content-type`];if(i===void 0){let r=e[`content-length`];if(e[`transfer-encoding`]===void 0&&(r===void 0||r===`0`)){g(t,n);return}t[d].contentTypeParser.run(``,g,t,n);return}let a=new r(i);if(a.isValid===!1){n[u]=!0,n.status(415).send(new c);return}t[d].contentTypeParser.run(a.toString(),g,t,n);return}g(t,n)}function g(e,t){try{e[d].preValidation===null?_(null,e,t):o(e[d].preValidation,e,t,_)}catch(n){_(n,e,t)}}function _(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let r=a(n[d],t);if(r&&typeof r.then==`function`){let e=v.bind(null,t,n);r.then(e,e)}else v(t,n,r)}function v(e,t,n){if(n){if(t[d].attachValidation===!1){t.send(n);return}t.request.validationError=n}e[d].preHandler===null?y(null,e,t):s(e[d].preHandler,e,t,y)}function y(e,t,n){if(n.sent)return;let r=t[d];if(!m.hasSubscribers||r[f]===null)b(e,t,n);else{let i={request:t,reply:n,async:!1,route:{url:r.config.url,method:r.config.method}};m.start.runStores(i,b,void 0,e,t,n,i)}}function b(e,t,n,r){let a=t[d];try{if(e!=null){n[u]=!0,r&&(r.error=e,l(n,e),m.error.publish(r)),n.send(e);return}let o;try{o=a.handler(t,n)}catch(e){r&&(r.error=e,l(n,e),m.error.publish(r)),n[u]=!0,n.send(e);return}o!==void 0&&(o!==null&&typeof o.then==`function`?i(o,n,r):n.send(o))}finally{r&&m.end.publish(r)}}t.exports=h,t.exports[Symbol.for(`internals`)]={handler:g,preHandlerCallback:y}})),ev=o(((e,t)=>{function n(){}let r={fatal:n,error:n,warn:n,info:n,debug:n,trace:n};Object.defineProperty(t,`exports`,{get(){return Object.create(r)}})})),tv=o(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
|
|
149
149
|
causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
|
|
150
150
|
caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),nv=o(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),rv=o(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=tv(),{pinoErrProto:a,pinoErrorSymbols:o}=nv(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),iv=o(((e,t)=>{t.exports=s;let{isErrorLike:n}=tv(),{pinoErrProto:r,pinoErrorSymbols:i}=nv(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),av=o(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),ov=o(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),sv=o(((e,t)=>{let n=rv(),r=iv(),i=av(),a=ov();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),cv=o(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),lv=o(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),uv=o(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),dv=o(((e,t)=>{let n=lv(),{redactFmtSym:r,wildcardFirstSym:i}=uv(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),fv=o(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),pv=o(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),mv=o(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),hv=o(((e,t)=>{let n=require(`fs`),r=require(`events`),i=require(`util`).inherits,a=require(`path`),o=mv(),s=require(`assert`),c=Buffer.allocUnsafe(0),l=`buffer`,u=`utf8`,[d,f]=(process.versions.node||`0.0`).split(`.`).map(Number),p=d>=22&&f>=7;function m(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,o=t.mode;if(t.sync)try{t.mkdir&&n.mkdirSync(a.dirname(e),{recursive:!0}),r(null,n.openSync(e,i,o))}catch(e){throw r(e),e}else t.mkdir?n.mkdir(a.dirname(e),{recursive:!0},t=>{if(t)return r(t);n.open(e,i,o,r)}):n.open(e,i,o,r)}function h(e){if(!(this instanceof h))return new h(e);let{fd:t,dest:r,minLength:i,maxLength:a,maxWrite:s,periodicFlush:d,sync:f,append:p=!0,mkdir:v,retryEAGAIN:x,fsync:k,contentMode:A,mode:j}=e||{};t||=r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=s||16384,this._periodicFlush=d||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=k||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=x||(()=>!0),this.mkdir=v||!1;let M,N;if(A===l)this._writingBuf=c,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>n.writeSync(this.fd,this._writingBuf),N=()=>n.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===u)this._writingBuf=``,this.write=y,this.flush=S,this.flushSync=w,this._actualWrite=E,M=()=>Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`),N=()=>Buffer.isBuffer(this._writingBuf)?n.write(this.fd,this._writingBuf,this.release):n.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${u}" and "${l}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)m(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{o(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(N,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let r=g(this._writingBuf,this._len,t);if(this._len=r.len,this._writingBuf=r.writingBuf,this._writingBuf.length){if(!this.sync){N();return}try{do{let e=M(),t=g(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&n.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,O(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(_,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function g(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function _(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}i(h,r);function v(e,t){return e.length===0?c:e.length===1?e[0]:Buffer.concat(e,t)}function y(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{n.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,r)},r=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,r)}function S(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}h.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&n.close(t,e=>{if(e)return this.emit(`error`,e)})}),m(this.file,this)},h.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():O(this)))};function w(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?n.writeSync(this.fd,e):n.writeSync(this.fd,e,`utf8`),r=g(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}try{n.fsyncSync(this.fd)}catch{}}function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=c);let e=c;for(;this._bufs.length||e.length;){e.length<=0&&(e=v(this._bufs[0],this._lens[0]));try{let t=n.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}}h.prototype.destroy=function(){this.destroyed||O(this)};function E(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else n.write(this.fd,this._writingBuf,e)}function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:v(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,n.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else p&&(this._writingBuf=Buffer.from(this._writingBuf)),n.write(this.fd,this._writingBuf,e)}function O(e){if(e.fd===-1){e.once(`ready`,O.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],s(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{n.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?n.close(e.fd,r):r()}function r(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}h.SonicBoom=h,h.default=h,t.exports=h})),gv=o(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),_v=o(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),vv=o(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),yv=o(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),bv=o(((e,t)=>{let{version:n}=_v(),{EventEmitter:r}=require(`events`),{Worker:i}=require(`worker_threads`),{join:a}=require(`path`),{pathToFileURL:o}=require(`url`),{wait:s}=vv(),{WRITE_INDEX:c,READ_INDEX:l}=yv(),u=require(`buffer`),d=require(`assert`),f=Symbol(`kImpl`),p=u.constants.MAX_STRING_LENGTH;var m=class{constructor(e){this._value=e}deref(){return this._value}},h=class{register(){}unregister(){}};let g=process.env.NODE_V8_COVERAGE?h:global.FinalizationRegistry||h,_=process.env.NODE_V8_COVERAGE?m:global.WeakRef||m,v=new g(e=>{e.exited||e.terminate()});function y(e,t){let{filename:r,workerData:s}=t,c=new i((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||a(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf(`file://`)===0?r:o(r).href,dataBuf:e[f].dataBuf,stateBuf:e[f].stateBuf,workerData:{$context:{threadStreamVersion:n},...s}}});return c.stream=new m(e),c.on(`message`,S),c.on(`exit`,C),v.register(e,c),c}function b(e){d(!e[f].sync),e[f].needDrain&&(e[f].needDrain=!1,e.emit(`drain`))}function x(e){let t=Atomics.load(e[f].state,c),n=e[f].data.length-t;if(n>0){if(e[f].buf.length===0){e[f].flushing=!1,e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e);return}let t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);r>e[f].data.length;)n/=2,t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))}})}else if(n===0){if(t===0&&e[f].buf.length===0)return;e.flush(()=>{Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l),x(e)})}else E(e,Error(`overwritten`))}function S(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new _(t),t.flush(()=>{t[f].ready=!0,t.emit(`ready`)});break;case`ERROR`:E(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:E(t,Error(`this should not happen: `+e.code))}}function C(e){let t=this.stream.deref();t!==void 0&&(v.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,C),E(t,e===0?null:Error(`the worker thread exited`)))}var w=class extends r{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[f]={},this[f].stateBuf=new SharedArrayBuffer(128),this[f].state=new Int32Array(this[f].stateBuf),this[f].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[f].data=Buffer.from(this[f].dataBuf),this[f].sync=e.sync||!1,this[f].ending=!1,this[f].ended=!1,this[f].needDrain=!1,this[f].destroyed=!1,this[f].flushing=!1,this[f].ready=!1,this[f].finished=!1,this[f].errored=null,this[f].closed=!1,this[f].buf=``,this.worker=y(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[f].destroyed)return T(this,Error(`the worker has exited`)),!1;if(this[f].ending)return T(this,Error(`the worker is ending`)),!1;if(this[f].flushing&&this[f].buf.length+e.length>=p)try{k(this),this[f].flushing=!0}catch(e){return E(this,e),!1}if(this[f].buf+=e,this[f].sync)try{return k(this),!0}catch(e){return E(this,e),!1}return this[f].flushing||(this[f].flushing=!0,setImmediate(x,this)),this[f].needDrain=this[f].data.length-this[f].buf.length-Atomics.load(this[f].state,c)<=0,!this[f].needDrain}end(){this[f].destroyed||(this[f].ending=!0,O(this))}flush(e){if(this[f].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[f].state,c);s(this[f].state,l,t,1/0,(t,n)=>{if(t){E(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[f].destroyed||(k(this),A(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[f].ready}get destroyed(){return this[f].destroyed}get closed(){return this[f].closed}get writable(){return!this[f].destroyed&&!this[f].ending}get writableEnded(){return this[f].ending}get writableFinished(){return this[f].finished}get writableNeedDrain(){return this[f].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[f].errored}};function T(e,t){setImmediate(()=>{e.emit(`error`,t)})}function E(e,t){e[f].destroyed||(e[f].destroyed=!0,t&&(e[f].errored=t,T(e,t)),e.worker.exited?setImmediate(()=>{e[f].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[f].closed=!0,e.emit(`close`)}))}function D(e,t,n){let r=Atomics.load(e[f].state,c),i=Buffer.byteLength(t);return e[f].data.write(t,r),Atomics.store(e[f].state,c,r+i),Atomics.notify(e[f].state,c),n(),!0}function O(e){if(!(e[f].ended||!e[f].ending||e[f].flushing)){e[f].ended=!0;try{e.flushSync();let t=Atomics.load(e[f].state,l);Atomics.store(e[f].state,c,-1),Atomics.notify(e[f].state,c);let n=0;for(;t!==-1;){if(Atomics.wait(e[f].state,l,t,1e3),t=Atomics.load(e[f].state,l),t===-2){E(e,Error(`end() failed`));return}if(++n===10){E(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[f].finished=!0,e.emit(`finish`)})}catch(t){E(e,t)}}}function k(e){let t=()=>{e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e)};for(e[f].flushing=!1;e[f].buf.length!==0;){let n=Atomics.load(e[f].state,c),r=e[f].data.length-n;if(r===0){A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);continue}else if(r<0)throw Error(`overwritten`);let i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[f].buf=e[f].buf.slice(r),D(e,i,t);else{for(A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);a>e[f].buf.length;)r/=2,i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);e[f].buf=e[f].buf.slice(r),D(e,i,t)}}}function A(e){if(e[f].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[f].state,c),n=0;for(;;){let r=Atomics.load(e[f].state,l);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[f].state,l,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=w})),xv=o(((e,t)=>{let{createRequire:n}=require(`module`),{existsSync:r}=require(`node:fs`),i=cv(),{join:a,isAbsolute:o,sep:s}=require(`node:path`),{fileURLToPath:c}=require(`node:url`),l=mv(),u=gv(),d=bv();function f(e){u.register(e,v),u.registerBeforeExit(e,y),e.on(`close`,function(){u.unregister(e)})}function p(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function m(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&h(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&h(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function h(e){let t=g(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=c(n)}catch{return!1}return o(n)&&!r(n)}function g(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function _(e,t,n,r,i){if(!n.execArgv&&p()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let e=m(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:e}})}n={...n,name:i};let a=new d({filename:e,workerData:t,workerOpts:n,sync:r});a.on(`ready`,o),a.on(`close`,function(){process.removeListener(`exit`,s)}),process.on(`exit`,s);function o(){process.removeListener(`exit`,s),a.unref(),n.autoEnd!==!1&&f(a)}function s(){a.closed||(a.flushSync(),l(100),a.end())}return a}function v(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function y(e){e.flushSync()}function b(e){let{pipeline:t,targets:r,levels:c,dedupe:l,worker:u={},caller:d=i(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&r)throw Error(`only one of target or targets can be specified`);r?(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.targets=r.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=r.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),c&&(p.levels=c),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let v=r||t?`pino.transport`:g;return _(y(g),p,u,f,v);function y(e){if(e=h[e]||e,o(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return a(__dirname,`..`,`file.js`);let t;for(let r of m)try{t=n(r===`node:repl`?process.cwd()+s:r).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=b})),Sv=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=pv(),{mapHttpRequest:i,mapHttpResponse:a}=sv(),o=hv(),s=gv(),{lsCacheSym:c,chindingsSym:l,writeSym:u,serializersSym:d,formatOptsSym:f,endSym:p,stringifiersSym:m,stringifySym:h,stringifySafeSym:g,wildcardFirstSym:_,nestedKeySym:v,formattersSym:y,messageKeySym:b,errorKeySym:x,nestedKeyStrSym:S,msgPrefixSym:C}=uv(),{isMainThread:w}=require(`worker_threads`),T=xv(),[E]=process.versions.node.split(`.`).map(e=>Number(e)),D=n.tracingChannel(`pino_asJson`),O=E>=25?e=>JSON.stringify(e):j;function k(){}function A(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let o=t;t!==null&&(t.method&&t.headers&&t.socket?t=i(t):typeof t.setHeader==`function`&&(t=a(t)));let s;o===null&&n.length===0?s=[null]:(o=n.shift(),s=n),typeof this[C]==`string`&&o!=null&&(o=this[C]+o),this[u](t,r(o,s,this[f]),e)}else{let i=t===void 0?n.shift():t;typeof this[C]==`string`&&i!=null&&(i=this[C]+i),this[u](null,r(i,n,this[f]),e)}}}function j(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function M(e,t,n,r){if(D.hasSubscribers===!1)return N.call(this,e,t,n,r);let i={instance:this,arguments};return D.traceSync(N,i,this,e,t,n,r)}function N(e,t,n,r){let i=this[h],a=this[g],o=this[m],s=this[p],u=this[l],f=this[d],C=this[y],w=this[b],T=this[x],E=this[c][n]+r;E+=u;let D;C.log&&(e=C.log(e));let k=o[_],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){f[t]?D=f[t](D):t===T&&f.err&&(D=f.err(D));let e=o[t]||k;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||O)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=O(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=f[w]?f[w](t):t;let e=o[w]||k;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||O)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[v]&&A?E+this[S]+A.slice(1)+`}`+j+s:E+A+j+s}function P(e,t){let n,r=e[l],i=e[h],a=e[g],o=e[m],s=o[_],c=e[d],u=e[y].bindings;t=u(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function F(e){return e.write!==e.constructor.prototype.write}function I(e){let t=new o(e);return t.on(`error`,n),!e.sync&&w&&(s.register(t,L),t.on(`close`,function(){s.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=k,t.end=k,t.flushSync=k,t.destroy=k;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function L(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function R(e){return function(t,n,r={},i){if(typeof r==`string`)i=I({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=I({dest:i})}else if(r instanceof o||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof o||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=T({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:s}=r;return a===!1&&(r.level=`silent`),s||(r.onChild=k),i||=F(process.stdout)?process.stdout:I({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function z(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[g])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ee(e,t,n){return{level:e,bindings:t,log:n}}function B(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:k,buildSafeSonicBoom:I,asChindings:P,asJson:M,genLog:A,createArgsNormalizer:R,stringify:z,buildFormatters:ee,normalizeDestFileDescriptor:B}})),Cv=o(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),wv=o(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=uv(),{noop:l,genLog:u}=Sv(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=Cv(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),Tv=o(((e,t)=>{t.exports={version:`10.3.1`}})),Ev=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{lsCacheSym:r,levelValSym:i,setLevelSym:a,getLevelSym:o,chindingsSym:s,mixinSym:c,asJsonSym:l,writeSym:u,mixinMergeStrategySym:d,timeSym:f,timeSliceIndexSym:p,streamSym:m,serializersSym:h,formattersSym:g,errorKeySym:_,messageKeySym:v,useOnlyCustomLevelsSym:y,needsMetadataGsym:b,redactFmtSym:x,stringifySym:S,formatOptsSym:C,stringifiersSym:w,msgPrefixSym:T,hooksSym:E}=uv(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:N}=wv(),{asChindings:P,asJson:F,buildFormatters:I,stringify:L,noop:R}=Sv(),{version:z}=Tv(),ee=dv(),B={constructor:class{},child:te,bindings:H,setBindings:ne,flush:ae,isLevelEnabled:k,version:z,get level(){return this[o]()},set level(e){this[a](e)},get levelVal(){return this[i]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[T]},get[Symbol.toStringTag](){return`Pino`},[r]:j,[u]:ie,[l]:F,[o]:D,[a]:O};Object.setPrototypeOf(B,n.prototype),t.exports=function(){return Object.create(B)};let V=e=>e;function te(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[h],r=this[g],i=Object.create(this);if(t==null)return i[g].bindings!==V&&(i[g]=I(r.level,V,r.log)),i[s]=P(i,e),this.onChild!==R&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[h]=Object.create(null);for(let e in n)i[h][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var o=0;o<e.length;o++){let t=e[o];i[h][t]=n[t]}for(let e in t.serializers)i[h][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var c=0;c<r.length;c++){let e=r[c];i[h][e]=t.serializers[e]}}else i[h]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[g]=I(e||r.level,n||V,a||r.log)}else i[g]=I(r.level,V,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(N(this.levels,t.customLevels),i.levels=A(t.customLevels,i[y]),M(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=ee(i.redact,L),n={stringify:e[x]};i[S]=L,i[w]=e,i[C]=n}if(typeof t.msgPrefix==`string`&&(i[T]=(this[T]||``)+t.msgPrefix),i[s]=P(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[a](e)}return this.onChild(i),i}function H(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function ne(e){this[s]=P(this,e)}function re(e,t){return Object.assign(t,e)}function ie(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||re,u,h=this[E].streamWrite;e==null?u={}:e instanceof Error?(u={[a]:e},t===void 0&&(t=e.message)):(u=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(u=s(u,i(u,n,this)));let g=this[l](u,t,n,r),y=this[m];y[b]===!0&&(y.lastLevel=n,y.lastObj=u,y.lastMsg=t,y.lastTime=r.slice(this[p]),y.lastLogger=this),y.write(h?h(g):g)}function ae(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[m];typeof t.flush==`function`?t.flush(e||R):e&&e()}})),Dv=o(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),Ov=o(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=Cv(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),kv=o(((e,t)=>{let n=require(`node:os`),r=sv(),i=cv(),a=dv(),o=fv(),s=Ev(),c=uv(),{configure:l}=Dv(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=wv(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=Cv(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=Sv(),{version:w}=Tv(),{chindingsSym:T,redactFmtSym:E,serializersSym:D,timeSym:O,timeSliceIndexSym:k,streamSym:A,stringifySym:j,stringifySafeSym:M,stringifiersSym:N,setLevelSym:P,endSym:F,formatOptsSym:I,messageKeySym:L,errorKeySym:R,nestedKeySym:z,mixinSym:ee,levelCompSym:B,useOnlyCustomLevelsSym:V,formattersSym:te,hooksSym:H,nestedKeyStrSym:ne,mixinMergeStrategySym:re,msgPrefixSym:ie}=c,{epochTime:ae,nullTime:oe}=o,{pid:se}=process,ce=n.hostname(),le=r.err,ue=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:se,hostname:ce},serializers:Object.assign(Object.create(null),{err:le}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ae,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),de=Object.assign(Object.create(null),r);function fe(...e){let t={},{opts:n,stream:r}=ue(t,i(),...e);n.level&&typeof n.level==`string`&&h[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:o,crlf:c,serializers:g,timestamp:_,messageKey:y,errorKey:S,nestedKey:w,base:se,name:ce,level:le,customLevels:de,levelComparison:fe,mixin:pe,mixinMergeStrategy:me,useOnlyCustomLevels:he,formatters:ge,hooks:_e,depthLimit:ve,edgeLimit:ye,onChild:be,msgPrefix:xe}=n,Se=l({maximumDepth:ve,maximumBreadth:ye}),Ce=b(ge.level,ge.bindings,ge.log),we=x.bind({[M]:Se}),Te=o?a(o,we):{},Ee=o?{stringify:Te[E]}:{stringify:we},De=`}`+(c?`\r
|
|
@@ -521,10 +521,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
521
521
|
`)}function vA(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=CA(e);if(t.type!==`image`)continue;let r=CA(t.remote_agent_attachment);if(Object.keys(r).length>0){n.push(r);continue}let i=CA(t.source),a=wA(i.media_type)??wA(i.mediaType),o=wA(i.path);n.push({id:wA(t.id)??o??`claude_image_${n.length+1}`,kind:`image`,mimeType:a,...o?{locator:{kind:`absolute`,path:o}}:{}})}return n}function yA(e){let t=CA(CA(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function bA(e,t=!1){if(t)return Kk;let n=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return n.length>0?n.join(`; `):wA(e.subtype)||`Claude turn failed`}function xA(e,t){return t||(wA(e.terminal_reason)??wA(e.terminalReason))===`aborted_streaming`?!0:(Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[]).some(e=>e.includes(`result_type=user`)||e.includes(`[Request interrupted by user]`)||e.includes(`[Request interrupted by user for tool use]`))}function SA(e){let t=CA(e);return{input_tokens:DA(t.input_tokens)??DA(t.inputTokens)??0,cached_input_tokens:DA(t.cached_input_tokens)??DA(t.cache_read_input_tokens)??DA(t.cacheReadInputTokens)??0,output_tokens:DA(t.output_tokens)??DA(t.outputTokens)??0}}function CA(e){return typeof e==`object`&&e?e:{}}function wA(e){if(typeof e==`string`&&e.trim())return e}function TA(e){if(typeof e==`string`&&e.length>0)return e}function EA(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function DA(e){if(typeof e==`number`&&Number.isFinite(e))return e}function OA(e){let t=wA(CA(e.message).id);if(t)return t;let n=wA(CA(CA(e.event).message).id);if(n)return n}function kA(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var AA=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){let n=XD(e);if((n.attachments?.length??0)>0)throw Error(`Native legacy session does not support image attachments`);let r=n.text;if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(r);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(r);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:r});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=jA(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 jA(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var MA=`@anthropic-ai/claude-agent-sdk`,NA=`claude-sonnet-4-6`,PA=1e4,FA=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(MA),!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(MA),n=await IA(LA(t,e),PA,`Claude native query session creation timed out`);if(n)return n;let r=await IA(RA(t,e),PA,`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 IA(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 LA(e,t){let n=zA(e);if(!n)return null;let r=t.model??NA;return new Zk(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=BA(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 RA(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 AA(`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 AA(`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 AA(`claude`,t.sessionId,t.model,n)}return null}function zA(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function BA(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 VA(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new kk(n,r):new FA(n,r)}const HA=p.default.join(`.claude`,`projects`),UA=/\u001B\[[0-?]*[ -/]*[@-~]/g,WA=[`/clear`,`/config`,`/copy`,`/cost`,`/effort`,`/exit`,`/help`,`/login`,`/model`,`/permissions`,`/plugin`,`/release-notes`,`/resume`,`/skills`,`/status`,`/usage`];async function GA(e){return(await(0,O.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>QA(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function KA(e,t){let n=XA(e,t?.homeDir),r=p.default.resolve(e);try{let i=await $A(e,n,r,{maxSessions:jj(t?.maxSessions),updatedAfterMs:Aj(t?.updatedAfterMs)});if(i.length>0)return i}catch{}return ej(n,{maxSessions:jj(t?.maxSessions),updatedAfterMs:Aj(t?.updatedAfterMs)})}async function qA(e){let t=await gj(e.nativeSessionId,e.projectPath),n=await _j(e.projectPath,e.nativeSessionId,e.homeDir),r=rj(t,{createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),i=oj(r.updatedAt,n.mtimeMs),a=ij(r.model);return{rawEvents:JA({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),model:r.model,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:a?i:void 0,updatedAt:i,status:sj(t),nativeWatchPath:YA(e.projectPath,e.nativeSessionId,e.homeDir)}}function JA(e){let t=[],n=rj(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)n.type!==`system`&&(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 YA(e,t,n){return p.default.join(XA(e,n),`${t}.jsonl`)}function XA(e,t){let n=t??f.default.homedir();return p.default.join(n,HA,ZA(e))}function ZA(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function QA(e){let t=Ej(e.customTitle)??Ej(e.summary)??Ej(e.firstPrompt),n=mj(e.createdAt??e.lastModified),r=mj(e.lastModified);return{nativeSessionId:e.sessionId,cwd:pj(e.cwd),title:t,createdAt:n,updatedAt:r,status:`idle`}}async function $A(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=Aj(e.lastModified);if(r.updatedAfterMs!==void 0&&i!==void 0&&i<r.updatedAfterMs){s=!0;break}let o=QA(e);if(typeof o.cwd!=`string`||p.default.resolve(o.cwd)!==n)continue;let c=await tj(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 nj(a,r)}async function ej(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 tj(e,{nativeSessionId:t.name.slice(0,-6)});n&&r.push(n)}return nj(r,t)}async function tj(e,t){let n=p.default.join(e,`${t.nativeSessionId}.jsonl`),r;try{r=await hj(n)}catch(e){if(e.code===`ENOENT`)return t.sdkSession;throw e}if(!fj(r))return;let i=await d.default.stat(n),a=t.sdkSession?.createdAt?kj(t.sdkSession.createdAt):void 0,o=t.sdkSession?.updatedAt?kj(t.sdkSession.updatedAt):void 0,s=rj(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:sj(r)}}function nj(e,t){let n=e.filter(e=>{if(t.updatedAfterMs===void 0)return!0;let n=kj(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 rj(e,t){let n,r,i,a;for(let t of e){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=Cj(xj(wj(t.raw.message))));let e=aj(t);e&&(n=e)}let o=i??Aj(t.createdAtFallbackMs)??0,s=a??Aj(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function ij(e){let t=pj(e);if(t)return{mode:`default`,model:t,reasoningEffort:null}}function aj(e){return pj(wj(e.raw.message).model)??pj(e.raw.model)}function oj(e,t){let n=kj(e)??0,r=Aj(t)??0;return new Date(Math.max(n,r)).toISOString()}function sj(e,t=Date.now()){let n=null;for(let t of e){let e=cj(t);e&&(n=e)}return!n?.unresolved||n.timestampMs!==void 0&&t-n.timestampMs>6e5?`idle`:`running`}function cj(e){let t=e.timestampMs??kj(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 lj(e.raw,t);default:return null}}function lj(e,t){let n=wj(e);if(n.isMeta===!0)return null;let r=wj(n.message);if(bj(r).length>0)return{unresolved:!0,timestampMs:t};let i=xj(r);return i?uj(i)?{unresolved:!1,timestampMs:t}:{unresolved:!0,timestampMs:t}:null}function uj(e){let t=e.toLowerCase();return t.includes(`[request interrupted by user]`)||t.includes(`[request interrupted by user for tool use]`)||t.includes(`<local-command-stdout>`)?!0:WA.some(e=>dj(t,e))}function dj(e,t){return e.includes(`<command-name>${t.toLowerCase()}</command-name>`)}function fj(e){for(let t of e){if(t.type===`user`){let e=wj(t.raw.message);if(xj(e)||bj(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=wj(t.raw.message);if(xj(e)||yj(e).length>0||Tj(t.raw.error))return!0}return!1}function pj(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function mj(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function hj(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
|
522
522
|
`),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=wj(i),o=Tj(a.timestamp),s=o?kj(o):void 0;n.push({line:e+1,raw:a,type:Tj(a.type),timestamp:o,timestampMs:s})}return n}async function gj(e,t){let n=await(0,O.getSessionMessages)(e,{dir:t,includeSystemMessages:!0});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>vj(e,t+1))}async function _j(e,t,n){let r=YA(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function vj(e,t){let n=wj(e),r=wj(n.message),i=Tj(n.timestamp)??Tj(r.timestamp)??Tj(r.created_at)??Tj(r.createdAt);return{line:t,raw:{...n,message:r},type:Tj(n.type),timestamp:i,timestampMs:i?kj(i):void 0}}function yj(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=wj(e);if(Tj(t.type)!==`tool_use`)continue;let r=wj(t.input),i=Tj(r.command),a=Tj(t.name)??`tool`,o=Tj(r.description);n.push({id:Tj(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function bj(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=wj(e);if(Tj(t.type)!==`tool_result`)continue;let r=Dj(Tj(t.content)??Tj(wj(t.toolUseResult).stdout)??Tj(wj(t.tool_use_result).stdout)??Tj(t.text));n.push({toolUseId:Tj(t.tool_use_id)??Tj(t.toolUseId),toolName:Tj(t.tool_name)??Tj(t.toolName),text:r,isError:t.is_error===!0})}return n}function xj(e){let t=Tj(e.content);if(t)return Dj(t);let n=Tj(e.text)??Tj(e.prompt);if(n)return Dj(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=wj(e),n=Tj(t.type);if(n&&n!==`text`)continue;let r=Tj(t.text)??Tj(t.content)??Sj(t);r&&i.push(r)}if(i.length!==0)return Dj(i.join(`
|
|
523
523
|
`))}function Sj(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=wj(e),r=Tj(t.text)??Tj(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function Cj(e,t=60){if(!e)return;let n=Oj(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 wj(e){return typeof e==`object`&&e?e:{}}function Tj(e){return typeof e==`string`&&e.trim()||void 0}function Ej(e){if(typeof e==`string`)return Dj(e)}function Dj(e){if(!e)return;let t=Oj(e).trim();return t.length>0?t:void 0}function Oj(e){return e.replace(UA,``)}function kj(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function Aj(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.round(e)}function jj(e){if(e===void 0||!Number.isFinite(e))return;let t=Math.floor(e);return t>0?t:void 0}var Mj=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}=Pj(r,[t,n]);if(Fj(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=Lj(await this.refreshProjects()),r=!0);let i=await Ij(n.projects,t);if(!i)throw NT(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Lj(await this.refreshProjects()),i=await Ij(n.projects,t),!i)throw NT(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 jk({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 Nj({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>Bj(e.cwd),mapSession:e=>{let t=Vj(e.createdAt),n=Vj(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:Bj(e.name)??Bj(e.preview),model:Bj(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 Nj({sessions:await GA(),canonicalPathCache:e,getRawPath:e=>Bj(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:Bj(e.title),model:Bj(e.model),createdAt:Bj(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 Nj(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 Rj(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Pj(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:zj(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=Hj(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(Wj)})).sort((e,t)=>Uj(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function Fj(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Ij(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await PD(t);return e.find(e=>e.path===r)}function Lj(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function Rj(e,t){let n=t.get(e);return n||(n=PD(e),t.set(e,n)),n}function zj(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function Bj(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Vj(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Hj(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function Uj(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 Wj(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Gj=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 Kj(this.getProjectPath(e),Yj);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 qj(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 qj(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 Kj(this.indexPath,Jj)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Kj(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 qj(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 Jj(e){return!Xj(e)||e.v!==1||typeof e.generatedAt!=`string`||!sf.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>cf.safeParse(e).success)}function Yj(e){return!Xj(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!cf.safeParse(e.project).success||!sf.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>lf.safeParse(e).success)}function Xj(e){return typeof e==`object`&&!!e}const Zj=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function Qj(e){let t=Gf.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=Ip(zp(nM(i.export({format:`jwk`})))),o=Ep({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:Kf.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 $j(e){let t=Gf.parse(e.clientHello),n=Kf.parse(e.gatewayHello),r=qf.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!Ff.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([Zj,Lp(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Dp({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,Lp(r.signature)))throw Error(`transcript_invalid`)}function eM(e){let t=Kf.parse(e.gatewayHello),n=qf.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:Rp(Lp(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return Ap({role:`gateway`,keySchedule:kp({gatewayId:e.gatewayId,clientHello:Gf.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function tM(e){return tp.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function nM(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}const rM=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;let iM=null;function aM(e){iM=e}function oM(e,t){rM&&(console.log(`[session-fetch][gateway] ${e}`,t),iM?.info({event:e,...t},`session fetch debug`))}const sM=64*1024;var cM=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}},lM=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(Cp.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=>gl.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=gl.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(Cp.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...hM(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Cp.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...hM(t,`auth.refresh`)})}}async handleFileContent(e,t){try{let n=await this.dependencies.handleFileContentRequest(e,t);this.dependencies.sendFrame(Cp.parse({type:`file.content.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...hM(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:{...mM(`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=>np.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(Cp.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=ap.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:mM(`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:mM(`BAD_REQUEST`,400,`plaintext relay payload missing`)});return}let i=np.parse(e.payload);try{let e=await this.dependencies.handleRpcRequest(i,{mobileId:t,deviceId:r.deviceId});this.dependencies.sendFrame(Cp.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=ap.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:mM(`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=Qj({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(Cp.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{$j({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,gM(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=eM({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(Cp.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,vM(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new cM(t=>{try{let n=Cp.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,_M(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:tM({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:mM(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 Fp({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,_M(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){let r=bf({payload:n,compressionThresholdBytes:uM(t.frameType,n)?sM:void 0});if(dM(n)){let i=fM(n),a=pM(n);oM(`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:sM,uncompressedByteLength:r.uncompressedByteLength,compressedByteLength:r.compressedByteLength})}if(e.handshake.status!==`ready`){let e=xf(r);return e?{compressedPayload:e}:{payload:n}}return{encryptedPayload:Pp({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},preparedPayload:r})}}};function uM(e,t){return e===`to_mobile`&&dM(t)}function dM(e){return typeof e==`object`&&!!e&&`kind`in e&&(e.kind===`session.stream.snapshot.chunk`||e.kind===`session.readable.snapshot.chunk`)}function fM(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 pM(e){return e.kind===`session.readable.snapshot.chunk`||`readable`in e.payload?e.payload.readable:void 0}function mM(e,t,n){return ap.parse({code:e,status:t,message:n})}function hM(e,t){if(_T(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=yM(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`||LT(e))||t===`file.content`&<(e)?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function gM(e){return bM(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function _M(e){return bM(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function vM(e){if(_T(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=yM(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 yM(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function bM(e,t){let n=yM(e);return t.find(e=>e===n)}function xM(e){return e?e.readyState:null}function SM(e){return(typeof e.extensions==`string`?e.extensions.trim():``)||null}var CM=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??EM}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=xM(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=Cp.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=wM(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:SM(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=Cp.parse(JSON.parse(TM(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 wM(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 TM(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 EM(e){return new YD(e,void 0,{perMessageDeflate:!0})}function DM(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(wp(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function OM(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(kM(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(DM({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 dp.parse(JSON.parse(r)).token}function kM(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 AM(e){return e?.trim()||void 0}function jM(e){if(!e)return;let t=e.codex?.sandboxMode??null;return{codex:e.codex?{approvalPolicy:Ga(t),sandboxMode:t}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function MM(e,t){let n=t.defaults.sandboxMode??null;return{modeDefault:`default`,model:AM(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:Ga(n),sandboxMode:n}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function NM(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function PM(e,t){let n=NM(e);if(!t)return n;if(e===`codex`){let e=t.execution?.codex?.sandboxMode??null;return{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:Ga(e),sandboxMode:e}}}}return{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}}function FM(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function IM(e){let t=PM(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||AM(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?LM({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function LM(e){let t=PM(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?FM(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=PM(e.provider,{...t,mode:n});if(e.config){if(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){let t=e.config.execution.codex.sandboxMode;r.execution={codex:{approvalPolicy:Ga(t),sandboxMode:t}}}e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}})}let i=AM(e.legacyModel);if(i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig){let t=e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null;r.execution={codex:{approvalPolicy:Ga(t),sandboxMode:t}}}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??AM(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0,n=Ga(t);n&&(o.approvalPolicy=n),t&&(o.sandboxMode=t)}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:jM(r.execution)}}}function RM(e,t){let n=Ha.safeParse({provider:e,...t&&typeof t==`object`&&!Array.isArray(t)?t:{}});if(!n.success)return;let{provider:r,...i}=Ka(n.data);return i}function zM(e,t,n){return e===`codex`&&(!(`codexAppServerTransport`in n)||n.codexAppServerTransport===void 0)&&t&&`codexAppServerTransport`in t&&t.codexAppServerTransport?{...n,codexAppServerTransport:t.codexAppServerTransport}:n}var BM=class{filePath;ready;preferences={};writeQueue=Promise.resolve();constructor(e){this.filePath=p.default.join(e,`provider-execution-preferences.json`),this.ready=this.loadFromDisk()}async get(e){await this.ready;let t=this.preferences[e];return t?{provider:e,...t}:null}async set(e){await this.ready;let{provider:t,...n}=Ka(e),r=n;return await this.enqueueWrite(async()=>{let e=this.preferences[t],i=zM(t,e,n);r=i,this.preferences[t]=i;try{await this.persist()}catch(n){throw e?this.preferences[t]=e:delete this.preferences[t],n}}),{provider:t,...r}}async loadFromDisk(){await d.default.mkdir(p.default.dirname(this.filePath),{recursive:!0});let e;try{e=await d.default.readFile(this.filePath,`utf8`)}catch(e){if(e?.code===`ENOENT`)return;throw e}let t;try{t=JSON.parse(e)}catch{return}if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t.providers;if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;for(let e of[`codex`,`claude`]){let t=RM(e,r[e]);t&&(this.preferences[e]=t)}}async persist(){let e={v:1,providers:this.preferences};await d.default.writeFile(this.filePath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}async enqueueWrite(e){let t=this.writeQueue.then(e,e);this.writeQueue=t.catch(()=>{}),await t}};const VM=[],HM=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],UM=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],WM=Ia.options,GM=[`read-only`,`workspace-write`,`danger-full-access`],KM=[`websocket`,`stdio`],qM=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],JM={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 YM(e,t){let n=t?.trim().toLowerCase();return n?(JM[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function XM(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:UM}:{}},...e.map(e=>({...e,isDefault:!1}))]}function ZM(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function QM(e){let t=new Set;for(let n of e){let e=ZM(n);e&&t.add(e)}return[...t]}function $M(e){return e?.trim()||void 0}function eN(e){let t=$M(e.runtimeModel);if(t)return t;let n=$M(e.discoveredModel);if(n)return n;let r=$M(e.existingModel),i=$M(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function tN(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:QM(e.supportedReasoningEfforts)}));return t.length===0?VM:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function nN(e){let t=Date.now();try{let n=tN(await Pk());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 rN(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(Eh(),`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=aN(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?QM(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 iN(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 aN(...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 oN=class{cache=new Map;inFlight=new Map;cacheEpochByProvider=new Map;executionPreferences;constructor(e){this.options=e,this.executionPreferences=new BM(this.options.providerExecutionPreferencesDir??p.default.join(Eh(),`settings`))}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=JM.claude.length>0?JM.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 MM(e,await this.getProviderCapabilities(e,t,n))}async updateProviderExecutionDefaults(e){let t=await this.executionPreferences.set(e);return this.invalidateProviderCache(e.provider),t}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw TT(t);let r=YM(e,n),i=r?.version??`default`,a=`${e}::${i}`,o=this.getProviderCacheEpoch(e),s={provider:e,projectId:t??null,requestedAgentVersion:n?.trim()||null,resolvedAgentVersion:i},c=Date.now(),l=this.cache.get(a);if(l){if(l.expiresAt>c)return this.options.logger?.info?.({...s,cacheStatus:`hit`,source:l.value.capabilities.source,modelCount:l.value.capabilities.models.length},`provider capabilities cache hit`),l.value;this.cache.delete(a)}let u=this.inFlight.get(a);if(u)return this.options.logger?.info?.({...s,cacheStatus:`in_flight`},`provider capabilities awaiting in-flight load`),u;let d=Date.now(),f=(async()=>{let t=VA(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=Date.now(),a=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1;this.options.logger?.info?.({...s,cacheStatus:`miss`,nativeAvailable:a,durationMs:Date.now()-n},`provider capabilities native availability checked`);let o=a?`native`:`fallback`,c=e===`codex`&&a?await nN(this.options.logger)??VM:VM,l=e===`claude`&&a?await rN(this.options.logger)??HM:HM,u=QM(l.flatMap(e=>e.supportedReasoningEfforts??[])),f=e===`codex`?{provider:e,source:o,models:c,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1,imageInput:a,codexAppServerTransport:!0},options:{reasoningEfforts:UM,approvalPolicies:WM,sandboxModes:GM,permissionModes:[],codexAppServerTransports:[...KM]},defaults:{model:c.find(e=>e.isDefault)?.id??c[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:o,models:l,support:{reasoningEffort:u.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0,imageInput:a},options:{reasoningEfforts:u,approvalPolicies:[],sandboxModes:[],permissionModes:qM},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:iN(l),permissionMode:`default`}},p=await this.executionPreferences.get(e),m={...f.defaults,...r?.defaults??{},...p?.provider===`codex`?{approvalPolicy:p.approvalPolicy,sandboxMode:p.sandboxMode,...p.codexAppServerTransport?{codexAppServerTransport:p.codexAppServerTransport}:{}}:{},...p?.provider===`claude`?{permissionMode:p.permissionMode}:{}},h=e===`codex`?{...m,approvalPolicy:Ga(m.sandboxMode)}:m,g=h.model?.trim(),_=o===`native`?f.models:g?XM(f.models,g,e):f.models;if(!r){let e={capabilities:{...f,models:_,defaults:h},resolvedAgentVersion:i};return this.options.logger?.info?.({...s,cacheStatus:`miss`,durationMs:Date.now()-d,source:e.capabilities.source,modelCount:e.capabilities.models.length},`provider capabilities resolved`),e}let v={capabilities:{...f,models:_,defaults:h},resolvedAgentVersion:r.version};return this.options.logger?.info?.({...s,cacheStatus:`miss`,durationMs:Date.now()-d,source:v.capabilities.source,modelCount:v.capabilities.models.length},`provider capabilities resolved`),v})();this.inFlight.set(a,f);try{let t=await f;return this.getProviderCacheEpoch(e)===o&&this.cache.set(a,{value:t,expiresAt:Date.now()+864e5}),t}catch(e){throw this.options.logger?.warn?.({...s,cacheStatus:`miss`,durationMs:Date.now()-d,err:e},`provider capabilities resolution failed`),e}finally{this.inFlight.get(a)===f&&this.inFlight.delete(a)}}invalidateProviderCache(e){this.cacheEpochByProvider.set(e,this.getProviderCacheEpoch(e)+1);for(let t of[...this.cache.keys()])t.startsWith(`${e}::`)&&this.cache.delete(t);for(let t of[...this.inFlight.keys()])t.startsWith(`${e}::`)&&this.inFlight.delete(t)}getProviderCacheEpoch(e){return this.cacheEpochByProvider.get(e)??0}};const sN=`.meta.json`;function cN(){let e=process.env.CODEX_HOME?.trim();return e?p.default.resolve(e):p.default.join(f.default.homedir(),`.codex`)}function lN(){return p.default.join(cN(),`auth.json`)}function uN(){return p.default.join(Eh(),`codex-accounts`)}var dN=class{currentAuthFilePath;snapshotsDir;readAccountMetadata;constructor(e={}){this.currentAuthFilePath=e.currentAuthFilePath??lN(),this.snapshotsDir=e.snapshotsDir??uN(),this.readAccountMetadata=e.readAccountMetadata??mN}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 jN(this.currentAuthFilePath),n=await this.readSavedSnapshot(e);return await MN(this.currentAuthFilePath,n.rawContent),{previousRawContent:t}}async deleteSavedAccount(e){let t=this.getSnapshotPath(e);if(await jN(t)===null)throw jT(e);return await Promise.all([d.default.rm(t,{force:!0}),d.default.rm(this.getSnapshotMetadataPath(e),{force:!0})]),this.getAccountsOverview()}async restoreCurrentAuthFile(e){await MN(this.currentAuthFilePath,e)}async listSavedAccounts(e){let t=await AN(this.snapshotsDir);return(await Promise.all(t.filter(e=>e.isFile()&&kN(e.name)).map(async t=>{let n=ON(t.name);if(!n)return null;let r=p.default.join(this.snapshotsDir,t.name);try{let t=fN(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 jN(this.getSnapshotPath(e));if(n===null)return`missing`;try{return fN(n,this.getSnapshotPath(e)).canonicalContent===t?`current`:`stale`}catch{return`stale`}}async writeSnapshot(e,t,n){let r=new Date().toISOString();await MN(this.getSnapshotPath(e),t.rawContent),await MN(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 jN(t);if(n===null)throw jT(e);return fN(n,t)}async readSnapshotMetadata(e){let t=await jN(this.getSnapshotMetadataPath(e));if(t===null)return null;try{return pN(t)}catch{return null}}async readCurrentAuthFile(){let e=await this.readCurrentAuthFileOrNull();if(!e)throw MT(`Current Codex auth.json is missing or unreadable`);return e}async readCurrentAuthFileOrNull(){let e=await jN(this.currentAuthFilePath);if(e===null)return null;try{return fN(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 MT(`Current Codex account does not expose a ChatGPT email via account/read`);return e}getSnapshotPath(e){return p.default.join(this.snapshotsDir,`${DN(e)}.json`)}getSnapshotMetadataPath(e){return p.default.join(this.snapshotsDir,`${DN(e)}${sN}`)}};function fN(e,t){let n;try{n=JSON.parse(e)}catch(e){throw MT(`Codex auth file is not valid JSON: ${t}`,{error:String(e)})}if(!n||typeof n!=`object`||Array.isArray(n))throw MT(`Codex auth file is not an object: ${t}`);let r=n;return{authMode:hN(r.auth_mode),lastRefreshAt:yN(r.last_refresh),rawContent:e,canonicalContent:TN(n)}}function pN(e){let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`invalid snapshot metadata`);let n=t,r=_N(n.accountId);if(!r)throw Error(`missing snapshot metadata accountId`);return{accountId:r,accountType:vN(n.accountType),planType:gN(n.planType),rateLimits:bN(n.rateLimits),savedAt:yN(n.savedAt)??new Date(0).toISOString()}}async function mN(){return NO(async e=>{let t=wN(await e.sendRequest(`account/read`,{refreshToken:!1}));if(!t)return null;let n=wN(t.account);if(!n)return null;let r=null;try{let t=wN(await e.sendRequest(`account/rateLimits/read`,void 0));r=t?bN(wN(t.rateLimits)):null}catch{r=null}let i=vN(n.type);if(i===`chatgpt`){let e=_N(n.email);return e?{accountId:e,accountType:i,planType:gN(n.planType)??r?.planType??null,rateLimits:r}:null}return i===`apiKey`?{accountId:`API Key`,accountType:i,planType:gN(n.planType)??r?.planType??null,rateLimits:r}:null})}function hN(e){return typeof e==`string`&&e.trim()?e.trim():`unknown`}function gN(e){return typeof e==`string`&&e.trim()?e.trim():null}function _N(e){return typeof e==`string`&&e.trim()?e.trim().toLowerCase():null}function vN(e){return e===`chatgpt`||e===`apiKey`?e:`unknown`}function yN(e){if(typeof e!=`string`||!e.trim())return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toISOString()}function bN(e){let t=wN(e);if(!t)return null;let n=xN(t.primary),r=xN(t.secondary),i=gN(t.planType??t.plan_type),a=wN(t.credits),o=gN(t.creditsBalance??a?.balance);return!n&&!r&&!i&&!o?null:{...n?{primary:n}:{},...r?{secondary:r}:{},...i?{planType:i}:{},...o?{creditsBalance:o}:{}}}function xN(e){let t=wN(e);if(!t)return null;let n=SN(t.usedPercent??t.used_percent);return n===null?null:{usedPercent:n,windowMinutes:CN(t.windowMinutes??t.windowDurationMins??t.window_minutes),resetsAt:SN(t.resetsAt??t.resets_at)}}function SN(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function CN(e){return typeof e==`number`&&Number.isFinite(e)?Math.trunc(e):null}function wN(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function TN(e){return JSON.stringify(EN(e))}function EN(e){return Array.isArray(e)?e.map(e=>EN(e)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,EN(t)])):e}function DN(e){let t=_N(e);if(!t)throw MT(`Codex account identifier cannot be empty`);return encodeURIComponent(t)}function ON(e){if(!kN(e))return null;try{return _N(decodeURIComponent(e.slice(0,-5)))}catch{return null}}function kN(e){return e.endsWith(`.json`)&&!e.endsWith(sN)}async function AN(e){try{return await d.default.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function jN(e){try{return await d.default.readFile(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function MN(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 NN=[`## 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 PN(e,t){let n=e.provider===`codex`?e.codex:void 0;if(!n)throw Error(`Codex review config is required`);return[...NN,``,IN(n.target),`## My request for Codex:`,FN(e,t)].join(`
|
|
524
|
-
`)}function FN(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 ${LN(r.sha,r.title)}.`:r.type===`custom`?r.instructions:`Please review my uncommitted changes.`,a=RN(t);return a?`${i}\n\nAdditional review instructions:\n${a}`:i}function IN(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 ${LN(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 LN(e,t){let n=RN(t);return n?`${e} (${JSON.stringify(n)})`:e}function RN(e){return e?.trim()||void 0}async function zN(e){let t=e.attachments??[];if(t.length===0)return{attachments:[],totalSizeBytes:0};if(t.length>5)throw Error(`Too many image attachments; maximum is 5`);let n=p.default.join(e.rootDir,HN(e.sessionId),HN(e.commandId??`turn_${hT(10)}`));await d.default.mkdir(n,{recursive:!0,mode:448});let r=0,i=[];for(let[e,a]of t.entries()){if(a.kind!==`image`)continue;let t=Buffer.from(a.dataBase64,`base64`);if(t.length===0)throw Error(`Image attachment is empty`);if(t.length>8388608)throw Error(`Image attachment exceeds 8388608 bytes`);if(r+=t.length,r>20971520)throw Error(`Image attachments exceed 20971520 bytes in total`);if(!VN(t,a.mimeType))throw Error(`Image attachment MIME/content mismatch: ${a.mimeType}`);let o=BN(a.mimeType),s=(0,l.createHash)(`sha256`).update(t).digest(`hex`).slice(0,16),c=`${String(e+1).padStart(2,`0`)}-${s}.${o}`,u=p.default.join(n,c);await d.default.writeFile(u,t,{mode:384}),i.push({id:a.id,kind:`image`,mimeType:a.mimeType,localPath:u,fileName:a.fileName,width:a.width,height:a.height,sizeBytes:t.length,dataBase64:a.dataBase64})}return{attachments:i,totalSizeBytes:r}}function BN(e){return e===`image/jpeg`?`jpg`:e===`image/webp`?`webp`:`png`}function VN(e,t){return t===`image/png`?e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10:t===`image/jpeg`?e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255:e.length>=12&&e.toString(`ascii`,0,4)===`RIFF`&&e.toString(`ascii`,8,12)===`WEBP`}function HN(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`).slice(0,80)||`unknown`}const UN=Symbol(`dispatchRollbackHandled`),WN=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function GN(e){return e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt}function KN(e,t){WN&&(!e.startsWith(`config.get`)&&!e.startsWith(`raw-events`)&&!e.startsWith(`sync-external`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function qN(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,codexExternalConfigHydrationVersion:e.codexExternalConfigHydrationVersion??null}:{sessionFound:!1}}function JN(e,t,n,r){let i=PM(e,n);if(!t)return XN(e,i,r);let a=PM(e,t);return XN(e,{mode:i.mode??a.mode,model:i.model===void 0?a.model:i.model,reasoningEffort:i.reasoningEffort===void 0?a.reasoningEffort:i.reasoningEffort},r)}function YN(e){return e.observedModel===void 0?e.observedSessionTurnConfig?.model===void 0?e.currentModel:$M(e.observedSessionTurnConfig.model??void 0):$M(e.observedModel)}function XN(e,t,n){let r=PM(e,t);return{mode:r.mode,model:r.model,reasoningEffort:e===`claude`&&n?.preserveReasoningEffort===!1?null:r.reasoningEffort}}function ZN(e){return e.provider!==`claude`||e.source===`gateway`}function QN(e){return!e||e.provider!==`claude`||e.source===`gateway`||!e.sessionTurnConfig?e:{...e,sessionTurnConfig:XN(`claude`,e.sessionTurnConfig,{preserveReasoningEffort:!1})}}function $N(e,t){return eP(e)?{status:`running`}:t?{status:`running`,interactionLockReason:`external_turn_running`}:{status:`idle`}}function eP(e){return!!(e&&(e.status===`running`||e.dispatchInFlight))}function tP(e){return e.status===`active`?!0:e.turns.some(e=>e.status===`inProgress`||e.status===`in_progress`)}function nP(e,t){if(!t)return tP(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 rP(e){return e.startsWith(`sess_`)}function iP(e){return e.source===`native_discovered`?!0:e.providerMode===`native`&&(e.provider===`codex`||e.provider===`claude`)}function aP(e){return e.nativeSessionId?.trim()??``?!0:e.provider===`codex`&&!rP(e.id)}function oP(e){return rP(e.id)?e.nativeSessionId??e.id:e.id}function sP(e){return e.provider!==`codex`&&e.provider!==`claude`||e.providerMode!==`native`?!1:aP(e)}function cP(e){return e instanceof Error&&/^Session .+ is closed$/i.test(e.message)}function lP(e,t){if(e.provider!==`codex`||t.type!==`error.runtime`)return!1;if(AF(t.source)?.startsWith(`codex.app_server`))return!0;let n=AF(t.message)??``;return/\bclosed\b/i.test(n)}function uP(e,t){return t.type===`error.runtime`?!0:e.provider===`claude`&&t.type===`error`}function dP(e){if(e&&(typeof e==`object`||typeof e==`function`))try{return Object.defineProperty(e,UN,{value:!0,configurable:!0}),e}catch{}let t=Error(e instanceof Error?e.message:String(e));return Object.defineProperty(t,UN,{value:!0,configurable:!0}),Object.defineProperty(t,`cause`,{value:e,configurable:!0}),t}function fP(e){return!!(e&&(typeof e==`object`||typeof e==`function`)&&UN in e)}function pP(e){return fP(e)&&e&&(typeof e==`object`||typeof e==`function`)&&`cause`in e&&e.cause!==void 0?e.cause:e}const mP={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function hP(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function gP(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}var _P=class{sessions=new Map;providerCapabilities;codexAccounts;nextRawSeqBySession=new Map;preparingRuntimeDispatches=new Set;queuedInterruptsBeforeDispatch=new Set;runtimeLifecycle;attachmentStoreDir;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.providerCapabilities=new oN({preferNativeProviders:e.preferNativeProviders,projectStore:e.projectStore,logger:e.logger,providerExecutionPreferencesDir:e.providerExecutionPreferencesDir}),this.codexAccounts=e.codexAccountService??new dN,this.attachmentStoreDir=e.attachmentStoreDir??p.default.join(f.default.tmpdir(),`craby-session-attachments`),this.runtimeLifecycle={idleTtlMs:hP(e.runtimeLifecycle?.idleTtlMs,mP.idleTtlMs),sweepIntervalMs:gP(e.runtimeLifecycle?.sweepIntervalMs,mP.sweepIntervalMs),maxSessions:hP(e.runtimeLifecycle?.maxSessions,mP.maxSessions),maxCodexSessions:hP(e.runtimeLifecycle?.maxCodexSessions,mP.maxCodexSessions),maxClaudeSessions:hP(e.runtimeLifecycle?.maxClaudeSessions,mP.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 hO(),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 kT(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.getRunningRuntimeSessionCount();if(e>0)throw AT(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 gO(),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 AT(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 hO();let i=null;try{i=await this.codexAccounts.applySavedAccount(e),await gO()}catch(e){if(i?.previousRawContent)try{await this.codexAccounts.restoreCurrentAuthFile(i.previousRawContent),await gO()}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 deleteSavedCodexAccount(e){let t=await this.codexAccounts.deleteSavedAccount(e);return await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.account.delete`,detail:{deletedAccountId:e,currentAccountId:t.current?.accountId??null,savedAccountCount:t.savedAccounts.length}}),{deleted:!0,accounts:t}}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 updateProviderExecutionDefaults(e){return this.providerCapabilities.updateProviderExecutionDefaults(e)}async warmStartupProviderCapabilities(){if(!this.shuttingDown)return this.providerCapabilities.warmStartupProviderCapabilities()}async getProviderDefaults(e,t,n){return this.providerCapabilities.getProviderDefaults(e,t,n)}async resolveCodexAppServerTransport(e){if(e.provider===`codex`)return(await this.getProviderCapabilities(`codex`,e.projectId)).defaults.codexAppServerTransport}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw TT(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)||QN(n)}isGatewayOwnedRuntimeLive(e,t){let n=this.sessions.get(t);if(n&&n.projectId===e&&eP(n))return!0;if(!this.preparingRuntimeDispatches.has(t))return!1;let r=this.options.historyStore.getProjectSession(e,t);return!!(r&&r.source===`gateway`&&r.providerMode===`native`)}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(KN(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:qN(n),runtime:qN(r)}),r)return KN(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...qN(r)}),r;let i=n?.provider===`codex`?await this.maybeHydrateCodexExternalSessionConfig(n):QN(n);return KN(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...qN(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw TT(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 ET(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=lF(i,o.rawEvents);KN(`sync-external.classify`,cF({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){return(await this.getProjectSessionRawEventsWithCoverage(e,t,n)).rawEvents}async getProjectSessionRawEventsWithCoverage(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw TT(e);let i=0,a=0,o,s=(s,c)=>{KN(`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`),{rawEvents:[],coveredToRawSeq:null};if(!c)throw ET(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEventsWithCoverage(c.id,Math.max(n,300)),d=u.rawEvents.slice(-Math.max(1,n));return i=Date.now()-l,a=d.length,s(`local_only_cached`,{localEventCount:u.rawEvents.length,coveredToRawSeq:u.coveredToRawSeq}),{rawEvents:d,coveredToRawSeq:u.coveredToRawSeq}}async getProjectSessionRawEventsCompacted(e,t,n=300){return(await this.getProjectSessionRawEventsCompactedWithCoverage(e,t,n)).rawEvents}async getProjectSessionRawEventsCompactedWithCoverage(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompactedWithCoverage(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 TT(e);let n=this.options.historyStore.getProjectSession(e,t);if(n||=this.getRuntimeSessionSummary(e,t),!n)throw ET(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${hT(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=VA(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=await this.resolveCodexAppServerTransport({provider:e.provider,projectId:t.id}),s=e.sessionTurnConfig?PM(e.provider,e.sessionTurnConfig):IM({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),c=LM({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:s}),l=XN(e.provider,s),u=await i.createSession({sessionId:n,model:c.model,cwd:t.path,sessionConfig:c.sessionConfig,codexAppServerTransport:o,metadata:e.metadata,logger:this.options.logger});if(r&&u.providerMode!==`native`)throw await u.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let d=this.resolveCanonicalSessionId(e.provider,u,n),f=this.resolveNativeSessionId(e.provider,u,d),p=new Date().toISOString(),m=await this.attachRuntimeSession({id:d,nativeSessionId:f,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:u.providerMode,model:c.model,title:void 0,sessionTurnConfig:l,sessionTurnConfigUpdatedAt:p,createdAt:p,updatedAt:p,status:`idle`,providerSession:u,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(m),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:m.id,detail:{provider:e.provider,model:c.model,sessionConfig:e.sessionConfig,sessionTurnConfig:l,codexAppServerTransport:o,projectId:t.id,projectPath:t.path}}),{sessionId:m.id,projectId:t.id}}async sendInput(e,t,n,r){let i=t??``,a=r?.attachments??[];if(!i.trim()&&a.length===0)throw Error(`turn.input requires text or image attachments`);let o=this.options.historyStore.getSession(e),s=this.sessions.get(e);if(s?.dispatchInFlight)throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!s&&this.preparingRuntimeDispatches.has(e))throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(o?.interactionLockReason===`external_turn_running`)throw OT(e,`an external native turn is still running`,{reason:`external_turn_running`,status:o.status,interactionLockReason:o.interactionLockReason,provider:o.provider,providerMode:o.providerMode});if(s?.status===`running`)throw OT(e,`the current turn is still running`,{reason:`runtime_running`,provider:s.provider,providerMode:s.providerMode});if(!s&&o?.status===`running`&&iP(o))throw OT(e,`the native session is still running`,{reason:`persisted_running`,status:o.status,provider:o.provider,providerMode:o.providerMode,source:o.source});let c=!s,l=s,u=!1,d=!1,f=!1;try{if(c&&this.preparingRuntimeDispatches.add(e),l=s??await this.resumeSessionFromHistory(e),!l)throw DT(e);let t=await this.getProviderDefaults(l.provider,l.projectId),o=LM({provider:l.provider,providerDefaults:t,currentSessionTurnConfig:l.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});if(l.dispatchInFlight=!0,this.touchSession(l),a.length>0&&(await this.getProviderCapabilities(l.provider,l.projectId,o.model)).support.imageInput!==!0)throw Error(`${l.provider} does not support image input`);let p=await zN({rootDir:this.attachmentStoreDir,sessionId:e,commandId:r?.commandId,attachments:a}),m={text:i,attachments:p.attachments};if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:i,attachments:p.attachments.map(e=>({id:e.id,kind:e.kind,mimeType:e.mimeType,fileName:e.fileName,width:e.width,height:e.height,sizeBytes:e.sizeBytes})),attachmentCount:p.attachments.length,attachmentTotalSizeBytes:p.totalSizeBytes,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(await this.persistGatewayOwnedDispatchStart(l),f=!0,this.consumeQueuedInterruptBeforeDispatch(e)))throw u=!0,this.createInterruptedBeforeDispatchError(e);if(l=await this.sendInputWithRuntimeRecovery(e,l,m,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),d=!0,!l.title){let e=OF(i)??(p.attachments.length>0?`图片消息`:void 0);e&&this.setSessionTitle(l,e)}let h=new Date().toISOString();l.sessionTurnConfig=XN(l.provider,o.sessionTurnConfig),l.sessionTurnConfigUpdatedAt=h,o.model&&l.model!==o.model&&(l.model=o.model),l.updatedAt=h,await this.persistSessionSnapshot(l)}catch(e){throw!fP(e)&&!d&&f&&l&&await this.restoreUnacceptedGatewayOwnedDispatch(l),pP(e)}finally{c&&this.preparingRuntimeDispatches.delete(e),this.queuedInterruptsBeforeDispatch.delete(e);let t=!1;u&&c&&l&&(await this.closeRuntimeSession(l.id,`dispatch_cancelled`,{suppressAudit:!0}),t=!0),!t&&l&&(l.dispatchInFlight=!1,this.touchSession(l))}}async startReview(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!a&&this.preparingRuntimeDispatches.has(e))throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(i?.interactionLockReason===`external_turn_running`)throw OT(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 OT(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&iP(i))throw OT(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,l=!1,u=!1;try{if(o&&this.preparingRuntimeDispatches.add(e),s=a??await this.resumeSessionFromHistory(e),!s)throw DT(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),d=LM({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:d.model,resolvedSessionConfig:d.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(await this.persistGatewayOwnedDispatchStart(s),u=!0,this.consumeQueuedInterruptBeforeDispatch(e)))throw c=!0,this.createInterruptedBeforeDispatchError(e);let f=PN(t,r?.input);if(s=await this.sendInputWithRuntimeRecovery(e,s,f,{model:d.model,sessionConfig:d.sessionConfig}),l=!0,!s.title){let e=kF(t,r?.input);e&&this.setSessionTitle(s,e)}let p=new Date().toISOString();s.sessionTurnConfig=XN(s.provider,d.sessionTurnConfig),s.sessionTurnConfigUpdatedAt=p,d.model&&s.model!==d.model&&(s.model=d.model),s.updatedAt=p,await this.persistSessionSnapshot(s)}catch(e){throw!fP(e)&&!l&&u&&s&&await this.restoreUnacceptedGatewayOwnedDispatch(s),pP(e)}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(!cP(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;o.dispatchInFlight=!0,await this.persistGatewayOwnedDispatchStart(o);try{await o.providerSession.sendInput(n,r)}catch(e){throw await this.restoreUnacceptedGatewayOwnedDispatch(o),dP(e)}return 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:jF(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 DT(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_${hT(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=VA(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=XN(t.provider,t.sessionTurnConfig,{preserveReasoningEffort:ZN(t)}),o=LM({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`?oP(t):t.nativeSessionId??t.id,c=await this.resolveCodexAppServerTransport({provider:t.provider,projectId:t.projectId}),l=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,codexAppServerTransport:c,metadata:{resumeFromHistory:!0,codexAppServerTransport:c},logger:this.options.logger});if(n&&l.providerMode!==`native`)throw await l.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let u=this.resolveCanonicalSessionId(t.provider,l,t.id),d=this.resolveNativeSessionId(t.provider,l,t.nativeSessionId),f=await this.attachRuntimeSession({id:u,nativeSessionId:d,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:l.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:l,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(f),f}consumeQueuedInterruptBeforeDispatch(e){return this.queuedInterruptsBeforeDispatch.delete(e)}createInterruptedBeforeDispatchError(e){return OT(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 Ak(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=MF(t.createdAt),s=MF(t.updatedAt),l=$N(i,tP(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:eN({runtimeModel:i?.model,discoveredModel:t.model,existingModel:n?.model,modelProvider:t.modelProvider}),title:i?.title??OF(t.name??t.preview)??n?.title,sessionTurnConfig:i?.sessionTurnConfig??(n?.sessionTurnConfig?XN(`codex`,n.sessionTurnConfig):void 0),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 KA(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=$N(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?XN(`claude`,n.sessionTurnConfig,{preserveReasoningEffort:ZN(n)}):void 0),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=GN(e),n=XP([e.nativeSessionId,e.id]);for(let r of n)try{KN(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:r,...qN(e)});let n=await Nk(r);if(!n){KN(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:r});continue}let i=n.sessionTurnConfig?JN(e.provider,e.sessionTurnConfig,n.sessionTurnConfig):e.sessionTurnConfig,a={...e,model:YN({currentModel:e.model,observedModel:n.model,observedSessionTurnConfig:i}),sessionTurnConfig:i,sessionTurnConfigUpdatedAt:n.sessionTurnConfigUpdatedAt,codexExternalConfigHydrationVersion:3,...t?{lastHydratedExternalConfigFreshnessAt:t}:{}};return await this.options.historyStore.upsertSession(a),KN(`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:qN(a)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??a}catch(t){KN(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:r,error:String(t)})}return e}shouldHydrateCodexExternalSessionConfig(e){if(!this.options.preferNativeProviders||e.provider!==`codex`||!sP(e)||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=GN(e),n=e.sessionTurnConfigUpdatedAt||``;if(!e.sessionTurnConfig||!$M(e.model)||!n||e.codexExternalConfigHydrationVersion!==3)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 TT(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await NF(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw TT(e);return await NF(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=AF(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,e.dispatchInFlight=!1,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,e.dispatchInFlight=!1,this.persistSessionSnapshot(e),e.provider===`claude`&&this.closeRuntimeSession(e.id,`turn_terminal`);return}if(uP(e,n)){let t=AF(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`,e.dispatchInFlight=!1,this.persistSessionSnapshot(e),lP(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_${hT(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_${hT(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=QP(e);if(!i)return{rawEvents:n};try{let a=Date.now(),o=await qA({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,sessionTurnConfig:o.sessionTurnConfig,sessionTurnConfigUpdatedAt:o.sessionTurnConfigUpdatedAt});return KN(`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`&&ZP(i)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),KN(`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=kP(n,(this.sessions.get(e.id)??(e.nativeSessionId?this.sessions.get(e.nativeSessionId):void 0))?.status===`running`),a=XP([e.nativeSessionId,e.id]);for(let o of a)try{let a=Date.now(),s=await Mk(o,!0),c=Date.now(),l,u;if(e.source===`gateway`&&n.length>0)l=xF({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=dF({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n});r?(l=r,u=`native_tail_incremental`):(l=uF({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localCodexLiveTurnState:i}),u=`full`)}else l=uF({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,MF(s.updatedAt),i),p=await this.patchObservedExternalSessionSummary(e,{updatedAt:MF(s.updatedAt),externallyRunning:e.source===`gateway`?nP(s,i):tP(s)});return KN(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:o,threadStatus:s.status,threadUpdatedAt:MF(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`?nP(s,i):tP(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){KN(`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 KN(`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=yP(e.provider,t,n,i),s=Date.now(),c=await this.maybePersistSyncedExternalRawEvents(e,t,o,!0);return await this.markExternalHistoryHydrated(e.id,r),KN(`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=ZN(n),a=t.sessionTurnConfig?JN(e.provider,n.sessionTurnConfig,t.sessionTurnConfig,{preserveReasoningEffort:i}):void 0,o=$N(r,t.externallyRunning),s=o.status===`running`?r?.pendingToolApprovals.size??0:0,c=o.status===`running`?r?.pendingUserInputs.size??0:0,l={...n,updatedAt:o.status===`running`?r?.updatedAt??t.updatedAt:t.updatedAt,status:o.status,model:r?.model??YN({currentModel:n.model,observedModel:t.model,observedSessionTurnConfig:a}),sessionTurnConfig:r?.sessionTurnConfig??a??(n.sessionTurnConfig?XN(e.provider,n.sessionTurnConfig,{preserveReasoningEffort:i}):void 0),sessionTurnConfigUpdatedAt:r?.sessionTurnConfigUpdatedAt??(a?t.sessionTurnConfigUpdatedAt??t.updatedAt:void 0)??n.sessionTurnConfigUpdatedAt,interactionLockReason:o.interactionLockReason,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c,...e.provider===`codex`&&a?{codexExternalConfigHydrationVersion:3}:{}};return await this.options.historyStore.upsertSession(l),this.options.historyStore.getSession(e.id)??l}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw DT(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))}async persistGatewayOwnedDispatchStart(e){e.status=`running`,e.updatedAt=new Date().toISOString(),this.touchSession(e),await this.persistSessionSnapshot(e)}async restoreUnacceptedGatewayOwnedDispatch(e){e.status=`idle`,e.dispatchInFlight=!1,e.updatedAt=new Date().toISOString(),this.touchSession(e),await this.persistSessionSnapshot(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=DF(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 vP=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function yP(e,t,n,r){if(e===`claude`)return xP(e,MP(t,n),n);if(e!==`codex`)return xP(e,t,n);if(t.length===0)return n.slice().sort((e,t)=>e.ts.localeCompare(t.ts));let i=r??kP(t),a=bP(e,t.filter(e=>!TP(e))),o=IP(e),s=t.filter(t=>{if(OP(t,i))return!1;if(!TP(t))return!0;let n=LP(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=IP(e),f=IP(e),p=jP(t)??jP(n)??Date.now();for(let[t,n]of s.entries()){c.set(n.eventId,n),l.set(n.eventId,t);for(let t of LP(e,n,d))u.add(t)}for(let t of n){if(OP(t,i))continue;let n=LP(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(!SP(r,t))continue;let e=l.get(t.eventId),n=AP(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 bP(e,t){let n=new Map,r=IP(e);for(let i of t)for(let t of LP(e,i,r))n.set(t,(n.get(t)??0)+1);return n}function xP(e,t,n){let r=new Map,i=new Set,a=IP(e),o=IP(e);for(let n of t){r.set(n.eventId,n);for(let t of LP(e,n,a))i.add(t)}for(let t of n){let n=LP(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 SP(e,t){return CP(e)&&CP(t)}function CP(e){return e.type===`native.raw`?$(Q(e.payload.raw).source)===`codex.history.thread_read`:!1}function wP(e){return e===`codex.history.thread_read`||e===`codex.history.thread_read.incremental`}function TP(e){let t=Q(e.payload.raw),n=$(t.source);return t.historyReplay===!0||wP(n)}function EP(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 DP(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&&TF(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&&TF(t)?t:void 0}if(n!==`codex.history.thread_read`||$(r.scope)!==`turn`)return;let i=$(Q(r.turn).status);return i&&TF(i)?i:void 0}function OP(e,t){if(!TP(e))return!1;let n=EP(e),r=DP(e);return!n||!r?!1:EF(t.terminalTurnStatusById.get(n),r)}function kP(e,t=!1){let n=new Set,r=new Map;for(let t of e){if(TP(t))continue;let e=EP(t);e&&n.add(e);let i=DP(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 AP(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function jP(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 MP(e,t){let n=NP(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=FP(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 NP(e){let t=new Map,n=new Map;for(let r of e){let e=PP(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 PP(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=JP(n);return r?{text:r,tsMs:t,syntheticMessageId:AF(n.id)??AF(n.item_id)??AF(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=YP(Q(Q(n.message).message));if(r)return{text:r,tsMs:t,syntheticMessageId:AF(Q(n.message).uuid)}}function FP(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||!vP.has(r))return;let i=Q(n.message);if(($(n.native_type)??$(i.type))!==`user`)return;let a=YP(Q(i.message));if(a)return{text:a,tsMs:t}}function IP(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function LP(e,t,n){return e===`codex`?RP(t,n):e===`claude`?WP(t):[]}function RP(e,t){let n=Q(e.payload.raw),r=new Set,i=GP(e.type,n);if(i){let a=zP(e.type,n);a?r.add(HP(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(KP(`turn.started`,{turn:Q(a.turn)})),[...r];if(i===`turn/completed`)return r.add(KP(`turn.completed`,{status:`completed`,turn:Q(a.turn)})),[...r];if(i===`turn/failed`||i===`turn/interrupted`)return r.add(KP(`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=zP(e,n);return o?r.add(HP(o,t,n)):r.add(KP(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(KP(`thread.started`,{thread_id:t,thread:e}));let n=OF(qP(e.preview)??qP(e.name)??``);return n&&r.add(KP(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(s===`turn`){let e=Q(o.turn),t=$(e.status);return r.add(KP(`turn.started`,{turn:e})),t===`completed`?r.add(KP(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(KP(`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),...o.semantic_occurrence===void 0?{}:{semantic_occurrence:o.semantic_occurrence}},n=zP(`item.completed`,e);return n?r.add(HP(n,t,e)):r.add(KP(`item.completed`,e)),[...r]}return[...r]}function zP(e,t){if(!e.startsWith(`item.`))return;let n=Q(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=BP($(n.type));if(!(!r||!i))return[`codex`,e,r,i,VP(i,$(n.phase)),$(n.status)??``,oF($(n.command)),oF(JP(n))].join(`|`)}function BP(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 VP(e,t){return e===`agent_message`&&(!t||t===`final_answer`)?``:t??``}function HP(e,t,n){let r=UP(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 UP(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 WP(e){let t=Q(e.payload.raw),n=GP(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!vP.has(r))return[];let i=Q(t.message),a=$(t.native_type)??$(i.type),o=Q(i.message);if(a===`user`){let e=YP(o),t=$(i.uuid);return!e||!t?[]:[KP(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=YP(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[KP(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function GP(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 KP(e,t);default:return}}function KP(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=oF($(n.command)),p=oF(JP(n)),m=oF(qP(t.message)),h=oF(qP(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 qP(e){if(typeof e==`string`)return e.length>0?e:void 0}function JP(e){let t=qP(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=qP(Q(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
524
|
+
`)}function FN(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 ${LN(r.sha,r.title)}.`:r.type===`custom`?r.instructions:`Please review my uncommitted changes.`,a=RN(t);return a?`${i}\n\nAdditional review instructions:\n${a}`:i}function IN(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 ${LN(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 LN(e,t){let n=RN(t);return n?`${e} (${JSON.stringify(n)})`:e}function RN(e){return e?.trim()||void 0}async function zN(e){let t=e.attachments??[];if(t.length===0)return{attachments:[],totalSizeBytes:0};if(t.length>5)throw Error(`Too many image attachments; maximum is 5`);let n=p.default.join(e.rootDir,HN(e.sessionId),HN(e.commandId??`turn_${hT(10)}`));await d.default.mkdir(n,{recursive:!0,mode:448});let r=0,i=[];for(let[e,a]of t.entries()){if(a.kind!==`image`)continue;let t=Buffer.from(a.dataBase64,`base64`);if(t.length===0)throw Error(`Image attachment is empty`);if(t.length>8388608)throw Error(`Image attachment exceeds 8388608 bytes`);if(r+=t.length,r>20971520)throw Error(`Image attachments exceed 20971520 bytes in total`);if(!VN(t,a.mimeType))throw Error(`Image attachment MIME/content mismatch: ${a.mimeType}`);let o=BN(a.mimeType),s=(0,l.createHash)(`sha256`).update(t).digest(`hex`).slice(0,16),c=`${String(e+1).padStart(2,`0`)}-${s}.${o}`,u=p.default.join(n,c);await d.default.writeFile(u,t,{mode:384}),i.push({id:a.id,kind:`image`,mimeType:a.mimeType,localPath:u,fileName:a.fileName,width:a.width,height:a.height,sizeBytes:t.length,dataBase64:a.dataBase64})}return{attachments:i,totalSizeBytes:r}}function BN(e){return e===`image/jpeg`?`jpg`:e===`image/webp`?`webp`:`png`}function VN(e,t){return t===`image/png`?e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10:t===`image/jpeg`?e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255:e.length>=12&&e.toString(`ascii`,0,4)===`RIFF`&&e.toString(`ascii`,8,12)===`WEBP`}function HN(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`).slice(0,80)||`unknown`}const UN=Symbol(`dispatchRollbackHandled`),WN=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function GN(e){return e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt}function KN(e,t){WN&&(!e.startsWith(`config.get`)&&!e.startsWith(`raw-events`)&&!e.startsWith(`sync-external`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function qN(e){return e?{sessionFound:!0,sessionId:e.id,nativeSessionId:e.nativeSessionId??null,sessionSource:e.source??null,sessionModel:e.model??null,sessionUpdatedAt:e.updatedAt,sessionActiveStartedAt:e.activeStartedAt??null,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,codexExternalConfigHydrationVersion:e.codexExternalConfigHydrationVersion??null}:{sessionFound:!1}}function JN(e,t,n,r){let i=PM(e,n);if(!t)return XN(e,i,r);let a=PM(e,t);return XN(e,{mode:i.mode??a.mode,model:i.model===void 0?a.model:i.model,reasoningEffort:i.reasoningEffort===void 0?a.reasoningEffort:i.reasoningEffort},r)}function YN(e){return e.observedModel===void 0?e.observedSessionTurnConfig?.model===void 0?e.currentModel:$M(e.observedSessionTurnConfig.model??void 0):$M(e.observedModel)}function XN(e,t,n){let r=PM(e,t);return{mode:r.mode,model:r.model,reasoningEffort:e===`claude`&&n?.preserveReasoningEffort===!1?null:r.reasoningEffort}}function ZN(e){return e.provider!==`claude`||e.source===`gateway`}function QN(e){return!e||e.provider!==`claude`||e.source===`gateway`||!e.sessionTurnConfig?e:{...e,sessionTurnConfig:XN(`claude`,e.sessionTurnConfig,{preserveReasoningEffort:!1})}}function $N(e,t){return eP(e)?{status:`running`}:t?{status:`running`,interactionLockReason:`external_turn_running`}:{status:`idle`}}function eP(e){return!!(e&&(e.status===`running`||e.dispatchInFlight))}function tP(e){return e.status===`active`?!0:e.turns.some(e=>e.status===`inProgress`||e.status===`in_progress`)}function nP(e,t){if(!t)return tP(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 rP(e){return e.startsWith(`sess_`)}function iP(e){return e.source===`native_discovered`?!0:e.providerMode===`native`&&(e.provider===`codex`||e.provider===`claude`)}function aP(e){return e.nativeSessionId?.trim()??``?!0:e.provider===`codex`&&!rP(e.id)}function oP(e){return rP(e.id)?e.nativeSessionId??e.id:e.id}function sP(e){return e.provider!==`codex`&&e.provider!==`claude`||e.providerMode!==`native`?!1:aP(e)}function cP(e){return e instanceof Error&&/^Session .+ is closed$/i.test(e.message)}function lP(e,t){if(e.provider!==`codex`||t.type!==`error.runtime`)return!1;if(AF(t.source)?.startsWith(`codex.app_server`))return!0;let n=AF(t.message)??``;return/\bclosed\b/i.test(n)}function uP(e,t){return t.type===`error.runtime`?!0:e.provider===`claude`&&t.type===`error`}function dP(e){if(e&&(typeof e==`object`||typeof e==`function`))try{return Object.defineProperty(e,UN,{value:!0,configurable:!0}),e}catch{}let t=Error(e instanceof Error?e.message:String(e));return Object.defineProperty(t,UN,{value:!0,configurable:!0}),Object.defineProperty(t,`cause`,{value:e,configurable:!0}),t}function fP(e){return!!(e&&(typeof e==`object`||typeof e==`function`)&&UN in e)}function pP(e){return fP(e)&&e&&(typeof e==`object`||typeof e==`function`)&&`cause`in e&&e.cause!==void 0?e.cause:e}const mP={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function hP(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function gP(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}var _P=class{sessions=new Map;providerCapabilities;codexAccounts;nextRawSeqBySession=new Map;preparingRuntimeDispatches=new Set;queuedInterruptsBeforeDispatch=new Set;runtimeLifecycle;attachmentStoreDir;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.providerCapabilities=new oN({preferNativeProviders:e.preferNativeProviders,projectStore:e.projectStore,logger:e.logger,providerExecutionPreferencesDir:e.providerExecutionPreferencesDir}),this.codexAccounts=e.codexAccountService??new dN,this.attachmentStoreDir=e.attachmentStoreDir??p.default.join(f.default.tmpdir(),`craby-session-attachments`),this.runtimeLifecycle={idleTtlMs:hP(e.runtimeLifecycle?.idleTtlMs,mP.idleTtlMs),sweepIntervalMs:gP(e.runtimeLifecycle?.sweepIntervalMs,mP.sweepIntervalMs),maxSessions:hP(e.runtimeLifecycle?.maxSessions,mP.maxSessions),maxCodexSessions:hP(e.runtimeLifecycle?.maxCodexSessions,mP.maxCodexSessions),maxClaudeSessions:hP(e.runtimeLifecycle?.maxClaudeSessions,mP.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 hO(),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 kT(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.getRunningRuntimeSessionCount();if(e>0)throw AT(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 gO(),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 AT(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 hO();let i=null;try{i=await this.codexAccounts.applySavedAccount(e),await gO()}catch(e){if(i?.previousRawContent)try{await this.codexAccounts.restoreCurrentAuthFile(i.previousRawContent),await gO()}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 deleteSavedCodexAccount(e){let t=await this.codexAccounts.deleteSavedAccount(e);return await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.account.delete`,detail:{deletedAccountId:e,currentAccountId:t.current?.accountId??null,savedAccountCount:t.savedAccounts.length}}),{deleted:!0,accounts:t}}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 updateProviderExecutionDefaults(e){return this.providerCapabilities.updateProviderExecutionDefaults(e)}async warmStartupProviderCapabilities(){if(!this.shuttingDown)return this.providerCapabilities.warmStartupProviderCapabilities()}async getProviderDefaults(e,t,n){return this.providerCapabilities.getProviderDefaults(e,t,n)}async resolveCodexAppServerTransport(e){if(e.provider===`codex`)return(await this.getProviderCapabilities(`codex`,e.projectId)).defaults.codexAppServerTransport}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw TT(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)||QN(n)}isGatewayOwnedRuntimeLive(e,t){let n=this.sessions.get(t);if(n&&n.projectId===e&&eP(n))return!0;if(!this.preparingRuntimeDispatches.has(t))return!1;let r=this.options.historyStore.getProjectSession(e,t);return!!(r&&r.source===`gateway`&&r.providerMode===`native`)}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(KN(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:qN(n),runtime:qN(r)}),r)return KN(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...qN(r)}),r;let i=n?.provider===`codex`?await this.maybeHydrateCodexExternalSessionConfig(n):QN(n);return KN(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...qN(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw TT(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 ET(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=lF(i,o.rawEvents);KN(`sync-external.classify`,cF({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){return(await this.getProjectSessionRawEventsWithCoverage(e,t,n)).rawEvents}async getProjectSessionRawEventsWithCoverage(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw TT(e);let i=0,a=0,o,s=(s,c)=>{KN(`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`),{rawEvents:[],coveredToRawSeq:null};if(!c)throw ET(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEventsWithCoverage(c.id,Math.max(n,300)),d=u.rawEvents.slice(-Math.max(1,n));return i=Date.now()-l,a=d.length,s(`local_only_cached`,{localEventCount:u.rawEvents.length,coveredToRawSeq:u.coveredToRawSeq}),{rawEvents:d,coveredToRawSeq:u.coveredToRawSeq}}async getProjectSessionRawEventsCompacted(e,t,n=300){return(await this.getProjectSessionRawEventsCompactedWithCoverage(e,t,n)).rawEvents}async getProjectSessionRawEventsCompactedWithCoverage(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompactedWithCoverage(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 TT(e);let n=this.options.historyStore.getProjectSession(e,t);if(n||=this.getRuntimeSessionSummary(e,t),!n)throw ET(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${hT(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=VA(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=await this.resolveCodexAppServerTransport({provider:e.provider,projectId:t.id}),s=e.sessionTurnConfig?PM(e.provider,e.sessionTurnConfig):IM({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),c=LM({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:s}),l=XN(e.provider,s),u=await i.createSession({sessionId:n,model:c.model,cwd:t.path,sessionConfig:c.sessionConfig,codexAppServerTransport:o,metadata:e.metadata,logger:this.options.logger});if(r&&u.providerMode!==`native`)throw await u.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let d=this.resolveCanonicalSessionId(e.provider,u,n),f=this.resolveNativeSessionId(e.provider,u,d),p=new Date().toISOString(),m=await this.attachRuntimeSession({id:d,nativeSessionId:f,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:u.providerMode,model:c.model,title:void 0,sessionTurnConfig:l,sessionTurnConfigUpdatedAt:p,createdAt:p,updatedAt:p,activeStartedAt:void 0,status:`idle`,providerSession:u,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(m),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:m.id,detail:{provider:e.provider,model:c.model,sessionConfig:e.sessionConfig,sessionTurnConfig:l,codexAppServerTransport:o,projectId:t.id,projectPath:t.path}}),{sessionId:m.id,projectId:t.id}}async sendInput(e,t,n,r){let i=t??``,a=r?.attachments??[];if(!i.trim()&&a.length===0)throw Error(`turn.input requires text or image attachments`);let o=this.options.historyStore.getSession(e),s=this.sessions.get(e);if(s?.dispatchInFlight)throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!s&&this.preparingRuntimeDispatches.has(e))throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(o?.interactionLockReason===`external_turn_running`)throw OT(e,`an external native turn is still running`,{reason:`external_turn_running`,status:o.status,interactionLockReason:o.interactionLockReason,provider:o.provider,providerMode:o.providerMode});if(s?.status===`running`)throw OT(e,`the current turn is still running`,{reason:`runtime_running`,provider:s.provider,providerMode:s.providerMode});if(!s&&o?.status===`running`&&iP(o))throw OT(e,`the native session is still running`,{reason:`persisted_running`,status:o.status,provider:o.provider,providerMode:o.providerMode,source:o.source});let c=!s,l=s,u=!1,d=!1,f=!1;try{if(c&&this.preparingRuntimeDispatches.add(e),l=s??await this.resumeSessionFromHistory(e),!l)throw DT(e);let t=await this.getProviderDefaults(l.provider,l.projectId),o=LM({provider:l.provider,providerDefaults:t,currentSessionTurnConfig:l.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});if(l.dispatchInFlight=!0,this.touchSession(l),a.length>0&&(await this.getProviderCapabilities(l.provider,l.projectId,o.model)).support.imageInput!==!0)throw Error(`${l.provider} does not support image input`);let p=await zN({rootDir:this.attachmentStoreDir,sessionId:e,commandId:r?.commandId,attachments:a}),m={text:i,attachments:p.attachments};if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:i,attachments:p.attachments.map(e=>({id:e.id,kind:e.kind,mimeType:e.mimeType,fileName:e.fileName,width:e.width,height:e.height,sizeBytes:e.sizeBytes})),attachmentCount:p.attachments.length,attachmentTotalSizeBytes:p.totalSizeBytes,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(await this.persistGatewayOwnedDispatchStart(l),f=!0,this.consumeQueuedInterruptBeforeDispatch(e)))throw u=!0,this.createInterruptedBeforeDispatchError(e);if(l=await this.sendInputWithRuntimeRecovery(e,l,m,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),d=!0,!l.title){let e=OF(i)??(p.attachments.length>0?`图片消息`:void 0);e&&this.setSessionTitle(l,e)}let h=new Date().toISOString();l.sessionTurnConfig=XN(l.provider,o.sessionTurnConfig),l.sessionTurnConfigUpdatedAt=h,o.model&&l.model!==o.model&&(l.model=o.model),l.updatedAt=h,await this.persistSessionSnapshot(l)}catch(e){throw!fP(e)&&!d&&f&&l&&await this.restoreUnacceptedGatewayOwnedDispatch(l),pP(e)}finally{c&&this.preparingRuntimeDispatches.delete(e),this.queuedInterruptsBeforeDispatch.delete(e);let t=!1;u&&c&&l&&(await this.closeRuntimeSession(l.id,`dispatch_cancelled`,{suppressAudit:!0}),t=!0),!t&&l&&(l.dispatchInFlight=!1,this.touchSession(l))}}async startReview(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(!a&&this.preparingRuntimeDispatches.has(e))throw OT(e,`the previous turn is still being dispatched`,{reason:`dispatch_preparing`});if(i?.interactionLockReason===`external_turn_running`)throw OT(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 OT(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&iP(i))throw OT(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,l=!1,u=!1;try{if(o&&this.preparingRuntimeDispatches.add(e),s=a??await this.resumeSessionFromHistory(e),!s)throw DT(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),d=LM({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:d.model,resolvedSessionConfig:d.sessionConfig}}),this.consumeQueuedInterruptBeforeDispatch(e)||(await this.persistGatewayOwnedDispatchStart(s),u=!0,this.consumeQueuedInterruptBeforeDispatch(e)))throw c=!0,this.createInterruptedBeforeDispatchError(e);let f=PN(t,r?.input);if(s=await this.sendInputWithRuntimeRecovery(e,s,f,{model:d.model,sessionConfig:d.sessionConfig}),l=!0,!s.title){let e=kF(t,r?.input);e&&this.setSessionTitle(s,e)}let p=new Date().toISOString();s.sessionTurnConfig=XN(s.provider,d.sessionTurnConfig),s.sessionTurnConfigUpdatedAt=p,d.model&&s.model!==d.model&&(s.model=d.model),s.updatedAt=p,await this.persistSessionSnapshot(s)}catch(e){throw!fP(e)&&!l&&u&&s&&await this.restoreUnacceptedGatewayOwnedDispatch(s),pP(e)}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(!cP(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;o.dispatchInFlight=!0,await this.persistGatewayOwnedDispatchStart(o);try{await o.providerSession.sendInput(n,r)}catch(e){throw await this.restoreUnacceptedGatewayOwnedDispatch(o),dP(e)}return 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:jF(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 DT(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_${hT(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=VA(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=XN(t.provider,t.sessionTurnConfig,{preserveReasoningEffort:ZN(t)}),o=LM({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`?oP(t):t.nativeSessionId??t.id,c=await this.resolveCodexAppServerTransport({provider:t.provider,projectId:t.projectId}),l=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,codexAppServerTransport:c,metadata:{resumeFromHistory:!0,codexAppServerTransport:c},logger:this.options.logger});if(n&&l.providerMode!==`native`)throw await l.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let u=this.resolveCanonicalSessionId(t.provider,l,t.id),d=this.resolveNativeSessionId(t.provider,l,t.nativeSessionId),f=await this.attachRuntimeSession({id:u,nativeSessionId:d,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:l.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),activeStartedAt:t.activeStartedAt,status:`idle`,providerSession:l,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(f),f}consumeQueuedInterruptBeforeDispatch(e){return this.queuedInterruptsBeforeDispatch.delete(e)}createInterruptedBeforeDispatchError(e){return OT(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 Ak(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=MF(t.createdAt),s=MF(t.updatedAt),l=$N(i,tP(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:eN({runtimeModel:i?.model,discoveredModel:t.model,existingModel:n?.model,modelProvider:t.modelProvider}),title:i?.title??OF(t.name??t.preview)??n?.title,sessionTurnConfig:i?.sessionTurnConfig??(n?.sessionTurnConfig?XN(`codex`,n.sessionTurnConfig):void 0),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 KA(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=$N(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?XN(`claude`,n.sessionTurnConfig,{preserveReasoningEffort:ZN(n)}):void 0),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=GN(e),n=XP([e.nativeSessionId,e.id]);for(let r of n)try{KN(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:r,...qN(e)});let n=await Nk(r);if(!n){KN(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:r});continue}let i=n.sessionTurnConfig?JN(e.provider,e.sessionTurnConfig,n.sessionTurnConfig):e.sessionTurnConfig,a={...e,model:YN({currentModel:e.model,observedModel:n.model,observedSessionTurnConfig:i}),sessionTurnConfig:i,sessionTurnConfigUpdatedAt:n.sessionTurnConfigUpdatedAt,codexExternalConfigHydrationVersion:3,...t?{lastHydratedExternalConfigFreshnessAt:t}:{}};return await this.options.historyStore.upsertSession(a),KN(`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:qN(a)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??a}catch(t){KN(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:r,error:String(t)})}return e}shouldHydrateCodexExternalSessionConfig(e){if(!this.options.preferNativeProviders||e.provider!==`codex`||!sP(e)||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=GN(e),n=e.sessionTurnConfigUpdatedAt||``;if(!e.sessionTurnConfig||!$M(e.model)||!n||e.codexExternalConfigHydrationVersion!==3)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 TT(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await NF(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw TT(e);return await NF(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);this.emitRawEnvelope(e,n),this.maybePersistUpdatedNativeSessionId(e);let r=new Date().toISOString();if(e.updatedAt=r,this.touchSession(e),n.type===`thread.title.updated`){let t=AF(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,e.activeStartedAt=e.activeStartedAt??r,e.dispatchInFlight=!1,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,e.dispatchInFlight=!1,this.persistSessionSnapshot(e),e.provider===`claude`&&this.closeRuntimeSession(e.id,`turn_terminal`);return}if(uP(e,n)){let t=AF(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`,e.dispatchInFlight=!1,this.persistSessionSnapshot(e),lP(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_${hT(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_${hT(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=QP(e);if(!i)return{rawEvents:n};try{let a=Date.now(),o=await qA({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,sessionTurnConfig:o.sessionTurnConfig,sessionTurnConfigUpdatedAt:o.sessionTurnConfigUpdatedAt});return KN(`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`&&ZP(i)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),KN(`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=kP(n,(this.sessions.get(e.id)??(e.nativeSessionId?this.sessions.get(e.nativeSessionId):void 0))?.status===`running`),a=XP([e.nativeSessionId,e.id]);for(let o of a)try{let a=Date.now(),s=await Mk(o,!0),c=Date.now(),l,u;if(e.source===`gateway`&&n.length>0)l=xF({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=dF({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n});r?(l=r,u=`native_tail_incremental`):(l=uF({thread:s,provider:e.provider,sessionId:e.id,projectId:t,localCodexLiveTurnState:i}),u=`full`)}else l=uF({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,MF(s.updatedAt),i),p=await this.patchObservedExternalSessionSummary(e,{updatedAt:MF(s.updatedAt),externallyRunning:e.source===`gateway`?nP(s,i):tP(s)});return KN(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:o,threadStatus:s.status,threadUpdatedAt:MF(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`?nP(s,i):tP(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){KN(`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 KN(`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=yP(e.provider,t,n,i),s=Date.now(),c=await this.maybePersistSyncedExternalRawEvents(e,t,o,!0);return await this.markExternalHistoryHydrated(e.id,r),KN(`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=ZN(n),a=t.sessionTurnConfig?JN(e.provider,n.sessionTurnConfig,t.sessionTurnConfig,{preserveReasoningEffort:i}):void 0,o=$N(r,t.externallyRunning),s=o.status===`running`?r?.pendingToolApprovals.size??0:0,c=o.status===`running`?r?.pendingUserInputs.size??0:0,l={...n,updatedAt:o.status===`running`?r?.updatedAt??t.updatedAt:t.updatedAt,status:o.status,model:r?.model??YN({currentModel:n.model,observedModel:t.model,observedSessionTurnConfig:a}),sessionTurnConfig:r?.sessionTurnConfig??a??(n.sessionTurnConfig?XN(e.provider,n.sessionTurnConfig,{preserveReasoningEffort:i}):void 0),sessionTurnConfigUpdatedAt:r?.sessionTurnConfigUpdatedAt??(a?t.sessionTurnConfigUpdatedAt??t.updatedAt:void 0)??n.sessionTurnConfigUpdatedAt,interactionLockReason:o.interactionLockReason,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c,...e.provider===`codex`&&a?{codexExternalConfigHydrationVersion:3}:{}};return await this.options.historyStore.upsertSession(l),this.options.historyStore.getSession(e.id)??l}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw DT(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))}async persistGatewayOwnedDispatchStart(e){e.status=`running`;let t=new Date().toISOString();e.updatedAt=t,e.activeStartedAt=t,this.touchSession(e),await this.persistSessionSnapshot(e)}async restoreUnacceptedGatewayOwnedDispatch(e){e.status=`idle`,e.dispatchInFlight=!1,e.updatedAt=new Date().toISOString(),this.touchSession(e),await this.persistSessionSnapshot(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,activeStartedAt:e.activeStartedAt,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=DF(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 vP=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function yP(e,t,n,r){if(e===`claude`)return xP(e,MP(t,n),n);if(e!==`codex`)return xP(e,t,n);if(t.length===0)return n.slice().sort((e,t)=>e.ts.localeCompare(t.ts));let i=r??kP(t),a=bP(e,t.filter(e=>!TP(e))),o=IP(e),s=t.filter(t=>{if(OP(t,i))return!1;if(!TP(t))return!0;let n=LP(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=IP(e),f=IP(e),p=jP(t)??jP(n)??Date.now();for(let[t,n]of s.entries()){c.set(n.eventId,n),l.set(n.eventId,t);for(let t of LP(e,n,d))u.add(t)}for(let t of n){if(OP(t,i))continue;let n=LP(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(!SP(r,t))continue;let e=l.get(t.eventId),n=AP(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 bP(e,t){let n=new Map,r=IP(e);for(let i of t)for(let t of LP(e,i,r))n.set(t,(n.get(t)??0)+1);return n}function xP(e,t,n){let r=new Map,i=new Set,a=IP(e),o=IP(e);for(let n of t){r.set(n.eventId,n);for(let t of LP(e,n,a))i.add(t)}for(let t of n){let n=LP(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 SP(e,t){return CP(e)&&CP(t)}function CP(e){return e.type===`native.raw`?$(Q(e.payload.raw).source)===`codex.history.thread_read`:!1}function wP(e){return e===`codex.history.thread_read`||e===`codex.history.thread_read.incremental`}function TP(e){let t=Q(e.payload.raw),n=$(t.source);return t.historyReplay===!0||wP(n)}function EP(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 DP(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&&TF(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&&TF(t)?t:void 0}if(n!==`codex.history.thread_read`||$(r.scope)!==`turn`)return;let i=$(Q(r.turn).status);return i&&TF(i)?i:void 0}function OP(e,t){if(!TP(e))return!1;let n=EP(e),r=DP(e);return!n||!r?!1:EF(t.terminalTurnStatusById.get(n),r)}function kP(e,t=!1){let n=new Set,r=new Map;for(let t of e){if(TP(t))continue;let e=EP(t);e&&n.add(e);let i=DP(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 AP(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function jP(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 MP(e,t){let n=NP(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=FP(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 NP(e){let t=new Map,n=new Map;for(let r of e){let e=PP(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 PP(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=JP(n);return r?{text:r,tsMs:t,syntheticMessageId:AF(n.id)??AF(n.item_id)??AF(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=YP(Q(Q(n.message).message));if(r)return{text:r,tsMs:t,syntheticMessageId:AF(Q(n.message).uuid)}}function FP(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||!vP.has(r))return;let i=Q(n.message);if(($(n.native_type)??$(i.type))!==`user`)return;let a=YP(Q(i.message));if(a)return{text:a,tsMs:t}}function IP(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function LP(e,t,n){return e===`codex`?RP(t,n):e===`claude`?WP(t):[]}function RP(e,t){let n=Q(e.payload.raw),r=new Set,i=GP(e.type,n);if(i){let a=zP(e.type,n);a?r.add(HP(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(KP(`turn.started`,{turn:Q(a.turn)})),[...r];if(i===`turn/completed`)return r.add(KP(`turn.completed`,{status:`completed`,turn:Q(a.turn)})),[...r];if(i===`turn/failed`||i===`turn/interrupted`)return r.add(KP(`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=zP(e,n);return o?r.add(HP(o,t,n)):r.add(KP(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(KP(`thread.started`,{thread_id:t,thread:e}));let n=OF(qP(e.preview)??qP(e.name)??``);return n&&r.add(KP(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(s===`turn`){let e=Q(o.turn),t=$(e.status);return r.add(KP(`turn.started`,{turn:e})),t===`completed`?r.add(KP(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(KP(`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),...o.semantic_occurrence===void 0?{}:{semantic_occurrence:o.semantic_occurrence}},n=zP(`item.completed`,e);return n?r.add(HP(n,t,e)):r.add(KP(`item.completed`,e)),[...r]}return[...r]}function zP(e,t){if(!e.startsWith(`item.`))return;let n=Q(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=BP($(n.type));if(!(!r||!i))return[`codex`,e,r,i,VP(i,$(n.phase)),$(n.status)??``,oF($(n.command)),oF(JP(n))].join(`|`)}function BP(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 VP(e,t){return e===`agent_message`&&(!t||t===`final_answer`)?``:t??``}function HP(e,t,n){let r=UP(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 UP(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 WP(e){let t=Q(e.payload.raw),n=GP(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!vP.has(r))return[];let i=Q(t.message),a=$(t.native_type)??$(i.type),o=Q(i.message);if(a===`user`){let e=YP(o),t=$(i.uuid);return!e||!t?[]:[KP(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=YP(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[KP(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function GP(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 KP(e,t);default:return}}function KP(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=oF($(n.command)),p=oF(JP(n)),m=oF(qP(t.message)),h=oF(qP(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 qP(e){if(typeof e==`string`)return e.length>0?e:void 0}function JP(e){let t=qP(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=qP(Q(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
525
525
|
`)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>qP(e)).filter(e=>!!e);if(e.length>0)return e.join(`
|
|
526
526
|
`)}return``}function YP(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(`
|
|
527
527
|
`)}function XP(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function ZP(e){return String(e).includes(`returned no messages from getSessionMessages`)}function QP(e){return oP(e)}function $P(e){return e?{rawSeq:e.rawSeq,type:e.type,eventId:e.eventId,ts:e.ts}:null}function eF(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(!tF(n,i))return r}return e.length===t.length?null:n}function tF(e,t){return iF(nF(e))===iF(nF(t))}function nF(e){let{ts:t,...n}=e;return n}function rF(e){if(typeof e==`string`)return aF(e);if(Array.isArray(e))return e.map(e=>rF(e));if(!e||typeof e!=`object`)return e;let t=e,n={};for(let e of Object.keys(t).sort())n[e]=rF(t[e]);return n}function iF(e){return JSON.stringify(rF(e))}function aF(e){return e.length<=4096?e:{__type:`hashed_text`,length:e.length,sha256:(0,l.createHash)(`sha256`).update(e).digest(`hex`)}}function oF(e){if(!e)return``;let t=aF(e);return typeof t==`string`?t:`sha256:${t.length}:${t.sha256}`}function sF(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 cF(e){let t=e.previousEvents[e.previousEvents.length-1]?.rawSeq??null,n=e.nextEvents[e.nextEvents.length-1]?.rawSeq??null,r=eF(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:sF(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:$P(r===null?void 0:e.previousEvents[r]),nextMismatchEvent:$P(r===null?void 0:e.nextEvents[r])}}function lF(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&&tF(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&&tF(e,r)})?{historyUpdated:!0,refreshMode:`delta`,fromRawSeq:n??0,toRawSeq:r??n??0}:{historyUpdated:!0,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}}function uF(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:bF(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);(TF(t.status)?!EF(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,AF(n.id)??null])}return t}function dF(e){let t=fF(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(jP(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:bF(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,AF(t.id)??null]);continue}let a=n!==c,o=mF(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,AF(t.id)??null])}}return r}function fF(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=pF(t,n),a=$(e.status);a&&(i.status=a),i.fingerprint=vF(e);continue}if(i!==`item`)continue;let a=Q(r.item),o=$(r.turn_id)??$(a.turn_id);if(!o)continue;let s=pF(t,o),c=hF(o,a,void 0,s.itemOccurrenceByBaseKey);c&&(s.itemFingerprintByKey.has(c)||s.itemOrder.push(c),s.itemFingerprintByKey.set(c,_F(a)))}return t}function pF(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 mF(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||hF(t.id,a,r,n)!==i||e.itemFingerprintByKey.get(i)!==_F(a))return{safe:!1,appendedItems:[],statusChanged:!1}}return e.fingerprint!==void 0&&e.fingerprint!==vF(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 hF(e,t,n,r){let i=gF(e,t,n);if(!i)return;let a=UP(t);if(a!==void 0)return`${i}|${a}`;if(!r)return i;let o=(r.get(i)??0)+1;return r.set(i,o),`${i}|${o}`}function gF(e,t,n){let r=zP(`item.completed`,{turn_id:e,item:t});if(r)return r;let i=AF(t.id);if(i)return`id:${i}`;if(n!==void 0)return`${e}::${n}`}function _F(e){let t=BP($(e.type)),n=t?VP(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),iF(r)}function vF(e){return iF({status:$(e.status)??null,error:Q(e.error)})}function yF(e){return String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``)}function bF(e,t,n){let r=n.map(yF).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 xF(e){let t=e.localCodexLiveTurnState??kP(e.localEvents),n=new Set,r=SF(e.localEvents),i=new Map(t.terminalTurnStatusById),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`)continue;if(s===`codex.app_server`){let e=Q(r.message),t=Q(e.params),i=$(e.method),a=$(Q(t.turn).id)??$(t.turn_id)??$(t.turnId);a&&(i===`turn/started`||i===`turn/completed`||i===`turn/failed`||i===`turn/interrupted`)&&n.add(a);continue}if(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&&TF(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)=>{let r=d();f.push({v:`1.0`,kind:`provider.raw`,rawSeq:o,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:u(n),ts:r,type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:t,historyReplay:!0,replaySynthetic:!0}}}),o+=1};for(let a of e.thread.turns){let s=i.get(a.id),c=EF(s,a.status);(!(n.has(a.id)||t.activeTurnIds.has(a.id))&&!c||TF(a.status)&&s!==a.status)&&p({scope:`turn`,thread_id:e.thread.id,turn:{id:a.id,status:a.status,error:a.error}},[`turn`,a.id,a.status]);let l=new Map;for(let t of a.items){let n=$(t.id),i=hF(a.id,t,void 0,l);if(i&&r.has(i))continue;let s=i?CF(i):void 0;p({scope:`item`,thread_id:e.thread.id,turn_id:a.id,item:t,...s?{semantic_occurrence:s}:{}},[`item`,a.id,n??`seq_${o}`])}}return f}function SF(e){let t=new Set,n=new Map;for(let r of e){let e=wF(r);if(!e)continue;let i=hF(e.turnId,e.item,void 0,n);i&&t.add(i)}return t}function CF(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 wF(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),...e.semantic_occurrence===void 0?{}:{semantic_occurrence:e.semantic_occurrence}},r=$(e.turn_id)??$(n.turn_id)??$(n.turnId);return!r||Object.keys(n).length===0?null:{turnId:r,item:n}}return null}function TF(e){return e===`completed`||e===`failed`||e===`interrupted`}function EF(e,t){return e===t&&TF(t)}function DF(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function OF(e,t=60){let n=DF(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function kF(e,t){if(t){let e=OF(t);if(e)return e}if(e.provider!==`codex`||!e.codex)return OF(`代码审查`);let n=e.codex.target;return n.type===`baseBranch`?OF(`审查 ${n.branch} 分支改动`):n.type===`custom`?OF(n.instructions):n.type===`commit`?OF(n.title||`审查提交 ${n.sha.slice(0,12)}`):OF(`审查未提交更改`)}function AF(e){if(typeof e!=`string`)return;let t=DF(e);if(t)return t}function jF(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function MF(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function NF(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var PF=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=FF(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,FF({...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)&&(nI(t)||await this.enqueueRawSessionWrite(t.sessionId,async()=>{if(JF(t)){let e=tI([...await this.readSessionRawEventsLocked(t.sessionId),t]);await this.replaceRawEventFile(t.sessionId,e),this.rawEventsCacheBySession.set(t.sessionId,e),this.compactedRawEventsCacheBySession.set(t.sessionId,HF(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=YF(await this.readSessionRawEventsLocked(e),r,n);await this.replaceRawEventFile(e,t);let a=HF(t);i=UF(a),this.rawEventsCacheBySession.set(e,t),this.compactedRawEventsCacheBySession.set(e,a)}),i}async getSessionRawEvents(e,t=300){return(await this.getSessionRawEventsWithCoverage(e,t)).rawEvents}async getSessionRawEventsWithCoverage(e,t=300){return this.getSessionRawEventsCompactedWithCoverage(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){return(await this.getSessionRawEventsCompactedWithCoverage(e,t)).rawEvents}async getSessionRawEventsCompactedWithCoverage(e,t=300){if(await this.ready,!this.sessions.has(e))return{rawEvents:[],coveredToRawSeq:null};let n=Math.max(1,t),r=this.readSessionRawEventsCompactedWithCoverageFromCache(e);if(r!==void 0)return BF(r,n);let i={rawEvents:[],coveredToRawSeq:null};return await this.enqueueWrite(async()=>{i=BF(await this.readSessionRawEventsCompactedWithCoverageLocked(e),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 Um(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=Um((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 zF(t);let n=null;return await this.enqueueWrite(async()=>{n=zF(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=`${RF(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=>RF(e)).join(`
|
|
528
528
|
`);await VF(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(qF(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&KF(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}GF(r,e)}}async readSessionRawEventsCompactedLocked(e){return(await this.readSessionRawEventsCompactedWithCoverageLocked(e)).rawEvents}async readSessionRawEventsCompactedWithCoverageLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return WF(t);let n=HF(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),WF(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(`
|
|
529
529
|
`).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!IF(t)||t.kind!==`provider.raw`)continue;let n=LF(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=Kl.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=>RF(e)).join(`
|
|
530
|
-
`),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){return this.readSessionRawEventsCompactedWithCoverageFromCache(e)?.rawEvents}readSessionRawEventsCompactedWithCoverageFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return WF(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=HF(n);return this.compactedRawEventsCacheBySession.set(e,r),WF(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 FF(e){let t=e.projectPath?.trim()||e.projectId;return t===e.projectId?e:{...e,projectId:t}}function IF(e){return typeof e==`object`&&!!e}function LF(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function RF(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 zF(e){if(e.length===0)return null;let t=null,n=null;for(let r of e)t=t===null?r.rawSeq:Math.min(t,r.rawSeq),n=n===null?r.rawSeq:Math.max(n,r.rawSeq);return t===null||n===null?null:{min:t,max:n}}function BF(e,t){return{rawEvents:e.rawEvents.slice(-Math.max(1,t)),coveredToRawSeq:e.coveredToRawSeq}}async function VF(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 HF(e){let t=Hm(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Gm(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t,coveredToRawSeq:zF(e)?.max??null}}function UF(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function WF(e){return{rawEvents:UF(e),coveredToRawSeq:e.coveredToRawSeq}}function GF(e,t){e.coveredToRawSeq=e.coveredToRawSeq===null?t.rawSeq:Math.max(e.coveredToRawSeq,t.rawSeq);let n=Gm(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=Km(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 KF(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function qF(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function JF(e){if(qF(e)||e.type===`turn.completed`||e.type===`turn.failed`)return!0;if(e.type!==`native.raw`)return!1;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(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 YF(e,t,n){if(n?.replaceMissing)return XF(e,t,n);let r=[...e].sort(eI),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&&ZF(n,e)&&(r[t]=$F(n,e));continue}let n={...e,rawSeq:a};a+=1,i.set(n.eventId,r.length),r.push(n)}return tI(r.sort(eI)).sort(eI)}function XF(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(eI),c=1;for(let t of e)c=Math.max(c,t.rawSeq+1);return tI(s.map(e=>{let t=r.get(e.eventId);if(t)return ZF(t,e)?$F(t,e):{...e,rawSeq:t.rawSeq};let n={...e,rawSeq:c};return c+=1,n})).sort(eI)}function ZF(e,t){return QF(e)&&QF(t)}function QF(e){return e.type===`native.raw`?sI((IF(e.payload.raw)?e.payload.raw:{}).source)===`codex.history.thread_read`:!1}function $F(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function eI(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 tI(e){let t=Wm(e).filter(e=>!nI(e)),n=new Set;for(let e of t){let t=rI(e);t&&n.add(t)}return n.size===0?t:t.filter(e=>{let t=iI(e);return!t||!n.has(t)})}function nI(e){let t=IF(e.payload.raw)?e.payload.raw:{},n=sI(t.source)??``;if(e.type!==`native.raw`&&(t.historyReplay===!0||n.startsWith(`codex.history.thread_read`)))return!0;if(e.type!==`native.raw`||n!==`codex.app_server`)return!1;let r=IF(t.message)?t.message:{};return sI(r.method)??sI(t.method)?!1:IF((IF(r.result)?r.result:{}).turn)}function rI(e){if(e.type===`item.completed`){let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.item)?t.item:{};return aI(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.message)?t.message:{},r=IF(n.params)?n.params:{};if((sI(n.method)??sI(t.method))!==`item/completed`)return null;let i=IF(r.item)?r.item:{};return aI(e.sessionId,i)}function iI(e){if(e.type===`item.updated`){let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.item)?t.item:{},r=sI(n.original_method)??sI(n.originalMethod)??``,i=IF(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`)&&!oI(r)?null:aI(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.message)?t.message:{},r=IF(n.params)?n.params:{};if(!oI(sI(n.method)??sI(t.method)??``))return null;let i=IF(r.msg)?r.msg:{},a=sI(r.itemId)??sI(r.item_id)??sI(i.itemId)??sI(i.item_id);return a?`${e.sessionId}|${a}`:null}function aI(e,t){let n=sI(t.id)??sI(t.item_id)??sI(t.itemId);return n?`${e}|${n}`:null}function oI(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function sI(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function cI(e){return!e||e.providerMode!==`native`?!1:e.interactionLockReason===`external_turn_running`?!0:e.status!==`running`}const lI=e=>e.filter(e=>!(e.kind===`system`&&e.title===`Turn Usage`)),uI=(e,t)=>e.find(e=>e.itemId===t||e.id===t)??null,dI=e=>e.kind!==`tool_card`&&e.kind!==`file_change_card`&&e.kind!==`terminal_card`||e.status!==void 0||`deferredDetail`in e&&e.deferredDetail!==void 0?null:e.itemId??e.id,fI=e=>{let t=lI(sm(e.sessionId,e.rawEvents,[]));return{timelineItems:Uo({rawEvents:e.rawEvents,messages:t,deferCompletedToolDetails:!1}).timelineItems,lastRawSeq:e.rawEvents[e.rawEvents.length-1]?.rawSeq??null}};async function pI(e){if(e.readableItemDetailLookup)return e.readableItemDetailLookup.getReadableItemDetailResult({projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId});let t=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,2**53-1),n=uI(fI({sessionId:e.sessionId,rawEvents:t}).timelineItems,e.itemId);return n?{item:n}:null}function mI(e,t){if(e&&e!==t)throw ST()}async function hI(e){let t=gI(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:_I(t)},`auth refresh attempt`);try{let t=await e.execute(),n=gI(e.authService,e.refreshToken),r=gI(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:_I(n),nextRefreshToken:_I(r)},`auth refresh succeeded`),t}catch(t){let n=gI(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:_I(n),error:vI(t)},`auth refresh failed`),t}}function gI(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function _I(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:yI(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:yI(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function vI(e){return _T(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function yI(e){return e?e.slice(-8):null}function bI(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:xI(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:hh(e.identity,e.privateKeyPem,i)}}function xI(e){return e.replace(/\s+/gu,``).toUpperCase()}async function SI(e,t){try{let n=np.parse(e);switch(n.method){case`auth.refresh`:{let e=await hI({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 mI(n.params.deviceId??t.relayDeviceId,e.deviceId),rp.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return rp.parse({method:n.method,result:{projects:e}})}case`codex.accounts.get`:{let e=await t.sessionManager.getCodexAccounts();return rp.parse({method:n.method,result:e})}case`codex.accounts.save`:{let e=await t.sessionManager.saveCurrentCodexAccount();return rp.parse({method:n.method,result:e})}case`codex.accounts.switch`:{let e=await t.sessionManager.switchCodexAccount(n.params.accountId);return rp.parse({method:n.method,result:e})}case`codex.accounts.delete`:{let e=await t.sessionManager.deleteSavedCodexAccount(n.params.accountId);return rp.parse({method:n.method,result:e})}case`gateway.settings.get`:return rp.parse({method:n.method,result:t.gatewaySettings.get()});case`gateway.settings.update`:{let e=await t.gatewaySettings.update(n.params);return rp.parse({method:n.method,result:e})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return rp.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return rp.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return rp.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return rp.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return rp.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return rp.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw wI(n.method,`NOT_FOUND`,404,`Project not found`);return rp.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 rp.parse({method:n.method,result:e})}case`workspace.directories.create`:{let e=await t.fsService.createDirectoryUnrestricted(n.params.path,n.params.name,200);return rp.parse({method:n.method,result:e})}case`workspace.entries.list`:{let e=await t.workspaceFileService.listEntries(n.params.locator,n.params.limit??200);return rp.parse({method:n.method,result:e})}case`workspace.files.resolve`:{let e=await t.workspaceFileService.resolveFile(n.params.locator);return rp.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 rp.parse({method:n.method,result:e})}case`workspace.files.preparePreview`:{let e=t.relayPreviewBaseUrl?.trim(),r=t.gatewayId?.trim();if(!e||!r)throw wI(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 rp.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 rp.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return rp.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw wI(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return rp.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 wI(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return rp.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}),rp.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 rp.parse({method:n.method,result:r})}case`sessions.readableItem.get`:{let e=await pI({sessionManager:t.sessionManager,readableItemDetailLookup:t.readableItemDetailLookup,projectId:n.params.projectId,sessionId:n.params.sessionId,itemId:n.params.itemId});if(!e)throw wI(n.method,`NOT_FOUND`,404,`Readable item ${n.params.itemId} not found`);return rp.parse({method:n.method,result:e})}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`),rp.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`providers.execution.update`:{let e=await t.sessionManager.updateProviderExecutionDefaults(n.params);return rp.parse({method:n.method,result:{defaults:e}})}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 rp.parse({method:n.method,result:e})}case`devices.list`:return rp.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw wI(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return rp.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw wI(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw CI(e)}}function CI(e){if(_T(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return wI(`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 wI(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return wI(`BAD_REQUEST`,e.status,String(e),e.details);default:return wI(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=ap.safeParse(e);if(t.success)return t.data;let n=ip.safeParse(e);if(n.success)return wI(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 wI(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?wI(`BAD_REQUEST`,400,r):TI(e)?wI(`UNAUTHORIZED`,401,r):EI(r)?wI(`BAD_REQUEST`,400,r):wI(`INTERNAL`,500,r)}function wI(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 ap.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function TI(e){return _T(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||LT(e)}function EI(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 DI(e,t){return e.length===0?[]:t===void 0?[...e]:e.filter(e=>e.rawSeq>t)}function OI(e){let t=e.coveredToRawSeq??void 0;for(let n of e.rawEvents)(t===void 0||n.rawSeq>t)&&(t=n.rawSeq);return t}function kI(e){return{baseRawEvents:Hm(e.rawEvents.filter(t=>t.rawSeq<=e.cursorRawSeq)),nextRawEvents:Hm(e.rawEvents)}}function AI(e,t){return t&&`kind`in t&&t.kind===`bootstrapping`?t:{kind:`bootstrapping`,sessionId:e,previousReadyState:t??null,queuedEnvelopes:[]}}function jI(e,t){let n=e.previousReadyState;if(!n)return{previousReadyState:null,nextReadyState:null,replayedEnvelopes:[]};let r=DI(e.queuedEnvelopes,OI(n)),i=n;for(let e of r)i=t(i,e);return{previousReadyState:n,nextReadyState:i,replayedEnvelopes:r}}function MI(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_${hT(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}}function NI(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.sessionSummary?{sessionSummary:e.sessionSummary}:{}},...e.timelineItems?{readable:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,...e.timelineItems?{timelineItems:e.timelineItems}:{}}}:{}}}}function PI(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},...e.sessionSummary?{sessionSummary:e.sessionSummary}:{}}}}}function FI(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 II(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_${hT(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,...e.sessionSummary?{sessionSummary:e.sessionSummary}:{}}}}}function LI(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 RI=1e3,zI=(e,t)=>`${e}::${t}`,BI=e=>e.purpose===`detail_view`&&e.bootstrapMode===`readable`,VI=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},HI=e=>{let t;for(let n of e)(t===void 0||n.rawSeq>t)&&(t=n.rawSeq);return t},UI=e=>e[e.length-1]?.rawSeq,WI=(e,t)=>{let n=HI(e);return t==null?n??null:n===void 0?t:Math.max(t,n)},GI=e=>WI(e.rawEvents,e.coveredToRawSeq)??void 0,KI=e=>{let t=WI(e.rawEvents,e.coveredToRawSeq);return{kind:`ready`,sessionId:e.target.sessionId,projectId:e.target.projectId,provider:e.target.provider,detailLevel:e.target.detailLevel,rawEvents:[...e.rawEvents],coveredToRawSeq:t,detailTransportRawEvents:[...e.detailTransportRawEvents??e.rawEvents],contextUsage:e.contextUsage??null,timelineItems:[...e.timelineItems],pendingApprovals:[...e.pendingApprovals],pendingUserInputs:[...e.pendingUserInputs]}},qI=e=>typeof e==`object`&&e?e:{},JI=(e,...t)=>{for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}},YI=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=qI(n),r=JI(e,`id`),i=JI(e,`header`),a=JI(e,`question`);if(!r||!i||!a)continue;let o=Array.isArray(e.options)?e.options.map(e=>{let t=qI(e),n=JI(t,`label`);if(!n)return null;let r=JI(t,`description`)??n,i=JI(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},XI=(e,t)=>{let n=om(e,t),r=new Map,i=new Map;for(let e of n){if(e.type===`tool.permission.requested`){let t=qI(e.payload.raw),n=JI(t,`requestId`,`request_id`);if(!n)continue;let i=qI(t.rawParams??t.raw_params),a=qI(i.networkApprovalContext??i.network_approval_context);r.set(n,{requestId:n,sessionId:e.sessionId,...JI(t,`toolName`,`tool_name`)?{toolName:JI(t,`toolName`,`tool_name`)}:{},...JI(t,`reason`)?{reason:JI(t,`reason`)}:{},...JI(i,`command`)?{command:JI(i,`command`)}:{},...JI(i,`cwd`)?{cwd:JI(i,`cwd`)}:{},...JI(i,`grantRoot`,`grant_root`)?{grantRoot:JI(i,`grantRoot`,`grant_root`)}:{},...JI(a,`host`)?{networkHost:JI(a,`host`)}:{},...JI(a,`protocol`)?{networkProtocol:JI(a,`protocol`)}:{},...JI(t,`itemId`,`item_id`)?{itemId:JI(t,`itemId`,`item_id`)}:{},...JI(t,`turnId`,`turn_id`)?{turnId:JI(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`tool.permission.resolved`){let t=JI(qI(e.payload.raw),`requestId`,`request_id`);t&&r.delete(t);continue}if(e.type===`user.input.requested`){let t=qI(e.payload.raw),n=JI(t,`requestId`,`request_id`);if(!n)continue;i.set(n,{requestId:n,sessionId:e.sessionId,questions:YI(t.questions),...JI(t,`itemId`,`item_id`)?{itemId:JI(t,`itemId`,`item_id`)}:{},...JI(t,`turnId`,`turn_id`)?{turnId:JI(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`user.input.resolved`){let t=JI(qI(e.payload.raw),`requestId`,`request_id`);t&&i.delete(t)}}return{pendingApprovals:[...r.values()],pendingUserInputs:[...i.values()]}},ZI=e=>{let t=e.rawEventsAlreadyMatchDetailTransport===!0?e.rawEvents:eL({rawEvents:e.rawEvents,detailLevel:e.target.detailLevel}),n=e.target.purpose===`detail_view`?Cl({provider:e.target.provider,rawEvents:t}):null,r=e.target.purpose===`detail_view`?lI(sm(e.target.sessionId,t,[])):[],i=e.target.purpose===`detail_view`?Uo({rawEvents:t,messages:r,deferCompletedToolDetails:!0}):{timelineItems:[],consumedMessageIds:[]},a=e.target.purpose===`detail_view`?XI(e.target.sessionId,t):{pendingApprovals:[],pendingUserInputs:[]};return{detailTransportRawEvents:t,contextUsage:n,timelineItems:i.timelineItems,pendingApprovals:a.pendingApprovals,pendingUserInputs:a.pendingUserInputs}},QI=e=>{let t=eL({rawEvents:e.rawEvents,detailLevel:e.target.detailLevel}),n=ZI({target:e.target,rawEvents:t,rawEventsAlreadyMatchDetailTransport:!0});return KI({target:e.target,rawEvents:e.rawEvents,coveredToRawSeq:e.coveredToRawSeq,detailTransportRawEvents:t,contextUsage:n.contextUsage,timelineItems:n.timelineItems,pendingApprovals:n.pendingApprovals,pendingUserInputs:n.pendingUserInputs})},$I=(e,t)=>{let n=cL(e.rawEvents,t),r=WI(n,GI(e)),i=eL({rawEvents:cL(e.detailTransportRawEvents,t),detailLevel:e.detailLevel}),a=ZI({target:{sessionId:e.sessionId,provider:e.provider,detailLevel:e.detailLevel,purpose:`detail_view`},rawEvents:i,rawEventsAlreadyMatchDetailTransport:!0});return{...e,rawEvents:n,coveredToRawSeq:r,detailTransportRawEvents:i,contextUsage:a.contextUsage,timelineItems:a.timelineItems,pendingApprovals:a.pendingApprovals,pendingUserInputs:a.pendingUserInputs}},eL=e=>{if(e.detailLevel!==`compact`||e.rawEvents.length===0)return e.rawEvents;let t=tL(e.rawEvents[0]?.sessionId??``,e.rawEvents);return lD(e.rawEvents,e.detailLevel,{preserveIncompleteCommandOutput:!0,additionalCompletedCommandItemKeys:t})},tL=(e,t)=>{if(!e||t.length===0)return new Set;let n=new Set,r=sm(e,t,[]);for(let t of r){if(t.itemType!==`command_execution`||!t.itemId||t.status!==`completed`&&t.status!==`failed`)continue;let r=aL(e,t.itemId);r&&n.add(r)}return n},nL=e=>JI(e,`id`,`itemId`,`item_id`)??null,rL=e=>{if(e.type===`item.started`||e.type===`item.updated`||e.type===`item.completed`)return nL(qI(qI(e.payload.raw).item));if(e.type!==`native.raw`)return null;let t=qI(qI(e.payload.raw).message),n=qI(t.params),r=qI(n.item),i=qI(n.msg);return nL(r)??nL(qI(t.item))??JI(n,`itemId`,`item_id`)??JI(i,`itemId`,`item_id`)??null},iL=e=>{if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=qI(e.payload.raw);return(JI(qI(t.message),`method`)??JI(t,`method`))===`item/completed`},aL=(e,t)=>t?`${e}|${t}`:null,oL=e=>aL(e.sessionId,rL(e)),sL=e=>{let t=oL(e);if(t)return`item:${t}`;let n=Gm(e);return n?`delta:${n.key}`:null},cL=(e,t)=>{let n=[...e],r=oL(t),i=sL(t),a=Gm(t),o=t;if(i&&a)for(let e=n.length-1;e>=0;--e){let r=n[e];if(!r||sL(r)!==i||!Gm(r))continue;let a=Km(r,t);if(a){n[e]=null,o=a;break}}return n.push(o),!r||!iL(t)?n.filter(e=>e!==null):n.filter(e=>e!==null&&(e.eventId===o.eventId||oL(e)!==r||!Gm(e)))},lL=e=>{let t=uL(e);if(!t)return null;let n=nL(t),r=qI(t.payload),i=JI(t,`output_delta`,`outputDelta`)??JI(r,`output_delta`,`outputDelta`);return!n||!i?null:{itemId:n,delta:i}},uL=e=>{if(e.type===`item.updated`){let t=qI(qI(e.payload.raw).item);return dL(t)?t:null}if(e.type!==`native.raw`)return null;let t=qI(e.payload.raw),n=qI(t.message);if((JI(n,`method`)??JI(t,`method`))!==`item/updated`)return null;let r=qI(qI(n.params).item);return dL(r)?r:null},dL=e=>{let t=JI(e,`type`);return t===`commandExecution`||t===`command_execution`},fL=e=>e.includes(`[compact history preview:`),pL=(e,t)=>{let n=lL(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`||fL(i.output))return null;let a=cL(e.rawEvents,t),o=eL({rawEvents:cL(e.detailTransportRawEvents,t),detailLevel:e.detailLevel}),s={...i,output:`${i.output}${n.delta}`},c=[...e.timelineItems];c[r]=s;let l=GI(e),u=WI(a,l)??t.rawSeq;return{nextState:{...e,rawEvents:a,coveredToRawSeq:u,detailTransportRawEvents:o,timelineItems:c},messageInput:{provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,fromRawSeq:l,toRawSeq:u,timelineUpserts:[],timelineRemovals:[],timelineTextDeltaPatches:[{id:i.id,field:`output`,delta:n.delta}]}}},mL=e=>Buffer.byteLength(JSON.stringify(PI(e)),`utf8`),hL=e=>{let t=Math.max(1,Math.floor(e.maxChunkBytes??524288)),n=[],r=(t,n)=>mL({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,sessionSummary:t===0?e.sessionSummary: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},gL=(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)}},_L=(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)}},vL=(e,t,n,r)=>{let i={},a=om(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=JI(qI(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};function yL(e){let t,n=e.previousState;for(let r of e.envelopes){let i=$I(n,r),a=vL(e.sessionId,r,n,i);a&&(t={...t??{},...a}),n=i}return t}const bL=e=>{if(!e)return{stateFound:!1};let t=HI(e.rawEvents),n=UI(e.rawEvents),r=GI(e);return{stateFound:!0,kind:e.kind,sessionId:e.sessionId,projectId:e.projectId,provider:e.provider,detailLevel:e.detailLevel,rawEventCount:e.rawEvents.length,detailTransportRawEventCount:e.detailTransportRawEvents.length,firstRawSeq:e.rawEvents[0]?.rawSeq??null,lastRawSeq:r??null,rawEventMaxRawSeq:t??null,orderedLastRawSeq:n??null,rawSeqOrderMismatch:t!==n,rawSeqCoverageMismatch:r!==t,timelineItemCount:e.timelineItems.length,pendingApprovalCount:e.pendingApprovals.length,pendingUserInputCount:e.pendingUserInputs.length,hasContextUsage:!!e.contextUsage}},xL=e=>e?e.kind===`ready`?bL(e):{stateFound:!0,kind:e.kind,sessionId:e.sessionId,queuedEnvelopeCount:e.queuedEnvelopes.length,previousReadyState:bL(e.previousReadyState)}:{stateFound:!1},SL=(e,t)=>{let n,r,i;try{n=Rc(e.previousState.timelineItems,e.nextState.timelineItems),r=gL(e.previousState.pendingApprovals,e.nextState.pendingApprovals),i=_L(e.previousState.pendingUserInputs,e.nextState.pendingUserInputs)}catch(n){throw t?.(`stream.readable.delta.build.error`,{sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,previousState:bL(e.previousState),nextState:bL(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=GI(e.nextState);return o===void 0?null:{provider:e.previousState.provider,sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,fromRawSeq:GI(e.previousState),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 CL(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}}function wL(e){return e===`external_turn_running`?e:void 0}function TL(e){return{status:e.status,...e.updatedAt?{updatedAt:e.updatedAt}:{},...e.interactionLockReason?{interactionLockReason:e.interactionLockReason}:{}}}var EL=class{stateByClientSession=new Map;pendingDeltaByClientSession=new Map;itemDetailCache=new Map;constructor(e,t,n,r,i=512){this.sessionHub=e,this.sessionManager=t,this.readableLiveDeltaCoalesceMs=n,this.log=r,this.itemDetailCacheMaxEntries=i}shutdown(){for(let e of this.pendingDeltaByClientSession.values())clearTimeout(e.timer);this.pendingDeltaByClientSession.clear(),this.stateByClientSession.clear(),this.itemDetailCache.clear()}handleSessionStreamSubscribeCommand=async(e,t,n)=>{let r=VI(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 BI(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=zI(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:xL(r),hadPendingDelta:!!i,pendingDeltaFromRawSeq:i?GI(i.previousState)??null:null,pendingDeltaToRawSeq:i?GI(i.nextState)??null: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))};getReadableItemDetailResult=async e=>{let t=this.getLatestReadableReadyStateForSession(e.projectId,e.sessionId),n=t?uI(t.timelineItems,e.itemId):null,r=n&&`deferredDetail`in n&&n.deferredDetail!==void 0;if(n&&!r){let r=dI(n);return r&&this.setReadableItemDetailCacheEntry({projectId:e.projectId,sessionId:e.sessionId,itemId:r,item:n}),this.log(`readable.item_detail.cache_hit`,{projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId,source:`live_state`,lastRawSeq:t?GI(t)??null:null}),{item:n}}let i=this.getReadableItemDetailCacheEntry(e.projectId,e.sessionId,e.itemId);if(i)return this.log(`readable.item_detail.cache_hit`,{projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId,source:`item_cache`}),{item:i.item};let a=await this.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,2**53-1),o=fI({sessionId:e.sessionId,rawEvents:a}),s=this.seedReadableItemDetailCache({projectId:e.projectId,sessionId:e.sessionId,timelineItems:o.timelineItems}),c=uI(o.timelineItems,e.itemId);return this.log(`readable.item_detail.projection_rebuilt`,{projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId,source:t?`session_history_after_live_state`:`session_history`,lastRawSeq:o.lastRawSeq,timelineItemCount:o.timelineItems.length,cachedItemCount:s,found:!!c}),c?{item:c}:null};routeReadableLiveDelta=e=>{let t=this.sessionHub.getClientSubscriptionsForSession(e.sessionId,`detail_view`);if(t.length!==0)for(let{clientId:n,subscription:r}of t){if(!BI(r))continue;let t=zI(n,e.sessionId),i=this.stateByClientSession.get(t);if(!i)continue;if(i.kind===`bootstrapping`){i.queuedEnvelopes.push(e);continue}let a=pL(i,e);if(a){this.flushPendingReadableLiveDelta(n,e.sessionId),this.stateByClientSession.set(t,a.nextState),this.sessionHub.sendSessionMessageToClient(n,e.sessionId,FI(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=$I(i,e);this.stateByClientSession.set(t,o);let s=vL(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 BI(r)&&this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:n,sessionId:e.sessionId}),t}finally{this.sessionHub.resumeSession(n,e.sessionId)}}}};sendSessionSnapshot=async(e,t,n)=>{let r=`snap_${hT(12)}`,{compactedRawEvents:i,detailTransportRawEvents:a,lastRawSeq:o,slimReadableProjection:s,pendingApprovals:c,pendingUserInputs:l}=await this.buildReadableSnapshotProjection(t),u=TL(t);this.sessionHub.sendStreamMessage(e,MI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...o===void 0?{}:{toRawSeq:o}}));let d=LI(a,RI),f=t.purpose===`detail_view`?LI(s.timelineItems,RI):[],p=t.purpose===`detail_view`?`raw+readable`:`raw`,m=Math.max(d.length,f.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:p,compactedEventCount:i.length,detailTransportEventCount:a.length,readableTimelineItemCount:s.timelineItems.length,totalChunks:m,firstRawSeq:a[0]?.rawSeq??null,lastRawSeq:o??null,orderedLastRawSeq:UI(i)??null,rawSeqOrderMismatch:o!==UI(i)});for(let n=0;n<m;n+=1){let i=d[n]??[],a=f[n]??[];this.sessionHub.sendStreamMessage(e,NI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:m,events:i,timelineItems:t.purpose===`detail_view`?a:void 0,sessionSummary:n===0?u:void 0}))}};sendSessionReadableSnapshot=async(e,t,n)=>{let r=`snap_${hT(12)}`,i=this.startReadableLiveProjectionBootstrap({clientId:e,sessionId:t.sessionId});try{let{compactedRawEvents:a,detailTransportRawEvents: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||!BI(f)||p&&p!==t.projectId||(f.detailLevel??`full`)!==t.detailLevel){this.clearState(e,t.sessionId);return}let m=TL(t),h=KI({target:t,rawEvents:a,coveredToRawSeq:c,detailTransportRawEvents:o,contextUsage:s,timelineItems:l.timelineItems,pendingApprovals:u,pendingUserInputs:d}),g=this.stateByClientSession.get(i),_=DI(g?.kind===`bootstrapping`?g.queuedEnvelopes:[],c),v=yL({sessionId:t.sessionId,previousState:h,envelopes:_});for(let e of _)h=$I(h,e);let y={...m,...v??{}};this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:h.rawEvents,coveredToRawSeq:GI(h),detailTransportRawEvents:h.detailTransportRawEvents,contextUsage:h.contextUsage,timelineItems:h.timelineItems,pendingApprovals:h.pendingApprovals,pendingUserInputs:h.pendingUserInputs});let b=GI(h),x=UI(h.rawEvents);this.sessionHub.sendStreamMessage(e,MI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...b===void 0?{}:{toRawSeq:b}}));let S=hL({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,timelineItems:h.timelineItems,pendingApprovals:h.pendingApprovals,pendingUserInputs:h.pendingUserInputs,contextUsage:h.contextUsage,sessionSummary:y}),C=Math.max(S.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:h.rawEvents.length,detailTransportRawEventCount:h.detailTransportRawEvents.length,readableTimelineItemCount:h.timelineItems.length,bufferedReadableDeltaCount:_.length,readableChunkTargetBytes:524288,readableChunkItemCounts:S.map(e=>e.timelineItems.length),readableChunkEstimatedBytes:S.map(e=>e.estimatedByteLength),totalChunks:C,firstRawSeq:h.rawEvents[0]?.rawSeq??null,lastRawSeq:b??null,orderedLastRawSeq:x??null,rawSeqOrderMismatch:b!==x});for(let n=0;n<C;n+=1){let i=S[n];this.sessionHub.sendStreamMessage(e,PI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:C,timelineItems:i?.timelineItems??[],pendingApprovals:n===0?h.pendingApprovals:void 0,pendingUserInputs:n===0?h.pendingUserInputs:void 0,contextUsage:n===0?h.contextUsage:void 0,sessionSummary:n===0?y:void 0}))}}catch(n){throw this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:e,sessionId:t.sessionId}),n}};sendSessionReadableResumeDelta=async(e,t,n,r)=>{let i=zI(e,t.sessionId),a=await this.sessionManager.getProjectSessionRawEventsWithCoverage(t.projectId,t.sessionId,2**53-1),o=a.rawEvents,s=a.coveredToRawSeq,{baseRawEvents:c,nextRawEvents:l}=kI({rawEvents:o,cursorRawSeq:n}),u=QI({target:t,rawEvents:c,coveredToRawSeq:n}),d=QI({target:t,rawEvents:l,coveredToRawSeq:Math.max(n,s??0)}),f=GI(d),p=this.stateByClientSession.get(i),m=DI(p?.kind===`bootstrapping`?p.queuedEnvelopes:[],f);for(let e of m)d=$I(d,e);let h=GI(u),g=UI(u.rawEvents),_=GI(d),v=UI(d.rawEvents),y=yL({sessionId:t.sessionId,previousState:u,envelopes:[...l.filter(e=>e.rawSeq>n),...m]});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:o.length,baseRawEventCount:c.length,nextRawEventCount:l.length,previousMaxRawSeq:h??null,previousOrderedLastRawSeq:g??null,nextMaxRawSeq:_??null,nextOrderedLastRawSeq:v??null,rawSeqOrderMismatch:h!==g||_!==v,bootstrapState:xL(p),bufferedEnvelopeCount:m.length,previousState:bL(u),nextState:bL(d),sessionSummaryKeys:y?Object.keys(y):[],sessionSummaryStatus:y?.status??null,sessionSummaryUpdatedAt:y?.updatedAt??null}),this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:d.rawEvents,coveredToRawSeq:GI(d),detailTransportRawEvents:d.detailTransportRawEvents,contextUsage:d.contextUsage,timelineItems:d.timelineItems,pendingApprovals:d.pendingApprovals,pendingUserInputs:d.pendingUserInputs});let b=GI(d)??n;this.sessionHub.sendStreamMessage(e,MI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`delta`,reason:r,fromRawSeq:n,...b===void 0?{}:{toRawSeq:b}}));let x=SL({previousState:u,nextState:d,sessionSummary:y},this.log);this.log(`stream.readable.resume.delta`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,reason:r,cursorRawSeq:n,emittedDelta:!!x,deltaFromRawSeq:x?.fromRawSeq??n,deltaToRawSeq:x?.toRawSeq??b??null,timelineUpsertCount:x?.timelineUpserts.length??0,timelineRemovalCount:x?.timelineRemovals.length??0,timelineTextDeltaPatchCount:x?.timelineTextDeltaPatches.length??0,pendingApprovalUpsertCount:x?.pendingApprovalUpserts.length??0,pendingUserInputUpsertCount:x?.pendingUserInputUpserts.length??0,sessionSummaryStatus:x?.sessionSummary?.status??null,sessionSummaryUpdatedAt:x?.sessionSummary?.updatedAt??null}),this.sessionHub.sendSessionMessageToClient(e,t.sessionId,FI(x??{provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,fromRawSeq:n,toRawSeq:b,timelineUpserts:[],timelineRemovals:[]}))};getReadableItemDetailCacheKey(e,t,n){return`${e}::${t}::${n}`}getReadableItemDetailCacheEntry(e,t,n){let r=this.getReadableItemDetailCacheKey(e,t,n),i=this.itemDetailCache.get(r);return i?(this.itemDetailCache.delete(r),this.itemDetailCache.set(r,i),i):null}setReadableItemDetailCacheEntry(e){let t=this.getReadableItemDetailCacheKey(e.projectId,e.sessionId,e.itemId);for(this.itemDetailCache.has(t)&&this.itemDetailCache.delete(t),this.itemDetailCache.set(t,e);this.itemDetailCache.size>Math.max(1,this.itemDetailCacheMaxEntries);){let e=this.itemDetailCache.keys().next().value;if(!e)break;this.itemDetailCache.delete(e)}}seedReadableItemDetailCache(e){let t=0;for(let n of e.timelineItems){let r=dI(n);r&&(this.setReadableItemDetailCacheEntry({projectId:e.projectId,sessionId:e.sessionId,itemId:r,item:n}),t+=1)}return t}getLatestReadableReadyStateForSession(e,t){let n=null,r=-1,i=i=>{if(!i||i.projectId!==e||i.sessionId!==t)return;let a=GI(i)??-1;a<r||(n=i,r=a)};for(let e of this.stateByClientSession.values())e.kind===`ready`&&i(e);for(let e of this.pendingDeltaByClientSession.values())i(e.nextState);return n}syncReadableLiveProjectionSubscriptions(e,t,n,r){let i=new Set(n.filter(BI).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)BI(t)||this.clearState(e,t.sessionId)}startReadableLiveProjectionBootstrap(e){let t=zI(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=AI(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:xL(n),clearedPendingDelta:!!r,carriedPendingEnvelopeCount:a.length}),t}getReadableDeliveredReadyState(e,t){let n=zI(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?DI(t.nextState.rawEvents,e?GI(e):void 0):[]}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=GI(n);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=KI(e);this.stateByClientSession.set(zI(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:bL(t)})}primeReadableBootstrapForSubscriptions(e,t){for(let n of t)BI(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,MI({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 ET(n,t);let i={sessionId:t,projectId:n,provider:r.provider,status:r.status,updatedAt:r.updatedAt,interactionLockReason:wL(r.interactionLockReason),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:CL(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`,updatedAt:i?.updatedAt,interactionLockReason:wL(i?.interactionLockReason),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:CL(i)}),a}async buildReadableSnapshotProjection(e){let t=await this.sessionManager.getProjectSessionRawEventsCompactedWithCoverage(e.projectId,e.sessionId,2**53-1),n=t.rawEvents,r=eL({rawEvents:n,detailLevel:e.detailLevel}),i=ZI({target:e,rawEvents:r,rawEventsAlreadyMatchDetailTransport:!0}),a=WI(n,t.coveredToRawSeq)??void 0;return{compactedRawEvents:n,detailTransportRawEvents:r,contextUsage:i.contextUsage,lastRawSeq:a,slimReadableProjection:{timelineItems:i.timelineItems,consumedMessageIds:[]},pendingApprovals:i.pendingApprovals,pendingUserInputs:i.pendingUserInputs}}restoreReadableLiveProjectionAfterBootstrapFailure(e){let t=zI(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=jI(n,$I);if(!a.previousReadyState||!r||!BI(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:xL(n),currentSubscriptionFound:!!r,currentSubscriptionProjectId:i||null,currentSubscriptionDetailLevel:r?.detailLevel??null,previousReadyState:bL(a.previousReadyState),nextReadyState:bL(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:bL(a.nextReadyState)});return}let o=yL({sessionId:e.sessionId,previousState:a.previousReadyState,envelopes:a.replayedEnvelopes}),s=SL({previousState:a.previousReadyState,nextState:a.nextReadyState,sessionSummary:o},this.log);if(!s){this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:bL(a.nextReadyState),emittedDelta:!1});return}this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:bL(a.nextReadyState),emittedDelta:!0,deltaFromRawSeq:s.fromRawSeq??null,deltaToRawSeq:s.toRawSeq}),this.sessionHub.sendSessionMessageToClient(e.clientId,a.previousReadyState.sessionId,FI(s))}sendReadableLiveDeltaNow(e){let t=SL({previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary},this.log);t&&this.sessionHub.sendSessionMessageToClient(e.clientId,e.previousState.sessionId,FI(t))}flushPendingReadableLiveDelta(e,t){let n=zI(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=zI(e.clientId,e.previousState.sessionId),n=this.pendingDeltaByClientSession.get(t);if(n){let t=DL({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 DL(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 OL(e){return e.sendProviderRaw?`relay_ws`:`direct_ws`}function kL(e){let t=performance.now(),n=JSON.stringify(e);return{payload:n,byteLength:Buffer.byteLength(n),serializeDurationMs:Number((performance.now()-t).toFixed(3))}}function AL(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 jL=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${hT(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??kL(t),i=AL(t);return i&&oM(`stream.snapshot.chunk.outbound`,{clientId:e.id,deviceId:e.deviceId,transport:OL(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 ML=1200,NL=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var PL=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){NL&&(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,lastSentConfigSummary:void 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,this.isGatewayOwnedRuntimeLive(n.projectId,n.sessionId,r)||!cI(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=this.isGatewayOwnedRuntimeLive(n.projectId,n.sessionId,i.session),o=n.lastObservedRawSeq,s=n.lastObservedRawEventCount,c=this.resolveObservedRawSeq(i),l=c>o||i.rawEvents.length>s;if(l?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:o,previousObservedRawEventCount:s,nextObservedRawSeq:c,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,c),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),a){this.clearCatchupRetry(n,{resetAttempts:!0}),n.stableIdleSyncCount=0,this.logDebug(`sync.result.stand_down.gateway_live`,{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});return}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:l,previousObservedRawSeq:o,previousObservedRawEventCount:s,nextObservedRawSeq:c,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount});let u=FL(i.session),d=RL(u);if(i.historyUpdated||i.statusChanged||IL(t)&&zL(t,n.lastSentConfigSummary,d)){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,sessionSummary:u});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e);d&&(n.lastSentConfigSummary=d)}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:ML,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`)},ML))))}stateKey(e,t){return JSON.stringify([e,t])}isGatewayOwnedRuntimeLive(e,t,n){return this.options.sessionManager.isGatewayOwnedRuntimeLive?.(e,t)?!0:n?n.status===`running`&&n.interactionLockReason!==`external_turn_running`:!1}};function FL(e){return{updatedAt:e.updatedAt,status:e.status,interactionLockReason:e.interactionLockReason,...e.model?{model:e.model}:e.sessionTurnConfig?.model===null?{model:null}:{},...e.sessionTurnConfig?{sessionTurnConfig:e.sessionTurnConfig}:{},...e.sessionTurnConfigUpdatedAt?{sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt}:{}}}function IL(e){return e===`lease_added`||e===`watch`||e===`watch_catchup`||e===`reconcile`||e===`rerun`}function LL(e){return!!(e&&Object.prototype.hasOwnProperty.call(e,`model`)||e?.sessionTurnConfig||e?.sessionTurnConfigUpdatedAt)}function RL(e){if(LL(e))return{...e&&Object.prototype.hasOwnProperty.call(e,`model`)?{model:e.model??null}:{},...e?.sessionTurnConfig?{sessionTurnConfig:e.sessionTurnConfig}:{},...e?.sessionTurnConfigUpdatedAt?{sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt}:{}}}function zL(e,t,n){return n?e===`lease_added`?!0:!BL(t,n):!1}function BL(e,t){if(!e||!t)return e===t;let n=Object.prototype.hasOwnProperty.call(e,`model`);return n!==Object.prototype.hasOwnProperty.call(t,`model`)||n&&e.model!==t.model||e.sessionTurnConfigUpdatedAt!==t.sessionTurnConfigUpdatedAt?!1:VL(e.sessionTurnConfig,t.sessionTurnConfig)}function VL(e,t){return!e||!t?e===t:e.mode===t.mode&&e.model===t.model&&e.reasoningEffort===t.reasoningEffort&&(e.execution?.codex?.approvalPolicy??null)===(t.execution?.codex?.approvalPolicy??null)&&(e.execution?.codex?.sandboxMode??null)===(t.execution?.codex?.sandboxMode??null)&&(e.execution?.claude?.permissionMode??null)===(t.execution?.claude?.permissionMode??null)}var HL=class{constructor(e){this.config=e}issue(e){let t=UL(e.sizeBytes??0),n=oT.default.sign({sub:e.deviceId,type:`workspace_preview`,gatewayId:this.config.gatewayId,path:e.canonicalPath,disposition:e.disposition},this.config.accessSecret,{expiresIn:t}),r=oT.default.decode(n);return{ticket:n,expiresAt:r?.exp?new Date(r.exp*1e3).toISOString():new Date().toISOString()}}getExpiresAt(e){let t=oT.default.decode(e);return t?.exp?new Date(t.exp*1e3).toISOString():new Date().toISOString()}verify(e){let t;try{t=oT.default.verify(e,this.config.accessSecret)}catch(e){if(e instanceof Error){if(e.name===`TokenExpiredError`)throw wT();if(e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)throw CT()}throw e}if(t.type!==`workspace_preview`||t.gatewayId!==this.config.gatewayId)throw CT();return t}};function UL(e){return e>20971520?7200:600}var WL=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:KL(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:KL(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=GL(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=GL(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 TT(e);return t}};function GL(e){return e.split(p.default.sep).join(`/`)}function KL(e,t){return`${e}; filename="${t.replace(/["\\]/g,`_`)}"`}function qL(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 JL=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;const YL=`[redacted:image-data]`;let XL=null;const ZL={perMessageDeflate:{threshold:1024}},QL={globalDecompression:!1,threshold:1024,customTypes:/^text\/(?!event-stream)|(?:\+|\/)json(?:;|$)|(?:\+|\/)text(?:;|$)|(?:\+|\/)xml(?:;|$)/u},$L=4096;function eR(e){if(Array.isArray(e))return e.map(e=>eR(e));if(!e||typeof e!=`object`)return e;let t={};for(let[n,r]of Object.entries(e))t[n]=n===`dataBase64`||n===`data_base64`?YL:eR(r);return t}function tR(e,t){if(e)try{return JSON.stringify(eR(e))}catch{}return t.replace(/("(?:dataBase64|data_base64)"\s*:\s*")([^"]*)(")/gu,`$1${YL}$3`)}function nR(e){return p.default.join(p.default.dirname(e),`session-attachments`)}function rR(e,t){JL&&(console.log(`[native-watch][gateway]`,e,t),XL?.info({event:e,...t},`native session watch debug`))}function iR(e){return e?typeof e==`string`?e:e.toString(`utf8`):``}function aR(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 oR(e){let t=e.limit??300,n=e.detailLevel??`full`,r=(r,i)=>{oM(`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:lD(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:lD(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:lD(o,n)};return r(s,{rangeMin:i.min,rangeMax:i.max,minExpectedCursor:a}),s}async function sR(e,t={}){await C_(e.gatewayLogPath);let n=lR(e,t),r=cR(e,n.instance);aM(r.log),XL=r.log,await r.register(cT.default,{origin:!0}),await r.register(lT.default,QL),await r.register(sT.default,{options:ZL});let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new RT(e);await s.init();let c=new JT(e.auditLogPath),l=new jL,u=new PE,d=new jD(e.projectStoreDir),f=new PF(e.sessionHistoryDir);await f.init();let m=new Gj(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Mj({store:m});await h.init();let g,_=null,v=new Map,y=await fh(e.authStoreDir),b=new HL(e),x=e.relayEnabled?Ng({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 _P({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,attachmentStoreDir:nR(e.sessionHistoryDir),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 WL({fsService:u,sessionManager:T,previewTicketService:b}),D=new EL(l,T,e.readableLiveDeltaCoalesceMs,oM),O=new PL({sessionManager:T,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>II(e),refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e)});T.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let k=new Hg({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{aM(null),XL=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:vh(),gatewayIdentity:y.identity})),r.get(`/api/pairing/descriptor`,async()=>Tg({gatewayId:e.gatewayId,gatewayName:e.name,machineName:vh(),relayBaseUrl:x,directBaseUrls:jg({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=ru.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}}),bI(y,{...n,gatewayName:e.name,machineName:vh()},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=ou.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await hI({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=()=>rf.parse({name:e.name,machineName:vh()}),j=async n=>{let r=rf.pick({name:!0}).parse(n);if(!t.configPath)throw Error(`Gateway config path is unavailable`);return e.name=await Nh(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=rf.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=Bd.safeParse(n?.requestedBy);try{let e=await k.applyUpdate(r.success?r.data:`mobile`);return Gd.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 gu.parse(await T.restartCodexAppServer())}catch(e){let n=_T(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 fu.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 pu.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 mu.parse(await T.switchCodexAccount(n.accountId))}catch(e){return re(t,e)}}),r.post(`/api/codex/accounts/delete`,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 hu.parse(await T.deleteSavedCodexAccount(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 _T(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):EI(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=Ja.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=io.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 _T(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/providers/:provider/execution-defaults`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=Pa.safeParse(n.provider);if(!r.success)return t.code(400).send({error:`Invalid provider`});let i=Ha.safeParse({...e.body&&typeof e.body==`object`&&!Array.isArray(e.body)?e.body:{},provider:r.data});if(!i.success)return t.code(400).send({error:i.error.message});try{return{defaults:await T.updateProviderExecutionDefaults(i.data)}}catch(e){return 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 _T(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 _T(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 _T(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=rl.safeParse(r.detailLevel).success?rl.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 _T(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/readable-items/:itemId`,async(e,t)=>{if(!ne(e,t))return;let n=e.params;try{return await pI({sessionManager:T,readableItemDetailLookup:D,projectId:n.projectId,sessionId:n.sessionId,itemId:n.itemId})||t.code(404).send({error:`Readable item not found`})}catch(e){return _T(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(_l(e),i.sub,a)}catch(e){await F({deviceId:i.sub,clientId:a,rawCommand:tR(n,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:iR(t),streamSubscriptionCount:n.length,streamSubscriptions:n.map(aR),externalWatchTargetCount:o.length,externalWatchTargets:o},`gateway websocket client disconnected`),O.removeClient(a),l.removeClient(a),D.clearStatesForClient(a)})});let M=new lM({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(aR),externalWatchTargetCount:n.length,externalWatchTargets:n}},handlePairingClaim:async t=>{let n=he(t.deviceName);return bI(y,{...await s.claimPairingCode(t.code,n,t.deviceIdentity),gatewayName:e.name,machineName:vh()},t.code,t.deviceIdentity)},handleRefresh:async t=>{let n=await hI({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return mI(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=dR({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 ep.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 ep.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)=>SI(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,readableItemDetailLookup:D,refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e),buildRawEventsListResult:oR}),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:tR(e,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,attachments:e.payload.attachments,commandId:e.commandId});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`:{rR(`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);rR(`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=qL(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`)=>oR({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=_T(t)?t.status:500;return _T(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=Ya.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=Ja.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=Pa.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=vh(),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},uR(pe,e.host,_e)),e.relayEnabled&&(_=new CM({gatewayId:e.gatewayId,machineName:e.name,relayUrl:e.relayUrl,relayTransportSecurityLevel:e.relayTransportSecurityLevel,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>OM({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:y.identity,privateKeyPem:y.privateKeyPem}),gatewayIdentity:y.identity,directBaseUrls:jg({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 cR(e,t){let n=t;if(!e.httpsEnabled)return(0,uT.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:$L}});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,uT.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:$L},https:r})}function lR(e,t){let n=process.env.NODE_ENV!==`production`,r=dT.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?dT.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,dT.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function uR(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function dR(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 fR(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,b.inspect)(e,{depth:6,breakLength:120})}async function pR(e){let t=await kh({configPath:e.configPath,ensureConfigFile:!0});Ph(t.config);let n=await sR(t.config,{configPath:t.configPath,logToConsole:e.logToConsole,onUpdatePrepared:async e=>{hR({type:`worker.update.prepared`,payload:e})}});hR({type:`worker.ready`,payload:mR(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=gR(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: ${fR(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${fR(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);hR({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);hR({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){hR({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function mR(e){return{protocol:e.protocol,listenPort:e.listenPort,gatewayName:e.gatewayName,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function hR(e){process.send&&process.send(e)}function gR(e){if(!_R(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 _R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}vR(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function vR(e){let t=ee(e);switch(t.command){case`help`:CR();return;case`version`:console.log(z.version);return;case`init`:await bR(t);return;case`doctor`:await xR(t);return;case`start`:await yR(t);return;case`__worker`:await SR(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function yR(e){let t=await kh({configPath:e.configPath,ensureConfigFile:!0});Ph(t.config);let n=await $h({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await h_({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(w_(e,t.config))}eg(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function bR(e){let t=await Oh({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 kh({configPath:t.configPath,ensureConfigFile:!1}),r=await $h({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(tg(r))}async function xR(e){let t=await kh({configPath:Dh(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await $h({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(tg(n)),eg(n)&&(process.exitCode=1)}async function SR(e){try{await pR(e)}catch(t){let n=await kh({configPath:e.configPath,ensureConfigFile:!0});throw Error(w_(t,n.config))}}function CR(){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=vR;
|
|
530
|
+
`),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){return this.readSessionRawEventsCompactedWithCoverageFromCache(e)?.rawEvents}readSessionRawEventsCompactedWithCoverageFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return WF(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=HF(n);return this.compactedRawEventsCacheBySession.set(e,r),WF(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 FF(e){let t=e.projectPath?.trim()||e.projectId;return t===e.projectId?e:{...e,projectId:t}}function IF(e){return typeof e==`object`&&!!e}function LF(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function RF(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 zF(e){if(e.length===0)return null;let t=null,n=null;for(let r of e)t=t===null?r.rawSeq:Math.min(t,r.rawSeq),n=n===null?r.rawSeq:Math.max(n,r.rawSeq);return t===null||n===null?null:{min:t,max:n}}function BF(e,t){return{rawEvents:e.rawEvents.slice(-Math.max(1,t)),coveredToRawSeq:e.coveredToRawSeq}}async function VF(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 HF(e){let t=Hm(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Gm(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t,coveredToRawSeq:zF(e)?.max??null}}function UF(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function WF(e){return{rawEvents:UF(e),coveredToRawSeq:e.coveredToRawSeq}}function GF(e,t){e.coveredToRawSeq=e.coveredToRawSeq===null?t.rawSeq:Math.max(e.coveredToRawSeq,t.rawSeq);let n=Gm(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=Km(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 KF(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function qF(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function JF(e){if(qF(e)||e.type===`turn.completed`||e.type===`turn.failed`)return!0;if(e.type!==`native.raw`)return!1;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(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 YF(e,t,n){if(n?.replaceMissing)return XF(e,t,n);let r=[...e].sort(eI),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&&ZF(n,e)&&(r[t]=$F(n,e));continue}let n={...e,rawSeq:a};a+=1,i.set(n.eventId,r.length),r.push(n)}return tI(r.sort(eI)).sort(eI)}function XF(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(eI),c=1;for(let t of e)c=Math.max(c,t.rawSeq+1);return tI(s.map(e=>{let t=r.get(e.eventId);if(t)return ZF(t,e)?$F(t,e):{...e,rawSeq:t.rawSeq};let n={...e,rawSeq:c};return c+=1,n})).sort(eI)}function ZF(e,t){return QF(e)&&QF(t)}function QF(e){return e.type===`native.raw`?sI((IF(e.payload.raw)?e.payload.raw:{}).source)===`codex.history.thread_read`:!1}function $F(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function eI(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 tI(e){let t=Wm(e).filter(e=>!nI(e)),n=new Set;for(let e of t){let t=rI(e);t&&n.add(t)}return n.size===0?t:t.filter(e=>{let t=iI(e);return!t||!n.has(t)})}function nI(e){let t=IF(e.payload.raw)?e.payload.raw:{},n=sI(t.source)??``;if(e.type!==`native.raw`&&(t.historyReplay===!0||n.startsWith(`codex.history.thread_read`)))return!0;if(e.type!==`native.raw`||n!==`codex.app_server`)return!1;let r=IF(t.message)?t.message:{};return sI(r.method)??sI(t.method)?!1:IF((IF(r.result)?r.result:{}).turn)}function rI(e){if(e.type===`item.completed`){let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.item)?t.item:{};return aI(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.message)?t.message:{},r=IF(n.params)?n.params:{};if((sI(n.method)??sI(t.method))!==`item/completed`)return null;let i=IF(r.item)?r.item:{};return aI(e.sessionId,i)}function iI(e){if(e.type===`item.updated`){let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.item)?t.item:{},r=sI(n.original_method)??sI(n.originalMethod)??``,i=IF(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`)&&!oI(r)?null:aI(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=IF(e.payload.raw)?e.payload.raw:{},n=IF(t.message)?t.message:{},r=IF(n.params)?n.params:{};if(!oI(sI(n.method)??sI(t.method)??``))return null;let i=IF(r.msg)?r.msg:{},a=sI(r.itemId)??sI(r.item_id)??sI(i.itemId)??sI(i.item_id);return a?`${e.sessionId}|${a}`:null}function aI(e,t){let n=sI(t.id)??sI(t.item_id)??sI(t.itemId);return n?`${e}|${n}`:null}function oI(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function sI(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function cI(e){return!e||e.providerMode!==`native`?!1:e.interactionLockReason===`external_turn_running`?!0:e.status!==`running`}const lI=e=>e.filter(e=>!(e.kind===`system`&&e.title===`Turn Usage`)),uI=(e,t)=>e.find(e=>e.itemId===t||e.id===t)??null,dI=e=>e.kind!==`tool_card`&&e.kind!==`file_change_card`&&e.kind!==`terminal_card`||e.status!==void 0||`deferredDetail`in e&&e.deferredDetail!==void 0?null:e.itemId??e.id,fI=e=>{let t=lI(sm(e.sessionId,e.rawEvents,[]));return{timelineItems:Uo({rawEvents:e.rawEvents,messages:t,deferCompletedToolDetails:!1}).timelineItems,lastRawSeq:e.rawEvents[e.rawEvents.length-1]?.rawSeq??null}};async function pI(e){if(e.readableItemDetailLookup)return e.readableItemDetailLookup.getReadableItemDetailResult({projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId});let t=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,2**53-1),n=uI(fI({sessionId:e.sessionId,rawEvents:t}).timelineItems,e.itemId);return n?{item:n}:null}function mI(e,t){if(e&&e!==t)throw ST()}async function hI(e){let t=gI(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:_I(t)},`auth refresh attempt`);try{let t=await e.execute(),n=gI(e.authService,e.refreshToken),r=gI(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:_I(n),nextRefreshToken:_I(r)},`auth refresh succeeded`),t}catch(t){let n=gI(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:_I(n),error:vI(t)},`auth refresh failed`),t}}function gI(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function _I(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:yI(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:yI(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function vI(e){return _T(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function yI(e){return e?e.slice(-8):null}function bI(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:xI(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:hh(e.identity,e.privateKeyPem,i)}}function xI(e){return e.replace(/\s+/gu,``).toUpperCase()}async function SI(e,t){try{let n=np.parse(e);switch(n.method){case`auth.refresh`:{let e=await hI({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 mI(n.params.deviceId??t.relayDeviceId,e.deviceId),rp.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return rp.parse({method:n.method,result:{projects:e}})}case`codex.accounts.get`:{let e=await t.sessionManager.getCodexAccounts();return rp.parse({method:n.method,result:e})}case`codex.accounts.save`:{let e=await t.sessionManager.saveCurrentCodexAccount();return rp.parse({method:n.method,result:e})}case`codex.accounts.switch`:{let e=await t.sessionManager.switchCodexAccount(n.params.accountId);return rp.parse({method:n.method,result:e})}case`codex.accounts.delete`:{let e=await t.sessionManager.deleteSavedCodexAccount(n.params.accountId);return rp.parse({method:n.method,result:e})}case`gateway.settings.get`:return rp.parse({method:n.method,result:t.gatewaySettings.get()});case`gateway.settings.update`:{let e=await t.gatewaySettings.update(n.params);return rp.parse({method:n.method,result:e})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return rp.parse({method:n.method,result:e})}case`gateway.update.check`:{let e=await t.updateService.checkForUpdates(n.params.requestedBy??`mobile`);return rp.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return rp.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return rp.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return rp.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return rp.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return rp.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw wI(n.method,`NOT_FOUND`,404,`Project not found`);return rp.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 rp.parse({method:n.method,result:e})}case`workspace.directories.create`:{let e=await t.fsService.createDirectoryUnrestricted(n.params.path,n.params.name,200);return rp.parse({method:n.method,result:e})}case`workspace.entries.list`:{let e=await t.workspaceFileService.listEntries(n.params.locator,n.params.limit??200);return rp.parse({method:n.method,result:e})}case`workspace.files.resolve`:{let e=await t.workspaceFileService.resolveFile(n.params.locator);return rp.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 rp.parse({method:n.method,result:e})}case`workspace.files.preparePreview`:{let e=t.relayPreviewBaseUrl?.trim(),r=t.gatewayId?.trim();if(!e||!r)throw wI(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 rp.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 rp.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return rp.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw wI(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return rp.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 wI(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return rp.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}),rp.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 rp.parse({method:n.method,result:r})}case`sessions.readableItem.get`:{let e=await pI({sessionManager:t.sessionManager,readableItemDetailLookup:t.readableItemDetailLookup,projectId:n.params.projectId,sessionId:n.params.sessionId,itemId:n.params.itemId});if(!e)throw wI(n.method,`NOT_FOUND`,404,`Readable item ${n.params.itemId} not found`);return rp.parse({method:n.method,result:e})}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`),rp.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`providers.execution.update`:{let e=await t.sessionManager.updateProviderExecutionDefaults(n.params);return rp.parse({method:n.method,result:{defaults:e}})}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 rp.parse({method:n.method,result:e})}case`devices.list`:return rp.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw wI(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return rp.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw wI(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw CI(e)}}function CI(e){if(_T(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return wI(`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 wI(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return wI(`BAD_REQUEST`,e.status,String(e),e.details);default:return wI(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=ap.safeParse(e);if(t.success)return t.data;let n=ip.safeParse(e);if(n.success)return wI(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 wI(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?wI(`BAD_REQUEST`,400,r):TI(e)?wI(`UNAUTHORIZED`,401,r):EI(r)?wI(`BAD_REQUEST`,400,r):wI(`INTERNAL`,500,r)}function wI(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 ap.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function TI(e){return _T(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||LT(e)}function EI(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 DI(e,t){return e.length===0?[]:t===void 0?[...e]:e.filter(e=>e.rawSeq>t)}function OI(e){let t=e.coveredToRawSeq??void 0;for(let n of e.rawEvents)(t===void 0||n.rawSeq>t)&&(t=n.rawSeq);return t}function kI(e){return{baseRawEvents:Hm(e.rawEvents.filter(t=>t.rawSeq<=e.cursorRawSeq)),nextRawEvents:Hm(e.rawEvents)}}function AI(e,t){return t&&`kind`in t&&t.kind===`bootstrapping`?t:{kind:`bootstrapping`,sessionId:e,previousReadyState:t??null,queuedEnvelopes:[]}}function jI(e,t){let n=e.previousReadyState;if(!n)return{previousReadyState:null,nextReadyState:null,replayedEnvelopes:[]};let r=DI(e.queuedEnvelopes,OI(n)),i=n;for(let e of r)i=t(i,e);return{previousReadyState:n,nextReadyState:i,replayedEnvelopes:r}}function MI(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_${hT(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}}function NI(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.sessionSummary?{sessionSummary:e.sessionSummary}:{}},...e.timelineItems?{readable:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,...e.timelineItems?{timelineItems:e.timelineItems}:{}}}:{}}}}function PI(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},...e.sessionSummary?{sessionSummary:e.sessionSummary}:{}}}}}function FI(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 II(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_${hT(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,...e.sessionSummary?{sessionSummary:e.sessionSummary}:{}}}}}function LI(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 RI=1e3,zI=(e,t)=>`${e}::${t}`,BI=e=>e.purpose===`detail_view`&&e.bootstrapMode===`readable`,VI=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},HI=e=>{let t;for(let n of e)(t===void 0||n.rawSeq>t)&&(t=n.rawSeq);return t},UI=e=>e[e.length-1]?.rawSeq,WI=(e,t)=>{let n=HI(e);return t==null?n??null:n===void 0?t:Math.max(t,n)},GI=e=>WI(e.rawEvents,e.coveredToRawSeq)??void 0,KI=e=>{let t=WI(e.rawEvents,e.coveredToRawSeq);return{kind:`ready`,sessionId:e.target.sessionId,projectId:e.target.projectId,provider:e.target.provider,detailLevel:e.target.detailLevel,rawEvents:[...e.rawEvents],coveredToRawSeq:t,detailTransportRawEvents:[...e.detailTransportRawEvents??e.rawEvents],contextUsage:e.contextUsage??null,timelineItems:[...e.timelineItems],pendingApprovals:[...e.pendingApprovals],pendingUserInputs:[...e.pendingUserInputs]}},qI=e=>typeof e==`object`&&e?e:{},JI=(e,...t)=>{for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}},YI=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=qI(n),r=JI(e,`id`),i=JI(e,`header`),a=JI(e,`question`);if(!r||!i||!a)continue;let o=Array.isArray(e.options)?e.options.map(e=>{let t=qI(e),n=JI(t,`label`);if(!n)return null;let r=JI(t,`description`)??n,i=JI(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},XI=(e,t)=>{let n=om(e,t),r=new Map,i=new Map;for(let e of n){if(e.type===`tool.permission.requested`){let t=qI(e.payload.raw),n=JI(t,`requestId`,`request_id`);if(!n)continue;let i=qI(t.rawParams??t.raw_params),a=qI(i.networkApprovalContext??i.network_approval_context);r.set(n,{requestId:n,sessionId:e.sessionId,...JI(t,`toolName`,`tool_name`)?{toolName:JI(t,`toolName`,`tool_name`)}:{},...JI(t,`reason`)?{reason:JI(t,`reason`)}:{},...JI(i,`command`)?{command:JI(i,`command`)}:{},...JI(i,`cwd`)?{cwd:JI(i,`cwd`)}:{},...JI(i,`grantRoot`,`grant_root`)?{grantRoot:JI(i,`grantRoot`,`grant_root`)}:{},...JI(a,`host`)?{networkHost:JI(a,`host`)}:{},...JI(a,`protocol`)?{networkProtocol:JI(a,`protocol`)}:{},...JI(t,`itemId`,`item_id`)?{itemId:JI(t,`itemId`,`item_id`)}:{},...JI(t,`turnId`,`turn_id`)?{turnId:JI(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`tool.permission.resolved`){let t=JI(qI(e.payload.raw),`requestId`,`request_id`);t&&r.delete(t);continue}if(e.type===`user.input.requested`){let t=qI(e.payload.raw),n=JI(t,`requestId`,`request_id`);if(!n)continue;i.set(n,{requestId:n,sessionId:e.sessionId,questions:YI(t.questions),...JI(t,`itemId`,`item_id`)?{itemId:JI(t,`itemId`,`item_id`)}:{},...JI(t,`turnId`,`turn_id`)?{turnId:JI(t,`turnId`,`turn_id`)}:{}});continue}if(e.type===`user.input.resolved`){let t=JI(qI(e.payload.raw),`requestId`,`request_id`);t&&i.delete(t)}}return{pendingApprovals:[...r.values()],pendingUserInputs:[...i.values()]}},ZI=e=>{let t=e.rawEventsAlreadyMatchDetailTransport===!0?e.rawEvents:eL({rawEvents:e.rawEvents,detailLevel:e.target.detailLevel}),n=e.target.purpose===`detail_view`?Cl({provider:e.target.provider,rawEvents:t}):null,r=e.target.purpose===`detail_view`?lI(sm(e.target.sessionId,t,[])):[],i=e.target.purpose===`detail_view`?Uo({rawEvents:t,messages:r,deferCompletedToolDetails:!0}):{timelineItems:[],consumedMessageIds:[]},a=e.target.purpose===`detail_view`?XI(e.target.sessionId,t):{pendingApprovals:[],pendingUserInputs:[]};return{detailTransportRawEvents:t,contextUsage:n,timelineItems:i.timelineItems,pendingApprovals:a.pendingApprovals,pendingUserInputs:a.pendingUserInputs}},QI=e=>{let t=eL({rawEvents:e.rawEvents,detailLevel:e.target.detailLevel}),n=ZI({target:e.target,rawEvents:t,rawEventsAlreadyMatchDetailTransport:!0});return KI({target:e.target,rawEvents:e.rawEvents,coveredToRawSeq:e.coveredToRawSeq,detailTransportRawEvents:t,contextUsage:n.contextUsage,timelineItems:n.timelineItems,pendingApprovals:n.pendingApprovals,pendingUserInputs:n.pendingUserInputs})},$I=(e,t)=>{let n=cL(e.rawEvents,t),r=WI(n,GI(e)),i=eL({rawEvents:cL(e.detailTransportRawEvents,t),detailLevel:e.detailLevel}),a=ZI({target:{sessionId:e.sessionId,provider:e.provider,detailLevel:e.detailLevel,purpose:`detail_view`},rawEvents:i,rawEventsAlreadyMatchDetailTransport:!0});return{...e,rawEvents:n,coveredToRawSeq:r,detailTransportRawEvents:i,contextUsage:a.contextUsage,timelineItems:a.timelineItems,pendingApprovals:a.pendingApprovals,pendingUserInputs:a.pendingUserInputs}},eL=e=>{if(e.detailLevel!==`compact`||e.rawEvents.length===0)return e.rawEvents;let t=tL(e.rawEvents[0]?.sessionId??``,e.rawEvents);return lD(e.rawEvents,e.detailLevel,{preserveIncompleteCommandOutput:!0,additionalCompletedCommandItemKeys:t})},tL=(e,t)=>{if(!e||t.length===0)return new Set;let n=new Set,r=sm(e,t,[]);for(let t of r){if(t.itemType!==`command_execution`||!t.itemId||t.status!==`completed`&&t.status!==`failed`)continue;let r=aL(e,t.itemId);r&&n.add(r)}return n},nL=e=>JI(e,`id`,`itemId`,`item_id`)??null,rL=e=>{if(e.type===`item.started`||e.type===`item.updated`||e.type===`item.completed`)return nL(qI(qI(e.payload.raw).item));if(e.type!==`native.raw`)return null;let t=qI(qI(e.payload.raw).message),n=qI(t.params),r=qI(n.item),i=qI(n.msg);return nL(r)??nL(qI(t.item))??JI(n,`itemId`,`item_id`)??JI(i,`itemId`,`item_id`)??null},iL=e=>{if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=qI(e.payload.raw);return(JI(qI(t.message),`method`)??JI(t,`method`))===`item/completed`},aL=(e,t)=>t?`${e}|${t}`:null,oL=e=>aL(e.sessionId,rL(e)),sL=e=>{let t=oL(e);if(t)return`item:${t}`;let n=Gm(e);return n?`delta:${n.key}`:null},cL=(e,t)=>{let n=[...e],r=oL(t),i=sL(t),a=Gm(t),o=t;if(i&&a)for(let e=n.length-1;e>=0;--e){let r=n[e];if(!r||sL(r)!==i||!Gm(r))continue;let a=Km(r,t);if(a){n[e]=null,o=a;break}}return n.push(o),!r||!iL(t)?n.filter(e=>e!==null):n.filter(e=>e!==null&&(e.eventId===o.eventId||oL(e)!==r||!Gm(e)))},lL=e=>{let t=uL(e);if(!t)return null;let n=nL(t),r=qI(t.payload),i=JI(t,`output_delta`,`outputDelta`)??JI(r,`output_delta`,`outputDelta`);return!n||!i?null:{itemId:n,delta:i}},uL=e=>{if(e.type===`item.updated`){let t=qI(qI(e.payload.raw).item);return dL(t)?t:null}if(e.type!==`native.raw`)return null;let t=qI(e.payload.raw),n=qI(t.message);if((JI(n,`method`)??JI(t,`method`))!==`item/updated`)return null;let r=qI(qI(n.params).item);return dL(r)?r:null},dL=e=>{let t=JI(e,`type`);return t===`commandExecution`||t===`command_execution`},fL=e=>e.includes(`[compact history preview:`),pL=(e,t)=>{let n=lL(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`||fL(i.output))return null;let a=cL(e.rawEvents,t),o=eL({rawEvents:cL(e.detailTransportRawEvents,t),detailLevel:e.detailLevel}),s={...i,output:`${i.output}${n.delta}`},c=[...e.timelineItems];c[r]=s;let l=GI(e),u=WI(a,l)??t.rawSeq;return{nextState:{...e,rawEvents:a,coveredToRawSeq:u,detailTransportRawEvents:o,timelineItems:c},messageInput:{provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,fromRawSeq:l,toRawSeq:u,timelineUpserts:[],timelineRemovals:[],timelineTextDeltaPatches:[{id:i.id,field:`output`,delta:n.delta}]}}},mL=e=>Buffer.byteLength(JSON.stringify(PI(e)),`utf8`),hL=e=>{let t=Math.max(1,Math.floor(e.maxChunkBytes??524288)),n=[],r=(t,n)=>mL({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,sessionSummary:t===0?e.sessionSummary: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},gL=(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)}},_L=(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)}},vL=(e,t,n,r)=>{let i={},a=om(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=JI(qI(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,s.type===`turn.started`&&(i.activeStartedAt=s.ts)),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};function yL(e){let t,n=e.previousState;for(let r of e.envelopes){let i=$I(n,r),a=vL(e.sessionId,r,n,i);a&&(t={...t??{},...a}),n=i}return t}const bL=e=>{if(!e)return{stateFound:!1};let t=HI(e.rawEvents),n=UI(e.rawEvents),r=GI(e);return{stateFound:!0,kind:e.kind,sessionId:e.sessionId,projectId:e.projectId,provider:e.provider,detailLevel:e.detailLevel,rawEventCount:e.rawEvents.length,detailTransportRawEventCount:e.detailTransportRawEvents.length,firstRawSeq:e.rawEvents[0]?.rawSeq??null,lastRawSeq:r??null,rawEventMaxRawSeq:t??null,orderedLastRawSeq:n??null,rawSeqOrderMismatch:t!==n,rawSeqCoverageMismatch:r!==t,timelineItemCount:e.timelineItems.length,pendingApprovalCount:e.pendingApprovals.length,pendingUserInputCount:e.pendingUserInputs.length,hasContextUsage:!!e.contextUsage}},xL=e=>e?e.kind===`ready`?bL(e):{stateFound:!0,kind:e.kind,sessionId:e.sessionId,queuedEnvelopeCount:e.queuedEnvelopes.length,previousReadyState:bL(e.previousReadyState)}:{stateFound:!1},SL=(e,t)=>{let n,r,i;try{n=Rc(e.previousState.timelineItems,e.nextState.timelineItems),r=gL(e.previousState.pendingApprovals,e.nextState.pendingApprovals),i=_L(e.previousState.pendingUserInputs,e.nextState.pendingUserInputs)}catch(n){throw t?.(`stream.readable.delta.build.error`,{sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,previousState:bL(e.previousState),nextState:bL(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=GI(e.nextState);return o===void 0?null:{provider:e.previousState.provider,sessionId:e.previousState.sessionId,projectId:e.previousState.projectId,fromRawSeq:GI(e.previousState),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 CL(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,activeStartedAt:e.activeStartedAt??null,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null}:{sessionFound:!1}}function wL(e){return e===`external_turn_running`?e:void 0}function TL(e){return{status:e.status,...e.updatedAt?{updatedAt:e.updatedAt}:{},...e.activeStartedAt?{activeStartedAt:e.activeStartedAt}:{},...e.interactionLockReason?{interactionLockReason:e.interactionLockReason}:{}}}var EL=class{stateByClientSession=new Map;pendingDeltaByClientSession=new Map;itemDetailCache=new Map;constructor(e,t,n,r,i=512){this.sessionHub=e,this.sessionManager=t,this.readableLiveDeltaCoalesceMs=n,this.log=r,this.itemDetailCacheMaxEntries=i}shutdown(){for(let e of this.pendingDeltaByClientSession.values())clearTimeout(e.timer);this.pendingDeltaByClientSession.clear(),this.stateByClientSession.clear(),this.itemDetailCache.clear()}handleSessionStreamSubscribeCommand=async(e,t,n)=>{let r=VI(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 BI(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=zI(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:xL(r),hadPendingDelta:!!i,pendingDeltaFromRawSeq:i?GI(i.previousState)??null:null,pendingDeltaToRawSeq:i?GI(i.nextState)??null: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))};getReadableItemDetailResult=async e=>{let t=this.getLatestReadableReadyStateForSession(e.projectId,e.sessionId),n=t?uI(t.timelineItems,e.itemId):null,r=n&&`deferredDetail`in n&&n.deferredDetail!==void 0;if(n&&!r){let r=dI(n);return r&&this.setReadableItemDetailCacheEntry({projectId:e.projectId,sessionId:e.sessionId,itemId:r,item:n}),this.log(`readable.item_detail.cache_hit`,{projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId,source:`live_state`,lastRawSeq:t?GI(t)??null:null}),{item:n}}let i=this.getReadableItemDetailCacheEntry(e.projectId,e.sessionId,e.itemId);if(i)return this.log(`readable.item_detail.cache_hit`,{projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId,source:`item_cache`}),{item:i.item};let a=await this.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,2**53-1),o=fI({sessionId:e.sessionId,rawEvents:a}),s=this.seedReadableItemDetailCache({projectId:e.projectId,sessionId:e.sessionId,timelineItems:o.timelineItems}),c=uI(o.timelineItems,e.itemId);return this.log(`readable.item_detail.projection_rebuilt`,{projectId:e.projectId,sessionId:e.sessionId,itemId:e.itemId,source:t?`session_history_after_live_state`:`session_history`,lastRawSeq:o.lastRawSeq,timelineItemCount:o.timelineItems.length,cachedItemCount:s,found:!!c}),c?{item:c}:null};routeReadableLiveDelta=e=>{let t=this.sessionHub.getClientSubscriptionsForSession(e.sessionId,`detail_view`);if(t.length!==0)for(let{clientId:n,subscription:r}of t){if(!BI(r))continue;let t=zI(n,e.sessionId),i=this.stateByClientSession.get(t);if(!i)continue;if(i.kind===`bootstrapping`){i.queuedEnvelopes.push(e);continue}let a=pL(i,e);if(a){this.flushPendingReadableLiveDelta(n,e.sessionId),this.stateByClientSession.set(t,a.nextState),this.sessionHub.sendSessionMessageToClient(n,e.sessionId,FI(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=$I(i,e);this.stateByClientSession.set(t,o);let s=vL(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 BI(r)&&this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:n,sessionId:e.sessionId}),t}finally{this.sessionHub.resumeSession(n,e.sessionId)}}}};sendSessionSnapshot=async(e,t,n)=>{let r=`snap_${hT(12)}`,{compactedRawEvents:i,detailTransportRawEvents:a,lastRawSeq:o,slimReadableProjection:s,pendingApprovals:c,pendingUserInputs:l}=await this.buildReadableSnapshotProjection(t),u=TL(t);this.sessionHub.sendStreamMessage(e,MI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...o===void 0?{}:{toRawSeq:o}}));let d=LI(a,RI),f=t.purpose===`detail_view`?LI(s.timelineItems,RI):[],p=t.purpose===`detail_view`?`raw+readable`:`raw`,m=Math.max(d.length,f.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:p,compactedEventCount:i.length,detailTransportEventCount:a.length,readableTimelineItemCount:s.timelineItems.length,totalChunks:m,firstRawSeq:a[0]?.rawSeq??null,lastRawSeq:o??null,orderedLastRawSeq:UI(i)??null,rawSeqOrderMismatch:o!==UI(i)});for(let n=0;n<m;n+=1){let i=d[n]??[],a=f[n]??[];this.sessionHub.sendStreamMessage(e,NI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:m,events:i,timelineItems:t.purpose===`detail_view`?a:void 0,sessionSummary:n===0?u:void 0}))}};sendSessionReadableSnapshot=async(e,t,n)=>{let r=`snap_${hT(12)}`,i=this.startReadableLiveProjectionBootstrap({clientId:e,sessionId:t.sessionId});try{let{compactedRawEvents:a,detailTransportRawEvents: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||!BI(f)||p&&p!==t.projectId||(f.detailLevel??`full`)!==t.detailLevel){this.clearState(e,t.sessionId);return}let m=TL(t),h=KI({target:t,rawEvents:a,coveredToRawSeq:c,detailTransportRawEvents:o,contextUsage:s,timelineItems:l.timelineItems,pendingApprovals:u,pendingUserInputs:d}),g=this.stateByClientSession.get(i),_=DI(g?.kind===`bootstrapping`?g.queuedEnvelopes:[],c),v=yL({sessionId:t.sessionId,previousState:h,envelopes:_});for(let e of _)h=$I(h,e);let y={...m,...v??{}};this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:h.rawEvents,coveredToRawSeq:GI(h),detailTransportRawEvents:h.detailTransportRawEvents,contextUsage:h.contextUsage,timelineItems:h.timelineItems,pendingApprovals:h.pendingApprovals,pendingUserInputs:h.pendingUserInputs});let b=GI(h),x=UI(h.rawEvents);this.sessionHub.sendStreamMessage(e,MI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...b===void 0?{}:{toRawSeq:b}}));let S=hL({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,timelineItems:h.timelineItems,pendingApprovals:h.pendingApprovals,pendingUserInputs:h.pendingUserInputs,contextUsage:h.contextUsage,sessionSummary:y}),C=Math.max(S.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:h.rawEvents.length,detailTransportRawEventCount:h.detailTransportRawEvents.length,readableTimelineItemCount:h.timelineItems.length,bufferedReadableDeltaCount:_.length,readableChunkTargetBytes:524288,readableChunkItemCounts:S.map(e=>e.timelineItems.length),readableChunkEstimatedBytes:S.map(e=>e.estimatedByteLength),totalChunks:C,firstRawSeq:h.rawEvents[0]?.rawSeq??null,lastRawSeq:b??null,orderedLastRawSeq:x??null,rawSeqOrderMismatch:b!==x});for(let n=0;n<C;n+=1){let i=S[n];this.sessionHub.sendStreamMessage(e,PI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:C,timelineItems:i?.timelineItems??[],pendingApprovals:n===0?h.pendingApprovals:void 0,pendingUserInputs:n===0?h.pendingUserInputs:void 0,contextUsage:n===0?h.contextUsage:void 0,sessionSummary:n===0?y:void 0}))}}catch(n){throw this.restoreReadableLiveProjectionAfterBootstrapFailure({clientId:e,sessionId:t.sessionId}),n}};sendSessionReadableResumeDelta=async(e,t,n,r)=>{let i=zI(e,t.sessionId),a=await this.sessionManager.getProjectSessionRawEventsWithCoverage(t.projectId,t.sessionId,2**53-1),o=a.rawEvents,s=a.coveredToRawSeq,{baseRawEvents:c,nextRawEvents:l}=kI({rawEvents:o,cursorRawSeq:n}),u=QI({target:t,rawEvents:c,coveredToRawSeq:n}),d=QI({target:t,rawEvents:l,coveredToRawSeq:Math.max(n,s??0)}),f=GI(d),p=this.stateByClientSession.get(i),m=DI(p?.kind===`bootstrapping`?p.queuedEnvelopes:[],f);for(let e of m)d=$I(d,e);let h=GI(u),g=UI(u.rawEvents),_=GI(d),v=UI(d.rawEvents),y=yL({sessionId:t.sessionId,previousState:u,envelopes:[...l.filter(e=>e.rawSeq>n),...m]});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:o.length,baseRawEventCount:c.length,nextRawEventCount:l.length,previousMaxRawSeq:h??null,previousOrderedLastRawSeq:g??null,nextMaxRawSeq:_??null,nextOrderedLastRawSeq:v??null,rawSeqOrderMismatch:h!==g||_!==v,bootstrapState:xL(p),bufferedEnvelopeCount:m.length,previousState:bL(u),nextState:bL(d),sessionSummaryKeys:y?Object.keys(y):[],sessionSummaryStatus:y?.status??null,sessionSummaryUpdatedAt:y?.updatedAt??null}),this.seedReadableLiveProjectionState({clientId:e,target:t,rawEvents:d.rawEvents,coveredToRawSeq:GI(d),detailTransportRawEvents:d.detailTransportRawEvents,contextUsage:d.contextUsage,timelineItems:d.timelineItems,pendingApprovals:d.pendingApprovals,pendingUserInputs:d.pendingUserInputs});let b=GI(d)??n;this.sessionHub.sendStreamMessage(e,MI({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`delta`,reason:r,fromRawSeq:n,...b===void 0?{}:{toRawSeq:b}}));let x=SL({previousState:u,nextState:d,sessionSummary:y},this.log);this.log(`stream.readable.resume.delta`,{clientId:e,sessionId:t.sessionId,projectId:t.projectId,reason:r,cursorRawSeq:n,emittedDelta:!!x,deltaFromRawSeq:x?.fromRawSeq??n,deltaToRawSeq:x?.toRawSeq??b??null,timelineUpsertCount:x?.timelineUpserts.length??0,timelineRemovalCount:x?.timelineRemovals.length??0,timelineTextDeltaPatchCount:x?.timelineTextDeltaPatches.length??0,pendingApprovalUpsertCount:x?.pendingApprovalUpserts.length??0,pendingUserInputUpsertCount:x?.pendingUserInputUpserts.length??0,sessionSummaryStatus:x?.sessionSummary?.status??null,sessionSummaryUpdatedAt:x?.sessionSummary?.updatedAt??null}),this.sessionHub.sendSessionMessageToClient(e,t.sessionId,FI(x??{provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,fromRawSeq:n,toRawSeq:b,timelineUpserts:[],timelineRemovals:[]}))};getReadableItemDetailCacheKey(e,t,n){return`${e}::${t}::${n}`}getReadableItemDetailCacheEntry(e,t,n){let r=this.getReadableItemDetailCacheKey(e,t,n),i=this.itemDetailCache.get(r);return i?(this.itemDetailCache.delete(r),this.itemDetailCache.set(r,i),i):null}setReadableItemDetailCacheEntry(e){let t=this.getReadableItemDetailCacheKey(e.projectId,e.sessionId,e.itemId);for(this.itemDetailCache.has(t)&&this.itemDetailCache.delete(t),this.itemDetailCache.set(t,e);this.itemDetailCache.size>Math.max(1,this.itemDetailCacheMaxEntries);){let e=this.itemDetailCache.keys().next().value;if(!e)break;this.itemDetailCache.delete(e)}}seedReadableItemDetailCache(e){let t=0;for(let n of e.timelineItems){let r=dI(n);r&&(this.setReadableItemDetailCacheEntry({projectId:e.projectId,sessionId:e.sessionId,itemId:r,item:n}),t+=1)}return t}getLatestReadableReadyStateForSession(e,t){let n=null,r=-1,i=i=>{if(!i||i.projectId!==e||i.sessionId!==t)return;let a=GI(i)??-1;a<r||(n=i,r=a)};for(let e of this.stateByClientSession.values())e.kind===`ready`&&i(e);for(let e of this.pendingDeltaByClientSession.values())i(e.nextState);return n}syncReadableLiveProjectionSubscriptions(e,t,n,r){let i=new Set(n.filter(BI).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)BI(t)||this.clearState(e,t.sessionId)}startReadableLiveProjectionBootstrap(e){let t=zI(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=AI(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:xL(n),clearedPendingDelta:!!r,carriedPendingEnvelopeCount:a.length}),t}getReadableDeliveredReadyState(e,t){let n=zI(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?DI(t.nextState.rawEvents,e?GI(e):void 0):[]}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=GI(n);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=KI(e);this.stateByClientSession.set(zI(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:bL(t)})}primeReadableBootstrapForSubscriptions(e,t){for(let n of t)BI(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,MI({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 ET(n,t);let i={sessionId:t,projectId:n,provider:r.provider,status:r.status,updatedAt:r.updatedAt,activeStartedAt:r.activeStartedAt,interactionLockReason:wL(r.interactionLockReason),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:CL(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`,updatedAt:i?.updatedAt,activeStartedAt:i?.activeStartedAt,interactionLockReason:wL(i?.interactionLockReason),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:CL(i)}),a}async buildReadableSnapshotProjection(e){let t=await this.sessionManager.getProjectSessionRawEventsCompactedWithCoverage(e.projectId,e.sessionId,2**53-1),n=t.rawEvents,r=eL({rawEvents:n,detailLevel:e.detailLevel}),i=ZI({target:e,rawEvents:r,rawEventsAlreadyMatchDetailTransport:!0}),a=WI(n,t.coveredToRawSeq)??void 0;return{compactedRawEvents:n,detailTransportRawEvents:r,contextUsage:i.contextUsage,lastRawSeq:a,slimReadableProjection:{timelineItems:i.timelineItems,consumedMessageIds:[]},pendingApprovals:i.pendingApprovals,pendingUserInputs:i.pendingUserInputs}}restoreReadableLiveProjectionAfterBootstrapFailure(e){let t=zI(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=jI(n,$I);if(!a.previousReadyState||!r||!BI(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:xL(n),currentSubscriptionFound:!!r,currentSubscriptionProjectId:i||null,currentSubscriptionDetailLevel:r?.detailLevel??null,previousReadyState:bL(a.previousReadyState),nextReadyState:bL(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:bL(a.nextReadyState)});return}let o=yL({sessionId:e.sessionId,previousState:a.previousReadyState,envelopes:a.replayedEnvelopes}),s=SL({previousState:a.previousReadyState,nextState:a.nextReadyState,sessionSummary:o},this.log);if(!s){this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:bL(a.nextReadyState),emittedDelta:!1});return}this.log(`readable.bootstrap.recovered`,{clientId:e.clientId,sessionId:e.sessionId,replayedEnvelopeCount:a.replayedEnvelopes.length,nextReadyState:bL(a.nextReadyState),emittedDelta:!0,deltaFromRawSeq:s.fromRawSeq??null,deltaToRawSeq:s.toRawSeq}),this.sessionHub.sendSessionMessageToClient(e.clientId,a.previousReadyState.sessionId,FI(s))}sendReadableLiveDeltaNow(e){let t=SL({previousState:e.previousState,nextState:e.nextState,sessionSummary:e.sessionSummary},this.log);t&&this.sessionHub.sendSessionMessageToClient(e.clientId,e.previousState.sessionId,FI(t))}flushPendingReadableLiveDelta(e,t){let n=zI(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=zI(e.clientId,e.previousState.sessionId),n=this.pendingDeltaByClientSession.get(t);if(n){let t=DL({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 DL(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 OL(e){return e.sendProviderRaw?`relay_ws`:`direct_ws`}function kL(e){let t=performance.now(),n=JSON.stringify(e);return{payload:n,byteLength:Buffer.byteLength(n),serializeDurationMs:Number((performance.now()-t).toFixed(3))}}function AL(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 jL=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${hT(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??kL(t),i=AL(t);return i&&oM(`stream.snapshot.chunk.outbound`,{clientId:e.id,deviceId:e.deviceId,transport:OL(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 ML=1200,NL=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var PL=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){NL&&(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,lastSentConfigSummary:void 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,this.isGatewayOwnedRuntimeLive(n.projectId,n.sessionId,r)||!cI(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=this.isGatewayOwnedRuntimeLive(n.projectId,n.sessionId,i.session),o=n.lastObservedRawSeq,s=n.lastObservedRawEventCount,c=this.resolveObservedRawSeq(i),l=c>o||i.rawEvents.length>s;if(l?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:o,previousObservedRawEventCount:s,nextObservedRawSeq:c,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,c),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),a){this.clearCatchupRetry(n,{resetAttempts:!0}),n.stableIdleSyncCount=0,this.logDebug(`sync.result.stand_down.gateway_live`,{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});return}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:l,previousObservedRawSeq:o,previousObservedRawEventCount:s,nextObservedRawSeq:c,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount});let u=FL(i.session),d=RL(u);if(i.historyUpdated||i.statusChanged||IL(t)&&zL(t,n.lastSentConfigSummary,d)){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,sessionSummary:u});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e);d&&(n.lastSentConfigSummary=d)}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:ML,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`)},ML))))}stateKey(e,t){return JSON.stringify([e,t])}isGatewayOwnedRuntimeLive(e,t,n){return this.options.sessionManager.isGatewayOwnedRuntimeLive?.(e,t)?!0:n?n.status===`running`&&n.interactionLockReason!==`external_turn_running`:!1}};function FL(e){return{updatedAt:e.updatedAt,status:e.status,interactionLockReason:e.interactionLockReason,...e.model?{model:e.model}:e.sessionTurnConfig?.model===null?{model:null}:{},...e.sessionTurnConfig?{sessionTurnConfig:e.sessionTurnConfig}:{},...e.sessionTurnConfigUpdatedAt?{sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt}:{}}}function IL(e){return e===`lease_added`||e===`watch`||e===`watch_catchup`||e===`reconcile`||e===`rerun`}function LL(e){return!!(e&&Object.prototype.hasOwnProperty.call(e,`model`)||e?.sessionTurnConfig||e?.sessionTurnConfigUpdatedAt)}function RL(e){if(LL(e))return{...e&&Object.prototype.hasOwnProperty.call(e,`model`)?{model:e.model??null}:{},...e?.sessionTurnConfig?{sessionTurnConfig:e.sessionTurnConfig}:{},...e?.sessionTurnConfigUpdatedAt?{sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt}:{}}}function zL(e,t,n){return n?e===`lease_added`?!0:!BL(t,n):!1}function BL(e,t){if(!e||!t)return e===t;let n=Object.prototype.hasOwnProperty.call(e,`model`);return n!==Object.prototype.hasOwnProperty.call(t,`model`)||n&&e.model!==t.model||e.sessionTurnConfigUpdatedAt!==t.sessionTurnConfigUpdatedAt?!1:VL(e.sessionTurnConfig,t.sessionTurnConfig)}function VL(e,t){return!e||!t?e===t:e.mode===t.mode&&e.model===t.model&&e.reasoningEffort===t.reasoningEffort&&(e.execution?.codex?.approvalPolicy??null)===(t.execution?.codex?.approvalPolicy??null)&&(e.execution?.codex?.sandboxMode??null)===(t.execution?.codex?.sandboxMode??null)&&(e.execution?.claude?.permissionMode??null)===(t.execution?.claude?.permissionMode??null)}var HL=class{constructor(e){this.config=e}issue(e){let t=UL(e.sizeBytes??0),n=oT.default.sign({sub:e.deviceId,type:`workspace_preview`,gatewayId:this.config.gatewayId,path:e.canonicalPath,disposition:e.disposition},this.config.accessSecret,{expiresIn:t}),r=oT.default.decode(n);return{ticket:n,expiresAt:r?.exp?new Date(r.exp*1e3).toISOString():new Date().toISOString()}}getExpiresAt(e){let t=oT.default.decode(e);return t?.exp?new Date(t.exp*1e3).toISOString():new Date().toISOString()}verify(e){let t;try{t=oT.default.verify(e,this.config.accessSecret)}catch(e){if(e instanceof Error){if(e.name===`TokenExpiredError`)throw wT();if(e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)throw CT()}throw e}if(t.type!==`workspace_preview`||t.gatewayId!==this.config.gatewayId)throw CT();return t}};function UL(e){return e>20971520?7200:600}var WL=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:KL(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:KL(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=GL(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=GL(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 TT(e);return t}};function GL(e){return e.split(p.default.sep).join(`/`)}function KL(e,t){return`${e}; filename="${t.replace(/["\\]/g,`_`)}"`}function qL(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 JL=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;const YL=`[redacted:image-data]`;let XL=null;const ZL={perMessageDeflate:{threshold:1024}},QL={globalDecompression:!1,threshold:1024,customTypes:/^text\/(?!event-stream)|(?:\+|\/)json(?:;|$)|(?:\+|\/)text(?:;|$)|(?:\+|\/)xml(?:;|$)/u},$L=4096;function eR(e){if(Array.isArray(e))return e.map(e=>eR(e));if(!e||typeof e!=`object`)return e;let t={};for(let[n,r]of Object.entries(e))t[n]=n===`dataBase64`||n===`data_base64`?YL:eR(r);return t}function tR(e,t){if(e)try{return JSON.stringify(eR(e))}catch{}return t.replace(/("(?:dataBase64|data_base64)"\s*:\s*")([^"]*)(")/gu,`$1${YL}$3`)}function nR(e){return p.default.join(p.default.dirname(e),`session-attachments`)}function rR(e,t){JL&&(console.log(`[native-watch][gateway]`,e,t),XL?.info({event:e,...t},`native session watch debug`))}function iR(e){return e?typeof e==`string`?e:e.toString(`utf8`):``}function aR(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 oR(e){let t=e.limit??300,n=e.detailLevel??`full`,r=(r,i)=>{oM(`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:lD(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:lD(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:lD(o,n)};return r(s,{rangeMin:i.min,rangeMax:i.max,minExpectedCursor:a}),s}async function sR(e,t={}){await C_(e.gatewayLogPath);let n=lR(e,t),r=cR(e,n.instance);aM(r.log),XL=r.log,await r.register(cT.default,{origin:!0}),await r.register(lT.default,QL),await r.register(sT.default,{options:ZL});let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new RT(e);await s.init();let c=new JT(e.auditLogPath),l=new jL,u=new PE,d=new jD(e.projectStoreDir),f=new PF(e.sessionHistoryDir);await f.init();let m=new Gj(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Mj({store:m});await h.init();let g,_=null,v=new Map,y=await fh(e.authStoreDir),b=new HL(e),x=e.relayEnabled?Ng({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 _P({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,attachmentStoreDir:nR(e.sessionHistoryDir),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 WL({fsService:u,sessionManager:T,previewTicketService:b}),D=new EL(l,T,e.readableLiveDeltaCoalesceMs,oM),O=new PL({sessionManager:T,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>II(e),refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e)});T.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let k=new Hg({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{aM(null),XL=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:vh(),gatewayIdentity:y.identity})),r.get(`/api/pairing/descriptor`,async()=>Tg({gatewayId:e.gatewayId,gatewayName:e.name,machineName:vh(),relayBaseUrl:x,directBaseUrls:jg({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=ru.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}}),bI(y,{...n,gatewayName:e.name,machineName:vh()},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=ou.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await hI({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=()=>rf.parse({name:e.name,machineName:vh()}),j=async n=>{let r=rf.pick({name:!0}).parse(n);if(!t.configPath)throw Error(`Gateway config path is unavailable`);return e.name=await Nh(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=rf.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/check`,async(e,t)=>{if(!ne(e,t))return;let n=e.body,r=Bd.safeParse(n?.requestedBy);try{return await k.checkForUpdates(r.success?r.data:`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=Bd.safeParse(n?.requestedBy);try{let e=await k.applyUpdate(r.success?r.data:`mobile`);return Gd.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 gu.parse(await T.restartCodexAppServer())}catch(e){let n=_T(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 fu.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 pu.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 mu.parse(await T.switchCodexAccount(n.accountId))}catch(e){return re(t,e)}}),r.post(`/api/codex/accounts/delete`,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 hu.parse(await T.deleteSavedCodexAccount(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 _T(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):EI(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=Ja.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=io.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 _T(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/providers/:provider/execution-defaults`,async(e,t)=>{if(!ne(e,t))return;let n=e.params,r=Pa.safeParse(n.provider);if(!r.success)return t.code(400).send({error:`Invalid provider`});let i=Ha.safeParse({...e.body&&typeof e.body==`object`&&!Array.isArray(e.body)?e.body:{},provider:r.data});if(!i.success)return t.code(400).send({error:i.error.message});try{return{defaults:await T.updateProviderExecutionDefaults(i.data)}}catch(e){return 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 _T(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 _T(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 _T(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=rl.safeParse(r.detailLevel).success?rl.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 _T(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/readable-items/:itemId`,async(e,t)=>{if(!ne(e,t))return;let n=e.params;try{return await pI({sessionManager:T,readableItemDetailLookup:D,projectId:n.projectId,sessionId:n.sessionId,itemId:n.itemId})||t.code(404).send({error:`Readable item not found`})}catch(e){return _T(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(_l(e),i.sub,a)}catch(e){await F({deviceId:i.sub,clientId:a,rawCommand:tR(n,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:iR(t),streamSubscriptionCount:n.length,streamSubscriptions:n.map(aR),externalWatchTargetCount:o.length,externalWatchTargets:o},`gateway websocket client disconnected`),O.removeClient(a),l.removeClient(a),D.clearStatesForClient(a)})});let M=new lM({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(aR),externalWatchTargetCount:n.length,externalWatchTargets:n}},handlePairingClaim:async t=>{let n=he(t.deviceName);return bI(y,{...await s.claimPairingCode(t.code,n,t.deviceIdentity),gatewayName:e.name,machineName:vh()},t.code,t.deviceIdentity)},handleRefresh:async t=>{let n=await hI({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return mI(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=dR({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 ep.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 ep.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)=>SI(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,readableItemDetailLookup:D,refreshDetailSessionSnapshots:e=>D.refreshDetailSessionSnapshots(e),buildRawEventsListResult:oR}),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:tR(e,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,attachments:e.payload.attachments,commandId:e.commandId});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`:{rR(`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);rR(`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=qL(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`)=>oR({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=_T(t)?t.status:500;return _T(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=Ya.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=Ja.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=Pa.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=vh(),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},uR(pe,e.host,_e)),e.relayEnabled&&(_=new CM({gatewayId:e.gatewayId,machineName:e.name,relayUrl:e.relayUrl,relayTransportSecurityLevel:e.relayTransportSecurityLevel,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>OM({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:y.identity,privateKeyPem:y.privateKeyPem}),gatewayIdentity:y.identity,directBaseUrls:jg({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 cR(e,t){let n=t;if(!e.httpsEnabled)return(0,uT.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:$L}});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,uT.default)({disableRequestLogging:!0,loggerInstance:n,routerOptions:{maxParamLength:$L},https:r})}function lR(e,t){let n=process.env.NODE_ENV!==`production`,r=dT.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?dT.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,dT.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function uR(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function dR(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 fR(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,b.inspect)(e,{depth:6,breakLength:120})}async function pR(e){let t=await kh({configPath:e.configPath,ensureConfigFile:!0});Ph(t.config);let n=await sR(t.config,{configPath:t.configPath,logToConsole:e.logToConsole,onUpdatePrepared:async e=>{hR({type:`worker.update.prepared`,payload:e})}});hR({type:`worker.ready`,payload:mR(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=gR(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: ${fR(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${fR(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);hR({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);hR({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){hR({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function mR(e){return{protocol:e.protocol,listenPort:e.listenPort,gatewayName:e.gatewayName,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function hR(e){process.send&&process.send(e)}function gR(e){if(!_R(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 _R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}vR(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function vR(e){let t=ee(e);switch(t.command){case`help`:CR();return;case`version`:console.log(z.version);return;case`init`:await bR(t);return;case`doctor`:await xR(t);return;case`start`:await yR(t);return;case`__worker`:await SR(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function yR(e){let t=await kh({configPath:e.configPath,ensureConfigFile:!0});Ph(t.config);let n=await $h({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await h_({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(w_(e,t.config))}eg(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function bR(e){let t=await Oh({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 kh({configPath:t.configPath,ensureConfigFile:!1}),r=await $h({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(tg(r))}async function xR(e){let t=await kh({configPath:Dh(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await $h({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(tg(n)),eg(n)&&(process.exitCode=1)}async function SR(e){try{await pR(e)}catch(t){let n=await kh({configPath:e.configPath,ensureConfigFile:!0});throw Error(w_(t,n.config))}}function CR(){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=vR;
|