craby-gateway 0.16.0 → 0.16.2

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.
@@ -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(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`node:util`),b=require(`fs`);b=c(b);let x=require(`path`);x=c(x);let S=require(`module`),C=require(`net`),w=require(`child_process`),T=require(`@anthropic-ai/claude-agent-sdk`);var E={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.16.0`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.86`,"@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:{"@openai/codex":`^0.111.0`,"@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 D=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function O(e){let t=e.match(D);return t?t[0]:null}function k(e){return typeof e==`string`?O(e):null}function A(e,t){let n=M(e),r=M(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 j(e,t){return A(e,t)>=0}function M(e){let t=e.match(D);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const ee=E,N=ee.dependencies??{};function te(e){return N[e]??``}const P={packageName:`craby-gateway`,cliName:`craby-gateway`,version:ee.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:te(`@anthropic-ai/claude-agent-sdk`),minimumVersion:k(te(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ne(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=re(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 re(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=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})),ie=o((e=>{var t=F();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})),I=o((e=>{var t=F(),n=ie();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(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`node:util`),b=require(`fs`);b=c(b);let x=require(`path`);x=c(x);let S=require(`module`),C=require(`net`),w=require(`child_process`),T=require(`@anthropic-ai/claude-agent-sdk`);var E={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.16.2`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.86`,"@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:{"@openai/codex":`^0.111.0`,"@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 D=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function O(e){let t=e.match(D);return t?t[0]:null}function k(e){return typeof e==`string`?O(e):null}function A(e,t){let n=M(e),r=M(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 j(e,t){return A(e,t)>=0}function M(e){let t=e.match(D);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const ee=E,N=ee.dependencies??{};function te(e){return N[e]??``}const P={packageName:`craby-gateway`,cliName:`craby-gateway`,version:ee.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:te(`@anthropic-ai/claude-agent-sdk`),minimumVersion:k(te(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ne(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=re(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 re(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=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})),ie=o((e=>{var t=F();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})),I=o((e=>{var t=F(),n=ie();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})),ae=o((e=>{var t=F(),n=ie();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})),oe=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})),L=o((e=>{var t=F();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})),se=o((e=>{var t=oe(),n=F(),r=L();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}}})),ce=o((e=>{var t=ae(),n=ie(),r=F(),i=se(),a=L(),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})),le=o((e=>{var t=F(),n=se(),r=L();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})),ue=o((e=>{var t=ce(),n=F(),r=le();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})),de=o((e=>{var t=ue(),n=F(),r=se();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})),fe=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
  `)?`
@@ -115,7 +115,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
115
115
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
116
116
  `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),gt=o((e=>{var t=ct(),n=Ge(),r=Ke(),i=_e(),a=F(),o=mt(),s=ht();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),_t=o((e=>{var t=ct(),n=Ge(),r=Ue(),i=Ke(),a=ce(),o=F(),s=be(),c=le(),l=Se(),u=we();ft();var d=pt(),f=mt(),p=ht(),m=gt(),h=ie();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})),vt;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(vt||={});var yt;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(yt||={});const z=vt.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),bt=e=>{switch(typeof e){case`undefined`:return z.undefined;case`string`:return z.string;case`number`:return Number.isNaN(e)?z.nan:z.number;case`boolean`:return z.boolean;case`function`:return z.function;case`bigint`:return z.bigint;case`symbol`:return z.symbol;case`object`:return Array.isArray(e)?z.array:e===null?z.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?z.promise:typeof Map<`u`&&e instanceof Map?z.map:typeof Set<`u`&&e instanceof Set?z.set:typeof Date<`u`&&e instanceof Date?z.date:z.object;default:return z.unknown}},B=vt.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var xt=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,vt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};xt.create=e=>new xt(e);const St=(e,t)=>{let n;switch(e.code){case B.invalid_type:n=e.received===z.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case B.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,vt.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:n=`Unrecognized key(s) in object: ${vt.joinValues(e.keys,`, `)}`;break;case B.invalid_union:n=`Invalid input`;break;case B.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${vt.joinValues(e.options)}`;break;case B.invalid_enum_value:n=`Invalid enum value. Expected ${vt.joinValues(e.options)}, received '${e.received}'`;break;case B.invalid_arguments:n=`Invalid function arguments`;break;case B.invalid_return_type:n=`Invalid function return type`;break;case B.invalid_date:n=`Invalid date`;break;case B.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:vt.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case B.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case B.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case B.custom:n=`Invalid input`;break;case B.invalid_intersection_types:n=`Intersection results could not be merged`;break;case B.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case B.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,vt.assertNever(e)}return{message:n}};let Ct=St;function wt(){return Ct}const Tt=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function V(e,t){let n=wt(),r=Tt({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===St?void 0:St].filter(e=>!!e)});e.common.issues.push(r)}var Et=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return H;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return H;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const H=Object.freeze({status:`aborted`}),Dt=e=>({status:`dirty`,value:e}),Ot=e=>({status:`valid`,value:e}),kt=e=>e.status===`aborted`,At=e=>e.status===`dirty`,jt=e=>e.status===`valid`,Mt=e=>typeof Promise<`u`&&e instanceof Promise;var U;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(U||={});var Nt=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const Pt=(e,t)=>{if(jt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new xt(e.common.issues),this._error}}};function W(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var Ft=class{get description(){return this._def.description}_getType(e){return bt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:bt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Et,ctx:{common:e.parent.common,data:e.data,parsedType:bt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Mt(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bt(e)};return Pt(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bt(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return jt(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>jt(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bt(e)},r=this._parse({data:e,path:n.path,parent:n});return Pt(n,await(Mt(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:B.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new Rn({schema:this,typeName:G.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return zn.create(this,this._def)}nullable(){return Bn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return yn.create(this)}promise(){return Ln.create(this,this._def)}or(e){return Sn.create([this,e],this._def)}and(e){return En.create(this,e,this._def)}transform(e){return new Rn({...W(this._def),schema:this,typeName:G.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Vn({...W(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new Wn({typeName:G.ZodBranded,type:this,...W(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Hn({...W(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Gn.create(this,e)}readonly(){return Kn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const It=/^c[^\s-]{8,}$/i,Lt=/^[0-9a-z]+$/,Rt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,zt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Bt=/^[a-z0-9_-]{21}$/i,Vt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ht=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ut=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Wt;const Gt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Kt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,qt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Jt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Yt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zt=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Qt=RegExp(`^${Zt}$`);function $t(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function en(e){return RegExp(`^${$t(e)}$`)}function tn(e){let t=`${Zt}T${$t(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function nn(e,t){return!!((t===`v4`||!t)&&Gt.test(e)||(t===`v6`||!t)&&qt.test(e))}function rn(e,t){if(!Vt.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function an(e,t){return!!((t===`v4`||!t)&&Kt.test(e)||(t===`v6`||!t)&&Jt.test(e))}var on=class e extends Ft{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.string,received:t.parsedType}),H}let t=new Et,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),V(n,{code:B.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),V(n,{code:B.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?V(n,{code:B.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&V(n,{code:B.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Ut.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`email`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Wt||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),Wt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`emoji`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)zt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`uuid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Bt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`nanoid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)It.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`cuid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Lt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`cuid2`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Rt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`ulid`,code:B.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),V(n,{validation:`url`,code:B.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`regex`,code:B.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?tn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Qt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?en(r).test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{code:B.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Ht.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`duration`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?nn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`ip`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?rn(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`jwt`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?an(e.data,r.version)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`cidr`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Yt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`base64`,code:B.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Xt.test(e.data)||(n=this._getOrReturnCtx(e,n),V(n,{validation:`base64url`,code:B.invalid_string,message:r.message}),t.dirty()):vt.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:B.invalid_string,...U.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...U.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...U.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...U.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...U.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...U.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...U.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...U.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...U.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...U.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...U.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...U.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...U.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...U.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...U.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...U.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...U.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...U.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...U.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...U.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...U.errToObj(t)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};on.create=e=>new on({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...W(e)});function sn(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var cn=class e extends Ft{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.number,received:t.parsedType}),H}let t,n=new Et;for(let r of this._def.checks)r.kind===`int`?vt.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:B.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),V(t,{code:B.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),V(t,{code:B.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?sn(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),V(t,{code:B.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:B.not_finite,message:r.message}),n.dirty()):vt.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,U.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,U.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,U.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,U.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:U.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:U.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:U.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:U.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:U.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&vt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};cn.create=e=>new cn({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...W(e)});var ln=class e extends Ft{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let t,n=new Et;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),V(t,{code:B.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),V(t,{code:B.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),V(t,{code:B.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):vt.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.bigint,received:t.parsedType}),H}gte(e,t){return this.setLimit(`min`,e,!0,U.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,U.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,U.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,U.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:U.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:U.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ln.create=e=>new ln({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...W(e)});var un=class extends Ft{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.boolean,received:t.parsedType}),H}return Ot(e.data)}};un.create=e=>new un({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...W(e)});var dn=class e extends Ft{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.date,received:t.parsedType}),H}if(Number.isNaN(e.data.getTime()))return V(this._getOrReturnCtx(e),{code:B.invalid_date}),H;let t=new Et,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),V(n,{code:B.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),V(n,{code:B.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):vt.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:U.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:U.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};dn.create=e=>new dn({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...W(e)});var fn=class extends Ft{_parse(e){if(this._getType(e)!==z.symbol){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.symbol,received:t.parsedType}),H}return Ot(e.data)}};fn.create=e=>new fn({typeName:G.ZodSymbol,...W(e)});var pn=class extends Ft{_parse(e){if(this._getType(e)!==z.undefined){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.undefined,received:t.parsedType}),H}return Ot(e.data)}};pn.create=e=>new pn({typeName:G.ZodUndefined,...W(e)});var mn=class extends Ft{_parse(e){if(this._getType(e)!==z.null){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.null,received:t.parsedType}),H}return Ot(e.data)}};mn.create=e=>new mn({typeName:G.ZodNull,...W(e)});var hn=class extends Ft{constructor(){super(...arguments),this._any=!0}_parse(e){return Ot(e.data)}};hn.create=e=>new hn({typeName:G.ZodAny,...W(e)});var gn=class extends Ft{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ot(e.data)}};gn.create=e=>new gn({typeName:G.ZodUnknown,...W(e)});var _n=class extends Ft{_parse(e){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.never,received:t.parsedType}),H}};_n.create=e=>new _n({typeName:G.ZodNever,...W(e)});var vn=class extends Ft{_parse(e){if(this._getType(e)!==z.undefined){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.void,received:t.parsedType}),H}return Ot(e.data)}};vn.create=e=>new vn({typeName:G.ZodVoid,...W(e)});var yn=class e extends Ft{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==z.array)return V(t,{code:B.invalid_type,expected:z.array,received:t.parsedType}),H;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(V(t,{code:e?B.too_big:B.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(V(t,{code:B.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(V(t,{code:B.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Nt(t,e,t.path,n)))).then(e=>Et.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Nt(t,e,t.path,n)));return Et.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:U.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:U.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:U.toString(n)}})}nonempty(e){return this.min(1,e)}};yn.create=(e,t)=>new yn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...W(t)});function bn(e){if(e instanceof xn){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=zn.create(bn(r))}return new xn({...e._def,shape:()=>t})}else if(e instanceof yn)return new yn({...e._def,type:bn(e.element)});else if(e instanceof zn)return zn.create(bn(e.unwrap()));else if(e instanceof Bn)return Bn.create(bn(e.unwrap()));else if(e instanceof Dn)return Dn.create(e.items.map(e=>bn(e)));else return e}var xn=class e extends Ft{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:vt.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==z.object){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.object,received:t.parsedType}),H}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof _n&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Nt(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof _n){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(V(n,{code:B.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Nt(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Et.mergeObjectSync(t,e)):Et.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return U.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:U.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:G.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of vt.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of vt.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return bn(this)}partial(t){let n={};for(let e of vt.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of vt.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof zn;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Pn(vt.objectKeys(this.shape))}};xn.create=(e,t)=>new xn({shape:()=>e,unknownKeys:`strip`,catchall:_n.create(),typeName:G.ZodObject,...W(t)}),xn.strictCreate=(e,t)=>new xn({shape:()=>e,unknownKeys:`strict`,catchall:_n.create(),typeName:G.ZodObject,...W(t)}),xn.lazycreate=(e,t)=>new xn({shape:e,unknownKeys:`strip`,catchall:_n.create(),typeName:G.ZodObject,...W(t)});var Sn=class extends Ft{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new xt(e.ctx.common.issues));return V(t,{code:B.invalid_union,unionErrors:n}),H}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new xt(e));return V(t,{code:B.invalid_union,unionErrors:i}),H}}get options(){return this._def.options}};Sn.create=(e,t)=>new Sn({options:e,typeName:G.ZodUnion,...W(t)});const Cn=e=>e instanceof Mn?Cn(e.schema):e instanceof Rn?Cn(e.innerType()):e instanceof Nn?[e.value]:e instanceof Fn?e.options:e instanceof In?vt.objectValues(e.enum):e instanceof Vn?Cn(e._def.innerType):e instanceof pn?[void 0]:e instanceof mn?[null]:e instanceof zn?[void 0,...Cn(e.unwrap())]:e instanceof Bn?[null,...Cn(e.unwrap())]:e instanceof Wn||e instanceof Kn?Cn(e.unwrap()):e instanceof Hn?Cn(e._def.innerType):[];var wn=class e extends Ft{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return V(t,{code:B.invalid_type,expected:z.object,received:t.parsedType}),H;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(V(t,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),H)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Cn(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...W(r)})}};function Tn(e,t){let n=bt(e),r=bt(t);if(e===t)return{valid:!0,data:e};if(n===z.object&&r===z.object){let n=vt.objectKeys(t),r=vt.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Tn(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Tn(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===z.date&&r===z.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var En=class extends Ft{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(kt(e)||kt(r))return H;let i=Tn(e.value,r.value);return i.valid?((At(e)||At(r))&&t.dirty(),{status:t.value,value:i.data}):(V(n,{code:B.invalid_intersection_types}),H)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};En.create=(e,t,n)=>new En({left:e,right:t,typeName:G.ZodIntersection,...W(n)});var Dn=class e extends Ft{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return V(n,{code:B.invalid_type,expected:z.array,received:n.parsedType}),H;if(n.data.length<this._def.items.length)return V(n,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),H;!this._def.rest&&n.data.length>this._def.items.length&&(V(n,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Nt(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Et.mergeArray(t,e)):Et.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Dn.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Dn({items:e,typeName:G.ZodTuple,rest:null,...W(t)})};var On=class e extends Ft{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return V(n,{code:B.invalid_type,expected:z.object,received:n.parsedType}),H;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Nt(n,e,n.path,e)),value:a._parse(new Nt(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Et.mergeObjectAsync(t,r):Et.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Ft?new e({keyType:t,valueType:n,typeName:G.ZodRecord,...W(r)}):new e({keyType:on.create(),valueType:t,typeName:G.ZodRecord,...W(n)})}},kn=class extends Ft{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return V(n,{code:B.invalid_type,expected:z.map,received:n.parsedType}),H;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Nt(n,e,n.path,[a,`key`])),value:i._parse(new Nt(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return H;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return H;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};kn.create=(e,t,n)=>new kn({valueType:t,keyType:e,typeName:G.ZodMap,...W(n)});var An=class e extends Ft{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return V(n,{code:B.invalid_type,expected:z.set,received:n.parsedType}),H;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(V(n,{code:B.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(V(n,{code:B.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return H;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Nt(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:U.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:U.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};An.create=(e,t)=>new An({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...W(t)});var jn=class e extends Ft{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return V(t,{code:B.invalid_type,expected:z.function,received:t.parsedType}),H;function n(e,n){return Tt({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,wt(),St].filter(e=>!!e),issueData:{code:B.invalid_arguments,argumentsError:n}})}function r(e,n){return Tt({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,wt(),St].filter(e=>!!e),issueData:{code:B.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Ln){let e=this;return Ot(async function(...t){let o=new xt([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return Ot(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new xt([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new xt([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Dn.create(t).rest(gn.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Dn.create([]).rest(gn.create()),returns:n||gn.create(),typeName:G.ZodFunction,...W(r)})}},Mn=class extends Ft{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Mn.create=(e,t)=>new Mn({getter:e,typeName:G.ZodLazy,...W(t)});var Nn=class extends Ft{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return V(t,{received:t.data,code:B.invalid_literal,expected:this._def.value}),H}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Nn.create=(e,t)=>new Nn({value:e,typeName:G.ZodLiteral,...W(t)});function Pn(e,t){return new Fn({values:e,typeName:G.ZodEnum,...W(t)})}var Fn=class e extends Ft{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return V(t,{expected:vt.joinValues(n),received:t.parsedType,code:B.invalid_type}),H}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return V(t,{received:t.data,code:B.invalid_enum_value,options:n}),H}return Ot(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Fn.create=Pn;var In=class extends Ft{_parse(e){let t=vt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let e=vt.objectValues(t);return V(n,{expected:vt.joinValues(e),received:n.parsedType,code:B.invalid_type}),H}if(this._cache||=new Set(vt.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=vt.objectValues(t);return V(n,{received:n.data,code:B.invalid_enum_value,options:e}),H}return Ot(e.data)}get enum(){return this._def.values}};In.create=(e,t)=>new In({values:e,typeName:G.ZodNativeEnum,...W(t)});var Ln=class extends Ft{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==z.promise&&t.common.async===!1?(V(t,{code:B.invalid_type,expected:z.promise,received:t.parsedType}),H):Ot((t.parsedType===z.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Ln.create=(e,t)=>new Ln({type:e,typeName:G.ZodPromise,...W(t)});var Rn=class extends Ft{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{V(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return H;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?H:r.status===`dirty`||t.value===`dirty`?Dt(r.value):r});{if(t.value===`aborted`)return H;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?H:r.status===`dirty`||t.value===`dirty`?Dt(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?H:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?H:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!jt(e))return H;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>jt(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):H);vt.assertNever(r)}};Rn.create=(e,t,n)=>new Rn({schema:e,typeName:G.ZodEffects,effect:t,...W(n)}),Rn.createWithPreprocess=(e,t,n)=>new Rn({schema:t,effect:{type:`preprocess`,transform:e},typeName:G.ZodEffects,...W(n)});var zn=class extends Ft{_parse(e){return this._getType(e)===z.undefined?Ot(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zn.create=(e,t)=>new zn({innerType:e,typeName:G.ZodOptional,...W(t)});var Bn=class extends Ft{_parse(e){return this._getType(e)===z.null?Ot(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bn.create=(e,t)=>new Bn({innerType:e,typeName:G.ZodNullable,...W(t)});var Vn=class extends Ft{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Vn.create=(e,t)=>new Vn({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...W(t)});var Hn=class extends Ft{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Mt(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Hn.create=(e,t)=>new Hn({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...W(t)});var Un=class extends Ft{_parse(e){if(this._getType(e)!==z.nan){let t=this._getOrReturnCtx(e);return V(t,{code:B.invalid_type,expected:z.nan,received:t.parsedType}),H}return{status:`valid`,value:e.data}}};Un.create=e=>new Un({typeName:G.ZodNaN,...W(e)});var Wn=class extends Ft{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Gn=class e extends Ft{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?H:e.status===`dirty`?(t.dirty(),Dt(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?H:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:G.ZodPipeline})}},Kn=class extends Ft{_parse(e){let t=this._def.innerType._parse(e),n=e=>(jt(e)&&(e.value=Object.freeze(e.value)),e);return Mt(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Kn.create=(e,t)=>new Kn({innerType:e,typeName:G.ZodReadonly,...W(t)}),xn.lazycreate;var G;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(G||={});const K=on.create,qn=cn.create;Un.create,ln.create;const Jn=un.create;dn.create,fn.create,pn.create,mn.create,hn.create;const Yn=gn.create;_n.create,vn.create;const Xn=yn.create,q=xn.create;xn.strictCreate;const Zn=Sn.create,Qn=wn.create;En.create,Dn.create;const $n=On.create;kn.create,An.create,jn.create,Mn.create;const J=Nn.create,Y=Fn.create;In.create,Ln.create,Rn.create,zn.create,Bn.create;const er=Rn.createWithPreprocess;Gn.create;var tr=c(_t(),1);
117
117
  /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
118
- function nr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function rr(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}function ir(e,t,n=``){let r=nr(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function ar(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function or(e,t){ir(e,void 0,`output`);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function sr(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function cr(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function lr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ur(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const dr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;typeof Uint8Array.from([]).toHex==`function`&&Uint8Array.fromHex;function fr(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const pr=(e,t)=>{function n(n,...r){if(ir(n,void 0,`key`),!dr)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];ir(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&ir(r[1],void 0,`AAD`);let a=t(n,...r),o=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);ir(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,ir(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(ir(e),i&&e.length<i)throw Error(`"ciphertext" expected length bigger than tagLength=`+i);return o(a.decrypt.length,t),a.decrypt(e,t)}}}return Object.assign(n,e),n};function mr(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw Error(`"output" expected Uint8Array of length `+e+`, got: `+t.length);if(n&&!gr(t))throw Error(`invalid output, must be aligned`);return t}function hr(e,t,n){rr(n);let r=new Uint8Array(16),i=ur(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function gr(e){return e.byteOffset%4==0}function _r(e){return Uint8Array.from(e)}const vr=new Uint8Array(16),yr=cr(vr),br=(e,t,n,r)=>{let i=r&1;return{s3:n<<31|r>>>1,s2:t<<31|n>>>1,s1:e<<31|t>>>1,s0:e>>>1^225<<24&-(i&1)}},xr=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255|0;function Sr(e){e.reverse();let t=e[15]&1,n=0;for(let t=0;t<e.length;t++){let r=e[t];e[t]=r>>>1|n,n=(r&1)<<7}return e[0]^=-t&225,e}const Cr=e=>e>64*1024?8:e>1024?4:2;var wr=class{blockLen=16;outputLen=16;s0=0;s1=0;s2=0;s3=0;finished=!1;t;W;windowSize;constructor(e,t){ir(e,16,`key`),e=_r(e);let n=ur(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=n.getUint32(8,!1),o=n.getUint32(12,!1),s=[];for(let e=0;e<128;e++)s.push({s0:xr(r),s1:xr(i),s2:xr(a),s3:xr(o)}),{s0:r,s1:i,s2:a,s3:o}=br(r,i,a,o);let c=Cr(t||1024);if(![1,2,4,8].includes(c))throw Error(`ghash: invalid window size, expected 2, 4 or 8`);this.W=c;let l=128/c,u=this.windowSize=2**c,d=[];for(let e=0;e<l;e++)for(let t=0;t<u;t++){let n=0,r=0,i=0,a=0;for(let o=0;o<c;o++){if(!(t>>>c-o-1&1))continue;let{s0:l,s1:u,s2:d,s3:f}=s[c*e+o];n^=l,r^=u,i^=d,a^=f}d.push({s0:n,s1:r,s2:i,s3:a})}this.t=d}_updateBlock(e,t,n,r){e^=this.s0,t^=this.s1,n^=this.s2,r^=this.s3;let{W:i,t:a,windowSize:o}=this,s=0,c=0,l=0,u=0,d=(1<<i)-1,f=0;for(let p of[e,t,n,r])for(let e=0;e<4;e++){let t=p>>>8*e&255;for(let e=8/i-1;e>=0;e--){let n=t>>>i*e&d,{s0:r,s1:p,s2:m,s3:h}=a[f*o+n];s^=r,c^=p,l^=m,u^=h,f+=1}}this.s0=s,this.s1=c,this.s2=l,this.s3=u}update(e){ar(this),ir(e),e=_r(e);let t=cr(e),n=Math.floor(e.length/16),r=e.length%16;for(let e=0;e<n;e++)this._updateBlock(t[e*4+0],t[e*4+1],t[e*4+2],t[e*4+3]);return r&&(vr.set(e.subarray(n*16)),this._updateBlock(yr[0],yr[1],yr[2],yr[3]),lr(yr)),this}destroy(){let{t:e}=this;for(let t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){ar(this),or(e,this),this.finished=!0;let{s0:t,s1:n,s2:r,s3:i}=this,a=cr(e);return a[0]=t,a[1]=n,a[2]=r,a[3]=i,e}digest(){let e=new Uint8Array(16);return this.digestInto(e),this.destroy(),e}},Tr=class extends wr{constructor(e,t){ir(e);let n=Sr(_r(e));super(n,t),lr(n)}update(e){ar(this),ir(e),e=_r(e);let t=cr(e),n=e.length%16,r=Math.floor(e.length/16);for(let e=0;e<r;e++)this._updateBlock(xr(t[e*4+3]),xr(t[e*4+2]),xr(t[e*4+1]),xr(t[e*4+0]));return n&&(vr.set(e.subarray(r*16)),this._updateBlock(xr(yr[3]),xr(yr[2]),xr(yr[1]),xr(yr[0])),lr(yr)),this}digestInto(e){ar(this),or(e,this),this.finished=!0;let{s0:t,s1:n,s2:r,s3:i}=this,a=cr(e);return a[0]=t,a[1]=n,a[2]=r,a[3]=i,e.reverse()}};function Er(e){let t=(t,n)=>e(n,t.length).update(t).digest(),n=e(new Uint8Array(16),0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=(t,n)=>e(t,n),t}const Dr=Er((e,t)=>new wr(e,t));Er((e,t)=>new Tr(e,t));const Or=new Uint8Array(16);function kr(e){if(![16,24,32].includes(e.length))throw Error(`"aes key" expected Uint8Array of length 16/24/32, got length=`+e.length)}function Ar(e){return e<<1^283&-(e>>7)}function jr(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=Ar(e);return n}const Mr=(()=>{let e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Ar(n))e[t]=n;let t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return lr(e),t})(),Nr=e=>e<<24|e>>>8,Pr=e=>e<<8|e>>>24;function Fr(e,t){if(e.length!==256)throw Error(`Wrong sbox length`);let n=new Uint32Array(256).map((n,r)=>t(e[r])),r=n.map(Pr),i=r.map(Pr),a=i.map(Pr),o=new Uint32Array(256*256),s=new Uint32Array(256*256),c=new Uint16Array(256*256);for(let t=0;t<256;t++)for(let l=0;l<256;l++){let u=t*256+l;o[u]=n[t]^r[l],s[u]=i[t]^a[l],c[u]=e[t]<<8|e[l]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:i,T3:a,T01:o,T23:s}}const Ir=Fr(Mr,e=>jr(e,3)<<24|e<<16|e<<8|jr(e,2)),Lr=(()=>{let e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Ar(n))e[t]=n;return e})();function Rr(e){ir(e);let t=e.length;kr(e);let{sbox2:n}=Ir,r=[];gr(e)||r.push(e=_r(e));let i=cr(e),a=i.length,o=e=>Br(n,e,e,e,e),s=new Uint32Array(t+28);s.set(i);for(let e=a;e<s.length;e++){let t=s[e-1];e%a===0?t=o(Nr(t))^Lr[e/a-1]:a>6&&e%a===4&&(t=o(t)),s[e]=s[e-a]^t}return lr(...r),s}function zr(e,t,n,r,i,a){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|a>>>24&255]}function Br(e,t,n,r,i){return e[t&255|n&65280]|e[r>>>16&255|i>>>16&65280]<<16}function Vr(e,t,n,r,i){let{sbox2:a,T01:o,T23:s}=Ir,c=0;t^=e[c++],n^=e[c++],r^=e[c++],i^=e[c++];let l=e.length/4-2;for(let a=0;a<l;a++){let a=e[c++]^zr(o,s,t,n,r,i),l=e[c++]^zr(o,s,n,r,i,t),u=e[c++]^zr(o,s,r,i,t,n),d=e[c++]^zr(o,s,i,t,n,r);t=a,n=l,r=u,i=d}return{s0:e[c++]^Br(a,t,n,r,i),s1:e[c++]^Br(a,n,r,i,t),s2:e[c++]^Br(a,r,i,t,n),s3:e[c++]^Br(a,i,t,n,r)}}function Hr(e,t,n,r,i){ir(n,16,`nonce`),ir(r),i=mr(r.length,i);let a=n,o=cr(a),s=ur(a),c=cr(r),l=cr(i),u=t?0:12,d=r.length,f=s.getUint32(u,t),{s0:p,s1:m,s2:h,s3:g}=Vr(e,o[0],o[1],o[2],o[3]);for(let n=0;n+4<=c.length;n+=4)l[n+0]=c[n+0]^p,l[n+1]=c[n+1]^m,l[n+2]=c[n+2]^h,l[n+3]=c[n+3]^g,f=f+1>>>0,s.setUint32(u,f,t),{s0:p,s1:m,s2:h,s3:g}=Vr(e,o[0],o[1],o[2],o[3]);let _=16*Math.floor(c.length/4);if(_<d){let e=new Uint32Array([p,m,h,g]),t=sr(e);for(let e=_,n=0;e<d;e++,n++)i[e]=r[e]^t[n];lr(e)}return i}function Ur(e,t,n,r,i){let a=i?i.length:0,o=e.create(n,r.length+a);i&&o.update(i);let s=hr(8*r.length,8*a,t);o.update(r),o.update(s);let c=o.digest();return lr(s),c}const Wr=pr({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(e,t,n){if(t.length<8)throw Error(`aes/gcm: invalid nonce length`);function r(e,t,r){let i=Ur(Dr,!1,e,r,n);for(let e=0;e<t.length;e++)i[e]^=t[e];return i}function i(){let n=Rr(e),r=Or.slice(),i=Or.slice();if(Hr(n,!1,i,i,r),t.length===12)i.set(t);else{let e=Or.slice();ur(e).setBigUint64(8,BigInt(t.length*8),!1);let n=Dr.create(r).update(t).update(e);n.digestInto(i),n.destroy()}return{xk:n,authKey:r,counter:i,tagMask:Hr(n,!1,i,Or)}}return{encrypt(e){let{xk:t,authKey:n,counter:a,tagMask:o}=i(),s=new Uint8Array(e.length+16),c=[t,n,a,o];gr(e)||c.push(e=_r(e)),Hr(t,!1,a,e,s.subarray(0,e.length));let l=r(n,o,s.subarray(0,s.length-16));return c.push(l),s.set(l,e.length),lr(...c),s},decrypt(e){let{xk:t,authKey:n,counter:a,tagMask:o}=i(),s=[t,n,o,a];gr(e)||s.push(e=_r(e));let c=e.subarray(0,-16),l=e.subarray(-16),u=r(n,o,c);if(s.push(u),!fr(u,l))throw Error(`aes/gcm: invalid ghash tag`);let d=Hr(t,!1,a,c);return lr(...s),d}}});function Gr(e){return e instanceof Uint32Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint32Array`}function Kr(e,t){if(ir(t,16,`block`),!Gr(e))throw Error(`_encryptBlock accepts result of expandKeyLE`);let n=cr(t),{s0:r,s1:i,s2:a,s3:o}=Vr(e,n[0],n[1],n[2],n[3]);return n[0]=r,n[1]=i,n[2]=a,n[3]=o,t}function qr(e){let t=0;for(let n=15;n>=0;n--){let r=(e[n]&128)>>>7;e[n]=e[n]<<1|t,t=r}return t&&(e[15]^=135),e}function Jr(e,t){if(e.length!==t.length)throw Error(`xorBlock: blocks must have same length`);for(let n=0;n<e.length;n++)e[n]=e[n]^t[n];return e}var Yr=class{buffer;destroyed;k1;k2;xk;constructor(e){ir(e),kr(e),this.xk=Rr(e),this.buffer=new Uint8Array,this.destroyed=!1;let t=new Uint8Array(16);Kr(this.xk,t),this.k1=qr(t),this.k2=qr(new Uint8Array(this.k1))}update(e){let{destroyed:t,buffer:n}=this;if(t)throw Error(`CMAC instance was destroyed`);ir(e);let r=new Uint8Array(n.length+e.length);return r.set(n),r.set(e,n.length),this.buffer=r,this}digest(){if(this.destroyed)throw Error(`CMAC instance was destroyed`);let{buffer:e}=this,t=e.length,n=Math.ceil(t/16),r;n===0?(n=1,r=!1):r=t%16==0;let i=(n-1)*16,a=e.subarray(i),o;if(r)o=Jr(new Uint8Array(a),this.k1);else{let e=new Uint8Array(16);e.set(a),e[a.length]=128,o=Jr(e,this.k2)}let s=new Uint8Array(16);for(let t=0;t<n-1;t++)Jr(s,e.subarray(t*16,(t+1)*16)),Kr(this.xk,s);return Jr(s,o),Kr(this.xk,s),lr(o),s}destroy(){let{buffer:e,destroyed:t,xk:n,k1:r,k2:i}=this;t||(this.destroyed=!0,lr(e,n,r,i))}};const Xr=(e,t)=>new Yr(e).update(t).digest();Xr.create=e=>new Yr(e);function Zr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function Qr(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function $r(e,...t){if(!Zr(e))throw Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function ei(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);Qr(e.outputLen),Qr(e.blockLen)}function ti(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function ni(e,t){$r(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function ri(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ii(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ai(e,t){return e<<32-t|e>>>t}new Uint8Array(new Uint32Array([287454020]).buffer)[0],typeof Uint8Array.from([]).toHex==`function`&&Uint8Array.fromHex;function oi(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function si(e){return typeof e==`string`&&(e=oi(e)),$r(e),e}var ci=class{};function li(e){let t=t=>e().update(si(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}var ui=class extends ci{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ei(e);let n=si(t);if(this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),ri(i)}update(e){return ti(this),this.iHash.update(e),this}digestInto(e){ti(this),$r(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const di=(e,t,n)=>new ui(e,t).update(n).digest();di.create=(e,t)=>new ui(e,t);function fi(e,t,n){return ei(e),n===void 0&&(n=new Uint8Array(e.outputLen)),di(e,si(n),si(t))}const pi=Uint8Array.from([0]),mi=Uint8Array.of();function hi(e,t,n,r=32){ei(e),Qr(r);let i=e.outputLen;if(r>255*i)throw Error(`Length should be <= 255*HashLen`);let a=Math.ceil(r/i);n===void 0&&(n=mi);let o=new Uint8Array(a*i),s=di.create(e,t),c=s._cloneInto(),l=new Uint8Array(s.outputLen);for(let e=0;e<a;e++)pi[0]=e+1,c.update(e===0?mi:l).update(n).update(pi).digestInto(l),o.set(l,i*e),s._cloneInto(c);return s.destroy(),c.destroy(),ri(l,pi),o.slice(0,r)}const gi=(e,t,n,r,i)=>hi(e,fi(e,t,n),r,i);function _i(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}function vi(e,t,n){return e&t^~e&n}function yi(e,t,n){return e&t^e&n^t&n}var bi=class extends ci{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ii(this.buffer)}update(e){ti(this),e=si(e),$r(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=ii(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ti(this),ni(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,ri(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;_i(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=ii(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const xi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Si=BigInt(2**32-1),Ci=BigInt(32);function wi(e,t=!1){return t?{h:Number(e&Si),l:Number(e>>Ci&Si)}:{h:Number(e>>Ci&Si)|0,l:Number(e&Si)|0}}function Ti(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=wi(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}const Ei=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Di=new Uint32Array(64);var Oi=class extends bi{constructor(e=32){super(64,e,8,!1),this.A=xi[0]|0,this.B=xi[1]|0,this.C=xi[2]|0,this.D=xi[3]|0,this.E=xi[4]|0,this.F=xi[5]|0,this.G=xi[6]|0,this.H=xi[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)Di[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Di[e-15],n=Di[e-2],r=ai(t,7)^ai(t,18)^t>>>3;Di[e]=(ai(n,17)^ai(n,19)^n>>>10)+Di[e-7]+r+Di[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=ai(o,6)^ai(o,11)^ai(o,25),u=l+t+vi(o,s,c)+Ei[e]+Di[e]|0,d=(ai(n,2)^ai(n,13)^ai(n,22))+yi(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){ri(Di)}destroy(){this.set(0,0,0,0,0,0,0,0),ri(this.buffer)}};const ki=Ti(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e)));ki[0],ki[1];const Ai=li(()=>new Oi);var ji=Y([`codex`,`claude`]),Mi=Y([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),Ni=Y([`untrusted`,`on-failure`,`on-request`,`never`]),Pi=Y([`read-only`,`workspace-write`,`danger-full-access`]),Fi=Y([`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`]),Ii=q({reasoningEffort:Mi.optional(),approvalPolicy:Ni.optional(),sandboxMode:Pi.optional(),permissionMode:Fi.optional()}),Li=Y([`native`,`fallback`]),Ri=q({provider:ji,models:Xn(q({id:K().min(1),label:K().min(1),description:K().min(1).optional(),isDefault:Jn().optional(),supportedReasoningEfforts:Xn(Mi).optional()})),support:q({reasoningEffort:Jn(),approvalPolicy:Jn(),sandboxMode:Jn(),permissionMode:Jn().optional()}),options:q({reasoningEfforts:Xn(Mi),approvalPolicies:Xn(Ni),sandboxModes:Xn(Pi),permissionModes:Xn(Fi).optional()}),defaults:q({model:K().min(1).optional(),reasoningEffort:Mi.optional(),approvalPolicy:Ni.optional(),sandboxMode:Pi.optional(),permissionMode:Fi.optional()}),source:Li}),zi=K().trim().min(1).nullable(),Bi=Y([`default`,`plan`]),Vi=q({approvalPolicy:Ni.nullable(),sandboxMode:Pi.nullable()}),Hi=q({permissionMode:Fi.nullable()}),Ui=q({codex:Vi.optional(),claude:Hi.optional()}),Wi=$n(Yn());q({modeDefault:Bi,model:K().trim().min(1).optional(),reasoningEffort:Mi.optional(),execution:Ui.optional()});var Gi=q({mode:Bi,model:zi,reasoningEffort:Mi.nullable(),execution:Ui.optional()});q({provider:ji,model:zi,reasoningEffort:Mi.nullable(),execution:Ui.optional()});var Ki=q({model:zi,reasoningEffort:Mi.nullable(),execution:Ui.optional(),context:Wi.optional()}),qi=q({target:Qn(`type`,[q({type:J(`uncommittedChanges`)}),q({type:J(`baseBranch`),branch:K().trim().min(1)}),q({type:J(`commit`),sha:K().trim().min(1),title:K().trim().min(1).optional()}),q({type:J(`custom`),instructions:K().trim().min(1)})]),delivery:Y([`inline`,`detached`]).optional()}),Ji=q({preset:Y([`general`,`security`,`performance`,`style`]),scope:Y([`workingTree`,`staged`,`selection`,`custom`]).optional(),instructions:K().trim().min(1).optional()}),Yi=q({provider:ji,codex:qi.optional(),claude:Ji.optional()}).superRefine((e,t)=>{if(e.provider===`codex`){e.codex||t.addIssue({code:B.custom,path:[`codex`],message:`codex review config is required when provider is codex`}),e.claude&&t.addIssue({code:B.custom,path:[`claude`],message:`claude review config must be omitted when provider is codex`});return}e.claude||t.addIssue({code:B.custom,path:[`claude`],message:`claude review config is required when provider is claude`}),e.codex&&t.addIssue({code:B.custom,path:[`codex`],message:`codex review config must be omitted when provider is claude`})}),Xi=K().min(1).regex(/^[A-Za-z0-9+/=]+$/u),Zi=q({v:J(`1.0`),provider:ji,sessionId:K().min(1),projectId:K().min(1).optional(),eventId:K().min(1),ts:K().datetime(),type:K().min(1),payload:q({raw:Yn()}).passthrough()}).passthrough(),Qi=q({commandId:K().min(1).optional()}),$i=Qi.extend({type:J(`session.start`),payload:q({provider:ji,model:K().min(1).optional(),projectId:K().min(1).optional(),cwd:K().min(1).optional(),sessionConfig:Ii.optional(),sessionTurnConfig:Gi.optional(),metadata:$n(Yn()).optional()})}),ea=Qi.extend({type:J(`turn.input`),payload:q({sessionId:K().min(1),text:K().min(1),model:K().min(1).optional(),sessionConfig:Ii.optional(),mode:Bi.optional(),config:Ki.optional()})}),ta=Qi.extend({type:J(`review.start`),payload:q({sessionId:K().min(1),input:K().min(1).optional(),config:Yi,turnConfig:Ki})}),na=Qi.extend({type:J(`tool.approval.respond`),payload:q({sessionId:K().min(1),requestId:K().min(1),decision:Y([`allow`,`deny`]),reason:K().min(1).optional()})}),ra=Qi.extend({type:J(`user.input.respond`),payload:q({sessionId:K().min(1),requestId:K().min(1),answers:$n(Xn(K()))})}),ia=Qi.extend({type:J(`session.interrupt`),payload:q({sessionId:K().min(1)})}),aa=Qi.extend({type:J(`session.close`),payload:q({sessionId:K().min(1)})}),oa=Qn(`kind`,[q({kind:J(`all`)}),q({kind:J(`raw_seq`),rawSeq:qn().int().nonnegative()})]),sa=q({sessionId:K().min(1),projectId:K().min(1).optional(),cursor:oa,purpose:Y([`detail_view`,`live_follow`]).optional()}),ca=Qi.extend({type:J(`session.stream.subscribe`),payload:q({replace:Jn().default(!0),sessions:Xn(sa)})}),la=q({sessionId:K().min(1),projectId:K().min(1).optional()}),ua=Qn(`type`,[$i,ea,ta,na,ra,ia,aa,Qi.extend({type:J(`session.external.watch.set`),payload:q({replace:Jn().default(!0),sessions:Xn(la)})}),ca,Qi.extend({type:J(`fs.read`),payload:q({sessionId:K().min(1),path:K().min(1)})}),Qi.extend({type:J(`fs.diff`),payload:q({sessionId:K().min(1),path:K().min(1),baseContent:K().optional()})})]);function da(e){let t=ua.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}var fa=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`]),pa=Zi.extend({type:fa}),ma=Zi.extend({kind:J(`provider.raw`),rawSeq:qn().int().positive(),type:K().min(1)});pa.extend({kind:J(`gateway.control`).optional(),derivedFrom:K().min(1).optional()});var ha=Zn([ma,Zi.extend({kind:J(`session.stream.sync`),type:J(`session.stream.sync`),payload:q({raw:q({decision:Y([`delta`,`snapshot`]),reason:K().min(1),snapshotId:K().min(1).optional(),fromRawSeq:qn().int().nonnegative().optional(),toRawSeq:qn().int().nonnegative().optional()}).passthrough()}).passthrough()}),Zi.extend({kind:J(`session.stream.snapshot.chunk`),type:J(`session.stream.snapshot.chunk`),payload:q({raw:q({snapshotId:K().min(1),chunkIndex:qn().int().nonnegative(),totalChunks:qn().int().positive(),events:Xn(ma)}).passthrough()}).passthrough()}),Zi.extend({kind:J(`session.external.update`),type:J(`session.external.update`),payload:q({raw:q({updatedAt:K().datetime(),status:Y([`running`,`idle`]),interactionLockReason:Y([`external_turn_running`]).optional(),refreshMode:Y([`delta`,`snapshot`]),fromRawSeq:qn().int().nonnegative().optional(),toRawSeq:qn().int().nonnegative().optional(),historyUpdated:Jn(),statusChanged:Jn()}).passthrough()}).passthrough()})]),ga=q({algorithm:Y([`ed25519`]),publicKey:Xi,publicKeyFingerprint:K().min(1),keyVersion:qn().int().min(1),createdAt:K().datetime()});q({code:K().min(4),expiresAt:K().datetime()});var _a=Y([`ed25519`]),va=Y([`active`,`revoked`,`rotating`,`unknown`]),ya=q({algorithm:_a,publicKey:Xi,publicKeyFingerprint:K().min(1)}),ba=q({pairingCode:K().min(4),signedAt:K().datetime()}),xa=q({gatewayId:K().min(1),deviceId:K().min(1),mobilePublicKey:Xi,pairingContext:ba}),Sa=q({algorithm:J(`ed25519`),gatewayPublicKeyFingerprint:K().min(1),payload:xa,signature:Xi}),Ca=q({code:K().min(4),deviceName:er(e=>{if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:void 0},K().min(1).optional()),deviceIdentity:ya.optional()}),wa=q({accessToken:K().min(1),refreshToken:K().min(1),expiresInSeconds:qn().int().positive()}),Ta=wa.extend({gatewayId:K().min(1),deviceId:K().min(1),gatewayIdentity:ga.optional(),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:va.optional(),pairingConfirmation:Sa.optional()}),Ea=q({refreshToken:K().min(1)}),Da=wa.extend({deviceId:K().min(1),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:va.optional()});function Oa(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var ka=q({restarted:J(!0),closedRuntimeSessionCount:qn().int().nonnegative()}),Aa=Y([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),ja=Y([`npm`,`pnpm`,`yarn`,`unknown`]),Ma=Y([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),Na=Y([`console`,`mobile`,`system`]),Pa=q({manager:ja,installType:Ma,packageName:K().min(1),packageRoot:K().min(1).optional(),binPath:K().min(1).optional(),canSelfUpdate:Jn(),reason:K().min(1).optional()}),Fa=q({id:K().min(1),targetVersion:K().min(1),requestedBy:Na,requestedAt:K().datetime(),startedAt:K().datetime().optional()}),Ia=q({packageName:K().min(1),currentVersion:K().min(1),latestVersion:K().min(1).optional(),available:Jn(),canApply:Jn(),status:Aa,checkedAt:K().datetime().optional(),install:Pa,job:Fa.optional(),lastError:K().min(1).optional()}),La=q({type:J(`gateway.update.status`),payload:Ia}),Ra=q({started:Jn(),update:Ia}),za=er(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},K().trim().min(1)),Ba=q({id:K().min(1),title:K().min(1),path:K().min(1),createdAt:K().datetime(),updatedAt:K().datetime(),lastSessionAt:K().datetime().optional(),runningCount:qn().int().nonnegative(),idleCount:qn().int().nonnegative().optional(),totalCount:qn().int().nonnegative().optional(),endedCount:qn().int().nonnegative()}),Va=q({name:K().min(1),path:K().min(1)}),Ha=q({rootPath:K().min(1),currentPath:K().min(1),parentPath:K().min(1).nullable(),directories:Xn(Va)}),Ua=Y([`running`,`idle`]),Wa=Y([`running`,`idle`,`all`]),Ga=Y([`external_turn_running`]);Y([`delta`,`snapshot`]);var Ka=q({id:K().min(1),nativeSessionId:K().min(1).optional(),source:Y([`gateway`,`native_discovered`]).optional(),projectId:K().min(1),projectPath:K().min(1),provider:ji,providerMode:Y([`native`,`mock`]).optional(),model:K().min(1).optional(),title:K().min(1).optional(),sessionTurnConfig:Gi.optional(),sessionTurnConfigUpdatedAt:K().datetime().optional(),createdAt:K().datetime(),updatedAt:K().datetime(),status:Ua,interactionLockReason:Ga.optional(),pendingApprovals:qn().int().nonnegative(),pendingUserInputs:qn().int().nonnegative(),pendingActions:qn().int().nonnegative()}),qa=q({id:K().min(1),name:K().min(1),createdAt:K().datetime(),revokedAt:K().datetime().optional(),identityAlgorithm:Y([`ed25519`]).optional(),publicKeyFingerprint:K().min(1).optional(),identityStatus:va.optional(),lastVerifiedAt:K().datetime().optional()}),Ja=q({agent:q({provider:ji,requestedVersion:K().min(1).nullable(),resolvedVersion:K().min(1)}),capabilities:Ri}),Ya=q({scannedAt:K().datetime(),sessionCount:qn().int().nonnegative(),status:Y([`ready`,`partial`,`failed`]),error:K().min(1).optional()}),Xa=q({codex:Ya.optional(),claude:Ya.optional()}),Za=q({key:K().min(1),path:K().min(1),title:K().min(1),lastSessionAt:K().datetime().optional(),sessionCount:qn().int().nonnegative(),providerCounts:q({codex:qn().int().nonnegative(),claude:qn().int().nonnegative()}),lastDiscoveryAt:K().datetime()}),Qa=q({provider:ji,nativeSessionId:K().min(1),title:K().min(1).optional(),model:K().min(1).optional(),createdAt:K().datetime().optional(),updatedAt:K().datetime()}),$a=q({generatedAt:K().datetime(),source:Y([`cache`,`fresh_scan`]),providers:Xa,projects:Xn(Za)}),eo=q({canonicalProjectPath:K().min(1),project:Za,providers:Xa,sessions:Xn(Qa)}),to=Y([`auth.refresh`,`codex.appServer.restart`,`gateway.update.get`,`gateway.update.apply`,`projects.list`,`projects.discovery.get`,`projects.discovery.refresh`,`projects.create`,`projects.delete`,`workspace.directories.list`,`sessions.list`,`sessions.discovery.list`,`sessions.get`,`sessions.config.get`,`sessions.history.sync`,`sessions.rawEvents.list`,`providers.capabilities.get`,`agents.config.get`,`devices.list`,`devices.revoke`]),no=q({}).strict(),ro=Qn(`method`,[q({method:J(`auth.refresh`),params:Ea.extend({deviceId:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),params:q({requestedBy:Na.optional()})}),q({method:J(`gateway.update.get`),params:no}),q({method:J(`gateway.update.apply`),params:q({requestedBy:Na.optional()})}),q({method:J(`projects.list`),params:no}),q({method:J(`projects.discovery.get`),params:no}),q({method:J(`projects.discovery.refresh`),params:no}),q({method:J(`projects.create`),params:q({path:za,title:K().min(1).optional()})}),q({method:J(`projects.delete`),params:q({projectId:K().min(1)})}),q({method:J(`workspace.directories.list`),params:q({path:K().min(1).optional(),limit:qn().int().positive().max(500).optional()})}),q({method:J(`sessions.list`),params:q({projectId:K().min(1),status:Wa.optional(),syncExternal:Jn().optional()})}),q({method:J(`sessions.discovery.list`),params:q({projectPath:za})}),q({method:J(`sessions.get`),params:q({projectId:K().min(1),sessionId:K().min(1)})}),q({method:J(`sessions.config.get`),params:q({projectId:K().min(1),sessionId:K().min(1)})}),q({method:J(`sessions.history.sync`),params:q({projectId:K().min(1),sessionId:K().min(1)})}),q({method:J(`sessions.rawEvents.list`),params:q({projectId:K().min(1),sessionId:K().min(1),limit:Zn([qn().int().positive().max(2e3),J(`all`)]).optional(),fromRawSeqExclusive:qn().int().nonnegative().optional()})}),q({method:J(`providers.capabilities.get`),params:q({provider:ji,projectId:K().min(1).optional(),agentVersion:K().min(1).optional()})}),q({method:J(`agents.config.get`),params:q({provider:ji,projectId:K().min(1).optional(),agentVersion:K().min(1).optional()})}),q({method:J(`devices.list`),params:no}),q({method:J(`devices.revoke`),params:q({deviceId:K().min(1)})})]),io=Qn(`method`,[q({method:J(`auth.refresh`),result:Da.extend({relayToken:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),result:ka}),q({method:J(`gateway.update.get`),result:Ia}),q({method:J(`gateway.update.apply`),result:Ra}),q({method:J(`projects.list`),result:q({projects:Xn(Ba)})}),q({method:J(`projects.discovery.get`),result:$a}),q({method:J(`projects.discovery.refresh`),result:$a}),q({method:J(`projects.create`),result:q({project:Ba})}),q({method:J(`projects.delete`),result:q({removed:J(!0)})}),q({method:J(`workspace.directories.list`),result:Ha}),q({method:J(`sessions.list`),result:q({sessions:Xn(Ka)})}),q({method:J(`sessions.discovery.list`),result:eo}),q({method:J(`sessions.get`),result:q({session:Ka})}),q({method:J(`sessions.config.get`),result:q({session:Ka})}),q({method:J(`sessions.history.sync`),result:q({session:Ka,rawEventCount:qn().int().nonnegative()})}),q({method:J(`sessions.rawEvents.list`),result:Qn(`decision`,[q({decision:J(`delta`),reason:Y([`cursor_valid_delta`]),fromRawSeqExclusive:qn().int().nonnegative(),toRawSeq:qn().int().nonnegative(),events:Xn(Yn())}),q({decision:J(`snapshot`),reason:Y([`cursor_out_of_range`,`rewrite_detected`,`initial_snapshot`,`empty_history_snapshot`]),events:Xn(Yn())})])}),q({method:J(`providers.capabilities.get`),result:q({capabilities:Ri})}),q({method:J(`agents.config.get`),result:Ja}),q({method:J(`devices.list`),result:q({devices:Xn(qa)})}),q({method:J(`devices.revoke`),result:q({revoked:J(!0)})})]),ao=K().url(),oo=Zn([ao,J(``)]),so=K().min(1).regex(/^[A-Za-z0-9_-]+$/u),co=Y([`plaintext-relay`,`e2ee-relay`]),lo=Y([`plain`,`crypt`]);function uo(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function fo(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=uo(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function po(e){return e.trim()}var mo=Y([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),ho=qn().int().positive(),go=qn().int().min(0).max(2**53-1),_o=Y([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`counter_gap_too_large`,`key_epoch_mismatch`,`decrypt_failed`,`unsupported_version`]),vo=Y([`guest`,`account`,`self_hosted`]);q({type:J(`relay.gateway`),grantType:vo,gatewayId:K().min(1),subjectId:K().min(1),gatewayIdentityFingerprint:K().min(1).optional(),jti:K().min(1),iss:K().min(1),aud:K().min(1),iat:qn().int().nonnegative(),exp:qn().int().positive()}),q({type:J(`relay.mobile`),gatewayId:K().min(1),deviceId:K().min(1),iat:qn().int().nonnegative(),exp:qn().int().positive()});var yo=q({v:J(1),gw:K().min(1),name:K().min(1),relay:oo.optional(),direct:Xn(ao).default([]),pc:K().min(1),tsl:lo.optional(),gatewayIdentity:ga.optional()});er(fo,yo);var bo=er(fo,yo.omit({pc:!0}));er(fo,q({v:J(1),gw:K().min(1),relay:oo.optional(),direct:oo.optional(),pc:K().min(1),tsl:lo.optional(),gatewayIdentity:ga.optional()}));var xo=er(fo,q({v:J(1),gw:K().min(1),relay:oo.optional(),direct:ao,pc:K().min(1),pkf:so,tsl:lo.optional()})),So=q({name:K().min(1),relayBaseUrl:oo.optional(),directBaseUrls:Xn(ao).default([]),transportSecurityLevel:co.default(`plaintext-relay`),gatewayIdentity:ga.optional(),gatewayAccessToken:K().min(1).optional(),connectedAt:K().datetime().optional()}),Co=q({gatewayId:K().min(1),deviceId:K().min(1),connectedAt:K().datetime().optional()}),wo=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:mo,deviceId:K().min(1),deviceIdentity:ya,clientNonce:Xi}),To=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:mo,gatewayId:K().min(1),deviceId:K().min(1),clientNonce:Xi,gatewayNonce:Xi,gatewayPublicKeyFingerprint:K().min(1),gatewayEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),Eo=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),deviceIdentityFingerprint:K().min(1),clientEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),Do=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:mo,gatewayId:K().min(1),deviceId:K().min(1),keyEpoch:ho,deviceIdentityFingerprint:K().min(1),deviceIdentityStatus:va}),Oo=Y([`gateway_restarted`,`gateway_available`]),ko=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),reason:Oo,retryable:J(!0)}),Ao=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1).optional(),code:_o,message:K().min(1),retryable:Jn().optional()}),jo=ro,Mo=io,No=q({code:Y([`BAD_REQUEST`,`NOT_FOUND`,`UNAUTHORIZED`,`TIMEOUT`,`INTERNAL`,`GATEWAY_OFFLINE`,`TOKEN_INVALID`,`TOKEN_EXPIRED`,`GATEWAY_MISMATCH`,`GATEWAY_REVOKED`]),message:K().min(1),status:qn().int().min(400).max(599),details:Yn().optional()}),Po=No.extend({method:to.optional()}),Fo=Ca.extend({gatewayId:K().min(1)}),Io=Ta.extend({relayToken:K().min(1).optional()}),Lo=Ea.extend({gatewayId:K().min(1),deviceId:K().min(1).optional()}),Ro=Da.extend({gatewayId:K().min(1),relayToken:K().min(1).optional()}),zo=q({gatewayId:K().min(1),gatewayIdentity:ga,requestedAt:K().datetime()});q({grantType:J(`guest`),payload:zo,signatureAlgorithm:J(`ed25519`),signature:Xi});var Bo=q({grantType:vo,token:K().min(1),expiresInSeconds:qn().int().positive()}),Vo=Y([`rpc`,`command`,`event`,`system`]),Ho=`json-utf8`,Uo=Y([Ho]),Wo=q({version:J(1),keyEpoch:ho,counter:go,iv:Xi,ciphertext:Xi,authTag:Xi,plaintextEncoding:Uo.default(Ho)});Y([`from_mobile`,`to_mobile`,`rpc.request`,`rpc.response`,`rpc.error`]);function Go(e){return{payload:e.optional(),encryptedPayload:Wo.optional()}}var Ko=q({gatewayId:K().min(1),mobileId:K().min(1).optional(),messageType:Vo,requestId:K().min(1).optional()}),qo=Y([`fresh_connect`,`gateway_replay`]),Jo=q({deviceId:K().min(1),deliveryMode:qo,gatewayAvailableAtConnect:Jn()}),Yo=q({deviceId:K().min(1)}),Xo=Zn([ha,La,q({type:J(`command.ack`),commandType:K().min(1),commandId:K().min(1).optional(),payload:Yn().optional()}),q({type:J(`command.error`),commandType:K().min(1).optional(),commandId:K().min(1).optional(),message:K().min(1)}),q({type:J(`relay.error`),error:No})]),Zo=Qn(`type`,[Ko.extend({type:J(`gateway.hello`),messageType:J(`system`),payload:So}),Ko.extend({type:J(`mobile.hello`),messageType:J(`system`),payload:Co}),Ko.extend({type:J(`secure.client_hello`),messageType:J(`system`),payload:wo}),Ko.extend({type:J(`secure.gateway_hello`),mobileId:K().min(1),messageType:J(`system`),payload:To}),Ko.extend({type:J(`secure.client_auth`),messageType:J(`system`),payload:Eo}),Ko.extend({type:J(`secure.ready`),mobileId:K().min(1),messageType:J(`system`),payload:Do}),Ko.extend({type:J(`secure.handshake_required`),mobileId:K().min(1),messageType:J(`system`),payload:ko}),Ko.extend({type:J(`secure.error`),mobileId:K().min(1),messageType:J(`system`),payload:Ao}),Ko.extend({type:J(`mobile.connected`),messageType:J(`system`),payload:Jo}),Ko.extend({type:J(`mobile.disconnected`),messageType:J(`system`),payload:Yo}),Ko.extend({type:J(`from_mobile`),messageType:J(`command`),mobileId:K().min(1),...Go(ua)}),Ko.extend({type:J(`to_mobile`),messageType:J(`event`),mobileId:K().min(1),...Go(Xo)}),Ko.extend({type:J(`rpc.request`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Go(jo)}),Ko.extend({type:J(`rpc.response`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Go(Mo)}),Ko.extend({type:J(`rpc.error`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Go(Po)}),Ko.extend({type:J(`broadcast`),messageType:J(`event`),payload:ha}),Ko.extend({type:J(`pairing.claim.forward`),messageType:J(`system`),requestId:K().min(1),payload:Fo}),Ko.extend({type:J(`pairing.claim.result`),messageType:J(`system`),requestId:K().min(1),payload:Io}),Ko.extend({type:J(`auth.refresh.forward`),messageType:J(`system`),requestId:K().min(1),payload:Lo}),Ko.extend({type:J(`auth.refresh.result`),messageType:J(`system`),requestId:K().min(1),payload:Ro}),Ko.extend({type:J(`relay.error`),messageType:J(`system`),payload:No})]);function Qo(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 $o(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 es(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,$o(e)])}function ts(e){return JSON.stringify([`relay-secure-client-auth-v1`,$o(e),e.clientAuth.clientEphemeralPublicKey])}function ns(e){let t=ho.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 rs(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=ho.parse(e.keyEpoch??1),r=hs(vs(ns({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=hs(_s(vs(`relay-secure-hkdf-salt-v1`),r)),a=vs(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=ms(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 is(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 as(e,t){let n=go.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(xs(n),4),r}function os(e,t){let n=go.parse(t);if(e===null)return;let r=go.parse(e);if(n<=r)throw Error(`counter_replay`);if(n-r>1e3)throw Error(`counter_gap_too_large`)}function ss(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 cs(e){gs(e.session.cipherSuite);let t=e.session.outboundCounter,n=as(e.session.outboundNoncePrefix,t),r=vs(JSON.stringify(e.payload)),i=vs(ss({metadata:e.metadata,encryptedPayload:{version:1,keyEpoch:e.session.keyEpoch,counter:t}})),a=Wr(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,Wo.parse({version:1,keyEpoch:e.session.keyEpoch,counter:t,iv:us(n),ciphertext:us(o),authTag:us(s),plaintextEncoding:Ho})}function ls(e){gs(e.session.cipherSuite);let t=Wo.parse(e.encryptedPayload);if(t.keyEpoch!==e.session.keyEpoch)throw Error(`key_epoch_mismatch`);os(e.session.highestInboundCounter,t.counter);let n=as(e.session.inboundNoncePrefix,t.counter),r=ds(t.iv);if(!bs(r,n))throw Error(`decrypt_failed`);let i=vs(ss({metadata:e.metadata,encryptedPayload:t})),a=_s(ds(t.ciphertext),ds(t.authTag)),o;try{o=Wr(e.session.inboundKey,r,i).decrypt(a)}catch{throw Error(`decrypt_failed`)}e.session.highestInboundCounter=t.counter;let s;try{s=JSON.parse(ys(o))}catch{throw Error(`decrypt_failed`)}return e.parse(s)}function us(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 ds(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 fs(e){return us(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function ps(e){return ds(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function ms(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(gi(Ai,e,t.length>0?t:new Uint8Array(32),n,r))}function hs(e){return new Uint8Array(Ai(e))}function gs(e){if(e!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${e}`)}function _s(...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 vs(e){return new TextEncoder().encode(e)}function ys(e){return new TextDecoder().decode(e)}function bs(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 xs(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 Ss(e){return fs(Ai(ds(e)).subarray(0,16))}function Cs(e){if(e.type!==`native.raw`)return null;let t=ks(e.payload.raw),n=ks(t.message),r=ks(n.params),i=ks(r.msg),a=As(n.method)??As(t.method);if(!a)return null;let o=As(i.type)??``;if(!Ds(a)&&!Os(o))return null;let s=Es(t);if(!s||!s.delta)return null;let c=As(r.conversationId)??As(r.conversation_id)??``,l=As(i.thread_id)??As(i.threadId)??As(r.threadId)??As(r.thread_id)??``,u=As(i.turn_id)??As(i.turnId)??As(r.turnId)??As(r.turn_id)??``,d=As(i.item_id)??As(i.itemId)??As(r.itemId)??As(r.item_id)??``,f=As(t.source)??``,p=js(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=js(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 ws(e,t){let n=Cs(e),r=Cs(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=ks(t.payload.raw),o=Es(a)?.location??Es(ks(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Ts(a,o,i)}}:null}function Ts(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=ks(e.message),i=ks(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=ks(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Es(e){let t=ks(ks(e.message).params),n=ks(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 Ds(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Os(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function ks(e){return typeof e==`object`&&e?e:{}}function As(e){return typeof e==`string`&&e.trim()||void 0}function js(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():As(e)??``}function Ms(e){let t=Is(Ws(e)),n=[],r=new Map;for(let e of t){let t=Ls(e);if(!t){n.push(e);continue}let i=r.get(t.key);if(i===void 0){n.push(e),r.set(t.key,n.length-1);continue}let a=n[i];if(!a){n.push(e),r.set(t.key,n.length-1);continue}let o=Fs(a,e);if(!o){n.push(e),r.set(t.key,n.length-1);continue}n[i]=null,n.push(o),r.set(t.key,n.length-1)}return n.filter(e=>e!==null)}function Ns(e){return Is(Ws(e))}function Ps(e){let t=Ls(e);return t?{key:t.key,delta:t.delta,method:t.method}:null}function Fs(e,t){let n=Ls(e),r=Ls(t);if(!n||!r||n.key!==r.key)return null;if(n.envelopeType===`native.raw`&&r.envelopeType===`native.raw`)return ws(e,t);if(n.envelopeType!==`item.updated`||r.envelopeType!==`item.updated`)return null;let i=n.location===`native.raw`?null:n.location,a=(r.location===`native.raw`?null:r.location)??i;if(!a)return null;let o=qs(t.payload.raw),s=`${n.delta}${r.delta}`;return{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Us(o,a,s)}}}function Is(e){let t=new Set;for(let n of e){let e=Rs(n);e&&t.add(e)}return t.size===0?e:e.filter(e=>{let n=zs(e);return!n||!t.has(n)})}function Ls(e){let t=Cs(e);return t?{...t,envelopeType:`native.raw`,location:`native.raw`,key:`native.raw|${t.key}`}:Bs(e)}function Rs(e){if(e.type===`item.completed`){let t=qs(qs(e.payload.raw).item);return Vs(e.sessionId,t)}if(e.type!==`native.raw`)return null;let t=qs(e.payload.raw),n=qs(t.message),r=qs(n.params);if((Js(n.method)??Js(t.method))!==`item/completed`)return null;let i=qs(r.item);return Vs(e.sessionId,i)}function zs(e){if(e.type===`item.updated`){let t=qs(qs(e.payload.raw).item);return Hs(t,qs(t.payload),Js(t.original_method)??Js(t.originalMethod)??``)?Vs(e.sessionId,t):null}if(e.type!==`native.raw`)return null;let t=qs(e.payload.raw),n=qs(t.message),r=qs(n.params);if(!Gs(Js(n.method)??Js(t.method)??``))return null;let i=Js(r.itemId)??Js(r.item_id)??Js(qs(r.msg).itemId)??Js(qs(r.msg).item_id);return i?`${e.sessionId}|${i}`:null}function Bs(e){if(e.type!==`item.updated`)return null;let t=qs(e.payload.raw),n=qs(t.item),r=qs(n.payload),i=Js(n.original_method)??Js(n.originalMethod)??``,a=Js(n.type)??``,o=Hs(n,r,i);if(!o)return null;let s=Js(n.id)??Js(n.item_id)??Js(n.itemId)??Js(r.item_id)??Js(r.itemId)??``,c=Js(n.turn_id)??Js(n.turnId)??Js(r.turn_id)??Js(r.turnId)??Js(t.turn_id)??Js(t.turnId)??``,l=Ys(r.summaryIndex??r.summary_index??n.summaryIndex??n.summary_index??t.summaryIndex??t.summary_index),u=Ys(r.contentIndex??r.content_index??n.contentIndex??n.content_index??t.contentIndex??t.content_index),d=o.method??(i||`item.updated`);return{envelopeType:`item.updated`,location:o.location,key:[`item.updated`,e.sessionId,s,a,c,o.method??i,l,u].join(`|`),delta:o.delta,method:d}}function Vs(e,t){let n=Js(t.id)??Js(t.item_id)??Js(t.itemId);return n?`${e}|${n}`:null}function Hs(e,t,n){if(typeof t.delta==`string`&&t.delta.length>0)return{delta:t.delta,location:`item.payload.delta`};if(typeof t.output_delta==`string`&&t.output_delta.length>0)return{delta:t.output_delta,location:`item.payload.output_delta`};if(typeof t.outputDelta==`string`&&t.outputDelta.length>0)return{delta:t.outputDelta,location:`item.payload.outputDelta`};if(typeof e.output_delta==`string`&&e.output_delta.length>0)return{delta:e.output_delta,location:`item.output_delta`};if(typeof e.outputDelta==`string`&&e.outputDelta.length>0)return{delta:e.outputDelta,location:`item.outputDelta`};let r=Gs(n)||Ks(n),i=(Js(e.source_event_type)??Js(e.sourceEventType)??Js(t.source_event_type)??Js(t.sourceEventType)??``)===`stream_event`&&(Js(e.type)??``)===`agent_message`;return(r||i)&&typeof e.text==`string`&&e.text.length>0?{delta:e.text,location:`item.text`,method:i&&!n?`claude/stream_event/textDelta`:void 0}:null}function Us(e,t,n){let r=qs(e.item),i=qs(r.payload);return t===`item.payload.delta`?{...e,item:{...r,payload:{...i,delta:n}}}:t===`item.payload.output_delta`?{...e,item:{...r,payload:{...i,output_delta:n}}}:t===`item.payload.outputDelta`?{...e,item:{...r,payload:{...i,outputDelta:n}}}:t===`item.output_delta`?{...e,item:{...r,output_delta:n}}:t===`item.outputDelta`?{...e,item:{...r,outputDelta:n}}:{...e,item:{...r,text:n}}}function Ws(e){let t=new Map;for(let[n,r]of e.entries()){let e=t.get(r.eventId);if(e){e.event=r;continue}t.set(r.eventId,{event:r,index:n})}return[...t.values()].sort((e,t)=>{let n=e.event.ts.localeCompare(t.event.ts);return n===0?e.index-t.index:n}).map(e=>e.event)}function Gs(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Ks(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function qs(e){return typeof e==`object`&&e?e:{}}function Js(e){return typeof e==`string`&&e.trim()||void 0}function Ys(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Js(e)??``}async function Xs(e){let t=p.default.join(e,`gateway-identity.json`);await d.default.mkdir(e,{recursive:!0,mode:448});try{let e=await d.default.readFile(t,`utf8`),n=tc(JSON.parse(e));return{identity:n.identity,privateKeyPem:n.privateKeyPem,path:t,created:!1}}catch(e){if(!ec(e))throw e}let n=Zs(),r={v:1,identity:n.identity,privateKeyPem:n.privateKeyPem};return await d.default.writeFile(t,`${JSON.stringify(r,null,2)}\n`,{encoding:`utf8`,mode:384}),{...n,path:t,created:!0}}function Zs(){let{publicKey:e,privateKey:t}=(0,l.generateKeyPairSync)(`ed25519`),n=e.export({format:`der`,type:`spki`}),r=t.export({format:`pem`,type:`pkcs8`}).toString(),i=new Date().toISOString();return{identity:{algorithm:`ed25519`,publicKey:n.toString(`base64`),publicKeyFingerprint:Qs(n),keyVersion:1,createdAt:i},privateKeyPem:r}}function Qs(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`)}function $s(e,t,n){let r=(0,l.createPrivateKey)(t),i=(0,l.sign)(null,Buffer.from(Oa(n),`utf8`),r).toString(`base64`);return{algorithm:`ed25519`,gatewayPublicKeyFingerprint:e.publicKeyFingerprint,payload:n,signature:i}}function ec(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}function tc(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid stored gateway identity`);let t=e,n=ga.safeParse(t.identity);if(t.v!==1||typeof t.privateKeyPem!=`string`||!t.privateKeyPem.trim()||!n.success)throw Error(`Invalid stored gateway identity`);return{v:1,identity:n.data,privateKeyPem:t.privateKeyPem}}process.cwd(),process.env.INIT_CWD;const nc=new Set([`dev-gateway-key`]),rc=new Set([`change-me-access`,`change-me-refresh`]),ic=`https://craby-relay.ai101.pro`;function ac(){return p.default.join(f.default.homedir(),`.craby-ai`)}function oc(e){let t=e?.trim();return t?p.default.resolve(xc(t)):p.default.join(ac(),`gateway.yaml`)}async function sc(e={}){let t=oc(e.configPath);return await Dc(t)&&!e.overwrite?{configPath:t,created:!1}:(await dc(t,uc(t)),{configPath:t,created:!0})}async function cc(e={}){let t=oc(e.configPath),n=!1;e.ensureConfigFile&&(n=(await sc({configPath:t})).created);let r=await lc(t),i=e.syncGatewayIdentityConfig===!1?r:await pc(t,r,n),a=mc(t),o=i?.gateway,s=i?.server,c=s?.https,l=c?.tls,u=i?.security,d=i?.providers,f=i?.storage,p=i?.runtime,m=Cc(i),h=_c(process.env.GATEWAY_PORT,o?.port??s?.port??i?.port,8787);return{config:{gatewayId:m||hc(process.env.GATEWAY_ID,void 0,``),host:hc(process.env.GATEWAY_HOST,o?.host??s?.host??i?.host,`0.0.0.0`),port:h,httpsEnabled:gc(process.env.GATEWAY_HTTPS_ENABLED,o?.httpsEnabled??c?.enabled??i?.httpsEnabled,!1),httpsPort:_c(process.env.GATEWAY_HTTPS_PORT,o?.httpsPort??c?.port??i?.httpsPort,h),tlsCertPath:bc(process.env.GATEWAY_TLS_CERT_PATH,o?.tlsCertPath??l?.certPath??i?.tlsCertPath),tlsKeyPath:bc(process.env.GATEWAY_TLS_KEY_PATH,o?.tlsKeyPath??l?.keyPath??i?.tlsKeyPath),tlsCaPath:bc(process.env.GATEWAY_TLS_CA_PATH,o?.tlsCaPath??l?.caPath??i?.tlsCaPath),apiKey:hc(process.env.GATEWAY_API_KEY,o?.apiKey??u?.apiKey??i?.apiKey,``),workspaceRoot:yc(process.env.GATEWAY_WORKSPACE_ROOT,o?.workspaceRoot??f?.workspaceRoot??i?.workspaceRoot,a.workspaceRoot),accessSecret:hc(process.env.GATEWAY_JWT_ACCESS_SECRET,o?.accessSecret??u?.accessSecret??i?.accessSecret,``),refreshSecret:hc(process.env.GATEWAY_JWT_REFRESH_SECRET,o?.refreshSecret??u?.refreshSecret??i?.refreshSecret,``),accessTtl:hc(process.env.GATEWAY_ACCESS_TOKEN_TTL,o?.accessTtl??u?.accessTtl??i?.accessTtl,`15m`),refreshTtl:hc(process.env.GATEWAY_REFRESH_TOKEN_TTL,o?.refreshTtl??u?.refreshTtl??i?.refreshTtl,`30d`),pairingCodeTtlSeconds:_c(process.env.GATEWAY_PAIRING_CODE_TTL_SECONDS,o?.pairingCodeTtlSeconds??u?.pairingCodeTtlSeconds??i?.pairingCodeTtlSeconds,300),bootstrapPairingCodeOnStart:gc(process.env.GATEWAY_BOOTSTRAP_PAIRING_CODE_ON_START,o?.bootstrapPairingCodeOnStart??u?.bootstrapPairingCodeOnStart??i?.bootstrapPairingCodeOnStart,!0),enableNativeProviders:gc(process.env.ENABLE_NATIVE_PROVIDERS,o?.enableNativeProviders??d?.enableNativeProviders??i?.enableNativeProviders,!0),requireNativeCodex:gc(process.env.REQUIRE_NATIVE_CODEX,o?.requireNativeCodex??d?.requireNativeCodex??i?.requireNativeCodex,!1),auditLogPath:yc(process.env.GATEWAY_AUDIT_LOG_PATH,o?.auditLogPath??f?.auditLogPath??i?.auditLogPath,a.auditLogPath),gatewayLogPath:yc(process.env.GATEWAY_LOG_PATH,o?.gatewayLogPath??f?.gatewayLogPath??i?.gatewayLogPath,a.gatewayLogPath),sessionHistoryDir:yc(process.env.GATEWAY_SESSION_HISTORY_DIR,o?.sessionHistoryDir??f?.sessionHistoryDir??i?.sessionHistoryDir,a.sessionHistoryDir),projectStoreDir:yc(process.env.GATEWAY_PROJECT_STORE_DIR,o?.projectStoreDir??f?.projectStoreDir??i?.projectStoreDir,a.projectStoreDir),authStoreDir:yc(process.env.GATEWAY_AUTH_STORE_DIR,o?.authStoreDir??f?.authStoreDir??i?.authStoreDir,a.authStoreDir),relayEnabled:gc(process.env.GATEWAY_RELAY_ENABLED,o?.relayEnabled??i?.relayEnabled,!0),relayUrl:hc(process.env.GATEWAY_RELAY_URL,o?.relayUrl??i?.relayUrl,ic),relayGatewayAccessToken:hc(process.env.GATEWAY_RELAY_GATEWAY_ACCESS_TOKEN,o?.relayGatewayAccessToken??i?.relayGatewayAccessToken,``),runtimeIdleTtlMs:_c(process.env.GATEWAY_RUNTIME_IDLE_TTL_MS,o?.idleTtlMs??p?.idleTtlMs??i?.runtimeIdleTtlMs,9e5),runtimeSweepIntervalMs:vc(process.env.GATEWAY_RUNTIME_SWEEP_INTERVAL_MS,o?.sweepIntervalMs??p?.sweepIntervalMs??i?.runtimeSweepIntervalMs,6e4),runtimeMaxSessions:_c(process.env.GATEWAY_RUNTIME_MAX_SESSIONS,o?.maxSessions??p?.maxSessions??i?.runtimeMaxSessions,24),runtimeMaxCodexSessions:_c(process.env.GATEWAY_RUNTIME_MAX_CODEX_SESSIONS,o?.maxCodexSessions??p?.maxCodexSessions??i?.runtimeMaxCodexSessions,8),runtimeMaxClaudeSessions:_c(process.env.GATEWAY_RUNTIME_MAX_CLAUDE_SESSIONS,o?.maxClaudeSessions??p?.maxClaudeSessions??i?.runtimeMaxClaudeSessions,16)},configPath:t,configExists:i!==null,createdDefaultConfig:n}}async function lc(e){if(!await Dc(e))return null;let t=await d.default.readFile(e,`utf8`),n=tr.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Gateway config must be a YAML object: ${e}`);let r=n,i=r.configVersion;if(typeof i==`number`&&i!==1)throw Error(`Unsupported gateway config version ${i} in ${e}`);return r}function uc(e){let t=mc(oc(e));return{configVersion:1,gateway:{gatewayId:wc(),host:`0.0.0.0`,port:8787,httpsEnabled:!1,httpsPort:8787,apiKey:Tc(24),accessSecret:Tc(36),refreshSecret:Tc(36),accessTtl:`15m`,refreshTtl:`30d`,pairingCodeTtlSeconds:300,bootstrapPairingCodeOnStart:!0,enableNativeProviders:!0,requireNativeCodex:!1,workspaceRoot:t.workspaceRoot,auditLogPath:t.auditLogPath,gatewayLogPath:t.gatewayLogPath,sessionHistoryDir:t.sessionHistoryDir,projectStoreDir:t.projectStoreDir,authStoreDir:t.authStoreDir,relayEnabled:!0,relayUrl:ic,relayGatewayAccessToken:``,idleTtlMs:9e5,sweepIntervalMs:6e4,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16}}}async function dc(e,t){let n=p.default.dirname(e);await d.default.mkdir(n,{recursive:!0,mode:448}),await Ec(n,448);let r=tr.stringify(t,{nullStr:`null`});await d.default.writeFile(e,r,{encoding:`utf8`,mode:384}),await Ec(e,384)}function fc(e){let t=[];e.gatewayId.trim()||t.push(`GATEWAY_ID must not be empty.`);let n=e.apiKey.trim();n?(nc.has(n)&&t.push(`GATEWAY_API_KEY is using an insecure default value.`),n.length<16&&t.push(`GATEWAY_API_KEY must be at least 16 characters.`)):t.push(`GATEWAY_API_KEY must not be empty.`);let r=e.accessSecret.trim();r?(rc.has(r)&&t.push(`GATEWAY_JWT_ACCESS_SECRET is using an insecure default value.`),r.length<24&&t.push(`GATEWAY_JWT_ACCESS_SECRET must be at least 24 characters.`)):t.push(`GATEWAY_JWT_ACCESS_SECRET must not be empty.`);let i=e.refreshSecret.trim();if(i?(rc.has(i)&&t.push(`GATEWAY_JWT_REFRESH_SECRET is using an insecure default value.`),i.length<24&&t.push(`GATEWAY_JWT_REFRESH_SECRET must be at least 24 characters.`)):t.push(`GATEWAY_JWT_REFRESH_SECRET must not be empty.`),e.httpsEnabled){e.tlsCertPath||t.push(`GATEWAY_TLS_CERT_PATH is required when GATEWAY_HTTPS_ENABLED=true.`),e.tlsKeyPath||t.push(`GATEWAY_TLS_KEY_PATH is required when GATEWAY_HTTPS_ENABLED=true.`);let n=[[`GATEWAY_TLS_CERT_PATH`,e.tlsCertPath],[`GATEWAY_TLS_KEY_PATH`,e.tlsKeyPath],[`GATEWAY_TLS_CA_PATH`,e.tlsCaPath]];for(let[e,r]of n)if(r)try{(0,u.accessSync)(r,u.constants.R_OK)}catch{t.push(`${e} file is not readable: ${r}`)}}if(e.relayEnabled&&(e.relayUrl.trim()||t.push(`GATEWAY_RELAY_URL must not be empty when GATEWAY_RELAY_ENABLED=true.`)),t.length>0)throw Error(`Gateway security config check failed:\n- ${t.join(`
118
+ function nr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function rr(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}function ir(e,t,n=``){let r=nr(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function ar(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function or(e,t){ir(e,void 0,`output`);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function sr(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function cr(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function lr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ur(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const dr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;typeof Uint8Array.from([]).toHex==`function`&&Uint8Array.fromHex;function fr(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const pr=(e,t)=>{function n(n,...r){if(ir(n,void 0,`key`),!dr)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];ir(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&ir(r[1],void 0,`AAD`);let a=t(n,...r),o=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);ir(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,ir(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(ir(e),i&&e.length<i)throw Error(`"ciphertext" expected length bigger than tagLength=`+i);return o(a.decrypt.length,t),a.decrypt(e,t)}}}return Object.assign(n,e),n};function mr(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw Error(`"output" expected Uint8Array of length `+e+`, got: `+t.length);if(n&&!gr(t))throw Error(`invalid output, must be aligned`);return t}function hr(e,t,n){rr(n);let r=new Uint8Array(16),i=ur(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function gr(e){return e.byteOffset%4==0}function _r(e){return Uint8Array.from(e)}const vr=new Uint8Array(16),yr=cr(vr),br=(e,t,n,r)=>{let i=r&1;return{s3:n<<31|r>>>1,s2:t<<31|n>>>1,s1:e<<31|t>>>1,s0:e>>>1^225<<24&-(i&1)}},xr=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255|0;function Sr(e){e.reverse();let t=e[15]&1,n=0;for(let t=0;t<e.length;t++){let r=e[t];e[t]=r>>>1|n,n=(r&1)<<7}return e[0]^=-t&225,e}const Cr=e=>e>64*1024?8:e>1024?4:2;var wr=class{blockLen=16;outputLen=16;s0=0;s1=0;s2=0;s3=0;finished=!1;t;W;windowSize;constructor(e,t){ir(e,16,`key`),e=_r(e);let n=ur(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=n.getUint32(8,!1),o=n.getUint32(12,!1),s=[];for(let e=0;e<128;e++)s.push({s0:xr(r),s1:xr(i),s2:xr(a),s3:xr(o)}),{s0:r,s1:i,s2:a,s3:o}=br(r,i,a,o);let c=Cr(t||1024);if(![1,2,4,8].includes(c))throw Error(`ghash: invalid window size, expected 2, 4 or 8`);this.W=c;let l=128/c,u=this.windowSize=2**c,d=[];for(let e=0;e<l;e++)for(let t=0;t<u;t++){let n=0,r=0,i=0,a=0;for(let o=0;o<c;o++){if(!(t>>>c-o-1&1))continue;let{s0:l,s1:u,s2:d,s3:f}=s[c*e+o];n^=l,r^=u,i^=d,a^=f}d.push({s0:n,s1:r,s2:i,s3:a})}this.t=d}_updateBlock(e,t,n,r){e^=this.s0,t^=this.s1,n^=this.s2,r^=this.s3;let{W:i,t:a,windowSize:o}=this,s=0,c=0,l=0,u=0,d=(1<<i)-1,f=0;for(let p of[e,t,n,r])for(let e=0;e<4;e++){let t=p>>>8*e&255;for(let e=8/i-1;e>=0;e--){let n=t>>>i*e&d,{s0:r,s1:p,s2:m,s3:h}=a[f*o+n];s^=r,c^=p,l^=m,u^=h,f+=1}}this.s0=s,this.s1=c,this.s2=l,this.s3=u}update(e){ar(this),ir(e),e=_r(e);let t=cr(e),n=Math.floor(e.length/16),r=e.length%16;for(let e=0;e<n;e++)this._updateBlock(t[e*4+0],t[e*4+1],t[e*4+2],t[e*4+3]);return r&&(vr.set(e.subarray(n*16)),this._updateBlock(yr[0],yr[1],yr[2],yr[3]),lr(yr)),this}destroy(){let{t:e}=this;for(let t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){ar(this),or(e,this),this.finished=!0;let{s0:t,s1:n,s2:r,s3:i}=this,a=cr(e);return a[0]=t,a[1]=n,a[2]=r,a[3]=i,e}digest(){let e=new Uint8Array(16);return this.digestInto(e),this.destroy(),e}},Tr=class extends wr{constructor(e,t){ir(e);let n=Sr(_r(e));super(n,t),lr(n)}update(e){ar(this),ir(e),e=_r(e);let t=cr(e),n=e.length%16,r=Math.floor(e.length/16);for(let e=0;e<r;e++)this._updateBlock(xr(t[e*4+3]),xr(t[e*4+2]),xr(t[e*4+1]),xr(t[e*4+0]));return n&&(vr.set(e.subarray(r*16)),this._updateBlock(xr(yr[3]),xr(yr[2]),xr(yr[1]),xr(yr[0])),lr(yr)),this}digestInto(e){ar(this),or(e,this),this.finished=!0;let{s0:t,s1:n,s2:r,s3:i}=this,a=cr(e);return a[0]=t,a[1]=n,a[2]=r,a[3]=i,e.reverse()}};function Er(e){let t=(t,n)=>e(n,t.length).update(t).digest(),n=e(new Uint8Array(16),0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=(t,n)=>e(t,n),t}const Dr=Er((e,t)=>new wr(e,t));Er((e,t)=>new Tr(e,t));const Or=new Uint8Array(16);function kr(e){if(![16,24,32].includes(e.length))throw Error(`"aes key" expected Uint8Array of length 16/24/32, got length=`+e.length)}function Ar(e){return e<<1^283&-(e>>7)}function jr(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=Ar(e);return n}const Mr=(()=>{let e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Ar(n))e[t]=n;let t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return lr(e),t})(),Nr=e=>e<<24|e>>>8,Pr=e=>e<<8|e>>>24;function Fr(e,t){if(e.length!==256)throw Error(`Wrong sbox length`);let n=new Uint32Array(256).map((n,r)=>t(e[r])),r=n.map(Pr),i=r.map(Pr),a=i.map(Pr),o=new Uint32Array(256*256),s=new Uint32Array(256*256),c=new Uint16Array(256*256);for(let t=0;t<256;t++)for(let l=0;l<256;l++){let u=t*256+l;o[u]=n[t]^r[l],s[u]=i[t]^a[l],c[u]=e[t]<<8|e[l]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:i,T3:a,T01:o,T23:s}}const Ir=Fr(Mr,e=>jr(e,3)<<24|e<<16|e<<8|jr(e,2)),Lr=(()=>{let e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Ar(n))e[t]=n;return e})();function Rr(e){ir(e);let t=e.length;kr(e);let{sbox2:n}=Ir,r=[];gr(e)||r.push(e=_r(e));let i=cr(e),a=i.length,o=e=>Br(n,e,e,e,e),s=new Uint32Array(t+28);s.set(i);for(let e=a;e<s.length;e++){let t=s[e-1];e%a===0?t=o(Nr(t))^Lr[e/a-1]:a>6&&e%a===4&&(t=o(t)),s[e]=s[e-a]^t}return lr(...r),s}function zr(e,t,n,r,i,a){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|a>>>24&255]}function Br(e,t,n,r,i){return e[t&255|n&65280]|e[r>>>16&255|i>>>16&65280]<<16}function Vr(e,t,n,r,i){let{sbox2:a,T01:o,T23:s}=Ir,c=0;t^=e[c++],n^=e[c++],r^=e[c++],i^=e[c++];let l=e.length/4-2;for(let a=0;a<l;a++){let a=e[c++]^zr(o,s,t,n,r,i),l=e[c++]^zr(o,s,n,r,i,t),u=e[c++]^zr(o,s,r,i,t,n),d=e[c++]^zr(o,s,i,t,n,r);t=a,n=l,r=u,i=d}return{s0:e[c++]^Br(a,t,n,r,i),s1:e[c++]^Br(a,n,r,i,t),s2:e[c++]^Br(a,r,i,t,n),s3:e[c++]^Br(a,i,t,n,r)}}function Hr(e,t,n,r,i){ir(n,16,`nonce`),ir(r),i=mr(r.length,i);let a=n,o=cr(a),s=ur(a),c=cr(r),l=cr(i),u=t?0:12,d=r.length,f=s.getUint32(u,t),{s0:p,s1:m,s2:h,s3:g}=Vr(e,o[0],o[1],o[2],o[3]);for(let n=0;n+4<=c.length;n+=4)l[n+0]=c[n+0]^p,l[n+1]=c[n+1]^m,l[n+2]=c[n+2]^h,l[n+3]=c[n+3]^g,f=f+1>>>0,s.setUint32(u,f,t),{s0:p,s1:m,s2:h,s3:g}=Vr(e,o[0],o[1],o[2],o[3]);let _=16*Math.floor(c.length/4);if(_<d){let e=new Uint32Array([p,m,h,g]),t=sr(e);for(let e=_,n=0;e<d;e++,n++)i[e]=r[e]^t[n];lr(e)}return i}function Ur(e,t,n,r,i){let a=i?i.length:0,o=e.create(n,r.length+a);i&&o.update(i);let s=hr(8*r.length,8*a,t);o.update(r),o.update(s);let c=o.digest();return lr(s),c}const Wr=pr({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(e,t,n){if(t.length<8)throw Error(`aes/gcm: invalid nonce length`);function r(e,t,r){let i=Ur(Dr,!1,e,r,n);for(let e=0;e<t.length;e++)i[e]^=t[e];return i}function i(){let n=Rr(e),r=Or.slice(),i=Or.slice();if(Hr(n,!1,i,i,r),t.length===12)i.set(t);else{let e=Or.slice();ur(e).setBigUint64(8,BigInt(t.length*8),!1);let n=Dr.create(r).update(t).update(e);n.digestInto(i),n.destroy()}return{xk:n,authKey:r,counter:i,tagMask:Hr(n,!1,i,Or)}}return{encrypt(e){let{xk:t,authKey:n,counter:a,tagMask:o}=i(),s=new Uint8Array(e.length+16),c=[t,n,a,o];gr(e)||c.push(e=_r(e)),Hr(t,!1,a,e,s.subarray(0,e.length));let l=r(n,o,s.subarray(0,s.length-16));return c.push(l),s.set(l,e.length),lr(...c),s},decrypt(e){let{xk:t,authKey:n,counter:a,tagMask:o}=i(),s=[t,n,o,a];gr(e)||s.push(e=_r(e));let c=e.subarray(0,-16),l=e.subarray(-16),u=r(n,o,c);if(s.push(u),!fr(u,l))throw Error(`aes/gcm: invalid ghash tag`);let d=Hr(t,!1,a,c);return lr(...s),d}}});function Gr(e){return e instanceof Uint32Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint32Array`}function Kr(e,t){if(ir(t,16,`block`),!Gr(e))throw Error(`_encryptBlock accepts result of expandKeyLE`);let n=cr(t),{s0:r,s1:i,s2:a,s3:o}=Vr(e,n[0],n[1],n[2],n[3]);return n[0]=r,n[1]=i,n[2]=a,n[3]=o,t}function qr(e){let t=0;for(let n=15;n>=0;n--){let r=(e[n]&128)>>>7;e[n]=e[n]<<1|t,t=r}return t&&(e[15]^=135),e}function Jr(e,t){if(e.length!==t.length)throw Error(`xorBlock: blocks must have same length`);for(let n=0;n<e.length;n++)e[n]=e[n]^t[n];return e}var Yr=class{buffer;destroyed;k1;k2;xk;constructor(e){ir(e),kr(e),this.xk=Rr(e),this.buffer=new Uint8Array,this.destroyed=!1;let t=new Uint8Array(16);Kr(this.xk,t),this.k1=qr(t),this.k2=qr(new Uint8Array(this.k1))}update(e){let{destroyed:t,buffer:n}=this;if(t)throw Error(`CMAC instance was destroyed`);ir(e);let r=new Uint8Array(n.length+e.length);return r.set(n),r.set(e,n.length),this.buffer=r,this}digest(){if(this.destroyed)throw Error(`CMAC instance was destroyed`);let{buffer:e}=this,t=e.length,n=Math.ceil(t/16),r;n===0?(n=1,r=!1):r=t%16==0;let i=(n-1)*16,a=e.subarray(i),o;if(r)o=Jr(new Uint8Array(a),this.k1);else{let e=new Uint8Array(16);e.set(a),e[a.length]=128,o=Jr(e,this.k2)}let s=new Uint8Array(16);for(let t=0;t<n-1;t++)Jr(s,e.subarray(t*16,(t+1)*16)),Kr(this.xk,s);return Jr(s,o),Kr(this.xk,s),lr(o),s}destroy(){let{buffer:e,destroyed:t,xk:n,k1:r,k2:i}=this;t||(this.destroyed=!0,lr(e,n,r,i))}};const Xr=(e,t)=>new Yr(e).update(t).digest();Xr.create=e=>new Yr(e);function Zr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function Qr(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function $r(e,...t){if(!Zr(e))throw Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function ei(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);Qr(e.outputLen),Qr(e.blockLen)}function ti(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function ni(e,t){$r(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function ri(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ii(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ai(e,t){return e<<32-t|e>>>t}new Uint8Array(new Uint32Array([287454020]).buffer)[0],typeof Uint8Array.from([]).toHex==`function`&&Uint8Array.fromHex;function oi(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function si(e){return typeof e==`string`&&(e=oi(e)),$r(e),e}var ci=class{};function li(e){let t=t=>e().update(si(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}var ui=class extends ci{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ei(e);let n=si(t);if(this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),ri(i)}update(e){return ti(this),this.iHash.update(e),this}digestInto(e){ti(this),$r(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const di=(e,t,n)=>new ui(e,t).update(n).digest();di.create=(e,t)=>new ui(e,t);function fi(e,t,n){return ei(e),n===void 0&&(n=new Uint8Array(e.outputLen)),di(e,si(n),si(t))}const pi=Uint8Array.from([0]),mi=Uint8Array.of();function hi(e,t,n,r=32){ei(e),Qr(r);let i=e.outputLen;if(r>255*i)throw Error(`Length should be <= 255*HashLen`);let a=Math.ceil(r/i);n===void 0&&(n=mi);let o=new Uint8Array(a*i),s=di.create(e,t),c=s._cloneInto(),l=new Uint8Array(s.outputLen);for(let e=0;e<a;e++)pi[0]=e+1,c.update(e===0?mi:l).update(n).update(pi).digestInto(l),o.set(l,i*e),s._cloneInto(c);return s.destroy(),c.destroy(),ri(l,pi),o.slice(0,r)}const gi=(e,t,n,r,i)=>hi(e,fi(e,t,n),r,i);function _i(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}function vi(e,t,n){return e&t^~e&n}function yi(e,t,n){return e&t^e&n^t&n}var bi=class extends ci{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ii(this.buffer)}update(e){ti(this),e=si(e),$r(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=ii(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ti(this),ni(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,ri(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;_i(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=ii(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const xi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Si=BigInt(2**32-1),Ci=BigInt(32);function wi(e,t=!1){return t?{h:Number(e&Si),l:Number(e>>Ci&Si)}:{h:Number(e>>Ci&Si)|0,l:Number(e&Si)|0}}function Ti(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=wi(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}const Ei=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Di=new Uint32Array(64);var Oi=class extends bi{constructor(e=32){super(64,e,8,!1),this.A=xi[0]|0,this.B=xi[1]|0,this.C=xi[2]|0,this.D=xi[3]|0,this.E=xi[4]|0,this.F=xi[5]|0,this.G=xi[6]|0,this.H=xi[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)Di[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Di[e-15],n=Di[e-2],r=ai(t,7)^ai(t,18)^t>>>3;Di[e]=(ai(n,17)^ai(n,19)^n>>>10)+Di[e-7]+r+Di[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=ai(o,6)^ai(o,11)^ai(o,25),u=l+t+vi(o,s,c)+Ei[e]+Di[e]|0,d=(ai(n,2)^ai(n,13)^ai(n,22))+yi(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){ri(Di)}destroy(){this.set(0,0,0,0,0,0,0,0),ri(this.buffer)}};const ki=Ti(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e)));ki[0],ki[1];const Ai=li(()=>new Oi);var ji=Y([`codex`,`claude`]),Mi=Y([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),Ni=Y([`untrusted`,`on-failure`,`on-request`,`never`]),Pi=Y([`read-only`,`workspace-write`,`danger-full-access`]),Fi=Y([`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`]),Ii=q({reasoningEffort:Mi.optional(),approvalPolicy:Ni.optional(),sandboxMode:Pi.optional(),permissionMode:Fi.optional()}),Li=Y([`native`,`fallback`]),Ri=q({provider:ji,models:Xn(q({id:K().min(1),label:K().min(1),description:K().min(1).optional(),isDefault:Jn().optional(),supportedReasoningEfforts:Xn(Mi).optional()})),support:q({reasoningEffort:Jn(),approvalPolicy:Jn(),sandboxMode:Jn(),permissionMode:Jn().optional()}),options:q({reasoningEfforts:Xn(Mi),approvalPolicies:Xn(Ni),sandboxModes:Xn(Pi),permissionModes:Xn(Fi).optional()}),defaults:q({model:K().min(1).optional(),reasoningEffort:Mi.optional(),approvalPolicy:Ni.optional(),sandboxMode:Pi.optional(),permissionMode:Fi.optional()}),source:Li}),zi=K().trim().min(1).nullable(),Bi=Y([`default`,`plan`]),Vi=q({approvalPolicy:Ni.nullable(),sandboxMode:Pi.nullable()}),Hi=q({permissionMode:Fi.nullable()}),Ui=q({codex:Vi.optional(),claude:Hi.optional()}),Wi=$n(Yn());q({modeDefault:Bi,model:K().trim().min(1).optional(),reasoningEffort:Mi.optional(),execution:Ui.optional()});var Gi=q({mode:Bi,model:zi,reasoningEffort:Mi.nullable(),execution:Ui.optional()});q({provider:ji,model:zi,reasoningEffort:Mi.nullable(),execution:Ui.optional()});var Ki=q({model:zi,reasoningEffort:Mi.nullable(),execution:Ui.optional(),context:Wi.optional()}),qi=q({target:Qn(`type`,[q({type:J(`uncommittedChanges`)}),q({type:J(`baseBranch`),branch:K().trim().min(1)}),q({type:J(`commit`),sha:K().trim().min(1),title:K().trim().min(1).optional()}),q({type:J(`custom`),instructions:K().trim().min(1)})]),delivery:Y([`inline`,`detached`]).optional()}),Ji=q({preset:Y([`general`,`security`,`performance`,`style`]),scope:Y([`workingTree`,`staged`,`selection`,`custom`]).optional(),instructions:K().trim().min(1).optional()}),Yi=q({provider:ji,codex:qi.optional(),claude:Ji.optional()}).superRefine((e,t)=>{if(e.provider===`codex`){e.codex||t.addIssue({code:B.custom,path:[`codex`],message:`codex review config is required when provider is codex`}),e.claude&&t.addIssue({code:B.custom,path:[`claude`],message:`claude review config must be omitted when provider is codex`});return}e.claude||t.addIssue({code:B.custom,path:[`claude`],message:`claude review config is required when provider is claude`}),e.codex&&t.addIssue({code:B.custom,path:[`codex`],message:`codex review config must be omitted when provider is claude`})}),Xi=K().min(1).regex(/^[A-Za-z0-9+/=]+$/u),Zi=q({v:J(`1.0`),provider:ji,sessionId:K().min(1),projectId:K().min(1).optional(),eventId:K().min(1),ts:K().datetime(),type:K().min(1),payload:q({raw:Yn()}).passthrough()}).passthrough(),Qi=q({commandId:K().min(1).optional()}),$i=Qi.extend({type:J(`session.start`),payload:q({provider:ji,model:K().min(1).optional(),projectId:K().min(1).optional(),cwd:K().min(1).optional(),sessionConfig:Ii.optional(),sessionTurnConfig:Gi.optional(),metadata:$n(Yn()).optional()})}),ea=Qi.extend({type:J(`turn.input`),payload:q({sessionId:K().min(1),text:K().min(1),model:K().min(1).optional(),sessionConfig:Ii.optional(),mode:Bi.optional(),config:Ki.optional()})}),ta=Qi.extend({type:J(`review.start`),payload:q({sessionId:K().min(1),input:K().min(1).optional(),config:Yi,turnConfig:Ki})}),na=Qi.extend({type:J(`tool.approval.respond`),payload:q({sessionId:K().min(1),requestId:K().min(1),decision:Y([`allow`,`deny`]),reason:K().min(1).optional()})}),ra=Qi.extend({type:J(`user.input.respond`),payload:q({sessionId:K().min(1),requestId:K().min(1),answers:$n(Xn(K()))})}),ia=Qi.extend({type:J(`session.interrupt`),payload:q({sessionId:K().min(1)})}),aa=Qi.extend({type:J(`session.close`),payload:q({sessionId:K().min(1)})}),oa=Qn(`kind`,[q({kind:J(`all`)}),q({kind:J(`raw_seq`),rawSeq:qn().int().nonnegative()})]),sa=q({sessionId:K().min(1),projectId:K().min(1).optional(),cursor:oa,purpose:Y([`detail_view`,`live_follow`]).optional()}),ca=Qi.extend({type:J(`session.stream.subscribe`),payload:q({replace:Jn().default(!0),sessions:Xn(sa)})}),la=q({sessionId:K().min(1),projectId:K().min(1).optional()}),ua=Qn(`type`,[$i,ea,ta,na,ra,ia,aa,Qi.extend({type:J(`session.external.watch.set`),payload:q({replace:Jn().default(!0),sessions:Xn(la)})}),ca,Qi.extend({type:J(`fs.read`),payload:q({sessionId:K().min(1),path:K().min(1)})}),Qi.extend({type:J(`fs.diff`),payload:q({sessionId:K().min(1),path:K().min(1),baseContent:K().optional()})})]);function da(e){let t=ua.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}var fa=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`]),pa=Zi.extend({type:fa}),ma=Zi.extend({kind:J(`provider.raw`),rawSeq:qn().int().positive(),type:K().min(1)});pa.extend({kind:J(`gateway.control`).optional(),derivedFrom:K().min(1).optional()});var ha=Zn([ma,Zi.extend({kind:J(`session.stream.sync`),type:J(`session.stream.sync`),payload:q({raw:q({decision:Y([`delta`,`snapshot`]),reason:K().min(1),snapshotId:K().min(1).optional(),fromRawSeq:qn().int().nonnegative().optional(),toRawSeq:qn().int().nonnegative().optional()}).passthrough()}).passthrough()}),Zi.extend({kind:J(`session.stream.snapshot.chunk`),type:J(`session.stream.snapshot.chunk`),payload:q({raw:q({snapshotId:K().min(1),chunkIndex:qn().int().nonnegative(),totalChunks:qn().int().positive(),events:Xn(ma)}).passthrough()}).passthrough()}),Zi.extend({kind:J(`session.external.update`),type:J(`session.external.update`),payload:q({raw:q({updatedAt:K().datetime(),status:Y([`running`,`idle`]),interactionLockReason:Y([`external_turn_running`]).optional(),refreshMode:Y([`delta`,`snapshot`]),fromRawSeq:qn().int().nonnegative().optional(),toRawSeq:qn().int().nonnegative().optional(),historyUpdated:Jn(),statusChanged:Jn()}).passthrough()}).passthrough()})]),ga=q({algorithm:Y([`ed25519`]),publicKey:Xi,publicKeyFingerprint:K().min(1),keyVersion:qn().int().min(1),createdAt:K().datetime()});q({code:K().min(4),expiresAt:K().datetime()});var _a=Y([`ed25519`]),va=Y([`active`,`revoked`,`rotating`,`unknown`]),ya=q({algorithm:_a,publicKey:Xi,publicKeyFingerprint:K().min(1)}),ba=q({pairingCode:K().min(4),signedAt:K().datetime()}),xa=q({gatewayId:K().min(1),deviceId:K().min(1),mobilePublicKey:Xi,pairingContext:ba}),Sa=q({algorithm:J(`ed25519`),gatewayPublicKeyFingerprint:K().min(1),payload:xa,signature:Xi}),Ca=q({code:K().min(4),deviceName:er(e=>{if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:void 0},K().min(1).optional()),deviceIdentity:ya.optional()}),wa=q({accessToken:K().min(1),refreshToken:K().min(1),expiresInSeconds:qn().int().positive()}),Ta=wa.extend({gatewayId:K().min(1),deviceId:K().min(1),gatewayIdentity:ga.optional(),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:va.optional(),pairingConfirmation:Sa.optional()}),Ea=q({refreshToken:K().min(1)}),Da=wa.extend({deviceId:K().min(1),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:va.optional()});function Oa(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var ka=q({restarted:J(!0),closedRuntimeSessionCount:qn().int().nonnegative()}),Aa=Y([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),ja=Y([`npm`,`pnpm`,`yarn`,`unknown`]),Ma=Y([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),Na=Y([`console`,`mobile`,`system`]),Pa=q({manager:ja,installType:Ma,packageName:K().min(1),packageRoot:K().min(1).optional(),binPath:K().min(1).optional(),canSelfUpdate:Jn(),reason:K().min(1).optional()}),Fa=q({id:K().min(1),targetVersion:K().min(1),requestedBy:Na,requestedAt:K().datetime(),startedAt:K().datetime().optional()}),Ia=q({packageName:K().min(1),currentVersion:K().min(1),latestVersion:K().min(1).optional(),available:Jn(),canApply:Jn(),status:Aa,checkedAt:K().datetime().optional(),install:Pa,job:Fa.optional(),lastError:K().min(1).optional()}),La=q({type:J(`gateway.update.status`),payload:Ia}),Ra=q({started:Jn(),update:Ia}),za=er(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},K().trim().min(1)),Ba=q({id:K().min(1),title:K().min(1),path:K().min(1),createdAt:K().datetime(),updatedAt:K().datetime(),lastSessionAt:K().datetime().optional(),runningCount:qn().int().nonnegative(),idleCount:qn().int().nonnegative().optional(),totalCount:qn().int().nonnegative().optional(),endedCount:qn().int().nonnegative()}),Va=q({name:K().min(1),path:K().min(1)}),Ha=q({rootPath:K().min(1),currentPath:K().min(1),parentPath:K().min(1).nullable(),directories:Xn(Va)}),Ua=Y([`running`,`idle`]),Wa=Y([`running`,`idle`,`all`]),Ga=Y([`external_turn_running`]);Y([`delta`,`snapshot`]);var Ka=q({id:K().min(1),nativeSessionId:K().min(1).optional(),source:Y([`gateway`,`native_discovered`]).optional(),projectId:K().min(1),projectPath:K().min(1),provider:ji,providerMode:Y([`native`,`mock`]).optional(),model:K().min(1).optional(),title:K().min(1).optional(),sessionTurnConfig:Gi.optional(),sessionTurnConfigUpdatedAt:K().datetime().optional(),createdAt:K().datetime(),updatedAt:K().datetime(),status:Ua,interactionLockReason:Ga.optional(),pendingApprovals:qn().int().nonnegative(),pendingUserInputs:qn().int().nonnegative(),pendingActions:qn().int().nonnegative()}),qa=q({id:K().min(1),name:K().min(1),createdAt:K().datetime(),revokedAt:K().datetime().optional(),identityAlgorithm:Y([`ed25519`]).optional(),publicKeyFingerprint:K().min(1).optional(),identityStatus:va.optional(),lastVerifiedAt:K().datetime().optional()}),Ja=q({agent:q({provider:ji,requestedVersion:K().min(1).nullable(),resolvedVersion:K().min(1)}),capabilities:Ri}),Ya=q({scannedAt:K().datetime(),sessionCount:qn().int().nonnegative(),status:Y([`ready`,`partial`,`failed`]),error:K().min(1).optional()}),Xa=q({codex:Ya.optional(),claude:Ya.optional()}),Za=q({key:K().min(1),path:K().min(1),title:K().min(1),lastSessionAt:K().datetime().optional(),sessionCount:qn().int().nonnegative(),providerCounts:q({codex:qn().int().nonnegative(),claude:qn().int().nonnegative()}),lastDiscoveryAt:K().datetime()}),Qa=q({provider:ji,nativeSessionId:K().min(1),title:K().min(1).optional(),model:K().min(1).optional(),createdAt:K().datetime().optional(),updatedAt:K().datetime()}),$a=q({generatedAt:K().datetime(),source:Y([`cache`,`fresh_scan`]),providers:Xa,projects:Xn(Za)}),eo=q({canonicalProjectPath:K().min(1),project:Za,providers:Xa,sessions:Xn(Qa)}),to=Y([`auth.refresh`,`codex.appServer.restart`,`gateway.update.get`,`gateway.update.apply`,`projects.list`,`projects.discovery.get`,`projects.discovery.refresh`,`projects.create`,`projects.delete`,`workspace.directories.list`,`sessions.list`,`sessions.discovery.list`,`sessions.get`,`sessions.config.get`,`sessions.history.sync`,`sessions.rawEvents.list`,`providers.capabilities.get`,`agents.config.get`,`devices.list`,`devices.revoke`]),no=q({}).strict(),ro=Qn(`method`,[q({method:J(`auth.refresh`),params:Ea.extend({deviceId:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),params:q({requestedBy:Na.optional()})}),q({method:J(`gateway.update.get`),params:no}),q({method:J(`gateway.update.apply`),params:q({requestedBy:Na.optional()})}),q({method:J(`projects.list`),params:no}),q({method:J(`projects.discovery.get`),params:no}),q({method:J(`projects.discovery.refresh`),params:no}),q({method:J(`projects.create`),params:q({path:za,title:K().min(1).optional()})}),q({method:J(`projects.delete`),params:q({projectId:K().min(1)})}),q({method:J(`workspace.directories.list`),params:q({path:K().min(1).optional(),limit:qn().int().positive().max(500).optional()})}),q({method:J(`sessions.list`),params:q({projectId:K().min(1),status:Wa.optional(),syncExternal:Jn().optional()})}),q({method:J(`sessions.discovery.list`),params:q({projectPath:za})}),q({method:J(`sessions.get`),params:q({projectId:K().min(1),sessionId:K().min(1)})}),q({method:J(`sessions.config.get`),params:q({projectId:K().min(1),sessionId:K().min(1)})}),q({method:J(`sessions.history.sync`),params:q({projectId:K().min(1),sessionId:K().min(1)})}),q({method:J(`sessions.rawEvents.list`),params:q({projectId:K().min(1),sessionId:K().min(1),limit:Zn([qn().int().positive().max(2e3),J(`all`)]).optional(),fromRawSeqExclusive:qn().int().nonnegative().optional()})}),q({method:J(`providers.capabilities.get`),params:q({provider:ji,projectId:K().min(1).optional(),agentVersion:K().min(1).optional()})}),q({method:J(`agents.config.get`),params:q({provider:ji,projectId:K().min(1).optional(),agentVersion:K().min(1).optional()})}),q({method:J(`devices.list`),params:no}),q({method:J(`devices.revoke`),params:q({deviceId:K().min(1)})})]),io=Qn(`method`,[q({method:J(`auth.refresh`),result:Da.extend({relayToken:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),result:ka}),q({method:J(`gateway.update.get`),result:Ia}),q({method:J(`gateway.update.apply`),result:Ra}),q({method:J(`projects.list`),result:q({projects:Xn(Ba)})}),q({method:J(`projects.discovery.get`),result:$a}),q({method:J(`projects.discovery.refresh`),result:$a}),q({method:J(`projects.create`),result:q({project:Ba})}),q({method:J(`projects.delete`),result:q({removed:J(!0)})}),q({method:J(`workspace.directories.list`),result:Ha}),q({method:J(`sessions.list`),result:q({sessions:Xn(Ka)})}),q({method:J(`sessions.discovery.list`),result:eo}),q({method:J(`sessions.get`),result:q({session:Ka})}),q({method:J(`sessions.config.get`),result:q({session:Ka})}),q({method:J(`sessions.history.sync`),result:q({session:Ka,rawEventCount:qn().int().nonnegative()})}),q({method:J(`sessions.rawEvents.list`),result:Qn(`decision`,[q({decision:J(`delta`),reason:Y([`cursor_valid_delta`]),fromRawSeqExclusive:qn().int().nonnegative(),toRawSeq:qn().int().nonnegative(),events:Xn(Yn())}),q({decision:J(`snapshot`),reason:Y([`cursor_out_of_range`,`initial_snapshot`,`empty_history_snapshot`]),events:Xn(Yn())})])}),q({method:J(`providers.capabilities.get`),result:q({capabilities:Ri})}),q({method:J(`agents.config.get`),result:Ja}),q({method:J(`devices.list`),result:q({devices:Xn(qa)})}),q({method:J(`devices.revoke`),result:q({revoked:J(!0)})})]),ao=K().url(),oo=Zn([ao,J(``)]),so=K().min(1).regex(/^[A-Za-z0-9_-]+$/u),co=Y([`plaintext-relay`,`e2ee-relay`]),lo=Y([`plain`,`crypt`]);function uo(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function fo(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=uo(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function po(e){return e.trim()}var mo=Y([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),ho=qn().int().positive(),go=qn().int().min(0).max(2**53-1),_o=Y([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`counter_gap_too_large`,`key_epoch_mismatch`,`decrypt_failed`,`unsupported_version`]),vo=Y([`guest`,`account`,`self_hosted`]);q({type:J(`relay.gateway`),grantType:vo,gatewayId:K().min(1),subjectId:K().min(1),gatewayIdentityFingerprint:K().min(1).optional(),jti:K().min(1),iss:K().min(1),aud:K().min(1),iat:qn().int().nonnegative(),exp:qn().int().positive()}),q({type:J(`relay.mobile`),gatewayId:K().min(1),deviceId:K().min(1),iat:qn().int().nonnegative(),exp:qn().int().positive()});var yo=q({v:J(1),gw:K().min(1),name:K().min(1),relay:oo.optional(),direct:Xn(ao).default([]),pc:K().min(1),tsl:lo.optional(),gatewayIdentity:ga.optional()});er(fo,yo);var bo=er(fo,yo.omit({pc:!0}));er(fo,q({v:J(1),gw:K().min(1),relay:oo.optional(),direct:oo.optional(),pc:K().min(1),tsl:lo.optional(),gatewayIdentity:ga.optional()}));var xo=er(fo,q({v:J(1),gw:K().min(1),relay:oo.optional(),direct:ao,pc:K().min(1),pkf:so,tsl:lo.optional()})),So=q({name:K().min(1),relayBaseUrl:oo.optional(),directBaseUrls:Xn(ao).default([]),transportSecurityLevel:co.default(`plaintext-relay`),gatewayIdentity:ga.optional(),gatewayAccessToken:K().min(1).optional(),connectedAt:K().datetime().optional()}),Co=q({gatewayId:K().min(1),deviceId:K().min(1),connectedAt:K().datetime().optional()}),wo=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:mo,deviceId:K().min(1),deviceIdentity:ya,clientNonce:Xi}),To=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:mo,gatewayId:K().min(1),deviceId:K().min(1),clientNonce:Xi,gatewayNonce:Xi,gatewayPublicKeyFingerprint:K().min(1),gatewayEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),Eo=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),deviceIdentityFingerprint:K().min(1),clientEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),Do=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:mo,gatewayId:K().min(1),deviceId:K().min(1),keyEpoch:ho,deviceIdentityFingerprint:K().min(1),deviceIdentityStatus:va}),Oo=Y([`gateway_restarted`,`gateway_available`]),ko=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),reason:Oo,retryable:J(!0)}),Ao=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1).optional(),code:_o,message:K().min(1),retryable:Jn().optional()}),jo=ro,Mo=io,No=q({code:Y([`BAD_REQUEST`,`NOT_FOUND`,`UNAUTHORIZED`,`TIMEOUT`,`INTERNAL`,`GATEWAY_OFFLINE`,`TOKEN_INVALID`,`TOKEN_EXPIRED`,`GATEWAY_MISMATCH`,`GATEWAY_REVOKED`]),message:K().min(1),status:qn().int().min(400).max(599),details:Yn().optional()}),Po=No.extend({method:to.optional()}),Fo=Ca.extend({gatewayId:K().min(1)}),Io=Ta.extend({relayToken:K().min(1).optional()}),Lo=Ea.extend({gatewayId:K().min(1),deviceId:K().min(1).optional()}),Ro=Da.extend({gatewayId:K().min(1),relayToken:K().min(1).optional()}),zo=q({gatewayId:K().min(1),gatewayIdentity:ga,requestedAt:K().datetime()});q({grantType:J(`guest`),payload:zo,signatureAlgorithm:J(`ed25519`),signature:Xi});var Bo=q({grantType:vo,token:K().min(1),expiresInSeconds:qn().int().positive()}),Vo=Y([`rpc`,`command`,`event`,`system`]),Ho=`json-utf8`,Uo=Y([Ho]),Wo=q({version:J(1),keyEpoch:ho,counter:go,iv:Xi,ciphertext:Xi,authTag:Xi,plaintextEncoding:Uo.default(Ho)});Y([`from_mobile`,`to_mobile`,`rpc.request`,`rpc.response`,`rpc.error`]);function Go(e){return{payload:e.optional(),encryptedPayload:Wo.optional()}}var Ko=q({gatewayId:K().min(1),mobileId:K().min(1).optional(),messageType:Vo,requestId:K().min(1).optional()}),qo=Y([`fresh_connect`,`gateway_replay`]),Jo=q({deviceId:K().min(1),deliveryMode:qo,gatewayAvailableAtConnect:Jn()}),Yo=q({deviceId:K().min(1)}),Xo=Zn([ha,La,q({type:J(`command.ack`),commandType:K().min(1),commandId:K().min(1).optional(),payload:Yn().optional()}),q({type:J(`command.error`),commandType:K().min(1).optional(),commandId:K().min(1).optional(),message:K().min(1)}),q({type:J(`relay.error`),error:No})]),Zo=Qn(`type`,[Ko.extend({type:J(`gateway.hello`),messageType:J(`system`),payload:So}),Ko.extend({type:J(`mobile.hello`),messageType:J(`system`),payload:Co}),Ko.extend({type:J(`secure.client_hello`),messageType:J(`system`),payload:wo}),Ko.extend({type:J(`secure.gateway_hello`),mobileId:K().min(1),messageType:J(`system`),payload:To}),Ko.extend({type:J(`secure.client_auth`),messageType:J(`system`),payload:Eo}),Ko.extend({type:J(`secure.ready`),mobileId:K().min(1),messageType:J(`system`),payload:Do}),Ko.extend({type:J(`secure.handshake_required`),mobileId:K().min(1),messageType:J(`system`),payload:ko}),Ko.extend({type:J(`secure.error`),mobileId:K().min(1),messageType:J(`system`),payload:Ao}),Ko.extend({type:J(`mobile.connected`),messageType:J(`system`),payload:Jo}),Ko.extend({type:J(`mobile.disconnected`),messageType:J(`system`),payload:Yo}),Ko.extend({type:J(`from_mobile`),messageType:J(`command`),mobileId:K().min(1),...Go(ua)}),Ko.extend({type:J(`to_mobile`),messageType:J(`event`),mobileId:K().min(1),...Go(Xo)}),Ko.extend({type:J(`rpc.request`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Go(jo)}),Ko.extend({type:J(`rpc.response`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Go(Mo)}),Ko.extend({type:J(`rpc.error`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Go(Po)}),Ko.extend({type:J(`broadcast`),messageType:J(`event`),payload:ha}),Ko.extend({type:J(`pairing.claim.forward`),messageType:J(`system`),requestId:K().min(1),payload:Fo}),Ko.extend({type:J(`pairing.claim.result`),messageType:J(`system`),requestId:K().min(1),payload:Io}),Ko.extend({type:J(`auth.refresh.forward`),messageType:J(`system`),requestId:K().min(1),payload:Lo}),Ko.extend({type:J(`auth.refresh.result`),messageType:J(`system`),requestId:K().min(1),payload:Ro}),Ko.extend({type:J(`relay.error`),messageType:J(`system`),payload:No})]);function Qo(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 $o(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 es(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,$o(e)])}function ts(e){return JSON.stringify([`relay-secure-client-auth-v1`,$o(e),e.clientAuth.clientEphemeralPublicKey])}function ns(e){let t=ho.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 rs(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=ho.parse(e.keyEpoch??1),r=hs(vs(ns({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=hs(_s(vs(`relay-secure-hkdf-salt-v1`),r)),a=vs(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=ms(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 is(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 as(e,t){let n=go.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(xs(n),4),r}function os(e,t){let n=go.parse(t);if(e===null)return;let r=go.parse(e);if(n<=r)throw Error(`counter_replay`);if(n-r>1e3)throw Error(`counter_gap_too_large`)}function ss(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 cs(e){gs(e.session.cipherSuite);let t=e.session.outboundCounter,n=as(e.session.outboundNoncePrefix,t),r=vs(JSON.stringify(e.payload)),i=vs(ss({metadata:e.metadata,encryptedPayload:{version:1,keyEpoch:e.session.keyEpoch,counter:t}})),a=Wr(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,Wo.parse({version:1,keyEpoch:e.session.keyEpoch,counter:t,iv:us(n),ciphertext:us(o),authTag:us(s),plaintextEncoding:Ho})}function ls(e){gs(e.session.cipherSuite);let t=Wo.parse(e.encryptedPayload);if(t.keyEpoch!==e.session.keyEpoch)throw Error(`key_epoch_mismatch`);os(e.session.highestInboundCounter,t.counter);let n=as(e.session.inboundNoncePrefix,t.counter),r=ds(t.iv);if(!bs(r,n))throw Error(`decrypt_failed`);let i=vs(ss({metadata:e.metadata,encryptedPayload:t})),a=_s(ds(t.ciphertext),ds(t.authTag)),o;try{o=Wr(e.session.inboundKey,r,i).decrypt(a)}catch{throw Error(`decrypt_failed`)}e.session.highestInboundCounter=t.counter;let s;try{s=JSON.parse(ys(o))}catch{throw Error(`decrypt_failed`)}return e.parse(s)}function us(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 ds(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 fs(e){return us(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function ps(e){return ds(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function ms(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(gi(Ai,e,t.length>0?t:new Uint8Array(32),n,r))}function hs(e){return new Uint8Array(Ai(e))}function gs(e){if(e!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${e}`)}function _s(...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 vs(e){return new TextEncoder().encode(e)}function ys(e){return new TextDecoder().decode(e)}function bs(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 xs(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 Ss(e){return fs(Ai(ds(e)).subarray(0,16))}function Cs(e){if(e.type!==`native.raw`)return null;let t=ks(e.payload.raw),n=ks(t.message),r=ks(n.params),i=ks(r.msg),a=As(n.method)??As(t.method);if(!a)return null;let o=As(i.type)??``;if(!Ds(a)&&!Os(o))return null;let s=Es(t);if(!s||!s.delta)return null;let c=As(r.conversationId)??As(r.conversation_id)??``,l=As(i.thread_id)??As(i.threadId)??As(r.threadId)??As(r.thread_id)??``,u=As(i.turn_id)??As(i.turnId)??As(r.turnId)??As(r.turn_id)??``,d=As(i.item_id)??As(i.itemId)??As(r.itemId)??As(r.item_id)??``,f=As(t.source)??``,p=js(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=js(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 ws(e,t){let n=Cs(e),r=Cs(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=ks(t.payload.raw),o=Es(a)?.location??Es(ks(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Ts(a,o,i)}}:null}function Ts(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=ks(e.message),i=ks(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=ks(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Es(e){let t=ks(ks(e.message).params),n=ks(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 Ds(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Os(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function ks(e){return typeof e==`object`&&e?e:{}}function As(e){return typeof e==`string`&&e.trim()||void 0}function js(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():As(e)??``}function Ms(e){let t=Is(Ws(e)),n=[],r=new Map;for(let e of t){let t=Ls(e);if(!t){n.push(e);continue}let i=r.get(t.key);if(i===void 0){n.push(e),r.set(t.key,n.length-1);continue}let a=n[i];if(!a){n.push(e),r.set(t.key,n.length-1);continue}let o=Fs(a,e);if(!o){n.push(e),r.set(t.key,n.length-1);continue}n[i]=null,n.push(o),r.set(t.key,n.length-1)}return n.filter(e=>e!==null)}function Ns(e){return Is(Ws(e))}function Ps(e){let t=Ls(e);return t?{key:t.key,delta:t.delta,method:t.method}:null}function Fs(e,t){let n=Ls(e),r=Ls(t);if(!n||!r||n.key!==r.key)return null;if(n.envelopeType===`native.raw`&&r.envelopeType===`native.raw`)return ws(e,t);if(n.envelopeType!==`item.updated`||r.envelopeType!==`item.updated`)return null;let i=n.location===`native.raw`?null:n.location,a=(r.location===`native.raw`?null:r.location)??i;if(!a)return null;let o=qs(t.payload.raw),s=`${n.delta}${r.delta}`;return{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Us(o,a,s)}}}function Is(e){let t=new Set;for(let n of e){let e=Rs(n);e&&t.add(e)}return t.size===0?e:e.filter(e=>{let n=zs(e);return!n||!t.has(n)})}function Ls(e){let t=Cs(e);return t?{...t,envelopeType:`native.raw`,location:`native.raw`,key:`native.raw|${t.key}`}:Bs(e)}function Rs(e){if(e.type===`item.completed`){let t=qs(qs(e.payload.raw).item);return Vs(e.sessionId,t)}if(e.type!==`native.raw`)return null;let t=qs(e.payload.raw),n=qs(t.message),r=qs(n.params);if((Js(n.method)??Js(t.method))!==`item/completed`)return null;let i=qs(r.item);return Vs(e.sessionId,i)}function zs(e){if(e.type===`item.updated`){let t=qs(qs(e.payload.raw).item);return Hs(t,qs(t.payload),Js(t.original_method)??Js(t.originalMethod)??``)?Vs(e.sessionId,t):null}if(e.type!==`native.raw`)return null;let t=qs(e.payload.raw),n=qs(t.message),r=qs(n.params);if(!Gs(Js(n.method)??Js(t.method)??``))return null;let i=Js(r.itemId)??Js(r.item_id)??Js(qs(r.msg).itemId)??Js(qs(r.msg).item_id);return i?`${e.sessionId}|${i}`:null}function Bs(e){if(e.type!==`item.updated`)return null;let t=qs(e.payload.raw),n=qs(t.item),r=qs(n.payload),i=Js(n.original_method)??Js(n.originalMethod)??``,a=Js(n.type)??``,o=Hs(n,r,i);if(!o)return null;let s=Js(n.id)??Js(n.item_id)??Js(n.itemId)??Js(r.item_id)??Js(r.itemId)??``,c=Js(n.turn_id)??Js(n.turnId)??Js(r.turn_id)??Js(r.turnId)??Js(t.turn_id)??Js(t.turnId)??``,l=Ys(r.summaryIndex??r.summary_index??n.summaryIndex??n.summary_index??t.summaryIndex??t.summary_index),u=Ys(r.contentIndex??r.content_index??n.contentIndex??n.content_index??t.contentIndex??t.content_index),d=o.method??(i||`item.updated`);return{envelopeType:`item.updated`,location:o.location,key:[`item.updated`,e.sessionId,s,a,c,o.method??i,l,u].join(`|`),delta:o.delta,method:d}}function Vs(e,t){let n=Js(t.id)??Js(t.item_id)??Js(t.itemId);return n?`${e}|${n}`:null}function Hs(e,t,n){if(typeof t.delta==`string`&&t.delta.length>0)return{delta:t.delta,location:`item.payload.delta`};if(typeof t.output_delta==`string`&&t.output_delta.length>0)return{delta:t.output_delta,location:`item.payload.output_delta`};if(typeof t.outputDelta==`string`&&t.outputDelta.length>0)return{delta:t.outputDelta,location:`item.payload.outputDelta`};if(typeof e.output_delta==`string`&&e.output_delta.length>0)return{delta:e.output_delta,location:`item.output_delta`};if(typeof e.outputDelta==`string`&&e.outputDelta.length>0)return{delta:e.outputDelta,location:`item.outputDelta`};let r=Gs(n)||Ks(n),i=(Js(e.source_event_type)??Js(e.sourceEventType)??Js(t.source_event_type)??Js(t.sourceEventType)??``)===`stream_event`&&(Js(e.type)??``)===`agent_message`;return(r||i)&&typeof e.text==`string`&&e.text.length>0?{delta:e.text,location:`item.text`,method:i&&!n?`claude/stream_event/textDelta`:void 0}:null}function Us(e,t,n){let r=qs(e.item),i=qs(r.payload);return t===`item.payload.delta`?{...e,item:{...r,payload:{...i,delta:n}}}:t===`item.payload.output_delta`?{...e,item:{...r,payload:{...i,output_delta:n}}}:t===`item.payload.outputDelta`?{...e,item:{...r,payload:{...i,outputDelta:n}}}:t===`item.output_delta`?{...e,item:{...r,output_delta:n}}:t===`item.outputDelta`?{...e,item:{...r,outputDelta:n}}:{...e,item:{...r,text:n}}}function Ws(e){let t=new Map;for(let[n,r]of e.entries()){let e=t.get(r.eventId);if(e){e.event=r;continue}t.set(r.eventId,{event:r,index:n})}return[...t.values()].sort((e,t)=>{let n=e.event.ts.localeCompare(t.event.ts);return n===0?e.index-t.index:n}).map(e=>e.event)}function Gs(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Ks(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function qs(e){return typeof e==`object`&&e?e:{}}function Js(e){return typeof e==`string`&&e.trim()||void 0}function Ys(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Js(e)??``}async function Xs(e){let t=p.default.join(e,`gateway-identity.json`);await d.default.mkdir(e,{recursive:!0,mode:448});try{let e=await d.default.readFile(t,`utf8`),n=tc(JSON.parse(e));return{identity:n.identity,privateKeyPem:n.privateKeyPem,path:t,created:!1}}catch(e){if(!ec(e))throw e}let n=Zs(),r={v:1,identity:n.identity,privateKeyPem:n.privateKeyPem};return await d.default.writeFile(t,`${JSON.stringify(r,null,2)}\n`,{encoding:`utf8`,mode:384}),{...n,path:t,created:!0}}function Zs(){let{publicKey:e,privateKey:t}=(0,l.generateKeyPairSync)(`ed25519`),n=e.export({format:`der`,type:`spki`}),r=t.export({format:`pem`,type:`pkcs8`}).toString(),i=new Date().toISOString();return{identity:{algorithm:`ed25519`,publicKey:n.toString(`base64`),publicKeyFingerprint:Qs(n),keyVersion:1,createdAt:i},privateKeyPem:r}}function Qs(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`)}function $s(e,t,n){let r=(0,l.createPrivateKey)(t),i=(0,l.sign)(null,Buffer.from(Oa(n),`utf8`),r).toString(`base64`);return{algorithm:`ed25519`,gatewayPublicKeyFingerprint:e.publicKeyFingerprint,payload:n,signature:i}}function ec(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}function tc(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid stored gateway identity`);let t=e,n=ga.safeParse(t.identity);if(t.v!==1||typeof t.privateKeyPem!=`string`||!t.privateKeyPem.trim()||!n.success)throw Error(`Invalid stored gateway identity`);return{v:1,identity:n.data,privateKeyPem:t.privateKeyPem}}process.cwd(),process.env.INIT_CWD;const nc=new Set([`dev-gateway-key`]),rc=new Set([`change-me-access`,`change-me-refresh`]),ic=`https://craby-relay.ai101.pro`;function ac(){return p.default.join(f.default.homedir(),`.craby-ai`)}function oc(e){let t=e?.trim();return t?p.default.resolve(xc(t)):p.default.join(ac(),`gateway.yaml`)}async function sc(e={}){let t=oc(e.configPath);return await Dc(t)&&!e.overwrite?{configPath:t,created:!1}:(await dc(t,uc(t)),{configPath:t,created:!0})}async function cc(e={}){let t=oc(e.configPath),n=!1;e.ensureConfigFile&&(n=(await sc({configPath:t})).created);let r=await lc(t),i=e.syncGatewayIdentityConfig===!1?r:await pc(t,r,n),a=mc(t),o=i?.gateway,s=i?.server,c=s?.https,l=c?.tls,u=i?.security,d=i?.providers,f=i?.storage,p=i?.runtime,m=Cc(i),h=_c(process.env.GATEWAY_PORT,o?.port??s?.port??i?.port,8787);return{config:{gatewayId:m||hc(process.env.GATEWAY_ID,void 0,``),host:hc(process.env.GATEWAY_HOST,o?.host??s?.host??i?.host,`0.0.0.0`),port:h,httpsEnabled:gc(process.env.GATEWAY_HTTPS_ENABLED,o?.httpsEnabled??c?.enabled??i?.httpsEnabled,!1),httpsPort:_c(process.env.GATEWAY_HTTPS_PORT,o?.httpsPort??c?.port??i?.httpsPort,h),tlsCertPath:bc(process.env.GATEWAY_TLS_CERT_PATH,o?.tlsCertPath??l?.certPath??i?.tlsCertPath),tlsKeyPath:bc(process.env.GATEWAY_TLS_KEY_PATH,o?.tlsKeyPath??l?.keyPath??i?.tlsKeyPath),tlsCaPath:bc(process.env.GATEWAY_TLS_CA_PATH,o?.tlsCaPath??l?.caPath??i?.tlsCaPath),apiKey:hc(process.env.GATEWAY_API_KEY,o?.apiKey??u?.apiKey??i?.apiKey,``),workspaceRoot:yc(process.env.GATEWAY_WORKSPACE_ROOT,o?.workspaceRoot??f?.workspaceRoot??i?.workspaceRoot,a.workspaceRoot),accessSecret:hc(process.env.GATEWAY_JWT_ACCESS_SECRET,o?.accessSecret??u?.accessSecret??i?.accessSecret,``),refreshSecret:hc(process.env.GATEWAY_JWT_REFRESH_SECRET,o?.refreshSecret??u?.refreshSecret??i?.refreshSecret,``),accessTtl:hc(process.env.GATEWAY_ACCESS_TOKEN_TTL,o?.accessTtl??u?.accessTtl??i?.accessTtl,`15m`),refreshTtl:hc(process.env.GATEWAY_REFRESH_TOKEN_TTL,o?.refreshTtl??u?.refreshTtl??i?.refreshTtl,`30d`),pairingCodeTtlSeconds:_c(process.env.GATEWAY_PAIRING_CODE_TTL_SECONDS,o?.pairingCodeTtlSeconds??u?.pairingCodeTtlSeconds??i?.pairingCodeTtlSeconds,300),bootstrapPairingCodeOnStart:gc(process.env.GATEWAY_BOOTSTRAP_PAIRING_CODE_ON_START,o?.bootstrapPairingCodeOnStart??u?.bootstrapPairingCodeOnStart??i?.bootstrapPairingCodeOnStart,!0),enableNativeProviders:gc(process.env.ENABLE_NATIVE_PROVIDERS,o?.enableNativeProviders??d?.enableNativeProviders??i?.enableNativeProviders,!0),requireNativeCodex:gc(process.env.REQUIRE_NATIVE_CODEX,o?.requireNativeCodex??d?.requireNativeCodex??i?.requireNativeCodex,!1),auditLogPath:yc(process.env.GATEWAY_AUDIT_LOG_PATH,o?.auditLogPath??f?.auditLogPath??i?.auditLogPath,a.auditLogPath),gatewayLogPath:yc(process.env.GATEWAY_LOG_PATH,o?.gatewayLogPath??f?.gatewayLogPath??i?.gatewayLogPath,a.gatewayLogPath),sessionHistoryDir:yc(process.env.GATEWAY_SESSION_HISTORY_DIR,o?.sessionHistoryDir??f?.sessionHistoryDir??i?.sessionHistoryDir,a.sessionHistoryDir),projectStoreDir:yc(process.env.GATEWAY_PROJECT_STORE_DIR,o?.projectStoreDir??f?.projectStoreDir??i?.projectStoreDir,a.projectStoreDir),authStoreDir:yc(process.env.GATEWAY_AUTH_STORE_DIR,o?.authStoreDir??f?.authStoreDir??i?.authStoreDir,a.authStoreDir),relayEnabled:gc(process.env.GATEWAY_RELAY_ENABLED,o?.relayEnabled??i?.relayEnabled,!0),relayUrl:hc(process.env.GATEWAY_RELAY_URL,o?.relayUrl??i?.relayUrl,ic),relayGatewayAccessToken:hc(process.env.GATEWAY_RELAY_GATEWAY_ACCESS_TOKEN,o?.relayGatewayAccessToken??i?.relayGatewayAccessToken,``),runtimeIdleTtlMs:_c(process.env.GATEWAY_RUNTIME_IDLE_TTL_MS,o?.idleTtlMs??p?.idleTtlMs??i?.runtimeIdleTtlMs,9e5),runtimeSweepIntervalMs:vc(process.env.GATEWAY_RUNTIME_SWEEP_INTERVAL_MS,o?.sweepIntervalMs??p?.sweepIntervalMs??i?.runtimeSweepIntervalMs,6e4),runtimeMaxSessions:_c(process.env.GATEWAY_RUNTIME_MAX_SESSIONS,o?.maxSessions??p?.maxSessions??i?.runtimeMaxSessions,24),runtimeMaxCodexSessions:_c(process.env.GATEWAY_RUNTIME_MAX_CODEX_SESSIONS,o?.maxCodexSessions??p?.maxCodexSessions??i?.runtimeMaxCodexSessions,8),runtimeMaxClaudeSessions:_c(process.env.GATEWAY_RUNTIME_MAX_CLAUDE_SESSIONS,o?.maxClaudeSessions??p?.maxClaudeSessions??i?.runtimeMaxClaudeSessions,16)},configPath:t,configExists:i!==null,createdDefaultConfig:n}}async function lc(e){if(!await Dc(e))return null;let t=await d.default.readFile(e,`utf8`),n=tr.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Gateway config must be a YAML object: ${e}`);let r=n,i=r.configVersion;if(typeof i==`number`&&i!==1)throw Error(`Unsupported gateway config version ${i} in ${e}`);return r}function uc(e){let t=mc(oc(e));return{configVersion:1,gateway:{gatewayId:wc(),host:`0.0.0.0`,port:8787,httpsEnabled:!1,httpsPort:8787,apiKey:Tc(24),accessSecret:Tc(36),refreshSecret:Tc(36),accessTtl:`15m`,refreshTtl:`30d`,pairingCodeTtlSeconds:300,bootstrapPairingCodeOnStart:!0,enableNativeProviders:!0,requireNativeCodex:!1,workspaceRoot:t.workspaceRoot,auditLogPath:t.auditLogPath,gatewayLogPath:t.gatewayLogPath,sessionHistoryDir:t.sessionHistoryDir,projectStoreDir:t.projectStoreDir,authStoreDir:t.authStoreDir,relayEnabled:!0,relayUrl:ic,relayGatewayAccessToken:``,idleTtlMs:9e5,sweepIntervalMs:6e4,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16}}}async function dc(e,t){let n=p.default.dirname(e);await d.default.mkdir(n,{recursive:!0,mode:448}),await Ec(n,448);let r=tr.stringify(t,{nullStr:`null`});await d.default.writeFile(e,r,{encoding:`utf8`,mode:384}),await Ec(e,384)}function fc(e){let t=[];e.gatewayId.trim()||t.push(`GATEWAY_ID must not be empty.`);let n=e.apiKey.trim();n?(nc.has(n)&&t.push(`GATEWAY_API_KEY is using an insecure default value.`),n.length<16&&t.push(`GATEWAY_API_KEY must be at least 16 characters.`)):t.push(`GATEWAY_API_KEY must not be empty.`);let r=e.accessSecret.trim();r?(rc.has(r)&&t.push(`GATEWAY_JWT_ACCESS_SECRET is using an insecure default value.`),r.length<24&&t.push(`GATEWAY_JWT_ACCESS_SECRET must be at least 24 characters.`)):t.push(`GATEWAY_JWT_ACCESS_SECRET must not be empty.`);let i=e.refreshSecret.trim();if(i?(rc.has(i)&&t.push(`GATEWAY_JWT_REFRESH_SECRET is using an insecure default value.`),i.length<24&&t.push(`GATEWAY_JWT_REFRESH_SECRET must be at least 24 characters.`)):t.push(`GATEWAY_JWT_REFRESH_SECRET must not be empty.`),e.httpsEnabled){e.tlsCertPath||t.push(`GATEWAY_TLS_CERT_PATH is required when GATEWAY_HTTPS_ENABLED=true.`),e.tlsKeyPath||t.push(`GATEWAY_TLS_KEY_PATH is required when GATEWAY_HTTPS_ENABLED=true.`);let n=[[`GATEWAY_TLS_CERT_PATH`,e.tlsCertPath],[`GATEWAY_TLS_KEY_PATH`,e.tlsKeyPath],[`GATEWAY_TLS_CA_PATH`,e.tlsCaPath]];for(let[e,r]of n)if(r)try{(0,u.accessSync)(r,u.constants.R_OK)}catch{t.push(`${e} file is not readable: ${r}`)}}if(e.relayEnabled&&(e.relayUrl.trim()||t.push(`GATEWAY_RELAY_URL must not be empty when GATEWAY_RELAY_ENABLED=true.`)),t.length>0)throw Error(`Gateway security config check failed:\n- ${t.join(`
119
119
  - `)}`)}async function pc(e,t,n){if(!t)return null;let r=mc(e),i=t.gateway,a=t.storage,o=yc(process.env.GATEWAY_AUTH_STORE_DIR,i?.authStoreDir??a?.authStoreDir??t.authStoreDir,r.authStoreDir),s=Cc(t),c=process.env.GATEWAY_ID?.trim()??``,l=await Xs(o),u=s;if(!u)u=c||wc();else if(l.created&&!n)if(c){if(c===s)throw Error(`GATEWAY_ID must change when gateway identity is recreated; rotate or remove the override`);u=c}else u=wc();if(u===s)return t;let d={...t,gateway:{...t.gateway??{},gatewayId:u}};return await dc(e,d),d}function mc(e){let t=p.default.dirname(e);return{homeDir:t,workspaceRoot:f.default.homedir(),auditLogPath:p.default.join(t,`logs`,`audit.log`),gatewayLogPath:p.default.join(t,`logs`,`gateway.log`),sessionHistoryDir:p.default.join(t,`logs`,`sessions-v2`),projectStoreDir:p.default.join(t,`logs`,`projects`),authStoreDir:p.default.join(t,`logs`,`auth`)}}function hc(e,t,n){return e?.trim()||t?.trim()||n}function gc(e,t,n){let r=e?.trim().toLowerCase();return r===`true`||r===`1`?!0:r===`false`||r===`0`?!1:typeof t==`boolean`?t:n}function _c(e,t,n){let r=Sc(e);return r===null?Number.isFinite(t)?Math.max(1,Math.trunc(t)):n:Math.max(1,r)}function vc(e,t,n){let r=Sc(e);return r===null?Number.isFinite(t)?Math.max(0,Math.trunc(t)):n:Math.max(0,r)}function yc(e,t,n){return bc(e,t)??p.default.resolve(xc(n))}function bc(e,t){let n=e?.trim()||t?.trim();return n?p.default.resolve(xc(n)):null}function xc(e){return e===`~`?f.default.homedir():e.startsWith(`~/`)||e.startsWith(`~\\`)?p.default.join(f.default.homedir(),e.slice(2)):e}function Sc(e){if(typeof e!=`string`||!e.trim())return null;let t=Number(e);return Number.isFinite(t)?Math.trunc(t):null}function Cc(e){return e?hc(void 0,e.gateway?.gatewayId??e.gateway?.relayGatewayId??e.gatewayId??e.relayGatewayId,``):``}function wc(){return`gw-${(0,l.randomBytes)(6).toString(`hex`)}`}function Tc(e){return(0,l.randomBytes)(e).toString(`hex`)}async function Ec(e,t){try{await d.default.chmod(e,t)}catch{}}async function Dc(e){try{return await d.default.access(e,u.constants.F_OK),!0}catch{return!1}}const Oc=(0,h.createRequire)(require(`url`).pathToFileURL(__filename).href),kc=(0,g.fileURLToPath)(require(`url`).pathToFileURL(__filename).href);async function Ac(e,t=Nc){let n=P.providerRequirements.map(e=>Pc(e,t));return{gatewayVersion:P.version,configPath:e.configPath,configExists:e.configExists,configSummary:e.config?{httpsEnabled:e.config.httpsEnabled,port:e.config.httpsEnabled?e.config.httpsPort:e.config.port,enableNativeProviders:e.config.enableNativeProviders,workspaceRoot:e.config.workspaceRoot}:null,checks:n}}function jc(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)}function Mc(e){let t=[`[gateway] version ${e.gatewayVersion}`,`[gateway] config ${e.configExists?`found`:`missing`}: ${e.configPath}`];e.configSummary&&(t.push(`[gateway] runtime https=${String(e.configSummary.httpsEnabled)} port=${e.configSummary.port} nativeProviders=${String(e.configSummary.enableNativeProviders)}`),t.push(`[gateway] workspaceRoot ${e.configSummary.workspaceRoot}`));for(let n of e.checks){let e=[`[doctor] ${n.id}`];n.minimumVersion&&e.push(`required>=${n.minimumVersion}`),n.dependencyName&&n.bundledStatus&&e.push(`bundled=${Lc(n.bundledDependencyVersion)}(${n.bundledStatus})`),e.push(`system=${Lc(n.systemToolVersion)}(${n.systemStatus})`),t.push(e.join(` `));for(let e of n.notes)t.push(`[doctor] ${n.id} note: ${e}`)}return t.join(`
120
120
  `)}const Nc={readInstalledPackageVersion:Fc,readSystemToolVersion:Ic};function Pc(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&&!j(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&&!j(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 Fc(e){try{let t=Rc(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 Ic(e,t){try{let n=(0,m.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?O(r):null}catch{return null}}function Lc(e){return e??`missing`}function Rc(e){try{return Oc.resolve(`${e}/package.json`)}catch{}try{let t=Oc.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(kc),process.cwd()]){let n=zc(t,e);if(n)return n}return null}function zc(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 Bc(e,t){let n=[e];return t.configPath&&n.push(`--config`,t.configPath),t.logToConsole&&n.push(`--log`),n}function Vc(e,t,n){let r=Bc(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 Hc(e,t,n,r){if(!e.binPath)throw Error(`gateway launch command is unavailable`);return{command:e.binPath,args:Bc(t,n),cwd:r}}var Uc=o(((e,t)=>{t.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}})),Wc=o(((e,t)=>{var n=Uc();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})),Gc=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})),Kc=o(((e,t)=>{var n=Gc();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})),qc=o(((e,t)=>{t.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}})),Jc=o(((e,t)=>{var n=Uc(),r=Kc(),i=Gc(),a=qc(),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})),Yc=o(((e,t)=>{t.exports={L:1,M:0,Q:3,H:2}})),Xc=o(((e,t)=>{var n=Yc();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})),Zc=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})),Qc=c(o(((e,t)=>{var n=Wc(),r=Jc(),i=Kc(),a=Xc(),o=Zc();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),$c=c(Yc(),1);const el={renderQr:il};function tl(e){return xo.parse({v:1,gw:po(e.gatewayId),relay:e.relayBaseUrl,direct:e.bootstrapDirectBaseUrl,pc:e.pairingCode,pkf:Ss(e.gatewayIdentityPublicKey)})}function nl(e){return bo.parse({v:1,gw:po(e.gatewayId),name:e.machineName,relay:e.relayBaseUrl,direct:e.directBaseUrls,gatewayIdentity:e.gatewayIdentity})}function rl(e,t=el){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(`
121
121
  `)}function il(e){let t=new Qc.default(-1,$c.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=al(r,n,e,i,!0,!1),o=al(r,n,e+1,i,!0,!1);t+=ol(a,o)}i.push(t)}return i.join(`
@@ -458,30 +458,30 @@ const asInteger = serializer.asInteger.bind(serializer)
458
458
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
459
459
  var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Zh=o((e=>{var t=Xh().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Qh=o(((e,t)=>{var n=Uh().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),$h=o(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Qh(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),eg=o(((e,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=Uh().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),tg=o(((e,t)=>{t.exports=E;var n;E.ReadableState=T,require(`events`).EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Bh(),a=require(`buffer`).Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=require(`util`),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Vh(),f=Hh(),p=Wh().getHighWaterMark,m=Uh().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;Kh()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=Yh(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=Zh().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Yh(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0)if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1);else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=Zh().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?se(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&se(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?L(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&se(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,te(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(te,e))}function te(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,oe(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(ne,e,t))}function ne(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=re(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&le(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function re(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,oe(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=le(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(ie,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(F,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(F,this),t};function F(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function ie(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,I(this,e)),e.paused=!1,this};function I(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ae,e,t))}function ae(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),oe(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function oe(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=$h()),b(this)}),Object.defineProperty(E.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=L,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function L(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function se(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ce,t,e))}function ce(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=eg()),x(E,e,t)});function le(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),ng=o(((e,t)=>{t.exports=l;var n=Uh().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=Yh();Kh()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),rg=o(((e,t)=>{t.exports=r;var n=ng();Kh()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),ig=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Uh().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Qh()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a(`streams`);var i,o=t.map(function(e,n){var a=n<t.length-1;return l(e,a,n>0,function(e){i||=e,e&&o.forEach(u),!a&&(o.forEach(u),r(i))})});return t.reduce(d)}t.exports=p})),ag=o(((e,t)=>{var n=require(`stream`);process.env.READABLE_STREAM===`disable`&&n?(t.exports=n.Readable,Object.assign(t.exports,n),t.exports.Stream=n):(e=t.exports=tg(),e.Stream=n||e,e.Readable=e,e.Writable=Jh(),e.Duplex=Yh(),e.Transform=ng(),e.PassThrough=rg(),e.finished=Qh(),e.pipeline=ig())})),og=o(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),sg=o(((e,t)=>{var n=og();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),cg=o(((e,t)=>{var n=sg(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),lg=o(((e,t)=>{t.exports=n;function n(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState==`number`?e.read():e.read(r(t)):null}function r(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}})),ug=o(((e,t)=>{var n=ag(),r=cg(),i=Kh(),a=lg(),o=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),s=function(e,t){e._corked?e.once(`uncork`,t):t()},c=function(e,t){e._autoDestroy&&e.destroy(t)},l=function(e,t){return function(n){n?c(e,n.message===`premature close`?null:n):t&&!e._ended&&e.end()}},u=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t()},d=function(){},f=function(e){return new n.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},p=function(e,t,r){if(!(this instanceof p))return new p(e,t,r);n.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==!1,this._forwardDestroy=!r||r.destroy!==!1,this._forwardEnd=!r||r.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};i(p,n.Duplex),p.obj=function(e,t,n){return n||={},n.objectMode=!0,n.highWaterMark=16,new p(e,t,n)},p.prototype.cork=function(){++this._corked===1&&this.emit(`cork`)},p.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit(`uncork`)},p.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.end();return}var t=this,n=r(e,{writable:!0,readable:!1},l(this,this._forwardEnd)),i=function(){var e=t._ondrain;t._ondrain=null,e&&e()};this._unwrite&&process.nextTick(i),this._writable=e,this._writable.on(`drain`,i),this._unwrite=function(){t._writable.removeListener(`drain`,i),n()},this.uncork()},p.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.push(null),this.resume();return}var t=this,n=r(e,{writable:!1,readable:!0},l(this)),i=function(){t._forward()},a=function(){t.push(null)};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on(`readable`,i),this._readable2.on(`end`,a),this._unread=function(){t._readable2.removeListener(`readable`,i),t._readable2.removeListener(`end`,a),n()},this._forward()},p.prototype._read=function(){this._drained=!0,this._forward()},p.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var e;this._drained&&(e=a(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},p.prototype.destroy=function(e,t){if(t||=d,this.destroyed)return t(null);this.destroyed=!0;var n=this;process.nextTick(function(){n._destroy(e),t(null)})},p.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit(`error`,e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit(`close`)},p.prototype._write=function(e,t,n){if(!this.destroyed){if(this._corked)return s(this,this._write.bind(this,e,t,n));if(e===o)return this._finish(n);if(!this._writable)return n();this._writable.write(e)===!1?this._ondrain=n:this.destroyed||n()}},p.prototype._finish=function(e){var t=this;this.emit(`preend`),s(this,function(){u(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===!1&&(t._writableState.prefinished=!0),t.emit(`prefinish`),s(t,e)})})},p.prototype.end=function(e,t,r){return typeof e==`function`?this.end(null,null,e):typeof t==`function`?this.end(e,null,t):(this._ended=!0,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(o),n.Writable.prototype.end.call(this,r))},t.exports=p})),dg=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=_h(),o=zh(),s=ug(),c=Symbol(`ws-socket`),l=Symbol(`ws-head`),u=/HTTP\/1.1 (\d+)/u;function d(e,t,a){e.decorateRequest(`ws`,null);let d=x;if(t.errorHandler){if(typeof t.errorHandler!=`function`)return a(Error(`invalid errorHandler function`));d=t.errorHandler}let f=y;if(t?.preClose){if(typeof t.preClose!=`function`)return a(Error(`invalid preClose function`));f=t.preClose}if(t.options?.noServer)return a(Error(`fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly.`));let p=Object.assign({noServer:!0},t.options);p.path&&e.log.warn(`ws server path option shouldn't be provided, use a route instead`);let m=p.server||e.server;delete p.server;let h=new o.Server(p);e.decorate(`websocketServer`,h);async function g(e=`/`,t={},n={}){let a=new r,d=new r,f=new s(a,d),p=new s(d,a),h=new o(null,void 0,{isServer:!1}),g=Buffer.from([]),_,v,y=new Promise((e,t)=>{_=e,v=t});typeof n.onInit==`function`&&n.onInit(h),h.on(`open`,()=>{typeof n.onOpen==`function`&&n.onOpen(h),p.removeListener(`data`,b),_(h)});let b=e=>{if(e.toString().includes(`HTTP/1.1 101 Switching Protocols`))h._isServer=!1,h.setSocket(p,g,{maxPayload:0});else{p.removeListener(`data`,b);let t=Number(u.exec(e.toString())[1]);v(Error(`Unexpected server response: `+t))}};p.on(`data`,b);let x={...t,method:`GET`,headers:{...t.headers,connection:`upgrade`,upgrade:`websocket`,"sec-websocket-version":13,"sec-websocket-key":i(16).toString(`base64`)},httpVersion:`1.1`,url:e,[c]:f,[l]:g};return m.emit(`upgrade`,x,x[c],x[l]),y}e.decorate(`injectWS`,g);function _(t,r,i){t[c]=r,t[l]=i;let a=new n(t);try{a.assignSocket(r),e.routing(t,a)}catch(t){e.log.warn({err:t},`websocket upgrade failed`)}}m.on(`upgrade`,_);let v=(t,n)=>{h.handleUpgrade(t,t[c],t[l],r=>{h.emit(`connection`,r,t),r.on(`error`,t=>{e.log.error(t)}),n(r)})};e.addHook(`onRequest`,(e,t,n)=>{e.raw[c]?e.ws=!0:e.ws=!1,n()}),e.addHook(`onResponse`,(e,t,n)=>{e.ws&&e.raw[c].destroy(),n()}),e.addHook(`onRoute`,e=>{let t=!1,n=e.wsHandler,r=e.handler;if(e.websocket||e.wsHandler){if(e.method===`HEAD`)return;if(e.method!==`GET`)throw Error(`websocket handler can only be declared in GET method`);if(t=!0,e.websocket&&(e.schema||={},e.schema.hide=!0,n=e.handler,r=function(e,t){t.code(404).send()}),typeof n!=`function`)throw TypeError(`invalid wsHandler function`)}e.handler=function(e,i){if(e.raw[c])i.hijack(),v(e.raw,r=>{let a;try{a=t?n.call(this,r,e):b.call(this,r,e)}catch(t){return d.call(this,t,r,e,i)}a&&typeof a.catch==`function`&&a.catch(t=>d.call(this,t,r,e,i))});else return r.call(this,e,i)}}),e.addHook(`preClose`,f);function y(t){let n=this.websocketServer;if(n.clients)for(let e of n.clients)e.close();e.server.removeListener(`upgrade`,_),n.close(t),t()}function b(e,t){this.log.info({path:t.url},`closed incoming websocket connection for path with no websocket handler`),e.close()}function x(e,t,n){n.log.error(e),t.terminate()}a()}t.exports=a(d,{fastify:`5.x`,name:`@fastify/websocket`}),t.exports.default=d,t.exports.fastifyWebsocket=d}))(),1),fg=c(Th(),1),pg=c(mh(),1);let mg,hg;function gg(e){!mg||mg.length<e?(mg=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(mg),hg=0):hg+e>mg.length&&(l.webcrypto.getRandomValues(mg),hg=0),hg+=e}function _g(e=21){gg(e|=0);let t=``;for(let n=hg-e;n<hg;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[mg[n]&63];return t}var vg=o(((e,t)=>{var n=Xh().Buffer,r=require(`stream`),i=require(`util`);function a(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if(typeof e.pipe==`function`)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||typeof e==`object`)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit(`end`,e),this.readable=!1,this.emit(`close`)}.bind(this)),this;throw TypeError(`Unexpected data type (`+typeof e+`)`)}i.inherits(a,r),a.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit(`data`,e)},a.prototype.end=function(e){e&&this.write(e),this.emit(`end`,e),this.emit(`close`),this.writable=!1,this.readable=!1},t.exports=a})),yg=o(((e,t)=>{function n(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:n(256),ES384:n(384),ES512:n(521)};function i(e){var t=r[e];if(t)return t;throw Error(`Unknown algorithm "`+e+`"`)}t.exports=i})),bg=o(((e,t)=>{var n=Xh().Buffer,r=yg(),i=128,a=0,o=32,s=16,c=2,l=s|o|a<<6,u=c|a<<6;function d(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function f(e){if(n.isBuffer(e))return e;if(typeof e==`string`)return n.from(e,`base64`);throw TypeError(`ECDSA signature must be a Base64 string or a Buffer`)}function p(e,t){e=f(e);var a=r(t),o=a+1,s=e.length,c=0;if(e[c++]!==l)throw Error(`Could not find expected "seq"`);var p=e[c++];if(p===(i|1)&&(p=e[c++]),s-c<p)throw Error(`"seq" specified length of "`+p+`", only "`+(s-c)+`" remaining`);if(e[c++]!==u)throw Error(`Could not find expected "int" for "r"`);var m=e[c++];if(s-c-2<m)throw Error(`"r" specified length of "`+m+`", only "`+(s-c-2)+`" available`);if(o<m)throw Error(`"r" specified length of "`+m+`", max of "`+o+`" is acceptable`);var h=c;if(c+=m,e[c++]!==u)throw Error(`Could not find expected "int" for "s"`);var g=e[c++];if(s-c!==g)throw Error(`"s" specified length of "`+g+`", expected "`+(s-c)+`"`);if(o<g)throw Error(`"s" specified length of "`+g+`", max of "`+o+`" is acceptable`);var _=c;if(c+=g,c!==s)throw Error(`Expected to consume entire buffer, but "`+(s-c)+`" bytes remain`);var v=a-m,y=a-g,b=n.allocUnsafe(v+m+y+g);for(c=0;c<v;++c)b[c]=0;e.copy(b,c,h+Math.max(-v,0),h+m),c=a;for(var x=c;c<x+y;++c)b[c]=0;return e.copy(b,c,_+Math.max(-y,0),_+g),b=b.toString(`base64`),b=d(b),b}function m(e,t,n){for(var r=0;t+r<n&&e[t+r]===0;)++r;return e[t+r]>=i&&--r,r}function h(e,t){e=f(e);var a=r(t),o=e.length;if(o!==a*2)throw TypeError(`"`+t+`" signatures must be "`+a*2+`" bytes, saw "`+o+`"`);var s=m(e,0,a),c=m(e,a,e.length),d=a-s,p=a-c,h=2+d+1+1+p,g=h<i,_=n.allocUnsafe((g?2:3)+h),v=0;return _[v++]=l,g?_[v++]=h:(_[v++]=i|1,_[v++]=h&255),_[v++]=u,_[v++]=d,s<0?(_[v++]=0,v+=e.copy(_,v,0,a)):v+=e.copy(_,v,s,a),_[v++]=u,_[v++]=p,c<0?(_[v++]=0,e.copy(_,v,a)):e.copy(_,v,a+c),_}t.exports={derToJose:p,joseToDer:h}})),xg=o(((e,t)=>{var n=require(`buffer`).Buffer,r=require(`buffer`).SlowBuffer;t.exports=i;function i(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}i.install=function(){n.prototype.equal=r.prototype.equal=function(e){return i(this,e)}};var a=n.prototype.equal,o=r.prototype.equal;i.restore=function(){n.prototype.equal=a,r.prototype.equal=o}})),Sg=o(((e,t)=>{var n=Xh().Buffer,r=require(`crypto`),i=bg(),a=require(`util`),o=`"%s" is not a valid algorithm.
460
460
  Supported algorithms are:
461
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=xg(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),Cg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),wg=o(((e,t)=>{var n=Xh().Buffer,r=vg(),i=Sg(),a=require(`stream`),o=Cg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),Tg=o(((e,t)=>{var n=Xh().Buffer,r=vg(),i=Sg(),a=require(`stream`),o=Cg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),Eg=o((e=>{var t=wg(),n=Tg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),Dg=o(((e,t)=>{var n=Eg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),Og=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),kg=o(((e,t)=>{var n=Og(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),Ag=o(((e,t)=>{var n=Og(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),jg=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Mg=o(((e,t)=>{var n=jg();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),Ng=o(((e,t)=>{t.exports=Sm().satisfies(process.version,`>=15.7.0`)})),Pg=o(((e,t)=>{t.exports=Sm().satisfies(process.version,`>=16.9.0`)})),Fg=o(((e,t)=>{let n=Ng(),r=Pg(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),Ig=o(((e,t)=>{t.exports=Sm().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Lg=o(((e,t)=>{let n=Og(),r=kg(),i=Ag(),a=Dg(),o=Mg(),s=Fg(),c=Ig(),l=Eg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Rg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:de(e),n=n&&!r?ce(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),oe(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return re(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&ie(e.length)&&!F(e)}function re(e){return ae(e)&&ne(e)}function F(e){var t=I(e)?E.call(e):``;return t==s||t==c}function ie(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function I(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ae(e){return!!e&&typeof e==`object`}function oe(e){return typeof e==`string`||!P(e)&&ae(e)&&E.call(e)==l}function L(e){return typeof e==`symbol`||ae(e)&&E.call(e)==u}function se(e){return e?(e=le(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function ce(e){var t=se(e),n=t%1;return t===t?n?t-n:t:0}function le(e){if(typeof e==`number`)return e;if(L(e))return a;if(I(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=I(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function ue(e){return ne(e)?A(e):j(e)}function de(e){return e?S(e,ue(e)):[]}t.exports=N})),zg=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),Bg=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),Vg=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),Hg=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),Ug=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Wg=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Gg=o(((e,t)=>{let n=Mg(),r=Ig(),i=Fg(),a=Eg(),o=Rg(),s=zg(),c=Bg(),l=Vg(),u=Hg(),d=Ug(),f=Wg(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Kg=c(o(((e,t)=>{t.exports={decode:Dg(),verify:Lg(),sign:Gg(),JsonWebTokenError:Og(),NotBeforeError:kg(),TokenExpiredError:Ag()}}))(),1),qg=c(dd(),1),Jg=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Yg(e){return e instanceof Jg}function Xg(){return new Jg({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function Zg(){return new Jg({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Qg(){return new Jg({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function $g(e=`Device revoked`){return new Jg({code:`DEVICE_REVOKED`,status:401,message:e})}function e_(){return new Jg({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function t_(e){return new Jg({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function n_(e,t){return new Jg({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function r_(e){return new Jg({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function i_(e,t,n){return new Jg({code:`SESSION_TURN_CONFLICT`,status:409,message:`Session ${e} cannot accept input: ${t}`,details:n})}function a_(e){return new Jg({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function o_(e){return new Jg({code:`CODEX_APP_SERVER_RESTART_CONFLICT`,status:409,message:`Codex app-server restart requires idle runtime, found ${e} running session${e===1?``:`s`}`})}function s_(e){return new Jg({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function c_(){return new Jg({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function l_(){return new Jg({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function u_(e){return new Jg({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function d_(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var f_=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=p_(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw Xg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),Zg();this.pairingCodes.delete(e);let i=`dev_${_g(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...o,gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Kg.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n||n.revoked)throw Qg();let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw $g();let i=new Date().toISOString();n.revoked=!0,n.revokedAt=i,this.refreshTokens.set(t.jti,n);let a=this.issueTokenPair(t.sub);return await this.persistState(),{...a,deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Kg.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw $g(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw $g(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw c_();if(!h_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw l_();if(n.identityStatus!==`active`)throw u_(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}inspectRefreshToken(e){let t=Kg.default.decode(e),n=t&&typeof t==`object`?t:null,r=typeof n?.jti==`string`?n.jti:void 0,i=typeof n?.sub==`string`?n.sub:void 0,a=r?this.refreshTokens.get(r):void 0,o=i||a?.deviceId?[...this.refreshTokens.values()].filter(e=>e.deviceId===(i??a?.deviceId)&&!e.revoked).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]:void 0;return{claimDeviceId:i,claimExpAt:typeof n?.exp==`number`?new Date(n.exp*1e3).toISOString():void 0,claimIssuedAt:typeof n?.iat==`number`?new Date(n.iat*1e3).toISOString():void 0,claimJti:r,claimType:typeof n?.type==`string`?n.type:void 0,latestActiveTokenCreatedAt:o?.createdAt,latestActiveTokenJti:o?.jti,tokenRecordCreatedAt:a?.createdAt,tokenRecordDeviceId:a?.deviceId,tokenRecordRevokedAt:a?.revokedAt,tokenRecordState:a?a.revoked?`revoked`:`active`:`missing`}}issueTokenPair(e){let t=Kg.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${_g(14)}`,r=Kg.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Kg.default.decode(r);this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0});let a=Kg.default.decode(t);return{accessToken:t,refreshToken:r,expiresInSeconds:a.exp-a.iat}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await __(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await __(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await __(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:m_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return g_(this.pairingCodes,e),g_(this.devices,t),g_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function p_(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function m_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function h_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function g_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function __(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var v_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function y_(){}y_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(b_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(b_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function b_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new y_;function x_(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function S_(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function C_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function w_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function T_(e,t){return C_(e,t,``)}function E_(e,t){return w_(e,t,``)}function D_(e,t){return t.slice(0,O_(e,t))}function O_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var k_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,A_=RegExp(`[${k_}]+|\\s+|[^${k_}]`,`ug`),j_=new y_;j_.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},j_.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(A_)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},j_.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},j_.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&M_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&M_(n,i,r,null),e};function M_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=x_(i,o);e.value=w_(e.value,o,c),t.value=T_(t.value,c),n.value=T_(n.value,c)}if(r){var l=S_(a,s);r.value=C_(r.value,s,l),t.value=E_(t.value,l),n.value=E_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=x_(u,d);t.value=T_(t.value,p);var m=S_(T_(u,p),f);t.value=E_(t.value,m),r.value=C_(r.value,u,m),e.value=w_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=D_(g,h);t.value=E_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=D_(v,y);t.value=T_(t.value,b)}}var N_=new y_;N_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${k_}]+|[^\\S\\n\\r]+|[^${k_}]`,`ug`);return e.match(t)||[]};var P_=new y_;P_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
462
- `));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var i=0;i<r.length;i++){var a=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n},P_.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
461
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=xg(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),Cg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),wg=o(((e,t)=>{var n=Xh().Buffer,r=vg(),i=Sg(),a=require(`stream`),o=Cg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),Tg=o(((e,t)=>{var n=Xh().Buffer,r=vg(),i=Sg(),a=require(`stream`),o=Cg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),Eg=o((e=>{var t=wg(),n=Tg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),Dg=o(((e,t)=>{var n=Eg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),Og=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),kg=o(((e,t)=>{var n=Og(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),Ag=o(((e,t)=>{var n=Og(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),jg=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Mg=o(((e,t)=>{var n=jg();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),Ng=o(((e,t)=>{t.exports=Sm().satisfies(process.version,`>=15.7.0`)})),Pg=o(((e,t)=>{t.exports=Sm().satisfies(process.version,`>=16.9.0`)})),Fg=o(((e,t)=>{let n=Ng(),r=Pg(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),Ig=o(((e,t)=>{t.exports=Sm().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Lg=o(((e,t)=>{let n=Og(),r=kg(),i=Ag(),a=Dg(),o=Mg(),s=Fg(),c=Ig(),l=Eg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Rg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:de(e),n=n&&!r?ce(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),oe(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return re(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&ie(e.length)&&!F(e)}function re(e){return ae(e)&&ne(e)}function F(e){var t=I(e)?E.call(e):``;return t==s||t==c}function ie(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function I(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ae(e){return!!e&&typeof e==`object`}function oe(e){return typeof e==`string`||!P(e)&&ae(e)&&E.call(e)==l}function L(e){return typeof e==`symbol`||ae(e)&&E.call(e)==u}function se(e){return e?(e=le(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function ce(e){var t=se(e),n=t%1;return t===t?n?t-n:t:0}function le(e){if(typeof e==`number`)return e;if(L(e))return a;if(I(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=I(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function ue(e){return ne(e)?A(e):j(e)}function de(e){return e?S(e,ue(e)):[]}t.exports=N})),zg=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),Bg=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),Vg=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),Hg=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),Ug=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Wg=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Gg=o(((e,t)=>{let n=Mg(),r=Ig(),i=Fg(),a=Eg(),o=Rg(),s=zg(),c=Bg(),l=Vg(),u=Hg(),d=Ug(),f=Wg(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Kg=c(o(((e,t)=>{t.exports={decode:Dg(),verify:Lg(),sign:Gg(),JsonWebTokenError:Og(),NotBeforeError:kg(),TokenExpiredError:Ag()}}))(),1),qg=c(dd(),1),Jg=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Yg(e){return e instanceof Jg}function Xg(){return new Jg({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function Zg(){return new Jg({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Qg(){return new Jg({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function $g(e=`Device revoked`){return new Jg({code:`DEVICE_REVOKED`,status:401,message:e})}function e_(){return new Jg({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function t_(e){return new Jg({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function n_(e,t){return new Jg({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function r_(e){return new Jg({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function i_(e,t,n){return new Jg({code:`SESSION_TURN_CONFLICT`,status:409,message:`Session ${e} cannot accept input: ${t}`,details:n})}function a_(e){return new Jg({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function o_(e){return new Jg({code:`CODEX_APP_SERVER_RESTART_CONFLICT`,status:409,message:`Codex app-server restart requires idle runtime, found ${e} running session${e===1?``:`s`}`})}function s_(e){return new Jg({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function c_(){return new Jg({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function l_(){return new Jg({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function u_(e){return new Jg({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function d_(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var f_=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=p_(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw Xg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),Zg();this.pairingCodes.delete(e);let i=`dev_${_g(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...m_(o),gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Kg.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n)throw Qg();if(n.revoked){let e=this.tryReplayRefresh(n,t.sub);if(e){let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw $g();return{...m_(e),deviceId:t.sub,deviceIdentityFingerprint:n.publicKeyFingerprint,deviceIdentityStatus:n.identityStatus}}throw Qg()}let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw $g();let i=this.issueTokenPair(t.sub),a=new Date().toISOString();return n.revoked=!0,n.revokedAt=a,n.replayUntilMs=Date.now()+3e4,n.rotatedToJti=i.refreshJti,n.rotatedToAccessJti=i.accessJti,n.rotatedToAccessIssuedAtMs=i.accessIssuedAtMs,n.rotatedToAccessExpiresAtMs=i.accessExpiresAtMs,this.refreshTokens.set(t.jti,n),await this.persistState(),{...m_(i),deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Kg.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw $g(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw $g(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw c_();if(!y_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw l_();if(n.identityStatus!==`active`)throw u_(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}inspectRefreshToken(e){let t=Kg.default.decode(e),n=t&&typeof t==`object`?t:null,r=typeof n?.jti==`string`?n.jti:void 0,i=typeof n?.sub==`string`?n.sub:void 0,a=r?this.refreshTokens.get(r):void 0,o=i||a?.deviceId?[...this.refreshTokens.values()].filter(e=>e.deviceId===(i??a?.deviceId)&&!e.revoked).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]:void 0;return{claimDeviceId:i,claimExpAt:typeof n?.exp==`number`?new Date(n.exp*1e3).toISOString():void 0,claimIssuedAt:typeof n?.iat==`number`?new Date(n.iat*1e3).toISOString():void 0,claimJti:r,claimType:typeof n?.type==`string`?n.type:void 0,latestActiveTokenCreatedAt:o?.createdAt,latestActiveTokenJti:o?.jti,tokenRecordCreatedAt:a?.createdAt,tokenRecordDeviceId:a?.deviceId,tokenRecordReplayUntilAt:typeof a?.replayUntilMs==`number`?new Date(a.replayUntilMs).toISOString():void 0,tokenRecordRotatedToJti:a?.rotatedToJti,tokenRecordRevokedAt:a?.revokedAt,tokenRecordState:a?a.revoked?`revoked`:`active`:`missing`}}issueTokenPair(e){let t=h_(e,this.config.accessSecret,this.config.accessTtl),n=`rt_${_g(14)}`,r=Kg.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Kg.default.decode(r);return this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),issuedAtMs:typeof i.iat==`number`?i.iat*1e3:void 0,expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0}),{accessToken:t.accessToken,refreshToken:r,expiresInSeconds:t.expiresInSeconds,refreshJti:n,accessJti:t.jti,accessIssuedAtMs:t.issuedAtMs,accessExpiresAtMs:t.expiresAtMs}}tryReplayRefresh(e,t){if(typeof e.replayUntilMs!=`number`||e.replayUntilMs<Date.now()||typeof e.rotatedToJti!=`string`)return null;let n=this.refreshTokens.get(e.rotatedToJti);if(!n||n.revoked||n.deviceId!==t)return null;let r=g_(n,this.config.refreshSecret);if(!r)return null;let i=__(t,e.rotatedToAccessJti,e.rotatedToAccessIssuedAtMs,e.rotatedToAccessExpiresAtMs,this.config.accessSecret);if(!i)return null;let a=e.rotatedToAccessIssuedAtMs,o=e.rotatedToAccessExpiresAtMs;return typeof a!=`number`||typeof o!=`number`?null:{accessToken:i,refreshToken:r,expiresInSeconds:Math.floor((o-a)/1e3)}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await x_(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await x_(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await x_(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:v_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,issuedAtMs:typeof e.issuedAtMs==`number`?e.issuedAtMs:void 0,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0,replayUntilMs:typeof e.replayUntilMs==`number`?e.replayUntilMs:void 0,rotatedToJti:typeof e.rotatedToJti==`string`?e.rotatedToJti:void 0,rotatedToAccessJti:typeof e.rotatedToAccessJti==`string`?e.rotatedToAccessJti:void 0,rotatedToAccessIssuedAtMs:typeof e.rotatedToAccessIssuedAtMs==`number`?e.rotatedToAccessIssuedAtMs:void 0,rotatedToAccessExpiresAtMs:typeof e.rotatedToAccessExpiresAtMs==`number`?e.rotatedToAccessExpiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return b_(this.pairingCodes,e),b_(this.devices,t),b_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function p_(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function m_(e){return{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresInSeconds:e.expiresInSeconds}}function h_(e,t,n){let r=`at_${_g(14)}`,i=Kg.default.sign({sub:e,type:`access`,jti:r},t,{expiresIn:n}),a=Kg.default.decode(i);return{accessToken:i,jti:r,issuedAtMs:a.iat*1e3,expiresAtMs:a.exp*1e3,expiresInSeconds:a.exp-a.iat}}function g_(e,t){return typeof e.issuedAtMs!=`number`||typeof e.expiresAtMs!=`number`?null:Kg.default.sign({sub:e.deviceId,type:`refresh`,jti:e.jti,iat:Math.floor(e.issuedAtMs/1e3),exp:Math.floor(e.expiresAtMs/1e3)},t)}function __(e,t,n,r,i){return typeof t!=`string`||typeof n!=`number`||typeof r!=`number`?null:Kg.default.sign({sub:e,type:`access`,jti:t,iat:Math.floor(n/1e3),exp:Math.floor(r/1e3)},i)}function v_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function y_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function b_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function x_(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var S_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function C_(){}C_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(w_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(w_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function w_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new C_;function T_(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function E_(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function D_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function O_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function k_(e,t){return D_(e,t,``)}function A_(e,t){return O_(e,t,``)}function j_(e,t){return t.slice(0,M_(e,t))}function M_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var N_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,P_=RegExp(`[${N_}]+|\\s+|[^${N_}]`,`ug`),F_=new C_;F_.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},F_.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(P_)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},F_.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},F_.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&I_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&I_(n,i,r,null),e};function I_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=T_(i,o);e.value=O_(e.value,o,c),t.value=k_(t.value,c),n.value=k_(n.value,c)}if(r){var l=E_(a,s);r.value=D_(r.value,s,l),t.value=A_(t.value,l),n.value=A_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=T_(u,d);t.value=k_(t.value,p);var m=E_(k_(u,p),f);t.value=A_(t.value,m),r.value=D_(r.value,u,m),e.value=O_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=j_(g,h);t.value=A_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=j_(v,y);t.value=k_(t.value,b)}}var L_=new C_;L_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${N_}]+|[^\\S\\n\\r]+|[^${N_}]`,`ug`);return e.match(t)||[]};var R_=new C_;R_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
462
+ `));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var i=0;i<r.length;i++){var a=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n},R_.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
463
463
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
464
464
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
465
465
  `)&&(e=e.slice(0,-1)),t.endsWith(`
466
- `)&&(t=t.slice(0,-1))),y_.prototype.equals.call(this,e,t,n)};function F_(e,t,n){return P_.diff(e,t,n)}var I_=new y_;I_.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var L_=new y_;L_.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function R_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function z_(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?R_(Object(n),!0).forEach(function(t){U_(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):R_(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function B_(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function V_(e){var t=B_(e,`string`);return typeof t==`symbol`?t:t+``}function H_(e){"@babel/helpers - typeof";return H_=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},H_(e)}function U_(e,t,n){return t=V_(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function W_(e){return G_(e)||K_(e)||q_(e)||Y_()}function G_(e){if(Array.isArray(e))return J_(e)}function K_(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function q_(e,t){if(e){if(typeof e==`string`)return J_(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return J_(e,t)}}function J_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Y_(){throw TypeError(`Invalid attempt to spread non-iterable instance.
467
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var X_=new y_;X_.useLongestToken=!0,X_.tokenize=P_.tokenize,X_.castInput=function(e,t){var n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(Z_(e,null,null,i),i,` `)},X_.equals=function(e,t,n){return y_.prototype.equals.call(X_,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)};function Z_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));var a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=Z_(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),H_(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=Z_(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var Q_=new y_;Q_.tokenize=function(e){return e.slice()},Q_.join=Q_.removeEmpty=function(e){return e};function $_(e,t,n,r,i,a,o){if(o||={},typeof o==`function`&&(o={callback:o}),o.context===void 0&&(o.context=4),o.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(o.callback){var s=o.callback;F_(n,r,z_(z_({},o),{},{callback:function(e){s(c(e))}}))}else return c(F_(n,r,o));function c(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}for(var s=[],c=0,l=0,u=[],d=1,f=1,p=function(){var e=n[m],t=e.lines||nv(e.value);if(e.lines=t,e.added||e.removed){var i;if(!c){var a=n[m-1];c=d,l=f,a&&(u=o.context>0?r(a.lines.slice(-o.context)):[],c-=u.length,l-=u.length)}(i=u).push.apply(i,W_(t.map(function(t){return(e.added?`+`:`-`)+t}))),e.added?f+=t.length:d+=t.length}else{if(c)if(t.length<=o.context*2&&m<n.length-2){var p;(p=u).push.apply(p,W_(r(t)))}else{var h,g=Math.min(t.length,o.context);(h=u).push.apply(h,W_(r(t.slice(0,g))));var _={oldStart:c,oldLines:d-c+g,newStart:l,newLines:f-l+g,lines:u};s.push(_),c=0,l=0,u=[]}d+=t.length,f+=t.length}},m=0;m<n.length;m++)p();for(var h=0,g=s;h<g.length;h++)for(var _=g[h],v=0;v<_.lines.length;v++)_.lines[v].endsWith(`
468
- `)?_.lines[v]=_.lines[v].slice(0,-1):(_.lines.splice(v+1,0,`\`),v++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:s}}}function ev(e){if(Array.isArray(e))return e.map(ev).join(`
466
+ `)&&(t=t.slice(0,-1))),C_.prototype.equals.call(this,e,t,n)};function z_(e,t,n){return R_.diff(e,t,n)}var B_=new C_;B_.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var V_=new C_;V_.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function H_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function U_(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?H_(Object(n),!0).forEach(function(t){q_(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):H_(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function W_(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function G_(e){var t=W_(e,`string`);return typeof t==`symbol`?t:t+``}function K_(e){"@babel/helpers - typeof";return K_=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},K_(e)}function q_(e,t,n){return t=G_(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function J_(e){return Y_(e)||X_(e)||Z_(e)||$_()}function Y_(e){if(Array.isArray(e))return Q_(e)}function X_(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function Z_(e,t){if(e){if(typeof e==`string`)return Q_(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Q_(e,t)}}function Q_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function $_(){throw TypeError(`Invalid attempt to spread non-iterable instance.
467
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var ev=new C_;ev.useLongestToken=!0,ev.tokenize=R_.tokenize,ev.castInput=function(e,t){var n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(tv(e,null,null,i),i,` `)},ev.equals=function(e,t,n){return C_.prototype.equals.call(ev,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)};function tv(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));var a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=tv(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),K_(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=tv(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var nv=new C_;nv.tokenize=function(e){return e.slice()},nv.join=nv.removeEmpty=function(e){return e};function rv(e,t,n,r,i,a,o){if(o||={},typeof o==`function`&&(o={callback:o}),o.context===void 0&&(o.context=4),o.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(o.callback){var s=o.callback;z_(n,r,U_(U_({},o),{},{callback:function(e){s(c(e))}}))}else return c(z_(n,r,o));function c(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}for(var s=[],c=0,l=0,u=[],d=1,f=1,p=function(){var e=n[m],t=e.lines||ov(e.value);if(e.lines=t,e.added||e.removed){var i;if(!c){var a=n[m-1];c=d,l=f,a&&(u=o.context>0?r(a.lines.slice(-o.context)):[],c-=u.length,l-=u.length)}(i=u).push.apply(i,J_(t.map(function(t){return(e.added?`+`:`-`)+t}))),e.added?f+=t.length:d+=t.length}else{if(c)if(t.length<=o.context*2&&m<n.length-2){var p;(p=u).push.apply(p,J_(r(t)))}else{var h,g=Math.min(t.length,o.context);(h=u).push.apply(h,J_(r(t.slice(0,g))));var _={oldStart:c,oldLines:d-c+g,newStart:l,newLines:f-l+g,lines:u};s.push(_),c=0,l=0,u=[]}d+=t.length,f+=t.length}},m=0;m<n.length;m++)p();for(var h=0,g=s;h<g.length;h++)for(var _=g[h],v=0;v<_.lines.length;v++)_.lines[v].endsWith(`
468
+ `)?_.lines[v]=_.lines[v].slice(0,-1):(_.lines.splice(v+1,0,`\`),v++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:s}}}function iv(e){if(Array.isArray(e))return e.map(iv).join(`
469
469
  `);var t=[];e.oldFileName==e.newFileName&&t.push(`Index: `+e.oldFileName),t.push(`===================================================================`),t.push(`--- `+e.oldFileName+(e.oldHeader===void 0?``:` `+e.oldHeader)),t.push(`+++ `+e.newFileName+(e.newHeader===void 0?``:` `+e.newHeader));for(var n=0;n<e.hunks.length;n++){var r=e.hunks[n];r.oldLines===0&&--r.oldStart,r.newLines===0&&--r.newStart,t.push(`@@ -`+r.oldStart+`,`+r.oldLines+` +`+r.newStart+`,`+r.newLines+` @@`),t.push.apply(t,r.lines)}return t.join(`
470
470
  `)+`
471
- `}function tv(e,t,n,r,i,a,o){var s;if(typeof o==`function`&&(o={callback:o}),(s=o)!=null&&s.callback){var c=o.callback;$_(e,t,n,r,i,a,z_(z_({},o),{},{callback:function(e){e?c(ev(e)):c()}}))}else{var l=$_(e,t,n,r,i,a,o);return l?ev(l):void 0}}function nv(e){var t=e.endsWith(`
471
+ `}function av(e,t,n,r,i,a,o){var s;if(typeof o==`function`&&(o={callback:o}),(s=o)!=null&&s.callback){var c=o.callback;rv(e,t,n,r,i,a,U_(U_({},o),{},{callback:function(e){e?c(iv(e)):c()}}))}else{var l=rv(e,t,n,r,i,a,o);return l?iv(l):void 0}}function ov(e){var t=e.endsWith(`
472
472
  `),n=e.split(`
473
473
  `).map(function(e){return e+`
474
- `});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var rv=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return dv(r,await lv(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await uv(e,n),i=p.default.parse(r).root;return dv(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await iv(e,t);return{path:r,absolutePath:n,content:await d.default.readFile(n,`utf8`)}}async diffFile(e,t,n=``){let{absolutePath:r,normalizedPath:i}=await iv(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:tv(i,i,n,a,`base`,`current`),currentContent:a}}async listTree(e,t=`.`,n=500){let r=await d.default.realpath(p.default.resolve(e)),i=av(t),a=await ov(r,i),o=[];async function s(e,t){let r=await d.default.readdir(e,{withFileTypes:!0});for(let i of r){if(o.length>=n)return;let r=p.default.join(e,i.name),a=t?p.default.join(t,i.name):i.name;i.isSymbolicLink()||(i.isDirectory()?(o.push({path:a,kind:`dir`}),await s(r,a)):o.push({path:a,kind:`file`}))}}return await s(a,``),{root:i,entries:o}}};async function iv(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=av(t),i=await ov(n,r),a=await d.default.realpath(i);return sv(n,a,r),{absolutePath:a,normalizedPath:r}}function av(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function ov(e,t){if(p.default.isAbsolute(t))throw Error(`Path must be relative to project root: ${t}`);let n=p.default.resolve(e,t);return sv(e,n,t),n}function sv(e,t,n){let r=cv(e),i=cv(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function cv(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function lv(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;sv(e,r,n??`.`);let i=await d.default.realpath(r);if(sv(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function uv(e,t=f.default.homedir()){let n=e?.trim(),r=p.default.resolve(t),i=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(r,n):r,a=await d.default.realpath(i);if(!(await d.default.stat(a)).isDirectory())throw Error(`Path is not a directory: ${a}`);return a}async function dv(e,t,n){let r=(await d.default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,Math.max(1,n)).map(e=>({name:e.name,path:p.default.join(t,e.name)}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),directories:r}}var fv=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await mv(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=pv(t)??(p.default.basename(n)||n),o=r?{...r,title:pv(t)??r.title,updatedAt:i}:{id:`proj_${_g(12)}`,title:a,path:n,createdAt:i,updatedAt:i};return this.projects.set(o.id,o),this.projectByPath.set(n,o),await this.enqueueWrite(async()=>{await this.persistIndex()}),o}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await mv(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`||(this.projects.set(e.id,e),this.projectByPath.set(e.path,e))}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function pv(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function mv(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}Ih(),jh(),Mh();var hv=c(Fh(),1);Rh();var gv=hv.default,_v=120,vv=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${_g(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await yv(_v);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function yv(e){return new Promise(t=>setTimeout(t,e))}var bv=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new vv(this.provider,e)}};function xv(e){let t=Tv(Cv(e)),n=Q(t.type);return n&&(t.type=Sv(n)),t}function Sv(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return wv(e)}}function Cv(e){if(Array.isArray(e))return e.map(e=>Cv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[wv(n)]=Cv(r);return t}return e}function wv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function Tv(e){return typeof e==`object`&&e?e:{}}function Q(e){if(typeof e==`string`)return e}function Ev(e){return typeof e==`string`||typeof e==`number`?String(e):``}var Dv=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],Ov=[x.default.join(x.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),x.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function kv(e,t){let n=Av(e);if(!n)return null;let r=JSON.parse(b.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:x.default.resolve(x.default.dirname(n),i)}function Av(e){for(let t of Ov)try{return(0,S.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}var jv=1e4,Mv=100,Nv=2e3;function Pv(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function Fv(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var Iv=new Map;async function Lv(e){return Vv(e).createConnection()}async function Rv(){let e=[...Iv.values()];await Promise.allSettled(e.map(e=>e.shutdown())),Iv.clear()}async function zv(e){let t=Iv.size>0?[...Iv.values()]:[Vv(e)];await Promise.all(t.map(e=>e.restart()))}function Bv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[x.default.resolve(t)]};try{let e=kv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function Vv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=Iv.get(t);if(n)return n;let r=new Hv(e);return Iv.set(t,r),r}var Hv=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await Wv(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise){await this.shutdownPromise;return}this.shutdownPromise=this.shutdownInternal();try{await this.shutdownPromise}finally{this.shutdownPromise=null}}async restart(){await this.shutdown();let e=await this.ensureRunning();await(await Wv(e.url,()=>this.buildStartupError(e.stderrTail))).close()}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await Jv(e.child,Nv)||(e.child.kill(`SIGKILL`),await Jv(e.child,Nv)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await qv()}`,t=Bv(this.codexBinOverride),n=(0,w.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await Kv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await Jv(n,Nv)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},Uv=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){if(!this.closed){if(this.closed=!0,this.socket.readyState<=1)try{this.socket.close(1e3,`Client closing`)}catch(e){Fv(`connection.close_failed`,{readyState:this.socket.readyState,...Pv(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=Yv(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function Wv(e,t){let n=Date.now()+jv,r=null;for(;Date.now()<n;)try{return await Gv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await Xv(Mv)}throw r??Error(t())}async function Gv(e,t){let n=new gv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),Fv(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){Fv(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...Pv(r)})}i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new Uv(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(r,o)=>{if(a)return;a=!0,s();let c=typeof r==`number`?r:`unknown`,l=o.length>0?`: ${o.toString(`utf8`)}`:``;Fv(`connect.closed_before_open`,{url:e,timeoutMs:t,readyState:n.readyState,closeCode:c,closeReason:l||null}),i(Error(`Connection closed before open (${String(c)})${l}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function Kv(e,t,n){let r=Date.now()+jv;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Gv(e,500)).close(),!0}catch{await Xv(Mv)}}return!1}async function qv(){let e=(0,C.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function Jv(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function Yv(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function Xv(e){return new Promise(t=>{setTimeout(t,e)})}var Zv=15e3,Qv=5e3,$v={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},ey=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??Zv,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:$v,capabilities:{experimentalApi:!1,optOutNotificationMethods:Dv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=Ev(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=Q(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=Ev(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=Tv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function ty(e,t={}){let n=new ey(await ry(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function ny(e={}){try{return await ty(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??Qv}),!0}catch{return!1}}async function ry(e){return e.spawnProcess?new ay(e.spawnProcess()):new iy(await Lv(e.codexBinOverride))}var iy=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},ay=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
474
+ `});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var sv=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return hv(r,await pv(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await mv(e,n),i=p.default.parse(r).root;return hv(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await cv(e,t);return{path:r,absolutePath:n,content:await d.default.readFile(n,`utf8`)}}async diffFile(e,t,n=``){let{absolutePath:r,normalizedPath:i}=await cv(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:av(i,i,n,a,`base`,`current`),currentContent:a}}async listTree(e,t=`.`,n=500){let r=await d.default.realpath(p.default.resolve(e)),i=lv(t),a=await uv(r,i),o=[];async function s(e,t){let r=await d.default.readdir(e,{withFileTypes:!0});for(let i of r){if(o.length>=n)return;let r=p.default.join(e,i.name),a=t?p.default.join(t,i.name):i.name;i.isSymbolicLink()||(i.isDirectory()?(o.push({path:a,kind:`dir`}),await s(r,a)):o.push({path:a,kind:`file`}))}}return await s(a,``),{root:i,entries:o}}};async function cv(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=lv(t),i=await uv(n,r),a=await d.default.realpath(i);return dv(n,a,r),{absolutePath:a,normalizedPath:r}}function lv(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function uv(e,t){if(p.default.isAbsolute(t))throw Error(`Path must be relative to project root: ${t}`);let n=p.default.resolve(e,t);return dv(e,n,t),n}function dv(e,t,n){let r=fv(e),i=fv(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function fv(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function pv(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;dv(e,r,n??`.`);let i=await d.default.realpath(r);if(dv(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function mv(e,t=f.default.homedir()){let n=e?.trim(),r=p.default.resolve(t),i=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(r,n):r,a=await d.default.realpath(i);if(!(await d.default.stat(a)).isDirectory())throw Error(`Path is not a directory: ${a}`);return a}async function hv(e,t,n){let r=(await d.default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,Math.max(1,n)).map(e=>({name:e.name,path:p.default.join(t,e.name)}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),directories:r}}var gv=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await vv(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=_v(t)??(p.default.basename(n)||n),o=r?{...r,title:_v(t)??r.title,updatedAt:i}:{id:`proj_${_g(12)}`,title:a,path:n,createdAt:i,updatedAt:i};return this.projects.set(o.id,o),this.projectByPath.set(n,o),await this.enqueueWrite(async()=>{await this.persistIndex()}),o}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await vv(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`||(this.projects.set(e.id,e),this.projectByPath.set(e.path,e))}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function _v(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function vv(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}Ih(),jh(),Mh();var yv=c(Fh(),1);Rh();var bv=yv.default,xv=120,Sv=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${_g(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await Cv(xv);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function Cv(e){return new Promise(t=>setTimeout(t,e))}var wv=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new Sv(this.provider,e)}};function Tv(e){let t=kv(Dv(e)),n=Q(t.type);return n&&(t.type=Ev(n)),t}function Ev(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return Ov(e)}}function Dv(e){if(Array.isArray(e))return e.map(e=>Dv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[Ov(n)]=Dv(r);return t}return e}function Ov(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function kv(e){return typeof e==`object`&&e?e:{}}function Q(e){if(typeof e==`string`)return e}function Av(e){return typeof e==`string`||typeof e==`number`?String(e):``}var jv=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],Mv=[x.default.join(x.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),x.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function Nv(e,t){let n=Pv(e);if(!n)return null;let r=JSON.parse(b.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:x.default.resolve(x.default.dirname(n),i)}function Pv(e){for(let t of Mv)try{return(0,S.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}var Fv=1e4,Iv=100,Lv=2e3;function Rv(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function zv(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var Bv=new Map;async function Vv(e){return Gv(e).createConnection()}async function Hv(){let e=[...Bv.values()];await Promise.allSettled(e.map(e=>e.shutdown())),Bv.clear()}async function Uv(e){let t=Bv.size>0?[...Bv.values()]:[Gv(e)];await Promise.all(t.map(e=>e.restart()))}function Wv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[x.default.resolve(t)]};try{let e=Nv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function Gv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=Bv.get(t);if(n)return n;let r=new Kv(e);return Bv.set(t,r),r}var Kv=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await Jv(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise){await this.shutdownPromise;return}this.shutdownPromise=this.shutdownInternal();try{await this.shutdownPromise}finally{this.shutdownPromise=null}}async restart(){await this.shutdown();let e=await this.ensureRunning();await(await Jv(e.url,()=>this.buildStartupError(e.stderrTail))).close()}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await Qv(e.child,Lv)||(e.child.kill(`SIGKILL`),await Qv(e.child,Lv)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await Zv()}`,t=Wv(this.codexBinOverride),n=(0,w.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await Xv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await Qv(n,Lv)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},qv=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){if(!this.closed){if(this.closed=!0,this.socket.readyState<=1)try{this.socket.close(1e3,`Client closing`)}catch(e){zv(`connection.close_failed`,{readyState:this.socket.readyState,...Rv(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=$v(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function Jv(e,t){let n=Date.now()+Fv,r=null;for(;Date.now()<n;)try{return await Yv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await ey(Iv)}throw r??Error(t())}async function Yv(e,t){let n=new bv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),zv(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){zv(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...Rv(r)})}i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new qv(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(r,o)=>{if(a)return;a=!0,s();let c=typeof r==`number`?r:`unknown`,l=o.length>0?`: ${o.toString(`utf8`)}`:``;zv(`connect.closed_before_open`,{url:e,timeoutMs:t,readyState:n.readyState,closeCode:c,closeReason:l||null}),i(Error(`Connection closed before open (${String(c)})${l}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function Xv(e,t,n){let r=Date.now()+Fv;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Yv(e,500)).close(),!0}catch{await ey(Iv)}}return!1}async function Zv(){let e=(0,C.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function Qv(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function $v(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function ey(e){return new Promise(t=>{setTimeout(t,e)})}var ty=15e3,ny=5e3,ry={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},iy=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??ty,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:ry,capabilities:{experimentalApi:!1,optOutNotificationMethods:jv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=Av(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=Q(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=Av(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=kv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function ay(e,t={}){let n=new iy(await sy(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function oy(e={}){try{return await ay(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??ny}),!0}catch{return!1}}async function sy(e){return e.spawnProcess?new ly(e.spawnProcess()):new cy(await Vv(e.codexBinOverride))}var cy=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},ly=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
475
475
  `)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}async close(){this.closed||(this.closed=!0,this.process.stdin.destroyed||this.process.stdin.end(),!this.process.killed&&this.process.exitCode===null&&this.process.kill())}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}),this.process.on(`error`,e=>{this.fail(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.closed)return;let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.fail(`Codex app-server exited unexpectedly (${i})${r}`)})}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
476
- `);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},oy=3,sy=250;function cy(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function ly(e,t){let n=Math.max(1,t?.maxAttempts??oy),r=Math.max(0,t?.retryDelayMs??sy),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!cy(e)||t>=n)throw e;r>0&&await uy(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function uy(e){return new Promise(t=>{setTimeout(t,e)})}function dy(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function fy(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var py=3e4,my=8,hy=160,gy={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},_y=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await Lv(),n.requestTimeoutMs??py);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0;try{let n=t?.model??this.activeModel,r=dy(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=Ey(this.activeSessionConfig.reasoningEffort),o,s=Dy(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&Oy(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:Dy(t?.mode,n,`low`)})}let c=Q(o.turn?.id);c&&(this.activeTurnId=c)}catch(e){throw this.turnInProgress=!1,e}}async interrupt(){if(this.ensureOpen(),!this.threadId||!this.activeTurnId)return;let e={threadId:this.threadId,turnId:this.activeTurnId};await this.sendRequest(`turn/interrupt`,e)}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=Ay(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:fy(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:gy,capabilities:{experimentalApi:!0,optOutNotificationMethods:Dv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return Q((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return Q((await ly(()=>this.sendRequest(`thread/resume`,i))).thread?.id)}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0;for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:Cy(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=Q(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=Ev(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=Tv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=Tv(r),a=Q(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${_g(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:Q(i.reason),threadId:a,turnId:Q(i.turnId),itemId:Q(i.itemId),approvalMethod:t,rawParams:Cv(i)})}registerUserInputRequest(e,t,n){let r=Q(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${_g(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(ky).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:Cv(n)})}handleNotification(e){switch(e.method){case`thread/started`:{let t=e.params,n=Q(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:Cv(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Q(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.emit({type:`turn.started`,turn:Cv(t.turn)});return}case`turn/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.status);if(this.turnInProgress=!1,this.activeTurnId=void 0,n===`failed`){this.emit({type:`turn.failed`,status:n,turn:Cv(t.turn),error:Cv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:Cv(t.turn)}),this.tryEmitTitleFromThreadRead();return}case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.started`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:xv(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.completed`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:xv(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=Tv(e.params);if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:Q(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Q(t.delta)??Q(t.text)??``,original_method:e.method,payload:Cv(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`error`,message:Q(t.error?.message)??`Codex app-server error`,error:Cv(t.error),will_retry:t.willRetry===!0,thread_id:Q(t.threadId),turn_id:Q(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=Ev(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=vy(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated(Q(e.thread?.name)??Q(e.thread?.preview),Q(e.thread?.name)?`codex.thread_read_name`:`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleConnectionFailure(e){if(this.closed)return;let t=wy(e),n=Ty(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(Ev(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Q(Tv(e.params).threadId)}extractThreadIdFromNotification(e){let t=Tv(e.params);return Q(t.threadId)||Q(Tv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Q(Tv(Tv(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(yy({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(yy({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>my&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-my)}};function vy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function yy(e){let t=Q(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=Tv(e.message.error),i=xy(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:by(t,n,e.direction),method:t,requestId:n?Ev(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??Cy(Q(r.message))}}function by(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function xy(e,t){let n=Tv(t),r=Tv(n.thread),i=Tv(n.turn),a=Tv(n.item),o=Q(n.delta)??Q(n.text),s=Sy(e,n,o);return{threadId:Q(n.threadId)??Q(r.id),turnId:Q(n.turnId)??Q(i.id),itemId:Q(n.itemId)??Q(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:Cy(s)}}function Sy(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return Q(Tv(t.error).message)??Q(t.message)}function Cy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=hy?t:`${t.slice(0,hy)}...`}function wy(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function Ty(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function Ey(e){return e?e===`max`?`xhigh`:e:null}function Dy(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function Oy(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function ky(e){let t=Tv(e),n=Q(t.id),r=Q(t.header),i=Q(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=Tv(e),n=Q(t.label),r=Q(t.description)??n,i=Q(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function Ay(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var jy=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new bv(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await ny()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??_y.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function My(e,t){let n=[],r=null,i=Ry(t?.maxThreads),a=t?.sortKey,o=t?.updatedAfterUnixSeconds;do{let t=i===null?100:Math.max(0,i-n.length);if(t===0)break;let s=await Ny({cwd:e,archived:!1,cursor:r,limit:i===null?100:Math.min(100,t),sortKey:a}),c=!1;for(let t of s.threads)if(t.cwd===e){if(o!==void 0&&t.updatedAt<o){if(a===`updated_at`){c=!0;break}continue}if(n.push(t),i!==null&&n.length>=i){c=!0;break}}if(c)break;r=s.nextCursor}while(r);return n}async function Ny(e){return ty(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>Ly(e)),nextCursor:n.nextCursor}})}async function Py(e,t=!0){return ty(async n=>Ly((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function Fy(e){return ty(async t=>{let n=!1;try{let r=await ly(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,Vy(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function Iy(){let e=[],t=null;do{let n=await ty(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>By(e))),t=n.nextCursor}while(t);return e}function Ly(e){let t=Q(Tv(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,status:zy(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:Uy(e.source),gitInfo:e.gitInfo?Tv(Cv(e.gitInfo)):null,turns:e.turns.map(e=>Hy(e))}}function Ry(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function zy(e){let t=Q(Tv(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function By(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function Vy(e){let t=Wy(e.model),n=Gy(e.reasoningEffort),r=Ky(e.approvalPolicy),i=qy(e.sandbox),a=r!==null||i!==null;return t||n!==null||a?{model:t,sessionTurnConfig:{mode:`default`,model:t??null,reasoningEffort:n,...a?{execution:{codex:{approvalPolicy:r,sandboxMode:i}}}:{}},sessionTurnConfigUpdatedAt:new Date(e.thread.updatedAt*1e3).toISOString()}:null}function Hy(e){return{id:e.id,status:e.status,error:e.error?Tv(Cv(e.error)):null,items:e.items.map(e=>xv(e))}}function Uy(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function Wy(e){return Q(e)?.trim()||void 0}function Gy(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function Ky(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function qy(e){let t=typeof e==`string`?e:Q(Tv(e).type);return t===`read-only`||t===`readOnly`?`read-only`:t===`workspace-write`||t===`workspaceWrite`?`workspace-write`:t===`danger-full-access`||t===`dangerFullAccess`?`danger-full-access`:null}var Jy=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=dy(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=$y(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:fy(r),questions:Zy(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=vb(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:yb(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(t){if(this.closed||this.activeQuery!==e)return;let n=t instanceof Error?t.message:String(t);this.interruptRequested||this.emit({type:`error`,message:n})}finally{if(this.closed||this.activeQuery!==e)return;this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>Xy(e,t)?this.requestUserInput(e,t,n):Yy(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${_g(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=Zy(t),i=`req_${_g(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1}captureResumeSessionId(e){let t=vb(e),n=yb(t.session_id)??yb(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${_g(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=Cb(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=yb(e.tool_id)??yb(e.tool_use_id)??xb(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=yb(e.uuid);if(n)return this.activeToolItemId=n,n;let r=wb(yb(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}mapClaudeMessage(e){let t=vb(e),n=yb(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!pb(t))return[];let n=mb(vb(t.message));return n?[{type:`item.completed`,item:{id:yb(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:yb(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=fb(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=vb(t.event);if(yb(e.type)===`message_start`){let t=Cb(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=hb(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||yb(t.subtype)?.startsWith(`error_`)===!0){let n=gb(t);return[...e,{type:`turn.failed`,error:{message:n},usage:_b(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:_b(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=yb(t.summary)??`tool summary`,i=yb(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=yb(t.tool_name)??`tool`,i=yb(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=yb(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(yb(t.session_id)??yb(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:yb(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=yb(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=eb(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=tb(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=nb({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function Yy(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function Xy(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function Zy(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=Qy(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function Qy(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function $y(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function eb(e){let t=vb(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=vb(e);if(t.type!==`tool_use`)continue;let n=yb(t.id),i=yb(t.name),a=vb(t.input);if(!(!n||!i)){if(i===`Task`){let e=yb(a.subagent_type),t=yb(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:yb(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=yb(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=yb(a.file_path);r.push({id:n,toolName:`Write`,title:sb(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function tb(e){let t=vb(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=vb(e);if(t.type!==`tool_result`)continue;let n=yb(t.tool_use_id);if(n)return{toolUseId:n}}return null}function nb(e){let t=vb(e.raw.tool_use_result),n=rb(t.content)??mb(vb(e.raw.message)),r=vb(t.usage),i=Sb(t.totalTokens)??Sb(r.total_tokens)??Sb(r.output_tokens),a=Sb(t.totalToolUseCount),o=Sb(t.totalDurationMs),s=yb(t.agentId),c=yb(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=ab(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=ib(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=bb(t.content),r=ob(lb(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function rb(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=vb(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
477
- `):void 0}function ib(e){return bb(vb(e.file).content)||rb(e.content)}function ab(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${ub(t)} tokens`),typeof n==`number`&&r.push(db(n)),r.join(` · `)}function ob(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function sb(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${cb(e)})`:`Write`}function cb(e){let t=e.split(`/`);return t[t.length-1]||e}function lb(e){if(e)return e.split(`
478
- `).length}function ub(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function db(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 fb(e){return mb(vb(e.message))||(bb(e.result)??``)}function pb(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=vb(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>vb(e).type===`tool_result`)}function mb(e){let t=bb(e.content);if(t)return t;let n=bb(e.text)??bb(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=vb(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
479
- `)}function hb(e){let t=vb(vb(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function gb(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):yb(e.subtype)||`Claude turn failed`}function _b(e){let t=vb(e);return{input_tokens:Sb(t.input_tokens)??Sb(t.inputTokens)??0,cached_input_tokens:Sb(t.cached_input_tokens)??Sb(t.cache_read_input_tokens)??Sb(t.cacheReadInputTokens)??0,output_tokens:Sb(t.output_tokens)??Sb(t.outputTokens)??0}}function vb(e){return typeof e==`object`&&e?e:{}}function yb(e){if(typeof e==`string`&&e.trim())return e}function bb(e){if(typeof e==`string`&&e.length>0)return e}function xb(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function Sb(e){if(typeof e==`number`&&Number.isFinite(e))return e}function Cb(e){let t=yb(vb(e.message).id);if(t)return t;let n=yb(vb(vb(e.event).message).id);if(n)return n}function wb(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var Tb=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=Eb(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 Eb(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var Db=`@anthropic-ai/claude-agent-sdk`,Ob=`claude-sonnet-4-6`,kb=1e4,Ab=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(Db),!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(Db),n=await jb(Mb(t,e),kb,`Claude native query session creation timed out`);if(n)return n;let r=await jb(Nb(t,e),kb,`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 jb(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 Mb(e,t){let n=Pb(e);if(!n)return null;let r=t.model??Ob;return new Jy(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=Fb(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 Nb(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 Tb(`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 Tb(`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 Tb(`claude`,t.sessionId,t.model,n)}return null}function Pb(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function Fb(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 Ib(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new jy(n,r):new Ab(n,r)}const Lb=p.default.join(`.claude`,`projects`),Rb=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function zb(e){return(await(0,T.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>Kb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Bb(e,t){let n=Wb(e,t?.homeDir),r=p.default.resolve(e);try{let i=await qb(e,n,r,{maxSessions:vx(t?.maxSessions),updatedAfterMs:_x(t?.updatedAfterMs)});if(i.length>0)return i}catch{}return Jb(n,{maxSessions:vx(t?.maxSessions),updatedAfterMs:_x(t?.updatedAfterMs)})}async function Vb(e){let t=await rx(e.nativeSessionId,e.projectPath),n=await ix(e.projectPath,e.nativeSessionId,e.homeDir),r=Zb(t,{createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs});return{rawEvents:Hb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),updatedAt:r.updatedAt,status:Qb(t)}}function Hb(e){let t=[],n=Zb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function Ub(e,t,n){return p.default.join(Wb(e,n),`${t}.jsonl`)}function Wb(e,t){let n=t??f.default.homedir();return p.default.join(n,Lb,Gb(e))}function Gb(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function Kb(e){let t=px(e.customTitle)??px(e.summary)??px(e.firstPrompt),n=tx(e.createdAt??e.lastModified),r=tx(e.lastModified);return{nativeSessionId:e.sessionId,cwd:ex(e.cwd),title:t,createdAt:n,updatedAt:r,status:`idle`}}async function qb(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,T.listSessions)({dir:e,limit:c,offset:o});if(l.length===0)break;for(let e of l){let i=_x(e.lastModified);if(r.updatedAfterMs!==void 0&&i!==void 0&&i<r.updatedAfterMs){s=!0;break}let o=Kb(e);if(typeof o.cwd!=`string`||p.default.resolve(o.cwd)!==n)continue;let c=await Yb(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 Xb(a,r)}async function Jb(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 Yb(e,{nativeSessionId:t.name.slice(0,-6)});n&&r.push(n)}return Xb(r,t)}async function Yb(e,t){let n=p.default.join(e,`${t.nativeSessionId}.jsonl`),r;try{r=await nx(n)}catch(e){if(e.code===`ENOENT`)return t.sdkSession;throw e}if(!$b(r))return;let i=await d.default.stat(n),a=t.sdkSession?.createdAt?gx(t.sdkSession.createdAt):void 0,o=t.sdkSession?.updatedAt?gx(t.sdkSession.updatedAt):void 0,s=Zb(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:Qb(r)}}function Xb(e,t){let n=e.filter(e=>{if(t.updatedAfterMs===void 0)return!0;let n=gx(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 Zb(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=ux(cx(dx(t.raw.message)))),!n&&t.type===`assistant`&&(n=fx(dx(t.raw.message).model));let o=i??_x(t.createdAtFallbackMs)??0,s=a??_x(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function Qb(e){let t=``;for(let n of e)switch(n.type){case`user`:case`assistant`:case`result`:case`stream_event`:case`tool_progress`:case`tool_use_summary`:t=n.type;break;default:break}return t===`user`||t===`stream_event`||t===`tool_progress`?`running`:`idle`}function $b(e){for(let t of e){if(t.type===`user`){let e=dx(t.raw.message);if(cx(e)||sx(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=dx(t.raw.message);if(cx(e)||ox(e).length>0||fx(t.raw.error))return!0}return!1}function ex(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function tx(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function nx(e){let t=(await d.default.readFile(e,`utf8`)).split(`
480
- `),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=dx(i),o=fx(a.timestamp),s=o?gx(o):void 0;n.push({line:e+1,raw:a,type:fx(a.type),timestamp:o,timestampMs:s})}return n}async function rx(e,t){let n=await(0,T.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>ax(e,t+1))}async function ix(e,t,n){let r=Ub(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function ax(e,t){let n=dx(e),r=dx(n.message),i=fx(n.timestamp)??fx(r.timestamp)??fx(r.created_at)??fx(r.createdAt);return{line:t,raw:{...n,message:r},type:fx(n.type),timestamp:i,timestampMs:i?gx(i):void 0}}function ox(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=dx(e);if(fx(t.type)!==`tool_use`)continue;let r=dx(t.input),i=fx(r.command),a=fx(t.name)??`tool`,o=fx(r.description);n.push({id:fx(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function sx(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=dx(e);if(fx(t.type)!==`tool_result`)continue;let r=mx(fx(t.content)??fx(dx(t.toolUseResult).stdout)??fx(dx(t.tool_use_result).stdout)??fx(t.text));n.push({toolUseId:fx(t.tool_use_id)??fx(t.toolUseId),toolName:fx(t.tool_name)??fx(t.toolName),text:r,isError:t.is_error===!0})}return n}function cx(e){let t=fx(e.content);if(t)return mx(t);let n=fx(e.text)??fx(e.prompt);if(n)return mx(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=dx(e),n=fx(t.type);if(n&&n!==`text`)continue;let r=fx(t.text)??fx(t.content)??lx(t);r&&i.push(r)}if(i.length!==0)return mx(i.join(`
481
- `))}function lx(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=dx(e),r=fx(t.text)??fx(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function ux(e,t=60){if(!e)return;let n=hx(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 dx(e){return typeof e==`object`&&e?e:{}}function fx(e){return typeof e==`string`&&e.trim()||void 0}function px(e){if(typeof e==`string`)return mx(e)}function mx(e){if(!e)return;let t=hx(e).trim();return t.length>0?t:void 0}function hx(e){return e.replace(Rb,``)}function gx(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function _x(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.round(e)}function vx(e){if(e===void 0||!Number.isFinite(e))return;let t=Math.floor(e);return t>0?t:void 0}var yx=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}=xx(r,[t,n]);if(Sx(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=wx(await this.refreshProjects()),r=!0);let i=await Cx(n.projects,t);if(!i)throw s_(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=wx(await this.refreshProjects()),i=await Cx(n.projects,t),!i)throw s_(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 Ny({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 bx({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>Dx(e.cwd),mapSession:e=>{let t=Ox(e.createdAt),n=Ox(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:Dx(e.name)??Dx(e.preview),model:Dx(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 bx({sessions:await zb(),canonicalPathCache:e,getRawPath:e=>Dx(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:Dx(e.title),model:Dx(e.model),createdAt:Dx(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 bx(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 Tx(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function xx(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:Ex(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=kx(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(jx)})).sort((e,t)=>Ax(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function Sx(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Cx(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await mv(t);return e.find(e=>e.path===r)}function wx(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function Tx(e,t){let n=t.get(e);return n||(n=mv(e),t.set(e,n)),n}function Ex(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function Dx(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ox(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function kx(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function Ax(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 jx(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Mx=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 Nx(this.getProjectPath(e),Ix);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 Px(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 Px(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 Nx(this.indexPath,Fx)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Nx(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 Px(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 Fx(e){return!Lx(e)||e.v!==1||typeof e.generatedAt!=`string`||!Xa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Za.safeParse(e).success)}function Ix(e){return!Lx(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Za.safeParse(e.project).success||!Xa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Qa.safeParse(e).success)}function Lx(e){return typeof e==`object`&&!!e}const Rx=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function zx(e){let t=wo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=us(ps(Ux(i.export({format:`jwk`})))),o=es({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:To.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 Bx(e){let t=wo.parse(e.clientHello),n=To.parse(e.gatewayHello),r=Eo.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!mo.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([Rx,ds(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(ts({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,ds(r.signature)))throw Error(`transcript_invalid`)}function Vx(e){let t=To.parse(e.gatewayHello),n=Eo.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:fs(ds(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return is({role:`gateway`,keySchedule:rs({gatewayId:e.gatewayId,clientHello:wo.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function Hx(e){return Ao.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function Ux(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var Wx=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}},Gx=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??``);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;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e)}addMobileConnection(e,t,n,r){e&&(this.removeMobileConnection(e),this.mobileConnections.set(e,{mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}}),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(Zo.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){let t=this.mobileConnections.get(e);t&&(t.socket?.close(),t.clientId&&this.dependencies.sessionHub.removeClient(t.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){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let r=n,i=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>ua.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});i&&await this.dependencies.dispatchCommand(i,r.deviceId,r.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(Zo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...qx(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Zo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...qx(t,`auth.refresh`)})}}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:{...Kx(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status!==`ready`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>jo.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(a)try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(Zo.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=Po.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:Kx(`INTERNAL`,500,String(e)),method:a.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=zx({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(Zo.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{Bx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Jx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=Vx({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(Zo.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,Xx(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new Wx(t=>{try{let n=Zo.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,Yx(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:Hx({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:Kx(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 ls({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,Yx(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:cs({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},payload:n})}:{payload:n}}};function Kx(e,t,n){return Po.parse({code:e,status:t,message:n})}function qx(e,t){if(Yg(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`: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=Zx(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`||d_(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Jx(e){return Qx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function Yx(e){return Qx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function Xx(e){if(Yg(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=Zx(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 Zx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function Qx(e,t){let n=Zx(e);return t.find(e=>e===n)}function $x(e){return e?e.readyState:null}var eS=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??1e4,this.webSocketFactory=e.webSocketFactory??rS}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=$x(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=Zo.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=tS(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},`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:`e2ee-relay`,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=Zo.parse(JSON.parse(nS(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 tS(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 nS(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 rS(e){return new gv(e)}function iS(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(Qo(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function aS(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(oS(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(iS({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 Bo.parse(JSON.parse(r)).token}function oS(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 sS(e){return e?.trim()||void 0}function cS(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function lS(e,t){return{modeDefault:`default`,model:sS(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function uS(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function dS(e,t){let n=uS(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function fS(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function pS(e){let t=dS(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||sS(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?mS({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function mS(e){let t=dS(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?fS(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=dS(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=sS(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??sS(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:cS(r.execution)}}}const hS=[],gS=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],_S=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],vS=Ni.options,yS=[`read-only`,`workspace-write`,`danger-full-access`],bS=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],xS=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function SS(e){return e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt}function CS(e,t){xS&&(!e.startsWith(`config.get`)&&!e.startsWith(`raw-events`)&&!e.startsWith(`sync-external`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function wS(e){return e?{sessionFound:!0,sessionId:e.id,nativeSessionId:e.nativeSessionId??null,sessionSource:e.source??null,sessionModel:e.model??null,sessionUpdatedAt:e.updatedAt,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt??null,sessionTurnConfigModel:e.sessionTurnConfig?.model??null,sessionTurnConfigReasoningEffort:e.sessionTurnConfig?.reasoningEffort??null,sessionTurnConfigApprovalPolicy:e.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,sessionTurnConfigSandboxMode:e.sessionTurnConfig?.execution?.codex?.sandboxMode??null,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null,lastHydratedExternalConfigFreshnessAt:e.lastHydratedExternalConfigFreshnessAt??null}:{sessionFound:!1}}function TS(e,t){return e?.status===`running`?{status:`running`}:t?{status:`running`,interactionLockReason:`external_turn_running`}:{status:`idle`}}function ES(e){return e.status===`active`?!0:e.turns.some(e=>e.status===`inProgress`||e.status===`in_progress`)}function DS(e){return e.source===`native_discovered`?!0:e.providerMode===`native`&&(e.provider===`codex`||e.provider===`claude`)}const OS={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`}}]},kS={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function AS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function jS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function MS(e,t){let n=t?.trim().toLowerCase();return n?(OS[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function NS(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:_S}:{}},...e.map(e=>({...e,isDefault:!1}))]}function PS(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function FS(e){let t=new Set;for(let n of e){let e=PS(n);e&&t.add(e)}return[...t]}function IS(e){return e?.trim()||void 0}function LS(e){let t=IS(e.runtimeModel);if(t)return t;let n=IS(e.discoveredModel);if(n)return n;let r=IS(e.existingModel),i=IS(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function RS(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:FS(e.supportedReasoningEfforts)}));return t.length===0?hS:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function zS(e){let t=Date.now();try{let n=RS(await Iy());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 BS(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(ac(),`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=HS(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?FS(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 VS(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 HS(...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 US=class{sessions=new Map;providerCapabilitiesCache=new Map;providerCapabilitiesInFlight=new Map;nextRawSeqBySession=new Map;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.runtimeLifecycle={idleTtlMs:AS(e.runtimeLifecycle?.idleTtlMs,kS.idleTtlMs),sweepIntervalMs:jS(e.runtimeLifecycle?.sweepIntervalMs,kS.sweepIntervalMs),maxSessions:AS(e.runtimeLifecycle?.maxSessions,kS.maxSessions),maxCodexSessions:AS(e.runtimeLifecycle?.maxCodexSessions,kS.maxCodexSessions),maxClaudeSessions:AS(e.runtimeLifecycle?.maxClaudeSessions,kS.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 Rv(),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 a_(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.listAllSessionsWithRuntime(`running`).length;if(e>0)throw o_(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 zv(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.app_server.restart`,detail:{closedRuntimeSessionCount:t.length}}),{restarted:!0,closedRuntimeSessionCount:t.length}}async getProject(e){return this.options.projectStore.getById(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(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||this.shuttingDown)return;let e=OS.claude.length>0?OS.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw t_(t);let r=MS(e,n),i=r?.version??`default`,a=`${e}::${i}`,o={provider:e,projectId:t??null,requestedAgentVersion:n?.trim()||null,resolvedAgentVersion:i},s=Date.now(),c=this.providerCapabilitiesCache.get(a);if(c){if(c.expiresAt>s)return this.options.logger?.info?.({...o,cacheStatus:`hit`,source:c.value.capabilities.source,modelCount:c.value.capabilities.models.length},`provider capabilities cache hit`),c.value;this.providerCapabilitiesCache.delete(a)}let l=this.providerCapabilitiesInFlight.get(a);if(l)return this.options.logger?.info?.({...o,cacheStatus:`in_flight`},`provider capabilities awaiting in-flight load`),l;let u=Date.now(),d=(async()=>{let t=Ib(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=Date.now(),a=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1;this.options.logger?.info?.({...o,cacheStatus:`miss`,nativeAvailable:a,durationMs:Date.now()-n},`provider capabilities native availability checked`);let s=a?`native`:`fallback`,c=e===`codex`&&a?await zS(this.options.logger)??hS:hS,l=e===`claude`&&a?await BS(this.options.logger)??gS:gS,d=FS(l.flatMap(e=>e.supportedReasoningEfforts??[])),f=e===`codex`?{provider:e,source:s,models:c,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:_S,approvalPolicies:vS,sandboxModes:yS,permissionModes:[]},defaults:{model:c.find(e=>e.isDefault)?.id??c[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:s,models:l,support:{reasoningEffort:d.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:d,approvalPolicies:[],sandboxModes:[],permissionModes:bS},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:VS(l),permissionMode:`default`}};if(!r){let e={capabilities:f,resolvedAgentVersion:i};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:e.capabilities.source,modelCount:e.capabilities.models.length},`provider capabilities resolved`),e}let p={...f.defaults,...r.defaults},m=p.model?.trim(),h=s===`native`?f.models:m?NS(f.models,m,e):f.models,g={capabilities:{...f,models:h,defaults:p},resolvedAgentVersion:r.version};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:g.capabilities.source,modelCount:g.capabilities.models.length},`provider capabilities resolved`),g})();this.providerCapabilitiesInFlight.set(a,d);try{let e=await d;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}catch(e){throw this.options.logger?.warn?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,err:e},`provider capabilities resolution failed`),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return lS(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw t_(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=await this.syncCodexSessionsForProject(r),a=await 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)||n}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(CS(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:wS(n),runtime:wS(r)}),r)return CS(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...wS(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return CS(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...wS(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw t_(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 n_(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.syncExternalRawHistory(r,e,i),o=a.session??this.options.historyStore.getProjectSession(e,r.id)??r,s=hC(i,a.rawEvents);CS(`sync-external.classify`,mC({projectId:e,sessionId:t,session:o,previousEvents:i,nextEvents:a.rawEvents,classification:s}));let c=o.status!==r.status||(o.interactionLockReason??``)!==(r.interactionLockReason??``);return{session:o,rawEvents:a.rawEvents,historyUpdated:s.historyUpdated,statusChanged:c,refreshMode:s.refreshMode,fromRawSeq:s.fromRawSeq,toRawSeq:s.toRawSeq,nativeWatchPath:a.nativeWatchPath}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw t_(e);let i=0,a=0,o,s=(s,c)=>{CS(`raw-events.read`,{projectId:e,sessionId:t,limit:n,provider:o?.provider,source:o?.source,providerMode:o?.providerMode,localReadDurationMs:i,finalCount:a,outcome:s,totalDurationMs:Date.now()-r,...c})},c=this.options.historyStore.getProjectSession(e,t);if(!c&&this.getRuntimeSessionSummary(e,t))return s(`runtime_session_empty`),[];if(!c)throw n_(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEvents(c.id,Math.max(n,300));return i=Date.now()-l,a=u.slice(-Math.max(1,n)).length,s(`local_only_cached`,{localEventCount:u.length}),u.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompacted(r.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3){let i=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsSinceSeq(i.id,n,r)}async getProjectSessionRawSeqRange(e,t){let n=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawSeqRange(n.id)}async resolveProjectSessionForRawRead(e,t){if(!await this.options.projectStore.getById(e))throw t_(e);let n=this.options.historyStore.getProjectSession(e,t);if(!n)throw n_(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${_g(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=Ib(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?dS(e.provider,e.sessionTurnConfig):pS({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=mS({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw i_(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(i?.interactionLockReason===`external_turn_running`)throw i_(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 i_(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&DS(i))throw i_(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??await this.resumeSessionFromHistory(e);if(!o)throw r_(e);let s=await this.getProviderDefaults(o.provider,o.projectId),c=mS({provider:o.provider,providerDefaults:s,currentSessionTurnConfig:o.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});o.dispatchInFlight=!0,this.touchSession(o);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:c.model,sessionConfig:r?.sessionConfig,mode:c.mode,config:r?.config,resolvedSessionConfig:c.sessionConfig}}),this.options.historyStore.getSession(o.id)||await this.persistSessionSnapshot(o),await o.providerSession.sendInput(t,{model:c.model,sessionConfig:c.sessionConfig,mode:c.mode}),!o.title){let e=SC(t);e&&this.setSessionTitle(o,e)}let i=new Date().toISOString();o.sessionTurnConfig=dS(o.provider,c.sessionTurnConfig),o.sessionTurnConfigUpdatedAt=i,c.model&&o.model!==c.model&&(o.model=c.model),o.updatedAt=i,await this.persistSessionSnapshot(o)}finally{o.dispatchInFlight=!1,this.touchSession(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:wC(n)}})}async interruptSession(e,t){let n=this.sessions.get(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}})}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 r_(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_${_g(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=Ib(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=dS(t.provider,t.sessionTurnConfig),o=mS({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}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 My(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=TC(t.createdAt),s=TC(t.updatedAt),l=TS(i,ES(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:LS({runtimeModel:i?.model,discoveredModel:t.model,existingModel:n?.model,modelProvider:t.modelProvider}),title:i?.title??SC(t.name??t.preview)??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??a,updatedAt:u===`running`?i?.updatedAt??s:s,status:u,interactionLockReason:l.interactionLockReason,pendingApprovals:d,pendingUserInputs:f,pendingActions:d+f};await this.options.historyStore.upsertSession(p),o.set(r,p),c+=1}let l={provider:`codex`,status:`ok`,discoveredCount:r.filter(t=>t.cwd===e.path).length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxThreads:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async syncClaudeSessionsForProject(e){let t=Date.now();if(!this.options.preferNativeProviders)return{provider:`claude`,status:`disabled`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:0,applyDurationMs:0,totalDurationMs:Date.now()-t};let n=Date.now(),r,i=Date.now()-14400*60*1e3;try{r=await Bb(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=TS(i,t.status===`running`),s=a.status,l=s===`running`?i?.pendingToolApprovals.size??0:0,u=s===`running`?i?.pendingUserInputs.size??0:0,d={id:r,nativeSessionId:t.nativeSessionId,source:n?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:i?.providerMode??n?.providerMode??`native`,model:i?.model??n?.model??t.model,title:i?.title??t.title??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??t.createdAt,updatedAt:s===`running`?i?.updatedAt??t.updatedAt:t.updatedAt,status:s,interactionLockReason:a.interactionLockReason,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),o.set(r,d),c+=1}let l={provider:`claude`,status:`ok`,discoveredCount:r.length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxSessions:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=SS(e),n=oC([e.nativeSessionId,e.id]);for(let r of n)try{CS(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:r,...wS(e)});let n=await Fy(r);if(!n){CS(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:r});continue}let i={...e,model:IS(n.model)??e.model,sessionTurnConfig:n.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:n.sessionTurnConfigUpdatedAt,...t?{lastHydratedExternalConfigFreshnessAt:t}:{}};return await this.options.historyStore.upsertSession(i),CS(`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:wS(i)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??i}catch(t){CS(`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`||e.source!==`native_discovered`||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=SS(e),n=e.sessionTurnConfigUpdatedAt||``;if(!e.sessionTurnConfig||!IS(e.model)||!n)return!0;if(!t)return!1;let r=e.lastHydratedExternalConfigFreshnessAt;return r?t.localeCompare(r)>0:!0}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw t_(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await EC(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw t_(e);return await EC(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=CC(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=CC(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e);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_${_g(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();try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}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_${_g(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n)return t;let r=await this.options.historyStore.mergeSessionRawEvents(e.id,t),i=r[r.length-1]?.rawSeq;return typeof i==`number`&&Number.isFinite(i)&&i>0&&this.nextRawSeqBySession.set(e.id,i+1),r}async syncExternalRawHistory(e,t,n){if(e.provider===`claude`){let r=cC(e);if(!r)return{rawEvents:n};try{let i=Date.now(),a=await Vb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t}),o=Date.now(),s=await this.finalizeExternalRawHistorySync(e,n,a.rawEvents,a.updatedAt),c=await this.patchObservedExternalSessionSummary(e,{updatedAt:a.updatedAt,externallyRunning:a.status===`running`});return CS(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,historyEventCount:a.rawEvents.length,resultEventCount:s.length,readHistoryDurationMs:o-i,finalizeDurationMs:Date.now()-o}),{rawEvents:s,session:c}}catch(r){return e.source===`native_discovered`&&sC(r)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),CS(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,error:r instanceof Error?r.message:String(r)}),{rawEvents:n}}}if(e.provider!==`codex`)return{rawEvents:n};let r=oC([e.nativeSessionId,e.id]);for(let i of r)try{let r=Date.now(),a=await Py(i,!0),o=Date.now(),s=e.source===`gateway`&&n.length>0?vC({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):gC({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localTerminalTurnStatusById:_C(n)}),c=Date.now(),l=await this.finalizeExternalRawHistorySync(e,n,s,TC(a.updatedAt)),u=await this.patchObservedExternalSessionSummary(e,{updatedAt:TC(a.updatedAt),externallyRunning:ES(a)});return CS(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,threadStatus:a.status,threadUpdatedAt:TC(a.updatedAt),threadTurnCount:a.turns.length,threadTurns:a.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:ES(a),localEventCount:n.length,historyEventCount:s.length,resultEventCount:l.length,readThreadDurationMs:o-r,buildHistoryDurationMs:c-o,finalizeDurationMs:Date.now()-c}),{rawEvents:l,session:u,nativeWatchPath:a.path??void 0}}catch(r){CS(`sync-external.codex.read.error`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,localEventCount:n.length,error:r instanceof Error?r.message:String(r)})}return CS(`sync-external.codex.read.exhausted`,{projectId:t,sessionId:e.id,source:e.source,attemptedThreadIds:r,localEventCount:n.length}),{rawEvents:n}}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt){let i=Date.now(),a=GS(e.provider,t,n),o=Date.now(),s=await this.maybePersistSyncedExternalRawEvents(e,a,!0);return await this.markExternalHistoryHydrated(e.id,r),CS(`sync-external.finalize`,{sessionId:e.id,provider:e.provider,source:e.source,localEventCount:t.length,historyEventCount:n.length,mergedEventCount:a.length,persistedEventCount:s.length,hydratedExternalUpdatedAt:r,mergeDurationMs:o-i,persistDurationMs:Date.now()-o}),s}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=TS(r,t.externallyRunning),a=i.status===`running`?r?.pendingToolApprovals.size??0:0,o=i.status===`running`?r?.pendingUserInputs.size??0:0,s={...n,updatedAt:i.status===`running`?r?.updatedAt??t.updatedAt:t.updatedAt,status:i.status,interactionLockReason:i.interactionLockReason,pendingApprovals:a,pendingUserInputs:o,pendingActions:a+o};return await this.options.historyStore.upsertSession(s),this.options.historyStore.getSession(e.id)??s}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw r_(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,interactionLockReason:void 0,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=xC(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 WS=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function GS(e,t,n){if(e!==`codex`){let r=new Map,i=new Set,a=JS(e),o=JS(e);for(let n of t){r.set(n.eventId,n);for(let t of YS(e,n,a))i.add(t)}for(let t of n){let n=YS(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))}if(t.length===0)return n.slice().sort((e,t)=>e.ts.localeCompare(t.ts));let r=t.slice(),i=new Map,a=new Map,o=new Set,s=JS(e),c=JS(e),l=KS(t)??KS(n)??Date.now();for(let[t,n]of r.entries()){i.set(n.eventId,n),a.set(n.eventId,t);for(let t of YS(e,n,s))o.add(t)}for(let t of n){let n=YS(e,t,c);if(!i.has(t.eventId)&&n.length>0&&n.every(e=>o.has(e)))continue;let s=i.get(t.eventId);if(s){let e=qS(s,t);i.set(t.eventId,e);let n=a.get(t.eventId);n!==void 0&&(r[n]=e)}else{l+=1;let e={...t,ts:new Date(l).toISOString()};i.set(e.eventId,e),a.set(e.eventId,r.length),r.push(e)}for(let e of n)o.add(e)}return r}function KS(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 qS(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function JS(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function YS(e,t,n){return e===`codex`?XS(t,n):e===`claude`?$S(t):[]}function XS(e,t){let n=nC(e.payload.raw),r=new Set,i=eC(e.type,n);if(i){let a=ZS(e.type,n);a?r.add(QS(a,t)):r.add(i)}if(e.type!==`native.raw`||$(n.source)!==`codex.history.thread_read`)return[...r];let a=nC(n.message),o=$(a.scope);if(o===`thread`){let e=nC(a.thread),t=$(e.id);t&&r.add(tC(`thread.started`,{thread_id:t,thread:e}));let n=SC(rC(e.preview)??rC(e.name)??``);return n&&r.add(tC(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(o===`turn`){let e=nC(a.turn),t=$(e.status);return r.add(tC(`turn.started`,{turn:e})),t===`completed`?r.add(tC(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(tC(`turn.failed`,{status:t,turn:e})),[...r]}if(o===`item`){let e={turn_id:$(a.turn_id)??$(nC(a.item).turn_id),item:nC(a.item)},n=ZS(`item.completed`,e);return n?r.add(QS(n,t)):r.add(tC(`item.completed`,e)),[...r]}return[...r]}function ZS(e,t){if(!e.startsWith(`item.`))return;let n=nC(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=$(n.type);if(!(!r||!i))return[`codex`,e,r,i,$(n.phase)??``,$(n.status)??``,$(n.command)??``,iC(n)??``].join(`|`)}function QS(e,t){let n=t?.codexTurnScopedItemOccurrences;if(!n)return e;let r=(n.get(e)??0)+1;return n.set(e,r),`${e}|${r}`}function $S(e){let t=nC(e.payload.raw),n=eC(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!WS.has(r))return[];let i=nC(t.message),a=$(t.native_type)??$(i.type),o=nC(i.message);if(a===`user`){let e=aC(o),t=$(i.uuid);return!e||!t?[]:[tC(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=aC(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[tC(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function eC(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 tC(e,t);default:return}}function tC(e,t){let n=nC(t.item),r=nC(t.turn),i=nC(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=$(n.command)??``,p=iC(n),m=rC(t.message)??``,h=rC(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 nC(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function rC(e){if(typeof e==`string`)return e.length>0?e:void 0}function iC(e){let t=rC(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=rC(nC(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
482
- `)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>rC(e)).filter(e=>!!e);if(e.length>0)return e.join(`
483
- `)}return``}function aC(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=nC(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(`
484
- `)}function oC(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function sC(e){return String(e).includes(`returned no messages from getSessionMessages`)}function cC(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function lC(e){return e?{rawSeq:e.rawSeq,type:e.type,eventId:e.eventId,ts:e.ts}:null}function uC(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(!dC(n,i))return r}return e.length===t.length?null:n}function dC(e,t){return JSON.stringify(fC(e))===JSON.stringify(fC(t))}function fC(e){let{ts:t,...n}=e;return n}function pC(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 mC(e){let t=e.previousEvents[e.previousEvents.length-1]?.rawSeq??null,n=e.nextEvents[e.nextEvents.length-1]?.rawSeq??null,r=uC(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:pC(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:lC(r===null?void 0:e.previousEvents[r]),nextMismatchEvent:lC(r===null?void 0:e.nextEvents[r])}}function hC(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&&dC(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&&dC(e,r)})?{historyUpdated:!0,refreshMode:`delta`,fromRawSeq:n??0,toRawSeq:r??n??0}:{historyUpdated:!0,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}}function gC(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=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),o=t=>{let n=t.map(a).filter(e=>e.length>0);return n.length===0?`raw_hist_codex_${e.sessionId}_${r.toString().padStart(6,`0`)}`:`raw_hist_codex_${e.sessionId}_${n.join(`_`)}`},s=(n,r)=>{let a=t.length+1;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:o(r),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};s({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.localTerminalTurnStatusById?.get(t.id);bC(n,t.status)||s({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)s({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,CC(n.id)??null])}return t}function _C(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=nC(n.payload.raw);if(n.type===`turn.completed`||n.type===`turn.failed`){let r=$(e.turn_id)??$(e.turnId)??$(nC(e.turn).id)??$(nC(e.item).turn_id)??$(nC(e.item).turnId),i=$(e.status)??(n.type===`turn.completed`?`completed`:`failed`);r&&t.set(r,i);continue}if(n.type!==`native.raw`||$(e.source)!==`codex.history.thread_read`)continue;let r=nC(e.message);if($(r.scope)===`turn`){let e=nC(r.turn),n=$(e.id),i=$(e.status);n&&i&&yC(i)&&t.set(n,i)}}return t}function vC(e){let t=new Set,n=new Set,r=new Map,i=0,a=1;for(let o of e.localEvents){let e=Date.parse(o.ts);Number.isFinite(e)&&(i=Math.max(i,e)),a=Math.max(a,o.rawSeq+1);let s=nC(o.payload.raw),c=$(s.source),l=c===`codex.history.thread_read.incremental`;if(o.type===`item.started`||o.type===`item.updated`||o.type===`item.completed`){if(o.type===`item.completed`){let e=$(nC(s.item).id);e&&!l&&n.add(e)}}else if(o.type===`turn.started`){let e=$(s.turn_id)??$(nC(s.turn).id);e&&!l&&t.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=$(s.turn_id)??$(nC(s.turn).id);if(!e)continue;l||t.add(e);let n=$(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||c!==`codex.history.thread_read`)continue;let u=nC(s.message);if($(u.scope)===`turn`){let e=nC(u.turn),t=$(e.id);if(!t)continue;let n=$(e.status);n&&yC(n)&&r.set(t,n);continue}}let o=Math.max(i,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),s=0,c=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),l=t=>{let n=t.map(c).filter(e=>e.length>0);return n.length===0?`raw_sync_codex_${e.sessionId}_${a.toString().padStart(6,`0`)}`:`raw_sync_codex_${e.sessionId}_${n.join(`_`)}`},u=()=>(s+=1,new Date(o+s).toISOString()),d=[],f=(t,n,r)=>{let i=u();d.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:l(r),ts:i,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),a+=1};for(let i of e.thread.turns){let e=r.get(i.id),o=bC(e,i.status);!t.has(i.id)&&!o&&f(`turn.started`,{type:`turn.started`,turn:{id:i.id,status:i.status,items:[],error:i.error}},[`turn_started`,i.id]);for(let e of i.items){let t=$(e.id);t&&n.has(t)||f(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e},[`item_completed`,i.id,t??`seq_${a}`])}if(yC(i.status)&&e!==i.status){if(i.status===`completed`){f(`turn.completed`,{type:`turn.completed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error}},[`turn_terminal`,i.id]);continue}f(`turn.failed`,{type:`turn.failed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error},...i.error?{error:i.error}:{}},[`turn_terminal`,i.id])}}return d}function yC(e){return e===`completed`||e===`failed`||e===`interrupted`}function bC(e,t){return e===t&&yC(t)}function xC(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function SC(e,t=60){let n=xC(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function CC(e){if(typeof e!=`string`)return;let t=xC(e);if(t)return t}function wC(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function TC(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function EC(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var DC=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=this.sessions.get(e.id);this.sessions.set(e.id,{...t,...e}),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,{...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,this.sessions.has(e.sessionId)&&await this.enqueueRawSessionWrite(e.sessionId,async()=>{if(RC(e)){let t=Ns([...await this.readSessionRawEventsLocked(e.sessionId),e]);await this.replaceRawEventFile(e.sessionId,t),this.rawEventsCacheBySession.set(e.sessionId,t),this.compactedRawEventsCacheBySession.set(e.sessionId,NC(t));return}await this.appendRawEventLine(e),this.appendRawEventToCache(e)})}async mergeSessionRawEvents(e,t){if(await this.ready,!this.sessions.has(e))return[];let n=t.filter(t=>t.sessionId===e),r=[];return await this.enqueueRawSessionWrite(e,async()=>{r=zC(await this.readSessionRawEventsLocked(e),n),await this.replaceRawEventFile(e,r),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.set(e,NC(r))}),r}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionRawEventsCompacted(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsCompactedFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),i}async getSessionRawEventsSinceSeq(e,t,n=2e3){if(await this.ready,!this.sessions.has(e))return[];let r=Math.max(1,n),i=this.readSessionRawEventsFromCache(e);if(i!==void 0)return Ns(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=Ns((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 jC(t);let n=null;return await this.enqueueWrite(async()=>{n=jC(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)e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath&&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=`${AC(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=>AC(e)).join(`
485
- `);await MC(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(LC(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&IC(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}FC(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return PC(t);let n=NC(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),PC(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(`
486
- `).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!OC(t)||t.kind!==`provider.raw`)continue;let n=kC(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 e of s){let t=ma.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>AC(e)).join(`
487
- `),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return PC(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=NC(n);return this.compactedRawEventsCacheBySession.set(e,r),PC(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 OC(e){return typeof e==`object`&&!!e}function kC(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function AC(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 jC(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function MC(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 NC(e){let t=Ms(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ps(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function PC(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function FC(e,t){let n=Ps(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=Fs(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 IC(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function LC(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=OC(e.payload.raw)?e.payload.raw:{},n=OC(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function RC(e){return LC(e)}function zC(e,t){let n=new Map;for(let t of e)n.set(t.eventId,t);for(let e of t)n.set(e.eventId,e);return Ns([...n.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n})).map((e,t)=>({...e,rawSeq:t+1}))}var BC=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${_g(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()]}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.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);if(!(!i||i.socket.readyState!==i.socket.OPEN)){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),i.socket.send(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].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}i.socket.send(JSON.stringify(e))}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendBroadcastMessage(e,t){let n=JSON.stringify(e);for(let e of this.clients.values())if(e.socket.readyState===e.socket.OPEN){if(t?.sessionId){let n=e.subscriptionsBySessionId.get(t.sessionId);if(!n||t.purpose&&n.purpose!==t.purpose)continue}e.socket.send(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}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)}};const VC=1200,HC=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var UC=class{statesByKey=new Map;targetsByClientId=new Map;constructor(e){this.options=e}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){HC&&(console.log(`[native-watch][gateway]`,e,t),this.options.logger.info?.({event:e,...t},`native session watch debug`))}addClientToState(e,t,n){if(!t||!n)return;let r=this.stateKey(t,n),i=this.statesByKey.get(r);i||(i={provider:`codex`,sessionId:n,projectId:t,ownerClientIds:new Set,fileWatcher:null,debounceTimer:null,catchupRetryTimer:null,reconcileTimer:setInterval(()=>{this.requestSync(r,`reconcile`)},25e3),syncInFlight:!1,rerunRequested:!1,stableIdleSyncCount:0,watchCatchupRetryCount:0,lastObservedRawSeq:0,lastObservedRawEventCount:0,lastTriggeredAt:0,lastSyncStartedAt:null,lastSyncCompletedAt:null},this.statesByKey.set(r,i),this.logDebug(`state.created`,{clientId:e,projectId:t,sessionId:n})),i.ownerClientIds.add(e),this.logDebug(`lease.added`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:i.ownerClientIds.size}),this.requestSync(r,`lease_added`)}removeClientFromState(e,t,n){let r=this.statesByKey.get(this.stateKey(t,n));r&&(r.ownerClientIds.delete(e),this.logDebug(`lease.removed`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:r.ownerClientIds.size}),!(r.ownerClientIds.size>0)&&(this.disposeState(r),this.statesByKey.delete(this.stateKey(t,n))))}disposeState(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null),this.clearCatchupRetry(e,{resetAttempts:!0}),clearInterval(e.reconcileTimer),e.fileWatcher?.close(),e.fileWatcher=null,this.logDebug(`state.disposed`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:e.watchedPath})}async requestSync(e,t){let n=this.statesByKey.get(e);if(n){if(n.lastTriggeredAt=Date.now(),n.syncInFlight){n.rerunRequested=!0;return}n.syncInFlight=!0,n.rerunRequested=!1,n.lastSyncStartedAt=Date.now(),this.logDebug(`sync.begin`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,ownerClientCount:n.ownerClientIds.size,watchedPath:n.watchedPath,watchedDir:n.watchedDir,watchedBaseName:n.watchedBaseName,stableIdleSyncCount:n.stableIdleSyncCount});try{let r=await this.options.sessionManager.getProjectSessionSummary(n.projectId,n.sessionId);if(!r||r.provider!==`codex`||r.providerMode!==`native`){this.logDebug(`sync.stop.unwatchable_summary`,{projectId:n.projectId,sessionId:n.sessionId,summaryProvider:r?.provider,summaryProviderMode:r?.providerMode,summaryStatus:r?.status}),this.stopState(e);return}let i=await this.options.sessionManager.syncProjectSessionHistory(n.projectId,n.sessionId);n.lastSyncCompletedAt=Date.now(),this.applyWatchPath(n,i.nativeWatchPath);let a=n.lastObservedRawSeq,o=n.lastObservedRawEventCount,s=this.resolveObservedRawSeq(i),c=s>a||i.rawEvents.length>o;if(c?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,s),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),i.session.status!==`running`&&!i.historyUpdated?n.stableIdleSyncCount+=1:n.stableIdleSyncCount=0,this.logDebug(`sync.result`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,status:i.session.status,interactionLockReason:i.session.interactionLockReason,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,nativeWatchPath:i.nativeWatchPath,rawEventCount:i.rawEvents.length,cursorAdvanced:c,previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount}),i.historyUpdated||i.statusChanged){let e=this.options.createExternalUpdateMessage({provider:i.session.provider,sessionId:i.session.id,projectId:i.session.projectId,updatedAt:i.session.updatedAt,status:i.session.status,interactionLockReason:i.session.interactionLockReason,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e)}}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:VC,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`)},VC))))}stateKey(e,t){return`${e}::${t}`}};function WC(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}))}const GC=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`,KC=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function qC(e,t){GC&&console.log(`[native-watch][gateway]`,e,t)}function JC(e,t){KC&&console.log(`[session-fetch][gateway] ${e}`,t)}async function YC(e){let t=e.limit??300,n=(n,r)=>{JC(`raw-events.list`,{requestSource:e.requestSource,projectId:e.projectId,sessionId:e.sessionId,limit:t,requestedCursor:e.fromRawSeqExclusive??null,decision:n.decision,reason:n.reason,fromRawSeqExclusive:n.fromRawSeqExclusive??null,toRawSeq:n.toRawSeq??null,returnedCount:n.events.length,returnedFirstRawSeq:n.events[0]?.rawSeq??null,returnedLastRawSeq:n.events[n.events.length-1]?.rawSeq??null,...r})};if(e.fromRawSeqExclusive===void 0){let r=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),i={decision:`snapshot`,reason:r.length===0?`empty_history_snapshot`:`initial_snapshot`,events:r};return n(i),i}let r=await e.sessionManager.getProjectSessionRawSeqRange(e.projectId,e.sessionId);if(!r){let e={decision:`snapshot`,reason:`empty_history_snapshot`,events:[]};return n(e,{rangeMin:null,rangeMax:null,minExpectedCursor:null}),e}let i=Math.max(0,r.min-1);if(e.fromRawSeqExclusive<i||e.fromRawSeqExclusive>r.max){let a={decision:`snapshot`,reason:`cursor_out_of_range`,events:await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t)};return n(a,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),a}let a=await e.sessionManager.getProjectSessionRawEventsSinceSeq(e.projectId,e.sessionId,e.fromRawSeqExclusive,t),o={decision:`delta`,reason:`cursor_valid_delta`,fromRawSeqExclusive:e.fromRawSeqExclusive,toRawSeq:a[a.length-1]?.rawSeq??e.fromRawSeqExclusive,events:a};return n(o,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),o}async function XC(e,t={}){await au(e.gatewayLogPath);let n=QC(e,t),r=ZC(e,n.instance);await r.register(fg.default,{origin:!0}),await r.register(dg.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new f_(e);await s.init();let c=new v_(e.auditLogPath),l=new BC,u=new rv,d=new fv(e.projectStoreDir),f=new DC(e.sessionHistoryDir);await f.init();let m=new Mx(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new yx({store:m});await h.init();let g,_=null,v=await Xs(e.authStoreDir),y=new US({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}}),b=new UC({sessionManager:y,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>N(e)});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let x=new wl({packageName:P.packageName,currentVersion:P.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>(await y.listProjects()).reduce((e,t)=>e+(t.runningCount??0),0),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{b.close(),_?.close(),S.close(),await x.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:re(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:sl(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>nl({gatewayId:e.gatewayId,machineName:sl(),relayBaseUrl:e.relayEnabled?hl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:pl({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ne(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(e,t)=>{let n=Ca.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=he(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),cw(v,t,n.data.code,n.data.deviceIdentity)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=Ea.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await tw({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)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await x.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Na.safeParse(n?.requestedBy);try{let e=await x.applyUpdate(r.success?r.data:`mobile`);return Ra.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(L(e,t))try{return ka.parse(await y.restartCodexAppServer())}catch(e){let n=Yg(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(L(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(L(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(!L(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 Yg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):fw(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(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.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Yg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Yg(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(!L(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 y.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(!L(e,t))return;let n=e.params;try{return await y.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(!L(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 y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Yg(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(!L(e,t))return;let n=e.params,r=await y.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(!L(e,t))return;let n=e.params,r=await y.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(!L(e,t))return;let n=e.params;try{let e=await y.syncProjectSessionHistory(n.projectId,n.sessionId);return{session:e.session,rawEventCount:e.rawEvents.length}}catch(e){return Yg(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(!L(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;try{return await te(n.projectId,n.sessionId,i,typeof a==`number`&&Number.isFinite(a)?Math.max(0,Math.floor(a)):void 0,`http`)}catch(e){return Yg(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(!L(e,t))return;let n=e.params,r=e.query,i=await y.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)=>ne(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ne(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 r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.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 w(da(e),r.sub,i)}catch(e){await T({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{b.removeClient(i),l.removeClient(i)})});let S=new Gx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=he(e.deviceName);return cw(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await tw({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return ew(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>ow(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:x,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await w(e,t,n)}catch(r){await T({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),C=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.external.watch.set`:{qC(`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=b.setClientWatchTargets(n,e.payload.sessions,e.payload.replace);qC(`command.applied`,{clientId:n,deviceId:t,replace:e.payload.replace,targetCount:i.length,targets:i}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,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=WC(e.payload.sessions);await E(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=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.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=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.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)}`)}}},w=async(e,t,n)=>{await C(e,t,n)},T=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 y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},E=async(e,t,n)=>{let r=D(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await O(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},D=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},O=async(e,t)=>{let n=await k(t);if(t.cursor.kind===`all`){await A(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await A(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await A(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,M({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},k=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw n_(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},A=async(e,t,n)=>{let r=`snap_${_g(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=j(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,ee({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},j=(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},M=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${_g(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),ee=e=>({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}}}),N=e=>({v:`1.0`,kind:`session.external.update`,type:`session.external.update`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`session_external_update_${_g(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}}}),te=async(e,t,n=300,r,i=`http`)=>YC({sessionManager:y,projectId:e,sessionId:t,limit:n,fromRawSeqExclusive:r,requestSource:i}),ne=t=>t.headers[`x-api-key`]===e.apiKey,re=e=>{if(e==null)return e;if(typeof e==`string`){let t=F(e);return t===void 0?ie(e,a):ae(I(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=F(t);return n===void 0?ie(t,a):ae(I(n))}return typeof e==`object`?ae(I(e)):String(e)},F=e=>{try{return JSON.parse(e)}catch{return}},ie=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,I=e=>{if(Array.isArray(e))return e.map(e=>I(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]=I(r)}return n}return e},ae=e=>{let t=oe(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ie(t,a)}},oe=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(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}},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=ji.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=sl(),he=e=>e?.trim()||me||`Gateway`;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},$C(pe,e.host,_e)),e.relayEnabled&&(_=new eS({gatewayId:e.gatewayId,machineName:me,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>aS({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:pl({protocol:pe,host:e.host,port:_e}),logger:r.log,onFrame:async e=>{await S.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 x.start(),{protocol:pe,listenPort:_e,machineName:me,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>x.getInfo(),requestGatewayUpdate:(e=`console`)=>x.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function ZC(e,t){let n=t;if(!e.httpsEnabled)return(0,pg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,pg.default)({disableRequestLogging:!0,loggerInstance:n,https:{key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}}})}function QC(e,t){let n=process.env.NODE_ENV!==`production`,r=qg.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?qg.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,qg.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function $C(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function ew(e,t){if(e&&e!==t)throw e_()}async function tw(e){let t=nw(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:rw(t)},`auth refresh attempt`);try{let t=await e.execute(),n=nw(e.authService,e.refreshToken),r=nw(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:rw(n),nextRefreshToken:rw(r)},`auth refresh succeeded`),t}catch(t){let n=nw(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:rw(n),error:iw(t)},`auth refresh failed`),t}}function nw(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function rw(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:aw(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:aw(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function iw(e){return Yg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function aw(e){return e?e.slice(-8):null}async function ow(e,t){try{let n=jo.parse(e);switch(n.method){case`auth.refresh`:{let e=await tw({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 ew(n.params.deviceId??t.relayDeviceId,e.deviceId),Mo.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Mo.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Mo.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return Mo.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Mo.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Mo.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Mo.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Mo.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw uw(n.method,`NOT_FOUND`,404,`Project not found`);return Mo.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 Mo.parse({method:n.method,result:e})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return Mo.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Mo.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw uw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Mo.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 uw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Mo.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return Mo.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=n.params.limit===`all`?2**53-1:n.params.limit,r=await YC({sessionManager:t.sessionManager,projectId:n.params.projectId,sessionId:n.params.sessionId,limit:e,fromRawSeqExclusive:n.params.fromRawSeqExclusive,requestSource:`rpc`});return Mo.parse({method:n.method,result:r})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),Mo.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Mo.parse({method:n.method,result:e})}case`devices.list`:return Mo.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw uw(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Mo.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw uw(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw sw(e)}}function sw(e){if(Yg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return uw(`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`:return uw(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return uw(`BAD_REQUEST`,e.status,String(e),e.details);default:return uw(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Po.safeParse(e);if(t.success)return t.data;let n=No.safeParse(e);if(n.success)return uw(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 uw(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?uw(`BAD_REQUEST`,400,r):dw(e)?uw(`UNAUTHORIZED`,401,r):fw(r)?uw(`BAD_REQUEST`,400,r):uw(`INTERNAL`,500,r)}function cw(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:lw(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:$s(e.identity,e.privateKeyPem,i)}}function lw(e){return e.replace(/\s+/gu,``).toUpperCase()}function uw(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 Po.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function dw(e){return Yg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||d_(e)}function fw(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 pw(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function mw(e){let t=await cc({configPath:e.configPath,ensureConfigFile:!0});fc(t.config);let n=await XC(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{gw({type:`worker.update.prepared`,payload:e})}});gw({type:`worker.ready`,payload:hw(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=_w(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: ${pw(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${pw(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);gw({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);gw({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){gw({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function hw(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function gw(e){process.send&&process.send(e)}function _w(e){if(!vw(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 vw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}yw(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function yw(e){let t=ne(e);switch(t.command){case`help`:ww();return;case`version`:console.log(P.version);return;case`init`:await xw(t);return;case`doctor`:await Sw(t);return;case`start`:await bw(t);return;case`__worker`:await Cw(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function bw(e){let t=await cc({configPath:e.configPath,ensureConfigFile:!0});fc(t.config);let n=await Ac({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await Zl({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(ou(e,t.config))}jc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function xw(e){let t=await sc({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 cc({configPath:t.configPath,ensureConfigFile:!1}),r=await Ac({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Mc(r))}async function Sw(e){let t=await cc({configPath:oc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Ac({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Mc(n)),jc(n)&&(process.exitCode=1)}async function Cw(e){try{await mw(e)}catch(t){let n=await cc({configPath:e.configPath,ensureConfigFile:!0});throw Error(ou(t,n.config))}}function ww(){console.log(`${P.cliName} ${P.version}`),console.log(``),console.log(`Usage:`),console.log(` ${P.cliName} [start] [--config <path>] [--log]`),console.log(` ${P.cliName} init [--config <path>] [--force]`),console.log(` ${P.cliName} doctor [--config <path>]`),console.log(` ${P.cliName} --version`)}exports.runCli=yw;
476
+ `);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},uy=3,dy=250;function fy(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function py(e,t){let n=Math.max(1,t?.maxAttempts??uy),r=Math.max(0,t?.retryDelayMs??dy),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!fy(e)||t>=n)throw e;r>0&&await my(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function my(e){return new Promise(t=>{setTimeout(t,e)})}function hy(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function gy(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var _y=3e4,vy=8,yy=160,by={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},xy=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await Vv(),n.requestTimeoutMs??_y);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0;try{let n=t?.model??this.activeModel,r=hy(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=Ay(this.activeSessionConfig.reasoningEffort),o,s=jy(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&My(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:jy(t?.mode,n,`low`)})}let c=Q(o.turn?.id);c&&(this.activeTurnId=c)}catch(e){throw this.turnInProgress=!1,e}}async interrupt(){if(this.ensureOpen(),!this.threadId||!this.activeTurnId)return;let e={threadId:this.threadId,turnId:this.activeTurnId};await this.sendRequest(`turn/interrupt`,e)}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=Py(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:gy(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:by,capabilities:{experimentalApi:!0,optOutNotificationMethods:jv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return Q((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return Q((await py(()=>this.sendRequest(`thread/resume`,i))).thread?.id)}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0;for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:Dy(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=Q(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=Av(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=kv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=kv(r),a=Q(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${_g(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:Q(i.reason),threadId:a,turnId:Q(i.turnId),itemId:Q(i.itemId),approvalMethod:t,rawParams:Dv(i)})}registerUserInputRequest(e,t,n){let r=Q(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${_g(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(Ny).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:Dv(n)})}handleNotification(e){switch(e.method){case`thread/started`:{let t=e.params,n=Q(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:Dv(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Q(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.emit({type:`turn.started`,turn:Dv(t.turn)});return}case`turn/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.status);if(this.turnInProgress=!1,this.activeTurnId=void 0,n===`failed`){this.emit({type:`turn.failed`,status:n,turn:Dv(t.turn),error:Dv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:Dv(t.turn)}),this.tryEmitTitleFromThreadRead();return}case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.started`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:Tv(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.completed`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:Tv(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=kv(e.params);if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:Q(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Q(t.delta)??Q(t.text)??``,original_method:e.method,payload:Dv(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`error`,message:Q(t.error?.message)??`Codex app-server error`,error:Dv(t.error),will_retry:t.willRetry===!0,thread_id:Q(t.threadId),turn_id:Q(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=Av(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=Sy(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated(Q(e.thread?.name)??Q(e.thread?.preview),Q(e.thread?.name)?`codex.thread_read_name`:`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleConnectionFailure(e){if(this.closed)return;let t=Oy(e),n=ky(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(Av(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Q(kv(e.params).threadId)}extractThreadIdFromNotification(e){let t=kv(e.params);return Q(t.threadId)||Q(kv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Q(kv(kv(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(Cy({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(Cy({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>vy&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-vy)}};function Sy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function Cy(e){let t=Q(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=kv(e.message.error),i=Ty(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:wy(t,n,e.direction),method:t,requestId:n?Av(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??Dy(Q(r.message))}}function wy(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function Ty(e,t){let n=kv(t),r=kv(n.thread),i=kv(n.turn),a=kv(n.item),o=Q(n.delta)??Q(n.text),s=Ey(e,n,o);return{threadId:Q(n.threadId)??Q(r.id),turnId:Q(n.turnId)??Q(i.id),itemId:Q(n.itemId)??Q(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:Dy(s)}}function Ey(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return Q(kv(t.error).message)??Q(t.message)}function Dy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=yy?t:`${t.slice(0,yy)}...`}function Oy(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function ky(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function Ay(e){return e?e===`max`?`xhigh`:e:null}function jy(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function My(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function Ny(e){let t=kv(e),n=Q(t.id),r=Q(t.header),i=Q(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=kv(e),n=Q(t.label),r=Q(t.description)??n,i=Q(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function Py(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var Fy=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new wv(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await oy()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??xy.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function Iy(e,t){let n=[],r=null,i=Hy(t?.maxThreads),a=t?.sortKey,o=t?.updatedAfterUnixSeconds;do{let t=i===null?100:Math.max(0,i-n.length);if(t===0)break;let s=await Ly({cwd:e,archived:!1,cursor:r,limit:i===null?100:Math.min(100,t),sortKey:a}),c=!1;for(let t of s.threads)if(t.cwd===e){if(o!==void 0&&t.updatedAt<o){if(a===`updated_at`){c=!0;break}continue}if(n.push(t),i!==null&&n.length>=i){c=!0;break}}if(c)break;r=s.nextCursor}while(r);return n}async function Ly(e){return ay(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>Vy(e)),nextCursor:n.nextCursor}})}async function Ry(e,t=!0){return ay(async n=>Vy((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function zy(e){return ay(async t=>{let n=!1;try{let r=await py(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,Gy(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function By(){let e=[],t=null;do{let n=await ay(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>Wy(e))),t=n.nextCursor}while(t);return e}function Vy(e){let t=Q(kv(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,status:Uy(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:qy(e.source),gitInfo:e.gitInfo?kv(Dv(e.gitInfo)):null,turns:e.turns.map(e=>Ky(e))}}function Hy(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function Uy(e){let t=Q(kv(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function Wy(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function Gy(e){let t=Jy(e.model),n=Yy(e.reasoningEffort),r=Xy(e.approvalPolicy),i=Zy(e.sandbox),a=r!==null||i!==null;return t||n!==null||a?{model:t,sessionTurnConfig:{mode:`default`,model:t??null,reasoningEffort:n,...a?{execution:{codex:{approvalPolicy:r,sandboxMode:i}}}:{}},sessionTurnConfigUpdatedAt:new Date(e.thread.updatedAt*1e3).toISOString()}:null}function Ky(e){return{id:e.id,status:e.status,error:e.error?kv(Dv(e.error)):null,items:e.items.map(e=>Tv(e))}}function qy(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function Jy(e){return Q(e)?.trim()||void 0}function Yy(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function Xy(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function Zy(e){let t=typeof e==`string`?e:Q(kv(e).type);return t===`read-only`||t===`readOnly`?`read-only`:t===`workspace-write`||t===`workspaceWrite`?`workspace-write`:t===`danger-full-access`||t===`dangerFullAccess`?`danger-full-access`:null}var Qy=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=hy(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=rb(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:gy(r),questions:tb(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=Sb(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:Cb(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(t){if(this.closed||this.activeQuery!==e)return;let n=t instanceof Error?t.message:String(t);this.interruptRequested||this.emit({type:`error`,message:n})}finally{if(this.closed||this.activeQuery!==e)return;this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>eb(e,t)?this.requestUserInput(e,t,n):$y(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${_g(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=tb(t),i=`req_${_g(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1}captureResumeSessionId(e){let t=Sb(e),n=Cb(t.session_id)??Cb(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${_g(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=Db(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=Cb(e.tool_id)??Cb(e.tool_use_id)??Tb(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=Cb(e.uuid);if(n)return this.activeToolItemId=n,n;let r=Ob(Cb(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}mapClaudeMessage(e){let t=Sb(e),n=Cb(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!_b(t))return[];let n=vb(Sb(t.message));return n?[{type:`item.completed`,item:{id:Cb(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:Cb(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=gb(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=Sb(t.event);if(Cb(e.type)===`message_start`){let t=Db(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=yb(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||Cb(t.subtype)?.startsWith(`error_`)===!0){let n=bb(t);return[...e,{type:`turn.failed`,error:{message:n},usage:xb(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:xb(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=Cb(t.summary)??`tool summary`,i=Cb(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=Cb(t.tool_name)??`tool`,i=Cb(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=Cb(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(Cb(t.session_id)??Cb(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:Cb(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=Cb(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=ib(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=ab(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=ob({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function $y(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function eb(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function tb(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=nb(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function nb(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function rb(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function ib(e){let t=Sb(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=Sb(e);if(t.type!==`tool_use`)continue;let n=Cb(t.id),i=Cb(t.name),a=Sb(t.input);if(!(!n||!i)){if(i===`Task`){let e=Cb(a.subagent_type),t=Cb(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:Cb(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=Cb(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=Cb(a.file_path);r.push({id:n,toolName:`Write`,title:db(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function ab(e){let t=Sb(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=Sb(e);if(t.type!==`tool_result`)continue;let n=Cb(t.tool_use_id);if(n)return{toolUseId:n}}return null}function ob(e){let t=Sb(e.raw.tool_use_result),n=sb(t.content)??vb(Sb(e.raw.message)),r=Sb(t.usage),i=Eb(t.totalTokens)??Eb(r.total_tokens)??Eb(r.output_tokens),a=Eb(t.totalToolUseCount),o=Eb(t.totalDurationMs),s=Cb(t.agentId),c=Cb(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=lb(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=cb(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=wb(t.content),r=ub(pb(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function sb(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=Sb(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
477
+ `):void 0}function cb(e){return wb(Sb(e.file).content)||sb(e.content)}function lb(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${mb(t)} tokens`),typeof n==`number`&&r.push(hb(n)),r.join(` · `)}function ub(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function db(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${fb(e)})`:`Write`}function fb(e){let t=e.split(`/`);return t[t.length-1]||e}function pb(e){if(e)return e.split(`
478
+ `).length}function mb(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function hb(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 gb(e){return vb(Sb(e.message))||(wb(e.result)??``)}function _b(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=Sb(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>Sb(e).type===`tool_result`)}function vb(e){let t=wb(e.content);if(t)return t;let n=wb(e.text)??wb(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=Sb(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
479
+ `)}function yb(e){let t=Sb(Sb(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function bb(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):Cb(e.subtype)||`Claude turn failed`}function xb(e){let t=Sb(e);return{input_tokens:Eb(t.input_tokens)??Eb(t.inputTokens)??0,cached_input_tokens:Eb(t.cached_input_tokens)??Eb(t.cache_read_input_tokens)??Eb(t.cacheReadInputTokens)??0,output_tokens:Eb(t.output_tokens)??Eb(t.outputTokens)??0}}function Sb(e){return typeof e==`object`&&e?e:{}}function Cb(e){if(typeof e==`string`&&e.trim())return e}function wb(e){if(typeof e==`string`&&e.length>0)return e}function Tb(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function Eb(e){if(typeof e==`number`&&Number.isFinite(e))return e}function Db(e){let t=Cb(Sb(e.message).id);if(t)return t;let n=Cb(Sb(Sb(e.event).message).id);if(n)return n}function Ob(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var kb=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=Ab(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 Ab(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var jb=`@anthropic-ai/claude-agent-sdk`,Mb=`claude-sonnet-4-6`,Nb=1e4,Pb=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(jb),!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(jb),n=await Fb(Ib(t,e),Nb,`Claude native query session creation timed out`);if(n)return n;let r=await Fb(Lb(t,e),Nb,`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 Fb(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 Ib(e,t){let n=Rb(e);if(!n)return null;let r=t.model??Mb;return new Qy(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=zb(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 Lb(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 kb(`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 kb(`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 kb(`claude`,t.sessionId,t.model,n)}return null}function Rb(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function zb(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 Bb(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new Fy(n,r):new Pb(n,r)}const Vb=p.default.join(`.claude`,`projects`),Hb=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function Ub(e){return(await(0,T.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>Xb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Wb(e,t){let n=Jb(e,t?.homeDir),r=p.default.resolve(e);try{let i=await Zb(e,n,r,{maxSessions:Sx(t?.maxSessions),updatedAfterMs:xx(t?.updatedAfterMs)});if(i.length>0)return i}catch{}return Qb(n,{maxSessions:Sx(t?.maxSessions),updatedAfterMs:xx(t?.updatedAfterMs)})}async function Gb(e){let t=await sx(e.nativeSessionId,e.projectPath),n=await cx(e.projectPath,e.nativeSessionId,e.homeDir),r=tx(t,{createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs});return{rawEvents:Kb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),updatedAt:r.updatedAt,status:nx(t)}}function Kb(e){let t=[],n=tx(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function qb(e,t,n){return p.default.join(Jb(e,n),`${t}.jsonl`)}function Jb(e,t){let n=t??f.default.homedir();return p.default.join(n,Vb,Yb(e))}function Yb(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function Xb(e){let t=_x(e.customTitle)??_x(e.summary)??_x(e.firstPrompt),n=ax(e.createdAt??e.lastModified),r=ax(e.lastModified);return{nativeSessionId:e.sessionId,cwd:ix(e.cwd),title:t,createdAt:n,updatedAt:r,status:`idle`}}async function Zb(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,T.listSessions)({dir:e,limit:c,offset:o});if(l.length===0)break;for(let e of l){let i=xx(e.lastModified);if(r.updatedAfterMs!==void 0&&i!==void 0&&i<r.updatedAfterMs){s=!0;break}let o=Xb(e);if(typeof o.cwd!=`string`||p.default.resolve(o.cwd)!==n)continue;let c=await $b(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 ex(a,r)}async function Qb(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 $b(e,{nativeSessionId:t.name.slice(0,-6)});n&&r.push(n)}return ex(r,t)}async function $b(e,t){let n=p.default.join(e,`${t.nativeSessionId}.jsonl`),r;try{r=await ox(n)}catch(e){if(e.code===`ENOENT`)return t.sdkSession;throw e}if(!rx(r))return;let i=await d.default.stat(n),a=t.sdkSession?.createdAt?bx(t.sdkSession.createdAt):void 0,o=t.sdkSession?.updatedAt?bx(t.sdkSession.updatedAt):void 0,s=tx(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:nx(r)}}function ex(e,t){let n=e.filter(e=>{if(t.updatedAfterMs===void 0)return!0;let n=bx(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 tx(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=mx(fx(hx(t.raw.message)))),!n&&t.type===`assistant`&&(n=gx(hx(t.raw.message).model));let o=i??xx(t.createdAtFallbackMs)??0,s=a??xx(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function nx(e){let t=``;for(let n of e)switch(n.type){case`user`:case`assistant`:case`result`:case`stream_event`:case`tool_progress`:case`tool_use_summary`:t=n.type;break;default:break}return t===`user`||t===`stream_event`||t===`tool_progress`?`running`:`idle`}function rx(e){for(let t of e){if(t.type===`user`){let e=hx(t.raw.message);if(fx(e)||dx(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=hx(t.raw.message);if(fx(e)||ux(e).length>0||gx(t.raw.error))return!0}return!1}function ix(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function ax(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function ox(e){let t=(await d.default.readFile(e,`utf8`)).split(`
480
+ `),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=hx(i),o=gx(a.timestamp),s=o?bx(o):void 0;n.push({line:e+1,raw:a,type:gx(a.type),timestamp:o,timestampMs:s})}return n}async function sx(e,t){let n=await(0,T.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>lx(e,t+1))}async function cx(e,t,n){let r=qb(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function lx(e,t){let n=hx(e),r=hx(n.message),i=gx(n.timestamp)??gx(r.timestamp)??gx(r.created_at)??gx(r.createdAt);return{line:t,raw:{...n,message:r},type:gx(n.type),timestamp:i,timestampMs:i?bx(i):void 0}}function ux(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=hx(e);if(gx(t.type)!==`tool_use`)continue;let r=hx(t.input),i=gx(r.command),a=gx(t.name)??`tool`,o=gx(r.description);n.push({id:gx(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function dx(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=hx(e);if(gx(t.type)!==`tool_result`)continue;let r=vx(gx(t.content)??gx(hx(t.toolUseResult).stdout)??gx(hx(t.tool_use_result).stdout)??gx(t.text));n.push({toolUseId:gx(t.tool_use_id)??gx(t.toolUseId),toolName:gx(t.tool_name)??gx(t.toolName),text:r,isError:t.is_error===!0})}return n}function fx(e){let t=gx(e.content);if(t)return vx(t);let n=gx(e.text)??gx(e.prompt);if(n)return vx(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=hx(e),n=gx(t.type);if(n&&n!==`text`)continue;let r=gx(t.text)??gx(t.content)??px(t);r&&i.push(r)}if(i.length!==0)return vx(i.join(`
481
+ `))}function px(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=hx(e),r=gx(t.text)??gx(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function mx(e,t=60){if(!e)return;let n=yx(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 hx(e){return typeof e==`object`&&e?e:{}}function gx(e){return typeof e==`string`&&e.trim()||void 0}function _x(e){if(typeof e==`string`)return vx(e)}function vx(e){if(!e)return;let t=yx(e).trim();return t.length>0?t:void 0}function yx(e){return e.replace(Hb,``)}function bx(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function xx(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.round(e)}function Sx(e){if(e===void 0||!Number.isFinite(e))return;let t=Math.floor(e);return t>0?t:void 0}var Cx=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}=Tx(r,[t,n]);if(Ex(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=Ox(await this.refreshProjects()),r=!0);let i=await Dx(n.projects,t);if(!i)throw s_(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Ox(await this.refreshProjects()),i=await Dx(n.projects,t),!i)throw s_(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 Ly({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 wx({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>jx(e.cwd),mapSession:e=>{let t=Mx(e.createdAt),n=Mx(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:jx(e.name)??jx(e.preview),model:jx(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 wx({sessions:await Ub(),canonicalPathCache:e,getRawPath:e=>jx(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:jx(e.title),model:jx(e.model),createdAt:jx(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 wx(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 kx(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Tx(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:Ax(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=Nx(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(Fx)})).sort((e,t)=>Px(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function Ex(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Dx(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await vv(t);return e.find(e=>e.path===r)}function Ox(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function kx(e,t){let n=t.get(e);return n||(n=vv(e),t.set(e,n)),n}function Ax(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function jx(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Mx(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Nx(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function Px(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 Fx(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Ix=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 Lx(this.getProjectPath(e),Bx);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 Rx(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 Rx(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 Lx(this.indexPath,zx)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Lx(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 Rx(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 zx(e){return!Vx(e)||e.v!==1||typeof e.generatedAt!=`string`||!Xa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Za.safeParse(e).success)}function Bx(e){return!Vx(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Za.safeParse(e.project).success||!Xa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Qa.safeParse(e).success)}function Vx(e){return typeof e==`object`&&!!e}const Hx=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function Ux(e){let t=wo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=us(ps(qx(i.export({format:`jwk`})))),o=es({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:To.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 Wx(e){let t=wo.parse(e.clientHello),n=To.parse(e.gatewayHello),r=Eo.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!mo.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([Hx,ds(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(ts({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,ds(r.signature)))throw Error(`transcript_invalid`)}function Gx(e){let t=To.parse(e.gatewayHello),n=Eo.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:fs(ds(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return is({role:`gateway`,keySchedule:rs({gatewayId:e.gatewayId,clientHello:wo.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function Kx(e){return Ao.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function qx(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var Jx=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}},Yx=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??``);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;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e)}addMobileConnection(e,t,n,r){e&&(this.removeMobileConnection(e),this.mobileConnections.set(e,{mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}}),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(Zo.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){let t=this.mobileConnections.get(e);t&&(t.socket?.close(),t.clientId&&this.dependencies.sessionHub.removeClient(t.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){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let r=n,i=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>ua.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});i&&await this.dependencies.dispatchCommand(i,r.deviceId,r.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(Zo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Zx(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Zo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Zx(t,`auth.refresh`)})}}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:{...Xx(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status!==`ready`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>jo.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(a)try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(Zo.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=Po.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:Xx(`INTERNAL`,500,String(e)),method:a.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=Ux({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(Zo.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{Wx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Qx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=Gx({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(Zo.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,eS(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new Jx(t=>{try{let n=Zo.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,$x(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:Kx({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:Xx(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 ls({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,$x(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:cs({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},payload:n})}:{payload:n}}};function Xx(e,t,n){return Po.parse({code:e,status:t,message:n})}function Zx(e,t){if(Yg(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`: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=tS(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`||d_(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Qx(e){return nS(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function $x(e){return nS(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function eS(e){if(Yg(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=tS(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 tS(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function nS(e,t){let n=tS(e);return t.find(e=>e===n)}function rS(e){return e?e.readyState:null}var iS=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??1e4,this.webSocketFactory=e.webSocketFactory??sS}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=rS(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=Zo.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=aS(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},`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:`e2ee-relay`,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=Zo.parse(JSON.parse(oS(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 aS(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 oS(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 sS(e){return new bv(e)}function cS(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(Qo(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function lS(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(uS(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(cS({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 Bo.parse(JSON.parse(r)).token}function uS(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 dS(e){return e?.trim()||void 0}function fS(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function pS(e,t){return{modeDefault:`default`,model:dS(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function mS(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function hS(e,t){let n=mS(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function gS(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function _S(e){let t=hS(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||dS(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?vS({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function vS(e){let t=hS(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?gS(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=hS(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=dS(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??dS(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:fS(r.execution)}}}const yS=[],bS=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],xS=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],SS=Ni.options,CS=[`read-only`,`workspace-write`,`danger-full-access`],wS=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],TS=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function ES(e){return e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt}function DS(e,t){TS&&(!e.startsWith(`config.get`)&&!e.startsWith(`raw-events`)&&!e.startsWith(`sync-external`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function OS(e){return e?{sessionFound:!0,sessionId:e.id,nativeSessionId:e.nativeSessionId??null,sessionSource:e.source??null,sessionModel:e.model??null,sessionUpdatedAt:e.updatedAt,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt??null,sessionTurnConfigModel:e.sessionTurnConfig?.model??null,sessionTurnConfigReasoningEffort:e.sessionTurnConfig?.reasoningEffort??null,sessionTurnConfigApprovalPolicy:e.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,sessionTurnConfigSandboxMode:e.sessionTurnConfig?.execution?.codex?.sandboxMode??null,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null,lastHydratedExternalConfigFreshnessAt:e.lastHydratedExternalConfigFreshnessAt??null}:{sessionFound:!1}}function kS(e,t){return e?.status===`running`?{status:`running`}:t?{status:`running`,interactionLockReason:`external_turn_running`}:{status:`idle`}}function AS(e){return e.status===`active`?!0:e.turns.some(e=>e.status===`inProgress`||e.status===`in_progress`)}function jS(e){return e.source===`native_discovered`?!0:e.providerMode===`native`&&(e.provider===`codex`||e.provider===`claude`)}const MS={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`}}]},NS={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function PS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function FS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function IS(e,t){let n=t?.trim().toLowerCase();return n?(MS[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function LS(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:xS}:{}},...e.map(e=>({...e,isDefault:!1}))]}function RS(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function zS(e){let t=new Set;for(let n of e){let e=RS(n);e&&t.add(e)}return[...t]}function BS(e){return e?.trim()||void 0}function VS(e){let t=BS(e.runtimeModel);if(t)return t;let n=BS(e.discoveredModel);if(n)return n;let r=BS(e.existingModel),i=BS(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function HS(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:zS(e.supportedReasoningEfforts)}));return t.length===0?yS:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function US(e){let t=Date.now();try{let n=HS(await By());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 WS(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(ac(),`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=KS(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?zS(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 GS(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 KS(...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 qS=class{sessions=new Map;providerCapabilitiesCache=new Map;providerCapabilitiesInFlight=new Map;nextRawSeqBySession=new Map;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.runtimeLifecycle={idleTtlMs:PS(e.runtimeLifecycle?.idleTtlMs,NS.idleTtlMs),sweepIntervalMs:FS(e.runtimeLifecycle?.sweepIntervalMs,NS.sweepIntervalMs),maxSessions:PS(e.runtimeLifecycle?.maxSessions,NS.maxSessions),maxCodexSessions:PS(e.runtimeLifecycle?.maxCodexSessions,NS.maxCodexSessions),maxClaudeSessions:PS(e.runtimeLifecycle?.maxClaudeSessions,NS.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 Hv(),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 a_(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.getRunningRuntimeSessionCount();if(e>0)throw o_(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 Uv(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.app_server.restart`,detail:{closedRuntimeSessionCount:t.length}}),{restarted:!0,closedRuntimeSessionCount:t.length}}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(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||this.shuttingDown)return;let e=MS.claude.length>0?MS.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw t_(t);let r=IS(e,n),i=r?.version??`default`,a=`${e}::${i}`,o={provider:e,projectId:t??null,requestedAgentVersion:n?.trim()||null,resolvedAgentVersion:i},s=Date.now(),c=this.providerCapabilitiesCache.get(a);if(c){if(c.expiresAt>s)return this.options.logger?.info?.({...o,cacheStatus:`hit`,source:c.value.capabilities.source,modelCount:c.value.capabilities.models.length},`provider capabilities cache hit`),c.value;this.providerCapabilitiesCache.delete(a)}let l=this.providerCapabilitiesInFlight.get(a);if(l)return this.options.logger?.info?.({...o,cacheStatus:`in_flight`},`provider capabilities awaiting in-flight load`),l;let u=Date.now(),d=(async()=>{let t=Bb(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=Date.now(),a=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1;this.options.logger?.info?.({...o,cacheStatus:`miss`,nativeAvailable:a,durationMs:Date.now()-n},`provider capabilities native availability checked`);let s=a?`native`:`fallback`,c=e===`codex`&&a?await US(this.options.logger)??yS:yS,l=e===`claude`&&a?await WS(this.options.logger)??bS:bS,d=zS(l.flatMap(e=>e.supportedReasoningEfforts??[])),f=e===`codex`?{provider:e,source:s,models:c,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:xS,approvalPolicies:SS,sandboxModes:CS,permissionModes:[]},defaults:{model:c.find(e=>e.isDefault)?.id??c[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:s,models:l,support:{reasoningEffort:d.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:d,approvalPolicies:[],sandboxModes:[],permissionModes:wS},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:GS(l),permissionMode:`default`}};if(!r){let e={capabilities:f,resolvedAgentVersion:i};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:e.capabilities.source,modelCount:e.capabilities.models.length},`provider capabilities resolved`),e}let p={...f.defaults,...r.defaults},m=p.model?.trim(),h=s===`native`?f.models:m?LS(f.models,m,e):f.models,g={capabilities:{...f,models:h,defaults:p},resolvedAgentVersion:r.version};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:g.capabilities.source,modelCount:g.capabilities.models.length},`provider capabilities resolved`),g})();this.providerCapabilitiesInFlight.set(a,d);try{let e=await d;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}catch(e){throw this.options.logger?.warn?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,err:e},`provider capabilities resolution failed`),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return pS(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw t_(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)||n}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(DS(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:OS(n),runtime:OS(r)}),r)return DS(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...OS(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return DS(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...OS(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw t_(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 n_(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.syncExternalRawHistory(r,e,i),o=a.session??this.options.historyStore.getProjectSession(e,r.id)??r,s=xC(i,a.rawEvents);DS(`sync-external.classify`,bC({projectId:e,sessionId:t,session:o,previousEvents:i,nextEvents:a.rawEvents,classification:s}));let c=o.status!==r.status||(o.interactionLockReason??``)!==(r.interactionLockReason??``);return{session:o,rawEvents:a.rawEvents,historyUpdated:s.historyUpdated,statusChanged:c,refreshMode:s.refreshMode,fromRawSeq:s.fromRawSeq,toRawSeq:s.toRawSeq,nativeWatchPath:a.nativeWatchPath}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw t_(e);let i=0,a=0,o,s=(s,c)=>{DS(`raw-events.read`,{projectId:e,sessionId:t,limit:n,provider:o?.provider,source:o?.source,providerMode:o?.providerMode,localReadDurationMs:i,finalCount:a,outcome:s,totalDurationMs:Date.now()-r,...c})},c=this.options.historyStore.getProjectSession(e,t);if(!c&&this.getRuntimeSessionSummary(e,t))return s(`runtime_session_empty`),[];if(!c)throw n_(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEvents(c.id,Math.max(n,300));return i=Date.now()-l,a=u.slice(-Math.max(1,n)).length,s(`local_only_cached`,{localEventCount:u.length}),u.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompacted(r.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3){let i=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsSinceSeq(i.id,n,r)}async getProjectSessionRawSeqRange(e,t){let n=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawSeqRange(n.id)}async resolveProjectSessionForRawRead(e,t){if(!await this.options.projectStore.getById(e))throw t_(e);let n=this.options.historyStore.getProjectSession(e,t);if(!n)throw n_(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${_g(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=Bb(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?hS(e.provider,e.sessionTurnConfig):_S({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=vS({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.options.historyStore.getSession(e),a=this.sessions.get(e);if(a?.dispatchInFlight)throw i_(e,`the previous turn is still being dispatched`,{reason:`dispatch_in_flight`});if(i?.interactionLockReason===`external_turn_running`)throw i_(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 i_(e,`the current turn is still running`,{reason:`runtime_running`,provider:a.provider,providerMode:a.providerMode});if(!a&&i?.status===`running`&&jS(i))throw i_(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??await this.resumeSessionFromHistory(e);if(!o)throw r_(e);let s=await this.getProviderDefaults(o.provider,o.projectId),c=vS({provider:o.provider,providerDefaults:s,currentSessionTurnConfig:o.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});o.dispatchInFlight=!0,this.touchSession(o);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:c.model,sessionConfig:r?.sessionConfig,mode:c.mode,config:r?.config,resolvedSessionConfig:c.sessionConfig}}),this.options.historyStore.getSession(o.id)||await this.persistSessionSnapshot(o),await o.providerSession.sendInput(t,{model:c.model,sessionConfig:c.sessionConfig,mode:c.mode}),!o.title){let e=LC(t);e&&this.setSessionTitle(o,e)}let i=new Date().toISOString();o.sessionTurnConfig=hS(o.provider,c.sessionTurnConfig),o.sessionTurnConfigUpdatedAt=i,c.model&&o.model!==c.model&&(o.model=c.model),o.updatedAt=i,await this.persistSessionSnapshot(o)}finally{o.dispatchInFlight=!1,this.touchSession(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:zC(n)}})}async interruptSession(e,t){let n=this.sessions.get(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}})}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 r_(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_${_g(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=Bb(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=hS(t.provider,t.sessionTurnConfig),o=vS({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}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 Iy(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=BC(t.createdAt),s=BC(t.updatedAt),l=kS(i,AS(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:VS({runtimeModel:i?.model,discoveredModel:t.model,existingModel:n?.model,modelProvider:t.modelProvider}),title:i?.title??LC(t.name??t.preview)??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??a,updatedAt:u===`running`?i?.updatedAt??s:s,status:u,interactionLockReason:l.interactionLockReason,pendingApprovals:d,pendingUserInputs:f,pendingActions:d+f};await this.options.historyStore.upsertSession(p),o.set(r,p),c+=1}let l={provider:`codex`,status:`ok`,discoveredCount:r.filter(t=>t.cwd===e.path).length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxThreads:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async syncClaudeSessionsForProject(e){let t=Date.now();if(!this.options.preferNativeProviders)return{provider:`claude`,status:`disabled`,discoveredCount:0,staleRemovedCount:0,upsertedCount:0,catalogDurationMs:0,applyDurationMs:0,totalDurationMs:Date.now()-t};let n=Date.now(),r,i=Date.now()-14400*60*1e3;try{r=await Wb(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=kS(i,t.status===`running`),s=a.status,l=s===`running`?i?.pendingToolApprovals.size??0:0,u=s===`running`?i?.pendingUserInputs.size??0:0,d={id:r,nativeSessionId:t.nativeSessionId,source:n?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:i?.providerMode??n?.providerMode??`native`,model:i?.model??n?.model??t.model,title:i?.title??t.title??n?.title,sessionTurnConfig:i?.sessionTurnConfig??n?.sessionTurnConfig,sessionTurnConfigUpdatedAt:i?.sessionTurnConfigUpdatedAt??n?.sessionTurnConfigUpdatedAt,createdAt:n?.createdAt??t.createdAt,updatedAt:s===`running`?i?.updatedAt??t.updatedAt:t.updatedAt,status:s,interactionLockReason:a.interactionLockReason,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),o.set(r,d),c+=1}let l={provider:`claude`,status:`ok`,discoveredCount:r.length,staleRemovedCount:0,upsertedCount:c,catalogDurationMs:a,applyDurationMs:Date.now()-s,totalDurationMs:Date.now()-t};return this.options.logger?.info?.({projectId:e.id,projectPath:e.path,maxSessions:100,lookbackDays:10,...l},`project external session sync provider completed`),l}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=ES(e),n=fC([e.nativeSessionId,e.id]);for(let r of n)try{DS(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:r,...OS(e)});let n=await zy(r);if(!n){DS(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:r});continue}let i={...e,model:BS(n.model)??e.model,sessionTurnConfig:n.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:n.sessionTurnConfigUpdatedAt,...t?{lastHydratedExternalConfigFreshnessAt:t}:{}};return await this.options.historyStore.upsertSession(i),DS(`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:OS(i)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??i}catch(t){DS(`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`||e.source!==`native_discovered`||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=ES(e),n=e.sessionTurnConfigUpdatedAt||``;if(!e.sessionTurnConfig||!BS(e.model)||!n)return!0;if(!t)return!1;let r=e.lastHydratedExternalConfigFreshnessAt;return r?t.localeCompare(r)>0:!0}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw t_(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await VC(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw t_(e);return await VC(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=RC(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=RC(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e);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_${_g(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();try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}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_${_g(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n)return t;let r=await this.options.historyStore.mergeSessionRawEvents(e.id,t),i=r[r.length-1]?.rawSeq;return typeof i==`number`&&Number.isFinite(i)&&i>0&&this.nextRawSeqBySession.set(e.id,i+1),r}async syncExternalRawHistory(e,t,n){if(e.provider===`claude`){let r=mC(e);if(!r)return{rawEvents:n};try{let i=Date.now(),a=await Gb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t}),o=Date.now(),s=await this.finalizeExternalRawHistorySync(e,n,a.rawEvents,a.updatedAt),c=await this.patchObservedExternalSessionSummary(e,{updatedAt:a.updatedAt,externallyRunning:a.status===`running`});return DS(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,historyEventCount:a.rawEvents.length,resultEventCount:s.length,readHistoryDurationMs:o-i,finalizeDurationMs:Date.now()-o}),{rawEvents:s,session:c}}catch(r){return e.source===`native_discovered`&&pC(r)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),DS(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,error:r instanceof Error?r.message:String(r)}),{rawEvents:n}}}if(e.provider!==`codex`)return{rawEvents:n};let r=fC([e.nativeSessionId,e.id]);for(let i of r)try{let r=Date.now(),a=await Ry(i,!0),o=Date.now(),s,c;if(e.source===`gateway`&&n.length>0)s=NC({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}),c=`gateway_incremental`;else if(e.source===`native_discovered`&&n.length>0){let r=CC({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n});r?(s=r,c=`native_tail_incremental`):(s=SC({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localTerminalTurnStatusById:MC(n)}),c=`full`)}else s=SC({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localTerminalTurnStatusById:MC(n)}),c=`full`;let l=Date.now(),u=await this.finalizeExternalRawHistorySync(e,n,s,BC(a.updatedAt)),d=await this.patchObservedExternalSessionSummary(e,{updatedAt:BC(a.updatedAt),externallyRunning:AS(a)});return DS(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,threadStatus:a.status,threadUpdatedAt:BC(a.updatedAt),threadTurnCount:a.turns.length,threadTurns:a.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:AS(a),localEventCount:n.length,historyBuildMode:c,historyEventCount:s.length,resultEventCount:u.length,readThreadDurationMs:o-r,buildHistoryDurationMs:l-o,finalizeDurationMs:Date.now()-l}),{rawEvents:u,session:d,nativeWatchPath:a.path??void 0}}catch(r){DS(`sync-external.codex.read.error`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,localEventCount:n.length,error:r instanceof Error?r.message:String(r)})}return DS(`sync-external.codex.read.exhausted`,{projectId:t,sessionId:e.id,source:e.source,attemptedThreadIds:r,localEventCount:n.length}),{rawEvents:n}}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt){let i=Date.now(),a=YS(e.provider,t,n),o=Date.now(),s=await this.maybePersistSyncedExternalRawEvents(e,a,!0);return await this.markExternalHistoryHydrated(e.id,r),DS(`sync-external.finalize`,{sessionId:e.id,provider:e.provider,source:e.source,localEventCount:t.length,historyEventCount:n.length,mergedEventCount:a.length,persistedEventCount:s.length,hydratedExternalUpdatedAt:r,mergeDurationMs:o-i,persistDurationMs:Date.now()-o}),s}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=kS(r,t.externallyRunning),a=i.status===`running`?r?.pendingToolApprovals.size??0:0,o=i.status===`running`?r?.pendingUserInputs.size??0:0,s={...n,updatedAt:i.status===`running`?r?.updatedAt??t.updatedAt:t.updatedAt,status:i.status,interactionLockReason:i.interactionLockReason,pendingApprovals:a,pendingUserInputs:o,pendingActions:a+o};return await this.options.historyStore.upsertSession(s),this.options.historyStore.getSession(e.id)??s}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw r_(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,interactionLockReason:void 0,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=IC(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 JS=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function YS(e,t,n){if(e!==`codex`){let r=new Map,i=new Set,a=eC(e),o=eC(e);for(let n of t){r.set(n.eventId,n);for(let t of tC(e,n,a))i.add(t)}for(let t of n){let n=tC(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))}if(t.length===0)return n.slice().sort((e,t)=>e.ts.localeCompare(t.ts));let r=t.slice(),i=new Map,a=new Map,o=new Set,s=eC(e),c=eC(e),l=$S(t)??$S(n)??Date.now();for(let[t,n]of r.entries()){i.set(n.eventId,n),a.set(n.eventId,t);for(let t of tC(e,n,s))o.add(t)}for(let t of n){let n=tC(e,t,c);if(!i.has(t.eventId)&&n.length>0&&n.every(e=>o.has(e)))continue;let s=i.get(t.eventId);if(s){if(!XS(s,t))continue;let e=a.get(t.eventId),n=QS(s,t);e!==void 0&&(r[e]=n),i.set(n.eventId,n)}else{l+=1;let e={...t,ts:new Date(l).toISOString()};i.set(e.eventId,e),a.set(e.eventId,r.length),r.push(e)}for(let e of n)o.add(e)}return r}function XS(e,t){return ZS(e)&&ZS(t)}function ZS(e){return e.type===`native.raw`?$(cC(e.payload.raw).source)===`codex.history.thread_read`:!1}function QS(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function $S(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 eC(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function tC(e,t,n){return e===`codex`?nC(t,n):e===`claude`?aC(t):[]}function nC(e,t){let n=cC(e.payload.raw),r=new Set,i=oC(e.type,n);if(i){let a=rC(e.type,n);a?r.add(iC(a,t)):r.add(i)}if(e.type!==`native.raw`||$(n.source)!==`codex.history.thread_read`)return[...r];let a=cC(n.message),o=$(a.scope);if(o===`thread`){let e=cC(a.thread),t=$(e.id);t&&r.add(sC(`thread.started`,{thread_id:t,thread:e}));let n=LC(lC(e.preview)??lC(e.name)??``);return n&&r.add(sC(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(o===`turn`){let e=cC(a.turn),t=$(e.status);return r.add(sC(`turn.started`,{turn:e})),t===`completed`?r.add(sC(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(sC(`turn.failed`,{status:t,turn:e})),[...r]}if(o===`item`){let e={turn_id:$(a.turn_id)??$(cC(a.item).turn_id),item:cC(a.item)},n=rC(`item.completed`,e);return n?r.add(iC(n,t)):r.add(sC(`item.completed`,e)),[...r]}return[...r]}function rC(e,t){if(!e.startsWith(`item.`))return;let n=cC(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=$(n.type);if(!(!r||!i))return[`codex`,e,r,i,$(n.phase)??``,$(n.status)??``,$(n.command)??``,uC(n)??``].join(`|`)}function iC(e,t){let n=t?.codexTurnScopedItemOccurrences;if(!n)return e;let r=(n.get(e)??0)+1;return n.set(e,r),`${e}|${r}`}function aC(e){let t=cC(e.payload.raw),n=oC(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!JS.has(r))return[];let i=cC(t.message),a=$(t.native_type)??$(i.type),o=cC(i.message);if(a===`user`){let e=dC(o),t=$(i.uuid);return!e||!t?[]:[sC(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=dC(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[sC(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function oC(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 sC(e,t);default:return}}function sC(e,t){let n=cC(t.item),r=cC(t.turn),i=cC(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=$(n.command)??``,p=uC(n),m=lC(t.message)??``,h=lC(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 cC(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function lC(e){if(typeof e==`string`)return e.length>0?e:void 0}function uC(e){let t=lC(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=lC(cC(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
482
+ `)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>lC(e)).filter(e=>!!e);if(e.length>0)return e.join(`
483
+ `)}return``}function dC(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=cC(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(`
484
+ `)}function fC(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function pC(e){return String(e).includes(`returned no messages from getSessionMessages`)}function mC(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function hC(e){return e?{rawSeq:e.rawSeq,type:e.type,eventId:e.eventId,ts:e.ts}:null}function gC(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(!_C(n,i))return r}return e.length===t.length?null:n}function _C(e,t){return JSON.stringify(vC(e))===JSON.stringify(vC(t))}function vC(e){let{ts:t,...n}=e;return n}function yC(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 bC(e){let t=e.previousEvents[e.previousEvents.length-1]?.rawSeq??null,n=e.nextEvents[e.nextEvents.length-1]?.rawSeq??null,r=gC(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:yC(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:hC(r===null?void 0:e.previousEvents[r]),nextMismatchEvent:hC(r===null?void 0:e.nextEvents[r])}}function xC(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&&_C(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&&_C(e,r)})?{historyUpdated:!0,refreshMode:`delta`,fromRawSeq:n??0,toRawSeq:r??n??0}:{historyUpdated:!0,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}}function SC(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:jC(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.localTerminalTurnStatusById?.get(t.id);FC(n,t.status)||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,RC(n.id)??null])}return t}function CC(e){let t=wC(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($S(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:jC(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,RC(t.id)??null]);continue}let a=n!==c,o=EC(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,RC(t.id)??null])}}return r}function wC(e){let t={hasHistoryReplay:!1,hasThreadEnvelope:!1,turnOrder:[],turnsById:new Map};for(let n of e){if(n.type!==`native.raw`)continue;let e=cC(n.payload.raw);if($(e.source)!==`codex.history.thread_read`)continue;let r=cC(e.message),i=$(r.scope);if(t.hasHistoryReplay=!0,i===`thread`){t.hasThreadEnvelope=!0;continue}if(i===`turn`){let e=cC(r.turn),n=$(e.id);if(!n)continue;let i=TC(t,n),a=$(e.status);a&&(i.status=a),i.fingerprint=kC(e);continue}if(i!==`item`)continue;let a=cC(r.item),o=$(r.turn_id)??$(a.turn_id);if(!o)continue;let s=DC(o,a,void 0);if(!s)continue;let c=TC(t,o);c.itemFingerprintByKey.has(s)||c.itemOrder.push(s),c.itemFingerprintByKey.set(s,OC(a))}return t}function TC(e,t){let n=e.turnsById.get(t);if(n)return n;let r={itemOrder:[],itemFingerprintByKey:new Map};return e.turnsById.set(t,r),e.turnOrder.push(t),r}function EC(e,t){if(t.items.length<e.itemOrder.length)return{safe:!1,appendedItems:[],statusChanged:!1};for(let[n,r]of e.itemOrder.entries()){let i=t.items[n];if(!i||DC(t.id,i,n)!==r||e.itemFingerprintByKey.get(r)!==OC(i))return{safe:!1,appendedItems:[],statusChanged:!1}}return e.fingerprint!==void 0&&e.fingerprint!==kC(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 DC(e,t,n){let r=RC(t.id);if(r)return r;if(n!==void 0)return`${e}::${n}`}function OC(e){return JSON.stringify(e)}function kC(e){return JSON.stringify({status:$(e.status)??null,error:cC(e.error)})}function AC(e){return String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``)}function jC(e,t,n){let r=n.map(AC).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 MC(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=cC(n.payload.raw);if(n.type===`turn.completed`||n.type===`turn.failed`){let r=$(e.turn_id)??$(e.turnId)??$(cC(e.turn).id)??$(cC(e.item).turn_id)??$(cC(e.item).turnId),i=$(e.status)??(n.type===`turn.completed`?`completed`:`failed`);r&&t.set(r,i);continue}if(n.type!==`native.raw`||$(e.source)!==`codex.history.thread_read`)continue;let r=cC(e.message);if($(r.scope)===`turn`){let e=cC(r.turn),n=$(e.id),i=$(e.status);n&&i&&PC(i)&&t.set(n,i)}}return t}function NC(e){let t=new Set,n=new Set,r=new Map,i=0,a=1;for(let o of e.localEvents){let e=Date.parse(o.ts);Number.isFinite(e)&&(i=Math.max(i,e)),a=Math.max(a,o.rawSeq+1);let s=cC(o.payload.raw),c=$(s.source),l=c===`codex.history.thread_read.incremental`;if(o.type===`item.started`||o.type===`item.updated`||o.type===`item.completed`){if(o.type===`item.completed`){let e=$(cC(s.item).id);e&&!l&&n.add(e)}}else if(o.type===`turn.started`){let e=$(s.turn_id)??$(cC(s.turn).id);e&&!l&&t.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=$(s.turn_id)??$(cC(s.turn).id);if(!e)continue;l||t.add(e);let n=$(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||c!==`codex.history.thread_read`)continue;let u=cC(s.message);if($(u.scope)===`turn`){let e=cC(u.turn),t=$(e.id);if(!t)continue;let n=$(e.status);n&&PC(n)&&r.set(t,n);continue}}let o=Math.max(i,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),s=0,c=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),l=t=>{let n=t.map(c).filter(e=>e.length>0);return n.length===0?`raw_sync_codex_${e.sessionId}_${a.toString().padStart(6,`0`)}`:`raw_sync_codex_${e.sessionId}_${n.join(`_`)}`},u=()=>(s+=1,new Date(o+s).toISOString()),d=[],f=(t,n,r)=>{let i=u();d.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:l(r),ts:i,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),a+=1};for(let i of e.thread.turns){let e=r.get(i.id),o=FC(e,i.status);!t.has(i.id)&&!o&&f(`turn.started`,{type:`turn.started`,turn:{id:i.id,status:i.status,items:[],error:i.error}},[`turn_started`,i.id]);for(let e of i.items){let t=$(e.id);t&&n.has(t)||f(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e},[`item_completed`,i.id,t??`seq_${a}`])}if(PC(i.status)&&e!==i.status){if(i.status===`completed`){f(`turn.completed`,{type:`turn.completed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error}},[`turn_terminal`,i.id]);continue}f(`turn.failed`,{type:`turn.failed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error},...i.error?{error:i.error}:{}},[`turn_terminal`,i.id])}}return d}function PC(e){return e===`completed`||e===`failed`||e===`interrupted`}function FC(e,t){return e===t&&PC(t)}function IC(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function LC(e,t=60){let n=IC(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function RC(e){if(typeof e!=`string`)return;let t=IC(e);if(t)return t}function zC(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function BC(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function VC(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var HC=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=this.sessions.get(e.id);this.sessions.set(e.id,{...t,...e}),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,{...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,this.sessions.has(e.sessionId)&&await this.enqueueRawSessionWrite(e.sessionId,async()=>{if($C(e)){let t=aw([...await this.readSessionRawEventsLocked(e.sessionId),e]);await this.replaceRawEventFile(e.sessionId,t),this.rawEventsCacheBySession.set(e.sessionId,t),this.compactedRawEventsCacheBySession.set(e.sessionId,JC(t));return}await this.appendRawEventLine(e),this.appendRawEventToCache(e)})}async mergeSessionRawEvents(e,t){if(await this.ready,!this.sessions.has(e))return[];let n=t.filter(t=>t.sessionId===e),r=[];return await this.enqueueRawSessionWrite(e,async()=>{let t=ew(await this.readSessionRawEventsLocked(e),n);await this.replaceRawEventFile(e,t);let i=JC(t);r=YC(i),this.rawEventsCacheBySession.set(e,t),this.compactedRawEventsCacheBySession.set(e,i)}),r}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionRawEventsCompacted(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsCompactedFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),i}async getSessionRawEventsSinceSeq(e,t,n=2e3){if(await this.ready,!this.sessions.has(e))return[];let r=Math.max(1,n),i=this.readSessionRawEventsFromCache(e);if(i!==void 0)return Ns(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=Ns((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 KC(t);let n=null;return await this.enqueueWrite(async()=>{n=KC(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)e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath&&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=`${GC(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=>GC(e)).join(`
485
+ `);await qC(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(QC(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&ZC(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}XC(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return YC(t);let n=JC(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),YC(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(`
486
+ `).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!UC(t)||t.kind!==`provider.raw`)continue;let n=WC(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 e of s){let t=ma.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>GC(e)).join(`
487
+ `),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return YC(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=JC(n);return this.compactedRawEventsCacheBySession.set(e,r),YC(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 UC(e){return typeof e==`object`&&!!e}function WC(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function GC(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 KC(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function qC(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 JC(e){let t=Ms(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ps(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function YC(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function XC(e,t){let n=Ps(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=Fs(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 ZC(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function QC(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=UC(e.payload.raw)?e.payload.raw:{},n=UC(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function $C(e){return QC(e)}function ew(e,t){let n=[...e].sort(iw),r=new Map,i=1;for(let[e,t]of n.entries())r.set(t.eventId,e),i=Math.max(i,t.rawSeq+1);for(let e of t){let t=r.get(e.eventId);if(t!==void 0){let r=n[t];r&&tw(r,e)&&(n[t]=rw(r,e));continue}let a={...e,rawSeq:i};i+=1,r.set(a.eventId,n.length),n.push(a)}return aw(n.sort(iw)).sort(iw)}function tw(e,t){return nw(e)&&nw(t)}function nw(e){return e.type===`native.raw`?uw((UC(e.payload.raw)?e.payload.raw:{}).source)===`codex.history.thread_read`:!1}function rw(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function iw(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 aw(e){let t=new Set;for(let n of e){let e=ow(n);e&&t.add(e)}return t.size===0?e:e.filter(e=>{let n=sw(e);return!n||!t.has(n)})}function ow(e){if(e.type===`item.completed`){let t=UC(e.payload.raw)?e.payload.raw:{},n=UC(t.item)?t.item:{};return cw(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=UC(e.payload.raw)?e.payload.raw:{},n=UC(t.message)?t.message:{},r=UC(n.params)?n.params:{};if((uw(n.method)??uw(t.method))!==`item/completed`)return null;let i=UC(r.item)?r.item:{};return cw(e.sessionId,i)}function sw(e){if(e.type===`item.updated`){let t=UC(e.payload.raw)?e.payload.raw:{},n=UC(t.item)?t.item:{},r=uw(n.original_method)??uw(n.originalMethod)??``,i=UC(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`)&&!lw(r)?null:cw(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=UC(e.payload.raw)?e.payload.raw:{},n=UC(t.message)?t.message:{},r=UC(n.params)?n.params:{};if(!lw(uw(n.method)??uw(t.method)??``))return null;let i=UC(r.msg)?r.msg:{},a=uw(r.itemId)??uw(r.item_id)??uw(i.itemId)??uw(i.item_id);return a?`${e.sessionId}|${a}`:null}function cw(e,t){let n=uw(t.id)??uw(t.item_id)??uw(t.itemId);return n?`${e}|${n}`:null}function lw(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function uw(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}var dw=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${_g(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()]}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.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);if(!(!i||i.socket.readyState!==i.socket.OPEN)){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),i.socket.send(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].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}i.socket.send(JSON.stringify(e))}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendBroadcastMessage(e,t){let n=JSON.stringify(e);for(let e of this.clients.values())if(e.socket.readyState===e.socket.OPEN){if(t?.sessionId){let n=e.subscriptionsBySessionId.get(t.sessionId);if(!n||t.purpose&&n.purpose!==t.purpose)continue}e.socket.send(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}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)}};const fw=1200,pw=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var mw=class{statesByKey=new Map;targetsByClientId=new Map;constructor(e){this.options=e}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){pw&&(console.log(`[native-watch][gateway]`,e,t),this.options.logger.info?.({event:e,...t},`native session watch debug`))}addClientToState(e,t,n){if(!t||!n)return;let r=this.stateKey(t,n),i=this.statesByKey.get(r);i||(i={provider:`codex`,sessionId:n,projectId:t,ownerClientIds:new Set,fileWatcher:null,debounceTimer:null,catchupRetryTimer:null,reconcileTimer:setInterval(()=>{this.requestSync(r,`reconcile`)},25e3),syncInFlight:!1,rerunRequested:!1,stableIdleSyncCount:0,watchCatchupRetryCount:0,lastObservedRawSeq:0,lastObservedRawEventCount:0,lastTriggeredAt:0,lastSyncStartedAt:null,lastSyncCompletedAt:null},this.statesByKey.set(r,i),this.logDebug(`state.created`,{clientId:e,projectId:t,sessionId:n})),i.ownerClientIds.add(e),this.logDebug(`lease.added`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:i.ownerClientIds.size}),this.requestSync(r,`lease_added`)}removeClientFromState(e,t,n){let r=this.statesByKey.get(this.stateKey(t,n));r&&(r.ownerClientIds.delete(e),this.logDebug(`lease.removed`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:r.ownerClientIds.size}),!(r.ownerClientIds.size>0)&&(this.disposeState(r),this.statesByKey.delete(this.stateKey(t,n))))}disposeState(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null),this.clearCatchupRetry(e,{resetAttempts:!0}),clearInterval(e.reconcileTimer),e.fileWatcher?.close(),e.fileWatcher=null,this.logDebug(`state.disposed`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:e.watchedPath})}async requestSync(e,t){let n=this.statesByKey.get(e);if(n){if(n.lastTriggeredAt=Date.now(),n.syncInFlight){n.rerunRequested=!0;return}n.syncInFlight=!0,n.rerunRequested=!1,n.lastSyncStartedAt=Date.now(),this.logDebug(`sync.begin`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,ownerClientCount:n.ownerClientIds.size,watchedPath:n.watchedPath,watchedDir:n.watchedDir,watchedBaseName:n.watchedBaseName,stableIdleSyncCount:n.stableIdleSyncCount});try{let r=await this.options.sessionManager.getProjectSessionSummary(n.projectId,n.sessionId);if(!r||r.provider!==`codex`||r.providerMode!==`native`){this.logDebug(`sync.stop.unwatchable_summary`,{projectId:n.projectId,sessionId:n.sessionId,summaryProvider:r?.provider,summaryProviderMode:r?.providerMode,summaryStatus:r?.status}),this.stopState(e);return}let i=await this.options.sessionManager.syncProjectSessionHistory(n.projectId,n.sessionId);n.lastSyncCompletedAt=Date.now(),this.applyWatchPath(n,i.nativeWatchPath);let a=n.lastObservedRawSeq,o=n.lastObservedRawEventCount,s=this.resolveObservedRawSeq(i),c=s>a||i.rawEvents.length>o;if(c?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,s),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),i.session.status!==`running`&&!i.historyUpdated?n.stableIdleSyncCount+=1:n.stableIdleSyncCount=0,this.logDebug(`sync.result`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,status:i.session.status,interactionLockReason:i.session.interactionLockReason,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,nativeWatchPath:i.nativeWatchPath,rawEventCount:i.rawEvents.length,cursorAdvanced:c,previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount}),i.historyUpdated||i.statusChanged){let e=this.options.createExternalUpdateMessage({provider:i.session.provider,sessionId:i.session.id,projectId:i.session.projectId,updatedAt:i.session.updatedAt,status:i.session.status,interactionLockReason:i.session.interactionLockReason,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e)}}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:fw,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`)},fw))))}stateKey(e,t){return`${e}::${t}`}};function hw(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}))}const gw=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`,_w=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function vw(e,t){gw&&console.log(`[native-watch][gateway]`,e,t)}function yw(e,t){_w&&console.log(`[session-fetch][gateway] ${e}`,t)}async function bw(e){let t=e.limit??300,n=(n,r)=>{yw(`raw-events.list`,{requestSource:e.requestSource,projectId:e.projectId,sessionId:e.sessionId,limit:t,requestedCursor:e.fromRawSeqExclusive??null,decision:n.decision,reason:n.reason,fromRawSeqExclusive:n.fromRawSeqExclusive??null,toRawSeq:n.toRawSeq??null,returnedCount:n.events.length,returnedFirstRawSeq:n.events[0]?.rawSeq??null,returnedLastRawSeq:n.events[n.events.length-1]?.rawSeq??null,...r})};if(e.fromRawSeqExclusive===void 0){let r=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),i={decision:`snapshot`,reason:r.length===0?`empty_history_snapshot`:`initial_snapshot`,events:r};return n(i),i}let r=await e.sessionManager.getProjectSessionRawSeqRange(e.projectId,e.sessionId);if(!r){let e={decision:`snapshot`,reason:`empty_history_snapshot`,events:[]};return n(e,{rangeMin:null,rangeMax:null,minExpectedCursor:null}),e}let i=Math.max(0,r.min-1);if(e.fromRawSeqExclusive<i||e.fromRawSeqExclusive>r.max){let a={decision:`snapshot`,reason:`cursor_out_of_range`,events:await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t)};return n(a,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),a}let a=await e.sessionManager.getProjectSessionRawEventsSinceSeq(e.projectId,e.sessionId,e.fromRawSeqExclusive,t),o={decision:`delta`,reason:`cursor_valid_delta`,fromRawSeqExclusive:e.fromRawSeqExclusive,toRawSeq:a[a.length-1]?.rawSeq??e.fromRawSeqExclusive,events:a};return n(o,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),o}async function xw(e,t={}){await au(e.gatewayLogPath);let n=Cw(e,t),r=Sw(e,n.instance);await r.register(fg.default,{origin:!0}),await r.register(dg.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new f_(e);await s.init();let c=new S_(e.auditLogPath),l=new dw,u=new sv,d=new gv(e.projectStoreDir),f=new HC(e.sessionHistoryDir);await f.init();let m=new Ix(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Cx({store:m});await h.init();let g,_=null,v=await Xs(e.authStoreDir),y=new qS({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}}),b=new mw({sessionManager:y,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>N(e)});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let x=new wl({packageName:P.packageName,currentVersion:P.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>y.getRunningRuntimeSessionCount(),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{b.close(),_?.close(),S.close(),await x.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:re(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:sl(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>nl({gatewayId:e.gatewayId,machineName:sl(),relayBaseUrl:e.relayEnabled?hl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:pl({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ne(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(e,t)=>{let n=Ca.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=he(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),Nw(v,t,n.data.code,n.data.deviceIdentity)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=Ea.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await Ew({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)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await x.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Na.safeParse(n?.requestedBy);try{let e=await x.applyUpdate(r.success?r.data:`mobile`);return Ra.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(L(e,t))try{return ka.parse(await y.restartCodexAppServer())}catch(e){let n=Yg(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(L(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(L(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(!L(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 Yg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):Lw(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(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.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Yg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Yg(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(!L(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 y.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(!L(e,t))return;let n=e.params;try{return await y.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(!L(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 y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Yg(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(!L(e,t))return;let n=e.params,r=await y.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(!L(e,t))return;let n=e.params,r=await y.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(!L(e,t))return;let n=e.params;try{let e=await y.syncProjectSessionHistory(n.projectId,n.sessionId);return{session:e.session,rawEventCount:e.rawEvents.length}}catch(e){return Yg(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(!L(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;try{return await te(n.projectId,n.sessionId,i,typeof a==`number`&&Number.isFinite(a)?Math.max(0,Math.floor(a)):void 0,`http`)}catch(e){return Yg(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(!L(e,t))return;let n=e.params,r=e.query,i=await y.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)=>ne(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ne(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 r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.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 w(da(e),r.sub,i)}catch(e){await T({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{b.removeClient(i),l.removeClient(i)})});let S=new Yx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=he(e.deviceName);return Nw(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await Ew({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return Tw(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>jw(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:x,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await w(e,t,n)}catch(r){await T({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),C=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.external.watch.set`:{vw(`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=b.setClientWatchTargets(n,e.payload.sessions,e.payload.replace);vw(`command.applied`,{clientId:n,deviceId:t,replace:e.payload.replace,targetCount:i.length,targets:i}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,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=hw(e.payload.sessions);await E(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=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.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=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.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)}`)}}},w=async(e,t,n)=>{await C(e,t,n)},T=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 y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},E=async(e,t,n)=>{let r=D(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await O(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},D=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},O=async(e,t)=>{let n=await k(t);if(t.cursor.kind===`all`){await A(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await A(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await A(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,M({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},k=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw n_(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},A=async(e,t,n)=>{let r=`snap_${_g(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=j(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,ee({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},j=(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},M=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${_g(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),ee=e=>({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}}}),N=e=>({v:`1.0`,kind:`session.external.update`,type:`session.external.update`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`session_external_update_${_g(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}}}),te=async(e,t,n=300,r,i=`http`)=>bw({sessionManager:y,projectId:e,sessionId:t,limit:n,fromRawSeqExclusive:r,requestSource:i}),ne=t=>t.headers[`x-api-key`]===e.apiKey,re=e=>{if(e==null)return e;if(typeof e==`string`){let t=F(e);return t===void 0?ie(e,a):ae(I(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=F(t);return n===void 0?ie(t,a):ae(I(n))}return typeof e==`object`?ae(I(e)):String(e)},F=e=>{try{return JSON.parse(e)}catch{return}},ie=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,I=e=>{if(Array.isArray(e))return e.map(e=>I(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]=I(r)}return n}return e},ae=e=>{let t=oe(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ie(t,a)}},oe=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(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}},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=ji.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=sl(),he=e=>e?.trim()||me||`Gateway`;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},ww(pe,e.host,_e)),e.relayEnabled&&(_=new iS({gatewayId:e.gatewayId,machineName:me,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>lS({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:pl({protocol:pe,host:e.host,port:_e}),logger:r.log,onFrame:async e=>{await S.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 x.start(),{protocol:pe,listenPort:_e,machineName:me,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>x.getInfo(),requestGatewayUpdate:(e=`console`)=>x.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function Sw(e,t){let n=t;if(!e.httpsEnabled)return(0,pg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,pg.default)({disableRequestLogging:!0,loggerInstance:n,https:{key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}}})}function Cw(e,t){let n=process.env.NODE_ENV!==`production`,r=qg.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?qg.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,qg.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function ww(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function Tw(e,t){if(e&&e!==t)throw e_()}async function Ew(e){let t=Dw(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:Ow(t)},`auth refresh attempt`);try{let t=await e.execute(),n=Dw(e.authService,e.refreshToken),r=Dw(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:Ow(n),nextRefreshToken:Ow(r)},`auth refresh succeeded`),t}catch(t){let n=Dw(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:Ow(n),error:kw(t)},`auth refresh failed`),t}}function Dw(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function Ow(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:Aw(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:Aw(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function kw(e){return Yg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function Aw(e){return e?e.slice(-8):null}async function jw(e,t){try{let n=jo.parse(e);switch(n.method){case`auth.refresh`:{let e=await Ew({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 Tw(n.params.deviceId??t.relayDeviceId,e.deviceId),Mo.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Mo.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Mo.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return Mo.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Mo.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Mo.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Mo.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Mo.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw Fw(n.method,`NOT_FOUND`,404,`Project not found`);return Mo.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 Mo.parse({method:n.method,result:e})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return Mo.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Mo.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw Fw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Mo.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 Fw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Mo.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return Mo.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=n.params.limit===`all`?2**53-1:n.params.limit,r=await bw({sessionManager:t.sessionManager,projectId:n.params.projectId,sessionId:n.params.sessionId,limit:e,fromRawSeqExclusive:n.params.fromRawSeqExclusive,requestSource:`rpc`});return Mo.parse({method:n.method,result:r})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),Mo.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Mo.parse({method:n.method,result:e})}case`devices.list`:return Mo.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw Fw(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Mo.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw Fw(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw Mw(e)}}function Mw(e){if(Yg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return Fw(`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`:return Fw(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return Fw(`BAD_REQUEST`,e.status,String(e),e.details);default:return Fw(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Po.safeParse(e);if(t.success)return t.data;let n=No.safeParse(e);if(n.success)return Fw(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 Fw(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?Fw(`BAD_REQUEST`,400,r):Iw(e)?Fw(`UNAUTHORIZED`,401,r):Lw(r)?Fw(`BAD_REQUEST`,400,r):Fw(`INTERNAL`,500,r)}function Nw(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:Pw(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:$s(e.identity,e.privateKeyPem,i)}}function Pw(e){return e.replace(/\s+/gu,``).toUpperCase()}function Fw(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 Po.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function Iw(e){return Yg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||d_(e)}function Lw(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 Rw(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function zw(e){let t=await cc({configPath:e.configPath,ensureConfigFile:!0});fc(t.config);let n=await xw(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{Vw({type:`worker.update.prepared`,payload:e})}});Vw({type:`worker.ready`,payload:Bw(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=Hw(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: ${Rw(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${Rw(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);Vw({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);Vw({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){Vw({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function Bw(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function Vw(e){process.send&&process.send(e)}function Hw(e){if(!Uw(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 Uw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}Ww(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function Ww(e){let t=ne(e);switch(t.command){case`help`:Yw();return;case`version`:console.log(P.version);return;case`init`:await Kw(t);return;case`doctor`:await qw(t);return;case`start`:await Gw(t);return;case`__worker`:await Jw(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function Gw(e){let t=await cc({configPath:e.configPath,ensureConfigFile:!0});fc(t.config);let n=await Ac({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await Zl({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(ou(e,t.config))}jc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function Kw(e){let t=await sc({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 cc({configPath:t.configPath,ensureConfigFile:!1}),r=await Ac({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Mc(r))}async function qw(e){let t=await cc({configPath:oc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Ac({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Mc(n)),jc(n)&&(process.exitCode=1)}async function Jw(e){try{await zw(e)}catch(t){let n=await cc({configPath:e.configPath,ensureConfigFile:!0});throw Error(ou(t,n.config))}}function Yw(){console.log(`${P.cliName} ${P.version}`),console.log(``),console.log(`Usage:`),console.log(` ${P.cliName} [start] [--config <path>] [--log]`),console.log(` ${P.cliName} init [--config <path>] [--force]`),console.log(` ${P.cliName} doctor [--config <path>]`),console.log(` ${P.cliName} --version`)}exports.runCli=Ww;