craby-gateway 0.13.5 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-sea/gateway.cjs +16 -16
- package/package.json +1 -1
package/dist-sea/gateway.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`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.13.5`,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.14.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(`
|
|
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,12 +115,12 @@ $&`).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}),ca=Qn(`type`,[$i,ea,ta,na,ra,ia,aa,Qi.extend({type:J(`session.stream.subscribe`),payload:q({replace:Jn().default(!0),sessions:Xn(sa)})}),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 la(e){let t=ca.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 ua=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`]),da=Zi.extend({type:ua}),fa=Zi.extend({kind:J(`provider.raw`),rawSeq:qn().int().positive(),type:K().min(1)});da.extend({kind:J(`gateway.control`).optional(),derivedFrom:K().min(1).optional()});var pa=Zn([fa,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(fa)}).passthrough()}).passthrough()})]),ma=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 ha=Y([`ed25519`]),ga=Y([`active`,`revoked`,`rotating`,`unknown`]),_a=q({algorithm:ha,publicKey:Xi,publicKeyFingerprint:K().min(1)}),va=q({pairingCode:K().min(4),signedAt:K().datetime()}),ya=q({gatewayId:K().min(1),deviceId:K().min(1),mobilePublicKey:Xi,pairingContext:va}),ba=q({algorithm:J(`ed25519`),gatewayPublicKeyFingerprint:K().min(1),payload:ya,signature:Xi}),xa=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:_a.optional()}),Sa=q({accessToken:K().min(1),refreshToken:K().min(1),expiresInSeconds:qn().int().positive()}),Ca=Sa.extend({gatewayId:K().min(1),deviceId:K().min(1),gatewayIdentity:ma.optional(),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:ga.optional(),pairingConfirmation:ba.optional()}),wa=q({refreshToken:K().min(1)}),Ta=Sa.extend({deviceId:K().min(1),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:ga.optional()});function Ea(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var Da=q({restarted:J(!0),closedRuntimeSessionCount:qn().int().nonnegative()}),Oa=Y([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),ka=Y([`npm`,`pnpm`,`yarn`,`unknown`]),Aa=Y([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),ja=Y([`console`,`mobile`,`system`]),Ma=q({manager:ka,installType:Aa,packageName:K().min(1),packageRoot:K().min(1).optional(),binPath:K().min(1).optional(),canSelfUpdate:Jn(),reason:K().min(1).optional()}),Na=q({id:K().min(1),targetVersion:K().min(1),requestedBy:ja,requestedAt:K().datetime(),startedAt:K().datetime().optional()}),Pa=q({packageName:K().min(1),currentVersion:K().min(1),latestVersion:K().min(1).optional(),available:Jn(),canApply:Jn(),status:Oa,checkedAt:K().datetime().optional(),install:Ma,job:Na.optional(),lastError:K().min(1).optional()}),Fa=q({type:J(`gateway.update.status`),payload:Pa}),Ia=q({started:Jn(),update:Pa}),La=er(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},K().trim().min(1)),Ra=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()}),za=q({name:K().min(1),path:K().min(1)}),Ba=q({rootPath:K().min(1),currentPath:K().min(1),parentPath:K().min(1).nullable(),directories:Xn(za)}),Va=Y([`running`,`idle`]),Ha=Y([`running`,`idle`,`all`]),Ua=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:Va,pendingApprovals:qn().int().nonnegative(),pendingUserInputs:qn().int().nonnegative(),pendingActions:qn().int().nonnegative()}),Wa=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:ga.optional(),lastVerifiedAt:K().datetime().optional()}),Ga=q({agent:q({provider:ji,requestedVersion:K().min(1).nullable(),resolvedVersion:K().min(1)}),capabilities:Ri}),Ka=q({scannedAt:K().datetime(),sessionCount:qn().int().nonnegative(),status:Y([`ready`,`partial`,`failed`]),error:K().min(1).optional()}),qa=q({codex:Ka.optional(),claude:Ka.optional()}),Ja=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()}),Ya=q({provider:ji,nativeSessionId:K().min(1),title:K().min(1).optional(),model:K().min(1).optional(),createdAt:K().datetime().optional(),updatedAt:K().datetime()}),Xa=q({generatedAt:K().datetime(),source:Y([`cache`,`fresh_scan`]),providers:qa,projects:Xn(Ja)}),Za=q({canonicalProjectPath:K().min(1),project:Ja,providers:qa,sessions:Xn(Ya)}),Qa=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`]),$a=q({}).strict(),eo=Qn(`method`,[q({method:J(`auth.refresh`),params:wa.extend({deviceId:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),params:q({requestedBy:ja.optional()})}),q({method:J(`gateway.update.get`),params:$a}),q({method:J(`gateway.update.apply`),params:q({requestedBy:ja.optional()})}),q({method:J(`projects.list`),params:$a}),q({method:J(`projects.discovery.get`),params:$a}),q({method:J(`projects.discovery.refresh`),params:$a}),q({method:J(`projects.create`),params:q({path:La,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:Ha.optional(),syncExternal:Jn().optional()})}),q({method:J(`sessions.discovery.list`),params:q({projectPath:La})}),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()})}),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:$a}),q({method:J(`devices.revoke`),params:q({deviceId:K().min(1)})})]),to=Qn(`method`,[q({method:J(`auth.refresh`),result:Ta.extend({relayToken:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),result:Da}),q({method:J(`gateway.update.get`),result:Pa}),q({method:J(`gateway.update.apply`),result:Ia}),q({method:J(`projects.list`),result:q({projects:Xn(Ra)})}),q({method:J(`projects.discovery.get`),result:Xa}),q({method:J(`projects.discovery.refresh`),result:Xa}),q({method:J(`projects.create`),result:q({project:Ra})}),q({method:J(`projects.delete`),result:q({removed:J(!0)})}),q({method:J(`workspace.directories.list`),result:Ba}),q({method:J(`sessions.list`),result:q({sessions:Xn(Ua)})}),q({method:J(`sessions.discovery.list`),result:Za}),q({method:J(`sessions.get`),result:q({session:Ua})}),q({method:J(`sessions.config.get`),result:q({session:Ua})}),q({method:J(`sessions.history.sync`),result:q({session:Ua,rawEventCount:qn().int().nonnegative()})}),q({method:J(`sessions.rawEvents.list`),result:q({events:Xn(Yn())})}),q({method:J(`providers.capabilities.get`),result:q({capabilities:Ri})}),q({method:J(`agents.config.get`),result:Ga}),q({method:J(`devices.list`),result:q({devices:Xn(Wa)})}),q({method:J(`devices.revoke`),result:q({revoked:J(!0)})})]),no=K().url(),ro=Zn([no,J(``)]),io=K().min(1).regex(/^[A-Za-z0-9_-]+$/u),ao=Y([`plaintext-relay`,`e2ee-relay`]),oo=Y([`plain`,`crypt`]);function so(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function co(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=so(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function lo(e){return e.trim()}var uo=Y([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),fo=qn().int().positive(),po=qn().int().min(0).max(2**53-1),mo=Y([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`counter_gap_too_large`,`key_epoch_mismatch`,`decrypt_failed`,`unsupported_version`]),ho=Y([`guest`,`account`,`self_hosted`]);q({type:J(`relay.gateway`),grantType:ho,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 go=q({v:J(1),gw:K().min(1),name:K().min(1),relay:ro.optional(),direct:Xn(no).default([]),pc:K().min(1),tsl:oo.optional(),gatewayIdentity:ma.optional()});er(co,go);var _o=er(co,go.omit({pc:!0}));er(co,q({v:J(1),gw:K().min(1),relay:ro.optional(),direct:ro.optional(),pc:K().min(1),tsl:oo.optional(),gatewayIdentity:ma.optional()}));var vo=er(co,q({v:J(1),gw:K().min(1),relay:ro.optional(),direct:no,pc:K().min(1),pkf:io,tsl:oo.optional()})),yo=q({name:K().min(1),relayBaseUrl:ro.optional(),directBaseUrls:Xn(no).default([]),transportSecurityLevel:ao.default(`plaintext-relay`),gatewayIdentity:ma.optional(),gatewayAccessToken:K().min(1).optional(),connectedAt:K().datetime().optional()}),bo=q({gatewayId:K().min(1),deviceId:K().min(1),connectedAt:K().datetime().optional()}),xo=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:uo,deviceId:K().min(1),deviceIdentity:_a,clientNonce:Xi}),So=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:uo,gatewayId:K().min(1),deviceId:K().min(1),clientNonce:Xi,gatewayNonce:Xi,gatewayPublicKeyFingerprint:K().min(1),gatewayEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),Co=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),deviceIdentityFingerprint:K().min(1),clientEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),wo=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:uo,gatewayId:K().min(1),deviceId:K().min(1),keyEpoch:fo,deviceIdentityFingerprint:K().min(1),deviceIdentityStatus:ga}),To=Y([`gateway_restarted`,`gateway_available`]),Eo=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),reason:To,retryable:J(!0)}),Do=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1).optional(),code:mo,message:K().min(1),retryable:Jn().optional()}),Oo=eo,ko=to,Ao=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()}),jo=Ao.extend({method:Qa.optional()}),Mo=xa.extend({gatewayId:K().min(1)}),No=Ca.extend({relayToken:K().min(1).optional()}),Po=wa.extend({gatewayId:K().min(1),deviceId:K().min(1).optional()}),Fo=Ta.extend({gatewayId:K().min(1),relayToken:K().min(1).optional()}),Io=q({gatewayId:K().min(1),gatewayIdentity:ma,requestedAt:K().datetime()});q({grantType:J(`guest`),payload:Io,signatureAlgorithm:J(`ed25519`),signature:Xi});var Lo=q({grantType:ho,token:K().min(1),expiresInSeconds:qn().int().positive()}),Ro=Y([`rpc`,`command`,`event`,`system`]),zo=`json-utf8`,Bo=Y([zo]),Vo=q({version:J(1),keyEpoch:fo,counter:po,iv:Xi,ciphertext:Xi,authTag:Xi,plaintextEncoding:Bo.default(zo)});Y([`from_mobile`,`to_mobile`,`rpc.request`,`rpc.response`,`rpc.error`]);function Ho(e){return{payload:e.optional(),encryptedPayload:Vo.optional()}}var Uo=q({gatewayId:K().min(1),mobileId:K().min(1).optional(),messageType:Ro,requestId:K().min(1).optional()}),Wo=Y([`fresh_connect`,`gateway_replay`]),Go=q({deviceId:K().min(1),deliveryMode:Wo,gatewayAvailableAtConnect:Jn()}),Ko=q({deviceId:K().min(1)}),qo=Zn([pa,Fa,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:Ao})]),Jo=Qn(`type`,[Uo.extend({type:J(`gateway.hello`),messageType:J(`system`),payload:yo}),Uo.extend({type:J(`mobile.hello`),messageType:J(`system`),payload:bo}),Uo.extend({type:J(`secure.client_hello`),messageType:J(`system`),payload:xo}),Uo.extend({type:J(`secure.gateway_hello`),mobileId:K().min(1),messageType:J(`system`),payload:So}),Uo.extend({type:J(`secure.client_auth`),messageType:J(`system`),payload:Co}),Uo.extend({type:J(`secure.ready`),mobileId:K().min(1),messageType:J(`system`),payload:wo}),Uo.extend({type:J(`secure.handshake_required`),mobileId:K().min(1),messageType:J(`system`),payload:Eo}),Uo.extend({type:J(`secure.error`),mobileId:K().min(1),messageType:J(`system`),payload:Do}),Uo.extend({type:J(`mobile.connected`),messageType:J(`system`),payload:Go}),Uo.extend({type:J(`mobile.disconnected`),messageType:J(`system`),payload:Ko}),Uo.extend({type:J(`from_mobile`),messageType:J(`command`),mobileId:K().min(1),...Ho(ca)}),Uo.extend({type:J(`to_mobile`),messageType:J(`event`),mobileId:K().min(1),...Ho(qo)}),Uo.extend({type:J(`rpc.request`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Ho(Oo)}),Uo.extend({type:J(`rpc.response`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Ho(ko)}),Uo.extend({type:J(`rpc.error`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Ho(jo)}),Uo.extend({type:J(`broadcast`),messageType:J(`event`),payload:pa}),Uo.extend({type:J(`pairing.claim.forward`),messageType:J(`system`),requestId:K().min(1),payload:Mo}),Uo.extend({type:J(`pairing.claim.result`),messageType:J(`system`),requestId:K().min(1),payload:No}),Uo.extend({type:J(`auth.refresh.forward`),messageType:J(`system`),requestId:K().min(1),payload:Po}),Uo.extend({type:J(`auth.refresh.result`),messageType:J(`system`),requestId:K().min(1),payload:Fo}),Uo.extend({type:J(`relay.error`),messageType:J(`system`),payload:Ao})]);function Yo(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 Xo(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 Zo(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,Xo(e)])}function Qo(e){return JSON.stringify([`relay-secure-client-auth-v1`,Xo(e),e.clientAuth.clientEphemeralPublicKey])}function $o(e){let t=fo.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 es(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=fo.parse(e.keyEpoch??1),r=fs(hs($o({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=fs(ms(hs(`relay-secure-hkdf-salt-v1`),r)),a=hs(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=ds(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 ts(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 ns(e,t){let n=po.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(vs(n),4),r}function rs(e,t){let n=po.parse(t);if(e===null)return;let r=po.parse(e);if(n<=r)throw Error(`counter_replay`);if(n-r>1e3)throw Error(`counter_gap_too_large`)}function is(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 as(e){ps(e.session.cipherSuite);let t=e.session.outboundCounter,n=ns(e.session.outboundNoncePrefix,t),r=hs(JSON.stringify(e.payload)),i=hs(is({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,Vo.parse({version:1,keyEpoch:e.session.keyEpoch,counter:t,iv:ss(n),ciphertext:ss(o),authTag:ss(s),plaintextEncoding:zo})}function os(e){ps(e.session.cipherSuite);let t=Vo.parse(e.encryptedPayload);if(t.keyEpoch!==e.session.keyEpoch)throw Error(`key_epoch_mismatch`);rs(e.session.highestInboundCounter,t.counter);let n=ns(e.session.inboundNoncePrefix,t.counter),r=cs(t.iv);if(!_s(r,n))throw Error(`decrypt_failed`);let i=hs(is({metadata:e.metadata,encryptedPayload:t})),a=ms(cs(t.ciphertext),cs(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(gs(o))}catch{throw Error(`decrypt_failed`)}return e.parse(s)}function ss(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 cs(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 ls(e){return ss(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function us(e){return cs(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function ds(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(gi(Ai,e,t.length>0?t:new Uint8Array(32),n,r))}function fs(e){return new Uint8Array(Ai(e))}function ps(e){if(e!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${e}`)}function ms(...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 hs(e){return new TextEncoder().encode(e)}function gs(e){return new TextDecoder().decode(e)}function _s(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 vs(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 ys(e){return ls(Ai(cs(e)).subarray(0,16))}function bs(e){if(e.type!==`native.raw`)return null;let t=Es(e.payload.raw),n=Es(t.message),r=Es(n.params),i=Es(r.msg),a=Ds(n.method)??Ds(t.method);if(!a)return null;let o=Ds(i.type)??``;if(!ws(a)&&!Ts(o))return null;let s=Cs(t);if(!s||!s.delta)return null;let c=Ds(r.conversationId)??Ds(r.conversation_id)??``,l=Ds(i.thread_id)??Ds(i.threadId)??Ds(r.threadId)??Ds(r.thread_id)??``,u=Ds(i.turn_id)??Ds(i.turnId)??Ds(r.turnId)??Ds(r.turn_id)??``,d=Ds(i.item_id)??Ds(i.itemId)??Ds(r.itemId)??Ds(r.item_id)??``,f=Ds(t.source)??``,p=Os(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=Os(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 xs(e,t){let n=bs(e),r=bs(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=Es(t.payload.raw),o=Cs(a)?.location??Cs(Es(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Ss(a,o,i)}}:null}function Ss(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=Es(e.message),i=Es(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=Es(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Cs(e){let t=Es(Es(e.message).params),n=Es(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 ws(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Ts(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function Es(e){return typeof e==`object`&&e?e:{}}function Ds(e){return typeof e==`string`&&e.trim()||void 0}function Os(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Ds(e)??``}function ks(e){let t=Ns(Vs(e)),n=[],r=new Map;for(let e of t){let t=Ps(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=Ms(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 As(e){return Ns(Vs(e))}function js(e){let t=Ps(e);return t?{key:t.key,delta:t.delta,method:t.method}:null}function Ms(e,t){let n=Ps(e),r=Ps(t);if(!n||!r||n.key!==r.key)return null;if(n.envelopeType===`native.raw`&&r.envelopeType===`native.raw`)return xs(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=Ws(t.payload.raw),s=`${n.delta}${r.delta}`;return{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Bs(o,a,s)}}}function Ns(e){let t=new Set;for(let n of e){let e=Fs(n);e&&t.add(e)}return t.size===0?e:e.filter(e=>{let n=Is(e);return!n||!t.has(n)})}function Ps(e){let t=bs(e);return t?{...t,envelopeType:`native.raw`,location:`native.raw`,key:`native.raw|${t.key}`}:Ls(e)}function Fs(e){if(e.type===`item.completed`){let t=Ws(Ws(e.payload.raw).item);return Rs(e.sessionId,t)}if(e.type!==`native.raw`)return null;let t=Ws(e.payload.raw),n=Ws(t.message),r=Ws(n.params);if((Gs(n.method)??Gs(t.method))!==`item/completed`)return null;let i=Ws(r.item);return Rs(e.sessionId,i)}function Is(e){if(e.type===`item.updated`){let t=Ws(Ws(e.payload.raw).item);return zs(t,Ws(t.payload),Gs(t.original_method)??Gs(t.originalMethod)??``)?Rs(e.sessionId,t):null}if(e.type!==`native.raw`)return null;let t=Ws(e.payload.raw),n=Ws(t.message),r=Ws(n.params);if(!Hs(Gs(n.method)??Gs(t.method)??``))return null;let i=Gs(r.itemId)??Gs(r.item_id)??Gs(Ws(r.msg).itemId)??Gs(Ws(r.msg).item_id);return i?`${e.sessionId}|${i}`:null}function Ls(e){if(e.type!==`item.updated`)return null;let t=Ws(e.payload.raw),n=Ws(t.item),r=Ws(n.payload),i=Gs(n.original_method)??Gs(n.originalMethod)??``,a=Gs(n.type)??``,o=zs(n,r,i);if(!o)return null;let s=Gs(n.id)??Gs(n.item_id)??Gs(n.itemId)??Gs(r.item_id)??Gs(r.itemId)??``,c=Gs(n.turn_id)??Gs(n.turnId)??Gs(r.turn_id)??Gs(r.turnId)??Gs(t.turn_id)??Gs(t.turnId)??``,l=Ks(r.summaryIndex??r.summary_index??n.summaryIndex??n.summary_index??t.summaryIndex??t.summary_index),u=Ks(r.contentIndex??r.content_index??n.contentIndex??n.content_index??t.contentIndex??t.content_index);return{envelopeType:`item.updated`,location:o.location,key:[`item.updated`,e.sessionId,s,a,c,i,l,u].join(`|`),delta:o.delta,method:i||`item.updated`}}function Rs(e,t){let n=Gs(t.id)??Gs(t.item_id)??Gs(t.itemId);return n?`${e}|${n}`:null}function zs(e,t,n){return typeof t.delta==`string`&&t.delta.length>0?{delta:t.delta,location:`item.payload.delta`}:typeof t.output_delta==`string`&&t.output_delta.length>0?{delta:t.output_delta,location:`item.payload.output_delta`}:typeof t.outputDelta==`string`&&t.outputDelta.length>0?{delta:t.outputDelta,location:`item.payload.outputDelta`}:typeof e.output_delta==`string`&&e.output_delta.length>0?{delta:e.output_delta,location:`item.output_delta`}:typeof e.outputDelta==`string`&&e.outputDelta.length>0?{delta:e.outputDelta,location:`item.outputDelta`}:(Hs(n)||Us(n))&&typeof e.text==`string`&&e.text.length>0?{delta:e.text,location:`item.text`}:null}function Bs(e,t,n){let r=Ws(e.item),i=Ws(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 Vs(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 Hs(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Us(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function Ws(e){return typeof e==`object`&&e?e:{}}function Gs(e){return typeof e==`string`&&e.trim()||void 0}function Ks(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Gs(e)??``}async function qs(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=Qs(JSON.parse(e));return{identity:n.identity,privateKeyPem:n.privateKeyPem,path:t,created:!1}}catch(e){if(!Zs(e))throw e}let n=Js(),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 Js(){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:Ys(n),keyVersion:1,createdAt:i},privateKeyPem:r}}function Ys(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`)}function Xs(e,t,n){let r=(0,l.createPrivateKey)(t),i=(0,l.sign)(null,Buffer.from(Ea(n),`utf8`),r).toString(`base64`);return{algorithm:`ed25519`,gatewayPublicKeyFingerprint:e.publicKeyFingerprint,payload:n,signature:i}}function Zs(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}function Qs(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid stored gateway identity`);let t=e,n=ma.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 $s=new Set([`dev-gateway-key`]),ec=new Set([`change-me-access`,`change-me-refresh`]),tc=`https://craby-relay.ai101.pro`;function nc(){return p.default.join(f.default.homedir(),`.craby-ai`)}function rc(e){let t=e?.trim();return t?p.default.resolve(vc(t)):p.default.join(nc(),`gateway.yaml`)}async function ic(e={}){let t=rc(e.configPath);return await wc(t)&&!e.overwrite?{configPath:t,created:!1}:(await cc(t,sc(t)),{configPath:t,created:!0})}async function ac(e={}){let t=rc(e.configPath),n=!1;e.ensureConfigFile&&(n=(await ic({configPath:t})).created);let r=await oc(t),i=e.syncGatewayIdentityConfig===!1?r:await uc(t,r,n),a=dc(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=bc(i),h=mc(process.env.GATEWAY_PORT,o?.port??s?.port??i?.port,8787);return{config:{gatewayId:m||fc(process.env.GATEWAY_ID,void 0,``),host:fc(process.env.GATEWAY_HOST,o?.host??s?.host??i?.host,`0.0.0.0`),port:h,httpsEnabled:pc(process.env.GATEWAY_HTTPS_ENABLED,o?.httpsEnabled??c?.enabled??i?.httpsEnabled,!1),httpsPort:mc(process.env.GATEWAY_HTTPS_PORT,o?.httpsPort??c?.port??i?.httpsPort,h),tlsCertPath:_c(process.env.GATEWAY_TLS_CERT_PATH,o?.tlsCertPath??l?.certPath??i?.tlsCertPath),tlsKeyPath:_c(process.env.GATEWAY_TLS_KEY_PATH,o?.tlsKeyPath??l?.keyPath??i?.tlsKeyPath),tlsCaPath:_c(process.env.GATEWAY_TLS_CA_PATH,o?.tlsCaPath??l?.caPath??i?.tlsCaPath),apiKey:fc(process.env.GATEWAY_API_KEY,o?.apiKey??u?.apiKey??i?.apiKey,``),workspaceRoot:gc(process.env.GATEWAY_WORKSPACE_ROOT,o?.workspaceRoot??f?.workspaceRoot??i?.workspaceRoot,a.workspaceRoot),accessSecret:fc(process.env.GATEWAY_JWT_ACCESS_SECRET,o?.accessSecret??u?.accessSecret??i?.accessSecret,``),refreshSecret:fc(process.env.GATEWAY_JWT_REFRESH_SECRET,o?.refreshSecret??u?.refreshSecret??i?.refreshSecret,``),accessTtl:fc(process.env.GATEWAY_ACCESS_TOKEN_TTL,o?.accessTtl??u?.accessTtl??i?.accessTtl,`15m`),refreshTtl:fc(process.env.GATEWAY_REFRESH_TOKEN_TTL,o?.refreshTtl??u?.refreshTtl??i?.refreshTtl,`30d`),pairingCodeTtlSeconds:mc(process.env.GATEWAY_PAIRING_CODE_TTL_SECONDS,o?.pairingCodeTtlSeconds??u?.pairingCodeTtlSeconds??i?.pairingCodeTtlSeconds,300),bootstrapPairingCodeOnStart:pc(process.env.GATEWAY_BOOTSTRAP_PAIRING_CODE_ON_START,o?.bootstrapPairingCodeOnStart??u?.bootstrapPairingCodeOnStart??i?.bootstrapPairingCodeOnStart,!0),enableNativeProviders:pc(process.env.ENABLE_NATIVE_PROVIDERS,o?.enableNativeProviders??d?.enableNativeProviders??i?.enableNativeProviders,!0),requireNativeCodex:pc(process.env.REQUIRE_NATIVE_CODEX,o?.requireNativeCodex??d?.requireNativeCodex??i?.requireNativeCodex,!1),auditLogPath:gc(process.env.GATEWAY_AUDIT_LOG_PATH,o?.auditLogPath??f?.auditLogPath??i?.auditLogPath,a.auditLogPath),gatewayLogPath:gc(process.env.GATEWAY_LOG_PATH,o?.gatewayLogPath??f?.gatewayLogPath??i?.gatewayLogPath,a.gatewayLogPath),sessionHistoryDir:gc(process.env.GATEWAY_SESSION_HISTORY_DIR,o?.sessionHistoryDir??f?.sessionHistoryDir??i?.sessionHistoryDir,a.sessionHistoryDir),projectStoreDir:gc(process.env.GATEWAY_PROJECT_STORE_DIR,o?.projectStoreDir??f?.projectStoreDir??i?.projectStoreDir,a.projectStoreDir),authStoreDir:gc(process.env.GATEWAY_AUTH_STORE_DIR,o?.authStoreDir??f?.authStoreDir??i?.authStoreDir,a.authStoreDir),relayEnabled:pc(process.env.GATEWAY_RELAY_ENABLED,o?.relayEnabled??i?.relayEnabled,!0),relayUrl:fc(process.env.GATEWAY_RELAY_URL,o?.relayUrl??i?.relayUrl,tc),relayGatewayAccessToken:fc(process.env.GATEWAY_RELAY_GATEWAY_ACCESS_TOKEN,o?.relayGatewayAccessToken??i?.relayGatewayAccessToken,``),runtimeIdleTtlMs:mc(process.env.GATEWAY_RUNTIME_IDLE_TTL_MS,o?.idleTtlMs??p?.idleTtlMs??i?.runtimeIdleTtlMs,9e5),runtimeSweepIntervalMs:hc(process.env.GATEWAY_RUNTIME_SWEEP_INTERVAL_MS,o?.sweepIntervalMs??p?.sweepIntervalMs??i?.runtimeSweepIntervalMs,6e4),runtimeMaxSessions:mc(process.env.GATEWAY_RUNTIME_MAX_SESSIONS,o?.maxSessions??p?.maxSessions??i?.runtimeMaxSessions,24),runtimeMaxCodexSessions:mc(process.env.GATEWAY_RUNTIME_MAX_CODEX_SESSIONS,o?.maxCodexSessions??p?.maxCodexSessions??i?.runtimeMaxCodexSessions,8),runtimeMaxClaudeSessions:mc(process.env.GATEWAY_RUNTIME_MAX_CLAUDE_SESSIONS,o?.maxClaudeSessions??p?.maxClaudeSessions??i?.runtimeMaxClaudeSessions,16)},configPath:t,configExists:i!==null,createdDefaultConfig:n}}async function oc(e){if(!await wc(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 sc(e){let t=dc(rc(e));return{configVersion:1,gateway:{gatewayId:xc(),host:`0.0.0.0`,port:8787,httpsEnabled:!1,httpsPort:8787,apiKey:Sc(24),accessSecret:Sc(36),refreshSecret:Sc(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:tc,relayGatewayAccessToken:``,idleTtlMs:9e5,sweepIntervalMs:6e4,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16}}}async function cc(e,t){let n=p.default.dirname(e);await d.default.mkdir(n,{recursive:!0,mode:448}),await Cc(n,448);let r=tr.stringify(t,{nullStr:`null`});await d.default.writeFile(e,r,{encoding:`utf8`,mode:384}),await Cc(e,384)}function lc(e){let t=[];e.gatewayId.trim()||t.push(`GATEWAY_ID must not be empty.`);let n=e.apiKey.trim();n?($s.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?(ec.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?(ec.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}),ca=Qn(`type`,[$i,ea,ta,na,ra,ia,aa,Qi.extend({type:J(`session.stream.subscribe`),payload:q({replace:Jn().default(!0),sessions:Xn(sa)})}),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 la(e){let t=ca.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 ua=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`]),da=Zi.extend({type:ua}),fa=Zi.extend({kind:J(`provider.raw`),rawSeq:qn().int().positive(),type:K().min(1)});da.extend({kind:J(`gateway.control`).optional(),derivedFrom:K().min(1).optional()});var pa=Zn([fa,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(fa)}).passthrough()}).passthrough()})]),ma=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 ha=Y([`ed25519`]),ga=Y([`active`,`revoked`,`rotating`,`unknown`]),_a=q({algorithm:ha,publicKey:Xi,publicKeyFingerprint:K().min(1)}),va=q({pairingCode:K().min(4),signedAt:K().datetime()}),ya=q({gatewayId:K().min(1),deviceId:K().min(1),mobilePublicKey:Xi,pairingContext:va}),ba=q({algorithm:J(`ed25519`),gatewayPublicKeyFingerprint:K().min(1),payload:ya,signature:Xi}),xa=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:_a.optional()}),Sa=q({accessToken:K().min(1),refreshToken:K().min(1),expiresInSeconds:qn().int().positive()}),Ca=Sa.extend({gatewayId:K().min(1),deviceId:K().min(1),gatewayIdentity:ma.optional(),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:ga.optional(),pairingConfirmation:ba.optional()}),wa=q({refreshToken:K().min(1)}),Ta=Sa.extend({deviceId:K().min(1),deviceIdentityFingerprint:K().min(1).optional(),deviceIdentityStatus:ga.optional()});function Ea(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var Da=q({restarted:J(!0),closedRuntimeSessionCount:qn().int().nonnegative()}),Oa=Y([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),ka=Y([`npm`,`pnpm`,`yarn`,`unknown`]),Aa=Y([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),ja=Y([`console`,`mobile`,`system`]),Ma=q({manager:ka,installType:Aa,packageName:K().min(1),packageRoot:K().min(1).optional(),binPath:K().min(1).optional(),canSelfUpdate:Jn(),reason:K().min(1).optional()}),Na=q({id:K().min(1),targetVersion:K().min(1),requestedBy:ja,requestedAt:K().datetime(),startedAt:K().datetime().optional()}),Pa=q({packageName:K().min(1),currentVersion:K().min(1),latestVersion:K().min(1).optional(),available:Jn(),canApply:Jn(),status:Oa,checkedAt:K().datetime().optional(),install:Ma,job:Na.optional(),lastError:K().min(1).optional()}),Fa=q({type:J(`gateway.update.status`),payload:Pa}),Ia=q({started:Jn(),update:Pa}),La=er(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},K().trim().min(1)),Ra=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()}),za=q({name:K().min(1),path:K().min(1)}),Ba=q({rootPath:K().min(1),currentPath:K().min(1),parentPath:K().min(1).nullable(),directories:Xn(za)}),Va=Y([`running`,`idle`]),Ha=Y([`running`,`idle`,`all`]),Ua=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:Va,pendingApprovals:qn().int().nonnegative(),pendingUserInputs:qn().int().nonnegative(),pendingActions:qn().int().nonnegative()}),Wa=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:ga.optional(),lastVerifiedAt:K().datetime().optional()}),Ga=q({agent:q({provider:ji,requestedVersion:K().min(1).nullable(),resolvedVersion:K().min(1)}),capabilities:Ri}),Ka=q({scannedAt:K().datetime(),sessionCount:qn().int().nonnegative(),status:Y([`ready`,`partial`,`failed`]),error:K().min(1).optional()}),qa=q({codex:Ka.optional(),claude:Ka.optional()}),Ja=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()}),Ya=q({provider:ji,nativeSessionId:K().min(1),title:K().min(1).optional(),model:K().min(1).optional(),createdAt:K().datetime().optional(),updatedAt:K().datetime()}),Xa=q({generatedAt:K().datetime(),source:Y([`cache`,`fresh_scan`]),providers:qa,projects:Xn(Ja)}),Za=q({canonicalProjectPath:K().min(1),project:Ja,providers:qa,sessions:Xn(Ya)}),Qa=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`]),$a=q({}).strict(),eo=Qn(`method`,[q({method:J(`auth.refresh`),params:wa.extend({deviceId:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),params:q({requestedBy:ja.optional()})}),q({method:J(`gateway.update.get`),params:$a}),q({method:J(`gateway.update.apply`),params:q({requestedBy:ja.optional()})}),q({method:J(`projects.list`),params:$a}),q({method:J(`projects.discovery.get`),params:$a}),q({method:J(`projects.discovery.refresh`),params:$a}),q({method:J(`projects.create`),params:q({path:La,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:Ha.optional(),syncExternal:Jn().optional()})}),q({method:J(`sessions.discovery.list`),params:q({projectPath:La})}),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()})}),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:$a}),q({method:J(`devices.revoke`),params:q({deviceId:K().min(1)})})]),to=Qn(`method`,[q({method:J(`auth.refresh`),result:Ta.extend({relayToken:K().min(1).optional()})}),q({method:J(`codex.appServer.restart`),result:Da}),q({method:J(`gateway.update.get`),result:Pa}),q({method:J(`gateway.update.apply`),result:Ia}),q({method:J(`projects.list`),result:q({projects:Xn(Ra)})}),q({method:J(`projects.discovery.get`),result:Xa}),q({method:J(`projects.discovery.refresh`),result:Xa}),q({method:J(`projects.create`),result:q({project:Ra})}),q({method:J(`projects.delete`),result:q({removed:J(!0)})}),q({method:J(`workspace.directories.list`),result:Ba}),q({method:J(`sessions.list`),result:q({sessions:Xn(Ua)})}),q({method:J(`sessions.discovery.list`),result:Za}),q({method:J(`sessions.get`),result:q({session:Ua})}),q({method:J(`sessions.config.get`),result:q({session:Ua})}),q({method:J(`sessions.history.sync`),result:q({session:Ua,rawEventCount:qn().int().nonnegative()})}),q({method:J(`sessions.rawEvents.list`),result:q({events:Xn(Yn())})}),q({method:J(`providers.capabilities.get`),result:q({capabilities:Ri})}),q({method:J(`agents.config.get`),result:Ga}),q({method:J(`devices.list`),result:q({devices:Xn(Wa)})}),q({method:J(`devices.revoke`),result:q({revoked:J(!0)})})]),no=K().url(),ro=Zn([no,J(``)]),io=K().min(1).regex(/^[A-Za-z0-9_-]+$/u),ao=Y([`plaintext-relay`,`e2ee-relay`]),oo=Y([`plain`,`crypt`]);function so(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function co(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=so(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function lo(e){return e.trim()}var uo=Y([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),fo=qn().int().positive(),po=qn().int().min(0).max(2**53-1),mo=Y([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`counter_gap_too_large`,`key_epoch_mismatch`,`decrypt_failed`,`unsupported_version`]),ho=Y([`guest`,`account`,`self_hosted`]);q({type:J(`relay.gateway`),grantType:ho,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 go=q({v:J(1),gw:K().min(1),name:K().min(1),relay:ro.optional(),direct:Xn(no).default([]),pc:K().min(1),tsl:oo.optional(),gatewayIdentity:ma.optional()});er(co,go);var _o=er(co,go.omit({pc:!0}));er(co,q({v:J(1),gw:K().min(1),relay:ro.optional(),direct:ro.optional(),pc:K().min(1),tsl:oo.optional(),gatewayIdentity:ma.optional()}));var vo=er(co,q({v:J(1),gw:K().min(1),relay:ro.optional(),direct:no,pc:K().min(1),pkf:io,tsl:oo.optional()})),yo=q({name:K().min(1),relayBaseUrl:ro.optional(),directBaseUrls:Xn(no).default([]),transportSecurityLevel:ao.default(`plaintext-relay`),gatewayIdentity:ma.optional(),gatewayAccessToken:K().min(1).optional(),connectedAt:K().datetime().optional()}),bo=q({gatewayId:K().min(1),deviceId:K().min(1),connectedAt:K().datetime().optional()}),xo=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:uo,deviceId:K().min(1),deviceIdentity:_a,clientNonce:Xi}),So=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:uo,gatewayId:K().min(1),deviceId:K().min(1),clientNonce:Xi,gatewayNonce:Xi,gatewayPublicKeyFingerprint:K().min(1),gatewayEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),Co=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),deviceIdentityFingerprint:K().min(1),clientEphemeralPublicKey:Xi,signatureAlgorithm:J(`ed25519`),signature:Xi}),wo=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:uo,gatewayId:K().min(1),deviceId:K().min(1),keyEpoch:fo,deviceIdentityFingerprint:K().min(1),deviceIdentityStatus:ga}),To=Y([`gateway_restarted`,`gateway_available`]),Eo=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1),reason:To,retryable:J(!0)}),Do=q({version:J(1),gatewayId:K().min(1),deviceId:K().min(1).optional(),code:mo,message:K().min(1),retryable:Jn().optional()}),Oo=eo,ko=to,Ao=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()}),jo=Ao.extend({method:Qa.optional()}),Mo=xa.extend({gatewayId:K().min(1)}),No=Ca.extend({relayToken:K().min(1).optional()}),Po=wa.extend({gatewayId:K().min(1),deviceId:K().min(1).optional()}),Fo=Ta.extend({gatewayId:K().min(1),relayToken:K().min(1).optional()}),Io=q({gatewayId:K().min(1),gatewayIdentity:ma,requestedAt:K().datetime()});q({grantType:J(`guest`),payload:Io,signatureAlgorithm:J(`ed25519`),signature:Xi});var Lo=q({grantType:ho,token:K().min(1),expiresInSeconds:qn().int().positive()}),Ro=Y([`rpc`,`command`,`event`,`system`]),zo=`json-utf8`,Bo=Y([zo]),Vo=q({version:J(1),keyEpoch:fo,counter:po,iv:Xi,ciphertext:Xi,authTag:Xi,plaintextEncoding:Bo.default(zo)});Y([`from_mobile`,`to_mobile`,`rpc.request`,`rpc.response`,`rpc.error`]);function Ho(e){return{payload:e.optional(),encryptedPayload:Vo.optional()}}var Uo=q({gatewayId:K().min(1),mobileId:K().min(1).optional(),messageType:Ro,requestId:K().min(1).optional()}),Wo=Y([`fresh_connect`,`gateway_replay`]),Go=q({deviceId:K().min(1),deliveryMode:Wo,gatewayAvailableAtConnect:Jn()}),Ko=q({deviceId:K().min(1)}),qo=Zn([pa,Fa,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:Ao})]),Jo=Qn(`type`,[Uo.extend({type:J(`gateway.hello`),messageType:J(`system`),payload:yo}),Uo.extend({type:J(`mobile.hello`),messageType:J(`system`),payload:bo}),Uo.extend({type:J(`secure.client_hello`),messageType:J(`system`),payload:xo}),Uo.extend({type:J(`secure.gateway_hello`),mobileId:K().min(1),messageType:J(`system`),payload:So}),Uo.extend({type:J(`secure.client_auth`),messageType:J(`system`),payload:Co}),Uo.extend({type:J(`secure.ready`),mobileId:K().min(1),messageType:J(`system`),payload:wo}),Uo.extend({type:J(`secure.handshake_required`),mobileId:K().min(1),messageType:J(`system`),payload:Eo}),Uo.extend({type:J(`secure.error`),mobileId:K().min(1),messageType:J(`system`),payload:Do}),Uo.extend({type:J(`mobile.connected`),messageType:J(`system`),payload:Go}),Uo.extend({type:J(`mobile.disconnected`),messageType:J(`system`),payload:Ko}),Uo.extend({type:J(`from_mobile`),messageType:J(`command`),mobileId:K().min(1),...Ho(ca)}),Uo.extend({type:J(`to_mobile`),messageType:J(`event`),mobileId:K().min(1),...Ho(qo)}),Uo.extend({type:J(`rpc.request`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Ho(Oo)}),Uo.extend({type:J(`rpc.response`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Ho(ko)}),Uo.extend({type:J(`rpc.error`),messageType:J(`rpc`),requestId:K().min(1),mobileId:K().min(1),...Ho(jo)}),Uo.extend({type:J(`broadcast`),messageType:J(`event`),payload:pa}),Uo.extend({type:J(`pairing.claim.forward`),messageType:J(`system`),requestId:K().min(1),payload:Mo}),Uo.extend({type:J(`pairing.claim.result`),messageType:J(`system`),requestId:K().min(1),payload:No}),Uo.extend({type:J(`auth.refresh.forward`),messageType:J(`system`),requestId:K().min(1),payload:Po}),Uo.extend({type:J(`auth.refresh.result`),messageType:J(`system`),requestId:K().min(1),payload:Fo}),Uo.extend({type:J(`relay.error`),messageType:J(`system`),payload:Ao})]);function Yo(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 Xo(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 Zo(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,Xo(e)])}function Qo(e){return JSON.stringify([`relay-secure-client-auth-v1`,Xo(e),e.clientAuth.clientEphemeralPublicKey])}function $o(e){let t=fo.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 es(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=fo.parse(e.keyEpoch??1),r=fs(hs($o({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=fs(ms(hs(`relay-secure-hkdf-salt-v1`),r)),a=hs(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=ds(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 ts(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 ns(e,t){let n=po.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(vs(n),4),r}function rs(e,t){let n=po.parse(t);if(e===null)return;let r=po.parse(e);if(n<=r)throw Error(`counter_replay`);if(n-r>1e3)throw Error(`counter_gap_too_large`)}function is(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 as(e){ps(e.session.cipherSuite);let t=e.session.outboundCounter,n=ns(e.session.outboundNoncePrefix,t),r=hs(JSON.stringify(e.payload)),i=hs(is({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,Vo.parse({version:1,keyEpoch:e.session.keyEpoch,counter:t,iv:ss(n),ciphertext:ss(o),authTag:ss(s),plaintextEncoding:zo})}function os(e){ps(e.session.cipherSuite);let t=Vo.parse(e.encryptedPayload);if(t.keyEpoch!==e.session.keyEpoch)throw Error(`key_epoch_mismatch`);rs(e.session.highestInboundCounter,t.counter);let n=ns(e.session.inboundNoncePrefix,t.counter),r=cs(t.iv);if(!_s(r,n))throw Error(`decrypt_failed`);let i=hs(is({metadata:e.metadata,encryptedPayload:t})),a=ms(cs(t.ciphertext),cs(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(gs(o))}catch{throw Error(`decrypt_failed`)}return e.parse(s)}function ss(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 cs(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 ls(e){return ss(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function us(e){return cs(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function ds(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(gi(Ai,e,t.length>0?t:new Uint8Array(32),n,r))}function fs(e){return new Uint8Array(Ai(e))}function ps(e){if(e!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${e}`)}function ms(...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 hs(e){return new TextEncoder().encode(e)}function gs(e){return new TextDecoder().decode(e)}function _s(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 vs(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 ys(e){return ls(Ai(cs(e)).subarray(0,16))}function bs(e){if(e.type!==`native.raw`)return null;let t=Es(e.payload.raw),n=Es(t.message),r=Es(n.params),i=Es(r.msg),a=Ds(n.method)??Ds(t.method);if(!a)return null;let o=Ds(i.type)??``;if(!ws(a)&&!Ts(o))return null;let s=Cs(t);if(!s||!s.delta)return null;let c=Ds(r.conversationId)??Ds(r.conversation_id)??``,l=Ds(i.thread_id)??Ds(i.threadId)??Ds(r.threadId)??Ds(r.thread_id)??``,u=Ds(i.turn_id)??Ds(i.turnId)??Ds(r.turnId)??Ds(r.turn_id)??``,d=Ds(i.item_id)??Ds(i.itemId)??Ds(r.itemId)??Ds(r.item_id)??``,f=Ds(t.source)??``,p=Os(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=Os(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 xs(e,t){let n=bs(e),r=bs(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=Es(t.payload.raw),o=Cs(a)?.location??Cs(Es(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Ss(a,o,i)}}:null}function Ss(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=Es(e.message),i=Es(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=Es(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Cs(e){let t=Es(Es(e.message).params),n=Es(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 ws(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Ts(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function Es(e){return typeof e==`object`&&e?e:{}}function Ds(e){return typeof e==`string`&&e.trim()||void 0}function Os(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Ds(e)??``}function ks(e){let t=Ns(Vs(e)),n=[],r=new Map;for(let e of t){let t=Ps(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=Ms(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 As(e){return Ns(Vs(e))}function js(e){let t=Ps(e);return t?{key:t.key,delta:t.delta,method:t.method}:null}function Ms(e,t){let n=Ps(e),r=Ps(t);if(!n||!r||n.key!==r.key)return null;if(n.envelopeType===`native.raw`&&r.envelopeType===`native.raw`)return xs(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=Ws(t.payload.raw),s=`${n.delta}${r.delta}`;return{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Bs(o,a,s)}}}function Ns(e){let t=new Set;for(let n of e){let e=Fs(n);e&&t.add(e)}return t.size===0?e:e.filter(e=>{let n=Is(e);return!n||!t.has(n)})}function Ps(e){let t=bs(e);return t?{...t,envelopeType:`native.raw`,location:`native.raw`,key:`native.raw|${t.key}`}:Ls(e)}function Fs(e){if(e.type===`item.completed`){let t=Ws(Ws(e.payload.raw).item);return Rs(e.sessionId,t)}if(e.type!==`native.raw`)return null;let t=Ws(e.payload.raw),n=Ws(t.message),r=Ws(n.params);if((Gs(n.method)??Gs(t.method))!==`item/completed`)return null;let i=Ws(r.item);return Rs(e.sessionId,i)}function Is(e){if(e.type===`item.updated`){let t=Ws(Ws(e.payload.raw).item);return zs(t,Ws(t.payload),Gs(t.original_method)??Gs(t.originalMethod)??``)?Rs(e.sessionId,t):null}if(e.type!==`native.raw`)return null;let t=Ws(e.payload.raw),n=Ws(t.message),r=Ws(n.params);if(!Hs(Gs(n.method)??Gs(t.method)??``))return null;let i=Gs(r.itemId)??Gs(r.item_id)??Gs(Ws(r.msg).itemId)??Gs(Ws(r.msg).item_id);return i?`${e.sessionId}|${i}`:null}function Ls(e){if(e.type!==`item.updated`)return null;let t=Ws(e.payload.raw),n=Ws(t.item),r=Ws(n.payload),i=Gs(n.original_method)??Gs(n.originalMethod)??``,a=Gs(n.type)??``,o=zs(n,r,i);if(!o)return null;let s=Gs(n.id)??Gs(n.item_id)??Gs(n.itemId)??Gs(r.item_id)??Gs(r.itemId)??``,c=Gs(n.turn_id)??Gs(n.turnId)??Gs(r.turn_id)??Gs(r.turnId)??Gs(t.turn_id)??Gs(t.turnId)??``,l=Ks(r.summaryIndex??r.summary_index??n.summaryIndex??n.summary_index??t.summaryIndex??t.summary_index),u=Ks(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 Rs(e,t){let n=Gs(t.id)??Gs(t.item_id)??Gs(t.itemId);return n?`${e}|${n}`:null}function zs(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=Hs(n)||Us(n),i=(Gs(e.source_event_type)??Gs(e.sourceEventType)??Gs(t.source_event_type)??Gs(t.sourceEventType)??``)===`stream_event`&&(Gs(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 Bs(e,t,n){let r=Ws(e.item),i=Ws(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 Vs(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 Hs(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Us(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function Ws(e){return typeof e==`object`&&e?e:{}}function Gs(e){return typeof e==`string`&&e.trim()||void 0}function Ks(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Gs(e)??``}async function qs(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=Qs(JSON.parse(e));return{identity:n.identity,privateKeyPem:n.privateKeyPem,path:t,created:!1}}catch(e){if(!Zs(e))throw e}let n=Js(),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 Js(){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:Ys(n),keyVersion:1,createdAt:i},privateKeyPem:r}}function Ys(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`)}function Xs(e,t,n){let r=(0,l.createPrivateKey)(t),i=(0,l.sign)(null,Buffer.from(Ea(n),`utf8`),r).toString(`base64`);return{algorithm:`ed25519`,gatewayPublicKeyFingerprint:e.publicKeyFingerprint,payload:n,signature:i}}function Zs(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}function Qs(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid stored gateway identity`);let t=e,n=ma.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 $s=new Set([`dev-gateway-key`]),ec=new Set([`change-me-access`,`change-me-refresh`]),tc=`https://craby-relay.ai101.pro`;function nc(){return p.default.join(f.default.homedir(),`.craby-ai`)}function rc(e){let t=e?.trim();return t?p.default.resolve(vc(t)):p.default.join(nc(),`gateway.yaml`)}async function ic(e={}){let t=rc(e.configPath);return await wc(t)&&!e.overwrite?{configPath:t,created:!1}:(await cc(t,sc(t)),{configPath:t,created:!0})}async function ac(e={}){let t=rc(e.configPath),n=!1;e.ensureConfigFile&&(n=(await ic({configPath:t})).created);let r=await oc(t),i=e.syncGatewayIdentityConfig===!1?r:await uc(t,r,n),a=dc(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=bc(i),h=mc(process.env.GATEWAY_PORT,o?.port??s?.port??i?.port,8787);return{config:{gatewayId:m||fc(process.env.GATEWAY_ID,void 0,``),host:fc(process.env.GATEWAY_HOST,o?.host??s?.host??i?.host,`0.0.0.0`),port:h,httpsEnabled:pc(process.env.GATEWAY_HTTPS_ENABLED,o?.httpsEnabled??c?.enabled??i?.httpsEnabled,!1),httpsPort:mc(process.env.GATEWAY_HTTPS_PORT,o?.httpsPort??c?.port??i?.httpsPort,h),tlsCertPath:_c(process.env.GATEWAY_TLS_CERT_PATH,o?.tlsCertPath??l?.certPath??i?.tlsCertPath),tlsKeyPath:_c(process.env.GATEWAY_TLS_KEY_PATH,o?.tlsKeyPath??l?.keyPath??i?.tlsKeyPath),tlsCaPath:_c(process.env.GATEWAY_TLS_CA_PATH,o?.tlsCaPath??l?.caPath??i?.tlsCaPath),apiKey:fc(process.env.GATEWAY_API_KEY,o?.apiKey??u?.apiKey??i?.apiKey,``),workspaceRoot:gc(process.env.GATEWAY_WORKSPACE_ROOT,o?.workspaceRoot??f?.workspaceRoot??i?.workspaceRoot,a.workspaceRoot),accessSecret:fc(process.env.GATEWAY_JWT_ACCESS_SECRET,o?.accessSecret??u?.accessSecret??i?.accessSecret,``),refreshSecret:fc(process.env.GATEWAY_JWT_REFRESH_SECRET,o?.refreshSecret??u?.refreshSecret??i?.refreshSecret,``),accessTtl:fc(process.env.GATEWAY_ACCESS_TOKEN_TTL,o?.accessTtl??u?.accessTtl??i?.accessTtl,`15m`),refreshTtl:fc(process.env.GATEWAY_REFRESH_TOKEN_TTL,o?.refreshTtl??u?.refreshTtl??i?.refreshTtl,`30d`),pairingCodeTtlSeconds:mc(process.env.GATEWAY_PAIRING_CODE_TTL_SECONDS,o?.pairingCodeTtlSeconds??u?.pairingCodeTtlSeconds??i?.pairingCodeTtlSeconds,300),bootstrapPairingCodeOnStart:pc(process.env.GATEWAY_BOOTSTRAP_PAIRING_CODE_ON_START,o?.bootstrapPairingCodeOnStart??u?.bootstrapPairingCodeOnStart??i?.bootstrapPairingCodeOnStart,!0),enableNativeProviders:pc(process.env.ENABLE_NATIVE_PROVIDERS,o?.enableNativeProviders??d?.enableNativeProviders??i?.enableNativeProviders,!0),requireNativeCodex:pc(process.env.REQUIRE_NATIVE_CODEX,o?.requireNativeCodex??d?.requireNativeCodex??i?.requireNativeCodex,!1),auditLogPath:gc(process.env.GATEWAY_AUDIT_LOG_PATH,o?.auditLogPath??f?.auditLogPath??i?.auditLogPath,a.auditLogPath),gatewayLogPath:gc(process.env.GATEWAY_LOG_PATH,o?.gatewayLogPath??f?.gatewayLogPath??i?.gatewayLogPath,a.gatewayLogPath),sessionHistoryDir:gc(process.env.GATEWAY_SESSION_HISTORY_DIR,o?.sessionHistoryDir??f?.sessionHistoryDir??i?.sessionHistoryDir,a.sessionHistoryDir),projectStoreDir:gc(process.env.GATEWAY_PROJECT_STORE_DIR,o?.projectStoreDir??f?.projectStoreDir??i?.projectStoreDir,a.projectStoreDir),authStoreDir:gc(process.env.GATEWAY_AUTH_STORE_DIR,o?.authStoreDir??f?.authStoreDir??i?.authStoreDir,a.authStoreDir),relayEnabled:pc(process.env.GATEWAY_RELAY_ENABLED,o?.relayEnabled??i?.relayEnabled,!0),relayUrl:fc(process.env.GATEWAY_RELAY_URL,o?.relayUrl??i?.relayUrl,tc),relayGatewayAccessToken:fc(process.env.GATEWAY_RELAY_GATEWAY_ACCESS_TOKEN,o?.relayGatewayAccessToken??i?.relayGatewayAccessToken,``),runtimeIdleTtlMs:mc(process.env.GATEWAY_RUNTIME_IDLE_TTL_MS,o?.idleTtlMs??p?.idleTtlMs??i?.runtimeIdleTtlMs,9e5),runtimeSweepIntervalMs:hc(process.env.GATEWAY_RUNTIME_SWEEP_INTERVAL_MS,o?.sweepIntervalMs??p?.sweepIntervalMs??i?.runtimeSweepIntervalMs,6e4),runtimeMaxSessions:mc(process.env.GATEWAY_RUNTIME_MAX_SESSIONS,o?.maxSessions??p?.maxSessions??i?.runtimeMaxSessions,24),runtimeMaxCodexSessions:mc(process.env.GATEWAY_RUNTIME_MAX_CODEX_SESSIONS,o?.maxCodexSessions??p?.maxCodexSessions??i?.runtimeMaxCodexSessions,8),runtimeMaxClaudeSessions:mc(process.env.GATEWAY_RUNTIME_MAX_CLAUDE_SESSIONS,o?.maxClaudeSessions??p?.maxClaudeSessions??i?.runtimeMaxClaudeSessions,16)},configPath:t,configExists:i!==null,createdDefaultConfig:n}}async function oc(e){if(!await wc(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 sc(e){let t=dc(rc(e));return{configVersion:1,gateway:{gatewayId:xc(),host:`0.0.0.0`,port:8787,httpsEnabled:!1,httpsPort:8787,apiKey:Sc(24),accessSecret:Sc(36),refreshSecret:Sc(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:tc,relayGatewayAccessToken:``,idleTtlMs:9e5,sweepIntervalMs:6e4,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16}}}async function cc(e,t){let n=p.default.dirname(e);await d.default.mkdir(n,{recursive:!0,mode:448}),await Cc(n,448);let r=tr.stringify(t,{nullStr:`null`});await d.default.writeFile(e,r,{encoding:`utf8`,mode:384}),await Cc(e,384)}function lc(e){let t=[];e.gatewayId.trim()||t.push(`GATEWAY_ID must not be empty.`);let n=e.apiKey.trim();n?($s.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?(ec.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?(ec.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 uc(e,t,n){if(!t)return null;let r=dc(e),i=t.gateway,a=t.storage,o=gc(process.env.GATEWAY_AUTH_STORE_DIR,i?.authStoreDir??a?.authStoreDir??t.authStoreDir,r.authStoreDir),s=bc(t),c=process.env.GATEWAY_ID?.trim()??``,l=await qs(o),u=s;if(!u)u=c||xc();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=xc();if(u===s)return t;let d={...t,gateway:{...t.gateway??{},gatewayId:u}};return await cc(e,d),d}function dc(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 fc(e,t,n){return e?.trim()||t?.trim()||n}function pc(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 mc(e,t,n){let r=yc(e);return r===null?Number.isFinite(t)?Math.max(1,Math.trunc(t)):n:Math.max(1,r)}function hc(e,t,n){let r=yc(e);return r===null?Number.isFinite(t)?Math.max(0,Math.trunc(t)):n:Math.max(0,r)}function gc(e,t,n){return _c(e,t)??p.default.resolve(vc(n))}function _c(e,t){let n=e?.trim()||t?.trim();return n?p.default.resolve(vc(n)):null}function vc(e){return e===`~`?f.default.homedir():e.startsWith(`~/`)||e.startsWith(`~\\`)?p.default.join(f.default.homedir(),e.slice(2)):e}function yc(e){if(typeof e!=`string`||!e.trim())return null;let t=Number(e);return Number.isFinite(t)?Math.trunc(t):null}function bc(e){return e?fc(void 0,e.gateway?.gatewayId??e.gateway?.relayGatewayId??e.gatewayId??e.relayGatewayId,``):``}function xc(){return`gw-${(0,l.randomBytes)(6).toString(`hex`)}`}function Sc(e){return(0,l.randomBytes)(e).toString(`hex`)}async function Cc(e,t){try{await d.default.chmod(e,t)}catch{}}async function wc(e){try{return await d.default.access(e,u.constants.F_OK),!0}catch{return!1}}const Tc=(0,h.createRequire)(require(`url`).pathToFileURL(__filename).href),Ec=(0,g.fileURLToPath)(require(`url`).pathToFileURL(__filename).href);async function Dc(e,t=Ac){let n=P.providerRequirements.map(e=>jc(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 Oc(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)}function kc(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=${Pc(n.bundledDependencyVersion)}(${n.bundledStatus})`),e.push(`system=${Pc(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 Ac={readInstalledPackageVersion:Mc,readSystemToolVersion:Nc};function jc(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 Mc(e){try{let t=Fc(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 Nc(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 Pc(e){return e??`missing`}function Fc(e){try{return Tc.resolve(`${e}/package.json`)}catch{}try{let t=Tc.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(Ec),process.cwd()]){let n=Ic(t,e);if(n)return n}return null}function Ic(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 Lc(e,t){let n=[e];return t.configPath&&n.push(`--config`,t.configPath),t.logToConsole&&n.push(`--log`),n}function Rc(e,t,n){let r=Lc(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 zc(e,t,n,r){if(!e.binPath)throw Error(`gateway launch command is unavailable`);return{command:e.binPath,args:Lc(t,n),cwd:r}}var Bc=o(((e,t)=>{t.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}})),Vc=o(((e,t)=>{var n=Bc();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})),Hc=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})),Uc=o(((e,t)=>{var n=Hc();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})),Wc=o(((e,t)=>{t.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}})),Gc=o(((e,t)=>{var n=Bc(),r=Uc(),i=Hc(),a=Wc(),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})),Kc=o(((e,t)=>{t.exports={L:1,M:0,Q:3,H:2}})),qc=o(((e,t)=>{var n=Kc();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})),Jc=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})),Yc=c(o(((e,t)=>{var n=Vc(),r=Gc(),i=Uc(),a=qc(),o=Jc();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),Xc=c(Kc(),1);const Zc={renderQr:tl};function Qc(e){return vo.parse({v:1,gw:lo(e.gatewayId),relay:e.relayBaseUrl,direct:e.bootstrapDirectBaseUrl,pc:e.pairingCode,pkf:ys(e.gatewayIdentityPublicKey)})}function $c(e){return _o.parse({v:1,gw:lo(e.gatewayId),name:e.machineName,relay:e.relayBaseUrl,direct:e.directBaseUrls,gatewayIdentity:e.gatewayIdentity})}function el(e,t=Zc){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 tl(e){let t=new Yc.default(-1,Xc.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=nl(r,n,e,i,!0,!1),o=nl(r,n,e+1,i,!0,!1);t+=rl(a,o)}i.push(t)}return i.join(`
|
|
122
122
|
`)}function nl(e,t,n,r,i,a){return n<0||n>=t||r<0||r>=t?a:e[n]?.[r]===i}function rl(e,t){return`\u001b[${e?30:37};${t?40:47}m\u2580\u001b[0m`}function il(){return f.default.hostname()}const al={networkInterfaces:()=>f.default.networkInterfaces()};function ol(e,t=al){if(!sl(e))return[e];let n=new Set([`127.0.0.1`]);for(let e of Object.values(t.networkInterfaces()))for(let t of e??[])t.internal||!cl(t.family)||n.add(t.address);return[...n]}function sl(e){return e===`0.0.0.0`||e===`::`||e===`[::]`}function cl(e){return e===`IPv4`||e===4}const ll={listGatewayListenHosts:ol,renderQr:tl};function ul(e,t=ll){return t.listGatewayListenHosts(e.host).map(t=>`${e.protocol}://${hl(t)}:${e.port}`)}function dl(e){return e.find(e=>!gl(e))??e[0]??``}function fl(e,t=ll){let n=e.relayUrl.trim();if(!n)return``;let r;try{r=new URL(n)}catch{return n}if(!_l(r.hostname))return n;let i=t.listGatewayListenHosts(e.gatewayHost).find(e=>!_l(e));return i?(r.hostname=i,r.toString().replace(/\/$/,``)):n}function pl(e,t=ll){let n=[];e.createdDefaultConfig&&n.push(`[gateway] created default config at ${e.configPath}`),n.push(`[gateway] log file ${e.config.gatewayLogPath}${e.logToConsole?` (console logging enabled)`:``}`),n.push(`[gateway] gatewayId ${e.config.gatewayId}`),n.push(`[gateway] machine ${e.startedServer.machineName}`),n.push(e.config.relayEnabled?`[gateway] relay enabled: ${fl({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t)}`:`[gateway] relay disabled`),n.push(`[gateway] available URLs:`);let r=ul({protocol:e.startedServer.protocol,host:e.config.host,port:e.startedServer.listenPort},t);for(let e of r)n.push(` ${e}`);return e.startedServer.startupPairingCode&&n.push(el({descriptor:Qc({gatewayId:e.config.gatewayId,bootstrapDirectBaseUrl:dl(r),pairingCode:e.startedServer.startupPairingCode.code,gatewayIdentityPublicKey:e.startedServer.gatewayIdentity.publicKey,relayBaseUrl:e.config.relayEnabled?fl({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t):void 0}),expiresAt:e.startedServer.startupPairingCode.expiresAt},{renderQr:t.renderQr??tl})),n.push(...ml(e.doctorReport)),n.join(`
|
|
123
|
-
`)}function ml(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function hl(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function gl(e){try{let t=new URL(e).hostname;return _l(t)}catch{return!1}}function _l(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const vl={platform:v.default.platform,now:()=>new Date,currentContext:()=>({pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}),runCommand:(e,t,n={})=>{let r=(0,m.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0,...n});return{status:r.status,stdout:typeof r.stdout==`string`?r.stdout:r.stdout?.toString(`utf8`)??``,stderr:typeof r.stderr==`string`?r.stderr:r.stderr?.toString(`utf8`)??``,...r.error?{error:r.error}:{}}}};function yl(){return p.default.join(nc(),`update-state.json`)}function bl(e){return Fa.parse({type:`gateway.update.status`,payload:e})}var xl=class{packageName;currentVersion;sessionHub;logger;consoleWrite;getRunningSessionCount;requestPreparedUpdate;stateFilePath;checkIntervalMs;runtime;state;scheduledCheckTimer=null;recurringCheckTimer=null;checkPromise=null;applyPromise=null;constructor(e){this.packageName=e.packageName,this.currentVersion=e.currentVersion,this.sessionHub=e.sessionHub,this.logger=e.logger,this.consoleWrite=e.consoleWrite,this.getRunningSessionCount=e.getRunningSessionCount,this.requestPreparedUpdate=e.requestPreparedUpdate,this.stateFilePath=e.stateFilePath??yl(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??vl,this.state=Pa.parse({packageName:this.packageName,currentVersion:this.currentVersion,available:!1,canApply:!1,status:`unknown`,install:{manager:`unknown`,installType:`unknown`,packageName:this.packageName,canSelfUpdate:!1}})}async start(){await this.reconcilePersistedState(),this.scheduledCheckTimer=setTimeout(()=>{this.checkForUpdates(`system`),this.scheduleRecurringChecks()},5e3)}async shutdown(){this.scheduledCheckTimer&&=(clearTimeout(this.scheduledCheckTimer),null),this.recurringCheckTimer&&=(clearInterval(this.recurringCheckTimer),null)}getInfo(){return Pa.parse(this.state)}async getOrCheckInfo(e){if(this.checkPromise)return this.checkPromise;let t=this.getInfo();return t.status===`unknown`||t.status===`failed`?this.checkForUpdates(e):t}async checkForUpdates(e){return this.checkPromise||=(async()=>{let t=this.runtime.now().toISOString(),n=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=wl(this.packageName,this.runtime);if(!r)return this.patchState({status:`failed`,available:!1,canApply:!1,latestVersion:void 0,checkedAt:t,install:n,lastError:`failed to query latest published gateway version`}),this.getInfo();let i=A(r,this.currentVersion)>0,a=i&&n.canSelfUpdate,o=i?a?`available`:`unsupported_install`:`up_to_date`;if(this.patchState({status:o,latestVersion:r,available:i,canApply:a,checkedAt:t,install:n,job:void 0,lastError:void 0}),i&&e!==`mobile`){let e=a?`[gateway] update available ${this.currentVersion} -> ${r}. Type update and press Enter to install and restart.`:`[gateway] update available ${this.currentVersion} -> ${r}, but this installation cannot self-update (${n.reason??`unsupported install`}).`;this.consoleWrite?.(e)}else e===`console`&&this.consoleWrite?.(`[gateway] already up to date at ${this.currentVersion}`);return this.getInfo()})().finally(()=>{this.checkPromise=null}),this.checkPromise}async applyUpdate(e){return this.applyPromise||=(async()=>{let t=await this.checkForUpdates(e);if(!t.available)throw Error(`gateway is already up to date`);if(!t.canApply||t.install.manager===`unknown`)throw Error(t.install.reason??`gateway installation does not support self-update`);if(t.status===`updating`||t.status===`restarting`)return Ia.parse({started:!1,update:t});let n=await this.getRunningSessionCount();if(n>0)throw Error(`gateway update requires idle runtime, found ${n} running session${n===1?``:`s`}`);let r=t.latestVersion;if(!r)throw Error(`latest gateway version is unknown`);let i=this.runtime.currentContext(),a={id:`gwupd_${Date.now()}`,targetVersion:r,requestedBy:e,requestedAt:this.runtime.now().toISOString(),startedAt:this.runtime.now().toISOString()},o={version:1,update:{...t,status:`updating`,job:a,lastError:void 0},helper:{manager:t.install.manager,packageName:this.packageName,targetVersion:r,originalPid:i.pid,restart:Pl(t.install,{cwd:i.cwd,argv:[...i.argv]}),requestedBy:e,requestedAt:a.requestedAt}},s=o.helper;if(!s)throw Error(`gateway update helper state was not prepared`);await Il(this.stateFilePath,o),this.patchState({status:`updating`,job:a,lastError:void 0}),this.consoleWrite?.(`[gateway] updating ${this.packageName} to ${r} via ${t.install.manager}; gateway will restart automatically.`),this.patchState({status:`restarting`,job:a}),this.logger.info?.({job:a,stateFilePath:this.stateFilePath,originalPid:i.pid,install:t.install,restart:s.restart},`gateway update handoff prepared`);try{await this.requestPreparedUpdate?.({stateFilePath:this.stateFilePath,targetVersion:r,requestedBy:e})}catch(e){let t=Pa.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await Il(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(bl(t)),e}return Ia.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=Pa.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(bl(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await Fl(this.stateFilePath);if(!e)return;let t=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime}),n=e.helper?.targetVersion??e.update.job?.targetVersion;if((e.update.status===`updating`||e.update.status===`restarting`)&&n){let r=A(this.currentVersion,n)>=0,i=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,latestVersion:r?this.currentVersion:n,available:!r,canApply:!r&&t.canSelfUpdate,status:r?`up_to_date`:`failed`,checkedAt:this.runtime.now().toISOString(),install:t,job:void 0,...r?{lastError:void 0}:{lastError:e.update.lastError??`gateway restarted before update completed`}});await Il(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Sl(e,t={}){let n=t.runtime??vl,r=t.waitForProcessExit??Ll,i=t.logger,a=await Fl(e);if(!a?.helper)throw Error(`gateway update helper state is missing`);i?.info?.({stateFilePath:e,originalPid:a.helper.originalPid,packageName:a.helper.packageName,targetVersion:a.helper.targetVersion,manager:a.helper.manager,cwd:a.helper.restart.cwd},`gateway update apply starting`);let o=Date.now();await r(a.helper.originalPid);let s=Date.now()-o,c=Rl(a.helper.originalPid);i?.[c?`warn`:`info`]?.({stateFilePath:e,originalPid:a.helper.originalPid,waitDurationMs:s,processStillRunning:c},c?`gateway update original process still running after wait window`:`gateway update original process exited`);let l=Cl(a.helper.manager,a.helper.packageName,a.helper.targetVersion);i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd},`gateway update install starting`);let u=Date.now(),d=n.runCommand(l.command,l.args,{cwd:a.helper.restart.cwd}),f=Date.now()-u;if(d.status!==0){let t={...a,update:{...a.update,status:`failed`,lastError:Bl(l.command,l.args,d)},helper:void 0};return await Il(e,t),i?.error?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status,error:d.error?.message,stderr:d.stderr.trim()||void 0,stdout:d.stdout.trim()||void 0},`gateway update install failed`),{updated:!1,update:Pa.parse(t.update)}}i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status},`gateway update install completed`);let p={...a,update:{...a.update,status:`restarting`,lastError:void 0},helper:void 0};return await Il(e,p),i?.info?.({stateFilePath:e,targetVersion:a.helper.targetVersion},`gateway update apply completed; worker restart may proceed`),{updated:!0,update:Pa.parse(p.update)}}function Cl(e,t,n){switch(e){case`npm`:return{command:`npm`,args:[`install`,`-g`,`${t}@${n}`]};case`pnpm`:return{command:`pnpm`,args:[`add`,`-g`,`${t}@${n}`]};case`yarn`:return{command:`yarn`,args:[`global`,`add`,`${t}@${n}`]}}}function wl(e,t){let n=t.runCommand(`npm`,[`view`,e,`version`,`--json`]);if(n.error||n.status!==0)return null;let r=n.stdout.trim();if(!r)return null;try{let e=JSON.parse(r);return typeof e==`string`&&e.trim()?e.trim():null}catch{return r.replace(/^"+|"+$/g,``)}}function Tl(e){let t=kl(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?Ma.parse({manager:`unknown`,installType:`dev_workspace`,packageName:e.packageName,packageRoot:t.packageRoot,canSelfUpdate:!1,reason:`workspace/development runtime does not support self-update`}):e.currentScriptPath?El(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Dl(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ol(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ma.parse({manager:`unknown`,installType:t.packageName===e.packageName?`unknown`:`standalone_binary`,packageName:e.packageName,...t.packageRoot?{packageRoot:t.packageRoot}:{},canSelfUpdate:!1,reason:t.packageName===e.packageName?`unable to determine global package manager installation`:`gateway is not running from a supported package-manager installation`}):Ma.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function El(e,t,n,r){let i=r.runCommand(`npm`,[`root`,`-g`]),a=r.runCommand(`npm`,[`prefix`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=jl(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),Nl(r.platform)),m=Ml(l,d)?`global_registry`:`global_file`;return Ma.parse({manager:`npm`,installType:m,packageName:e,packageRoot:l,binPath:f,canSelfUpdate:m===`global_registry`,...m===`global_registry`?{}:{reason:`npm file-linked global install is not supported`}})}function Dl(e,t,n,r){let i=r.runCommand(`pnpm`,[`root`,`-g`]),a=r.runCommand(`pnpm`,[`bin`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=Ml(l,jl(p.default.dirname(o)))?`global_registry`:`global_file`;return Ma.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Ol(e,t,n,r){let i=r.runCommand(`yarn`,[`global`,`dir`]),a=r.runCommand(`yarn`,[`global`,`bin`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,`node_modules`,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);return Al(l,t,n)?Ma.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:!0}):null}function kl(e){if(!e)return{packageRoot:null,packageName:null};let t=p.default.dirname(e);for(;;){let e=p.default.join(t,`package.json`);if(u.default.existsSync(e))try{let n=JSON.parse(u.default.readFileSync(e,`utf8`));if(typeof n.name==`string`)return{packageRoot:t,packageName:n.name}}catch{return{packageRoot:t,packageName:null}}let n=p.default.dirname(t);if(n===t)return{packageRoot:null,packageName:null};t=n}}function Al(e,t,n){let r=jl(e),i=t?jl(t):null,a=jl(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function jl(e){try{return u.default.realpathSync(e)}catch{return e}}function Ml(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function Nl(e=v.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function Pl(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function Fl(e){try{let t=await d.default.readFile(e,`utf8`);return Vl(JSON.parse(t))}catch{return null}}async function Il(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0}),await d.default.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}async function Ll(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!Rl(e))return;await zl(500)}}function Rl(e){try{return v.default.kill(e,0),!0}catch{return!1}}function zl(e){return new Promise(t=>setTimeout(t,e))}function Bl(e,t,n){let r=n.stderr.trim(),i=n.stdout.trim(),a=r||i||n.error?.message||`exit code ${String(n.status)}`;return`${e} ${t.join(` `)} failed: ${a}`}function Vl(e){if(!Wl(e)||e.version!==1)return null;let t=Pa.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=Hl(e.helper);return n?{version:1,update:t.data,helper:n}:null}function Hl(e){if(!Wl(e))return null;let t=ka.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=ja.safeParse(e.requestedBy);if(!n.success||!Gl(e.packageName)||!Gl(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!Kl(e.requestedAt))return null;let r=Ul(e.restart);return r?{manager:t.data,packageName:e.packageName,targetVersion:e.targetVersion,originalPid:e.originalPid,restart:r,requestedBy:n.data,requestedAt:e.requestedAt}:null}function Ul(e){return!Wl(e)||!Gl(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!Gl(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function Wl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gl(e){return typeof e==`string`&&e.trim().length>0}function Kl(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}async function ql(e){let t=Yl(),n=Ql(e.loaded.config.gatewayLogPath),r=new Map,i=0,a=null,o=!1,s=null,c=null,l=!1,u=null,d=null,f=null,p=new Promise((e,t)=>{s=e,c=t}),h=()=>{f&&=(clearTimeout(f),null)},g=()=>{d&&=(clearTimeout(d),null)},_=Jl({enabled:v.default.stdin.isTTY&&v.default.stdout.isTTY,onUpdate:async()=>{if(!(!a||l))try{let e=await E(`console`);if(e.started){console.log(`[gateway] update accepted; restarting into ${e.update.job?.targetVersion??`latest`}...`);return}console.log(`[gateway] update already ${e.update.status}`)}catch(e){console.error(`[gateway] update failed: ${String(e)}`)}},onRestartCodex:async()=>{if(!(!a||l))try{let e=await D(`console`);console.log(`[gateway] codex app-server restarted; closed ${e.closedRuntimeSessionCount} runtime session${e.closedRuntimeSessionCount===1?``:`s`}.`)}catch(e){console.error(`[gateway] codex app-server restart failed: ${String(e)}`)}}}),y=e=>{for(let t of r.values())t.reject(e);r.clear()},b=e=>{g(),h(),_(),y(Error(`gateway supervisor shutting down`)),n.close(),v.default.exit(e)},x=e=>{if(a){n.info({reason:e,workerPid:a.pid??void 0,preparedUpdate:u},`gateway supervisor requested worker shutdown`);try{a.send?.({type:`supervisor.shutdown`,reason:e})}catch(t){n.warn({reason:e,workerPid:a.pid??void 0,error:t},`gateway supervisor failed to send graceful shutdown message; sending SIGTERM`),a.kill(`SIGTERM`)}h(),f=setTimeout(()=>{a?.kill(`SIGTERM`)},1e4)}},S=async r=>{n.info(r,`gateway supervisor continuing prepared update`),console.log(`[gateway] applying update to ${r.targetVersion}...`);let i=await Sl(r.stateFilePath,{logger:n}),a=i.updated&&i.update.install.binPath?zc(i.update.install,`__worker`,e.args,t.cwd):Rc(t,`__worker`,e.args);n.info({updated:i.updated,update:i.update,nextInvocation:a},`gateway supervisor prepared next worker invocation`),!i.updated&&i.update.lastError&&console.error(`[gateway] update failed: ${i.update.lastError}`),i.updated?console.log(`[gateway] update installed; restarting worker...`):console.log(`[gateway] relaunching current worker after failed update.`),u=null,T(a)},C=(e,t)=>{if(h(),g(),n.info({workerPid:a?.pid??void 0,code:e,signal:t,preparedUpdate:u,shuttingDown:l},`gateway supervisor observed worker exit`),a=null,u){y(Error(`gateway worker restarting for update`)),S(u).catch(e=>{n.error({error:e,preparedUpdate:u},`gateway update handoff failed`),console.error(`[gateway] update handoff failed: ${String(e)}`),b(1)});return}if(l){b(0);return}if(y(Error(`gateway worker exited`)),!o){c?.(Error(`gateway worker exited before signaling ready (code=${String(e)}, signal=${String(t)})`)),c=null,s=null;return}t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),b(e??1)},w=t=>{switch(t.type){case`worker.ready`:if(!o){o=!0,n.info(t.payload,`gateway supervisor received initial worker ready`),console.log(pl({configPath:e.loaded.configPath,createdDefaultConfig:e.loaded.createdDefaultConfig,config:e.loaded.config,doctorReport:e.doctorReport,startedServer:t.payload,logToConsole:e.args.logToConsole})),s?.(),s=null,c=null;return}n.info(t.payload,`gateway supervisor received worker ready after update`),console.log(`[gateway] worker ready after update.`);return;case`worker.response`:{let e=r.get(t.id);if(!e)return;r.delete(t.id),t.ok?e.resolve(t.result):e.reject(Error(t.error));return}case`worker.update.prepared`:if(u)return;u=t.payload,n.info(t.payload,`gateway supervisor received worker update prepared`),g(),d=setTimeout(()=>{x(`update`)},250);return}},T=e=>{n.info(e,`gateway supervisor spawning worker`);let t=(0,m.spawn)(e.command,e.args,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0});a=t,n.info({workerPid:t.pid??void 0,invocation:e},`gateway supervisor spawned worker`),t.stdout&&t.stdout.pipe(v.default.stdout),t.stderr&&t.stderr.pipe(v.default.stderr),t.on(`message`,e=>{let t=Xl(e);t&&w(t)}),t.on(`exit`,(e,n)=>{t.stdout&&t.stdout.unpipe(v.default.stdout),t.stderr&&t.stderr.unpipe(v.default.stderr),C(e,n)}),t.on(`error`,t=>{if(n.error({error:t,invocation:e},`gateway supervisor failed to launch worker`),console.error(`[gateway] failed to launch worker: ${String(t)}`),!o){c?.(t instanceof Error?t:Error(String(t))),c=null,s=null;return}b(1)})},E=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`gateway.update.apply`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},D=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`codex.appServer.restart`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},O=e=>{if(!l){if(l=!0,n.info({signal:e},`gateway supervisor received shutdown signal`),console.log(`[gateway] received ${e}; shutting down...`),!a){b(0);return}x(`signal`)}};v.default.on(`SIGINT`,O),v.default.on(`SIGTERM`,O),T(Rc(t,`__worker`,e.args)),await p}function Jl(e){if(!e.enabled)return()=>{};let t=_.default.createInterface({input:v.default.stdin,output:v.default.stdout,terminal:!0});return t.on(`line`,t=>{let n=t.trim().toLowerCase();if(n===`update`){e.onUpdate();return}if(n===`restart codex`||n===`codex restart`){e.onRestartCodex();return}}),()=>{t.close()}}function Yl(){return{pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}}function Xl(e){if(!Zl(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return Zl(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||typeof e.ok!=`boolean`?null:e.ok?(e.method,{type:`worker.response`,id:e.id,method:e.method,ok:!0,result:e.result}):typeof e.error==`string`?{type:`worker.response`,id:e.id,method:e.method,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!Zl(e.payload)||typeof e.payload.stateFilePath!=`string`||typeof e.payload.targetVersion!=`string`||e.payload.requestedBy!==`console`&&e.payload.requestedBy!==`mobile`&&e.payload.requestedBy!==`system`?null:{type:`worker.update.prepared`,payload:{stateFilePath:e.payload.stateFilePath,targetVersion:e.payload.targetVersion,requestedBy:e.payload.requestedBy}};default:return null}}function Zl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ql(e){let t=f.default.hostname();u.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=(n,r,i)=>{let a={level:n,time:Date.now(),pid:v.default.pid,hostname:t,...$l(r),msg:i??``};try{u.default.appendFileSync(e,`${JSON.stringify(a,eu)}\n`,`utf8`)}catch{}};return{info:(e,t)=>{n(30,e,t)},warn:(e,t)=>{n(40,e,t)},error:(e,t)=>{n(50,e,t)},close:()=>{}}}function $l(e){return Zl(e)?e:{detail:e}}function eu(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t==`bigint`?t.toString():t}async function tu(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function nu(e,t){let n=t.httpsEnabled?t.httpsPort:t.port,r=t.httpsEnabled?`https`:`http`,i=e;return i?.code===`EADDRINUSE`?`[gateway] failed to start: ${r.toUpperCase()} ${t.host}:${n} is already in use.`:i?.code===`EACCES`?`[gateway] failed to start: permission denied for ${r.toUpperCase()} ${t.host}:${n}.`:i?.code===`ENOENT`||i?.code===`EISDIR`?`[gateway] failed to start: log path is invalid or unavailable: ${t.gatewayLogPath}`:i instanceof Error?`[gateway] failed to start: ${i.message}`:`[gateway] failed to start: ${String(e)}`}var ru=o(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),iu=o(((e,t)=>{var n=ru();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:w,abort:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(){var e=s;for(s=null,c=null;e;){var t=e.next,n=e.callback,r=e.errorHandler,a=e.value,o=e.context;e.value=null,e.callback=i,e.errorHandler=null,r&&r(Error(`abort`),a),n.call(o,Error(`abort`)),e.release(e),e=t}d.drain=i}function w(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),au=o(((e,t)=>{let{format:n}=require(`node:util`);function r(){return`${this.name} [${this.code}]: ${this.message}`}let i=Symbol.for(`fastify-error-generic`);function a(e,t,o=500,s=Error,c=a.captureStackTrace){let l=e===i;if(l&&(e=`FST_ERR`),!e)throw Error(`Fastify error code must not be empty`);if(!t)throw Error(`Fastify error message must not be empty`);e=e.toUpperCase(),!o&&(o=void 0);let u=Symbol.for(`fastify-error ${e}`);function d(...r){if(!new.target)return new d(...r);this.code=e,this.name=`FastifyError`,this.statusCode=o;let i=r.length-1;i!==-1&&r[i]&&typeof r[i]==`object`&&`cause`in r[i]&&(this.cause=r.pop().cause),this.message=n(t,...r),Error.stackTraceLimit&&c&&Error.captureStackTrace(this,d)}return d.prototype=Object.create(s.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0},[i]:{value:!0,enumerable:!1,writable:!1,configurable:!1},[u]:{value:!0,enumerable:!1,writable:!1,configurable:!1}}),l?Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[i]},configurable:!1,writable:!1,enumerable:!1}):Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[u]},configurable:!1,writable:!1,enumerable:!1}),d.prototype[Symbol.toStringTag]=`Error`,d.prototype.toString=r,d}a.captureStackTrace=!0;let o=a(i,`Fastify Error`,500,Error);t.exports=a,t.exports.FastifyError=o,t.exports.default=a,t.exports.createError=a})),ou=o(((e,t)=>{let{createError:n}=au();t.exports={AVV_ERR_EXPOSE_ALREADY_DEFINED:n(`AVV_ERR_EXPOSE_ALREADY_DEFINED`,`'%s' is already defined, specify an expose option for '%s'`),AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:n(`AVV_ERR_ATTRIBUTE_ALREADY_DEFINED`,`'%s' is already defined`),AVV_ERR_CALLBACK_NOT_FN:n(`AVV_ERR_CALLBACK_NOT_FN`,`Callback for '%s' hook is not a function. Received: '%s'`),AVV_ERR_PLUGIN_NOT_VALID:n(`AVV_ERR_PLUGIN_NOT_VALID`,`Plugin must be a function or a promise. Received: '%s'`),AVV_ERR_ROOT_PLG_BOOTED:n(`AVV_ERR_ROOT_PLG_BOOTED`,`Root plugin has already booted`),AVV_ERR_PARENT_PLG_LOADED:n(`AVV_ERR_PARENT_PLG_LOADED`,`Impossible to load '%s' plugin because the parent '%s' was already loaded`),AVV_ERR_READY_TIMEOUT:n(`AVV_ERR_READY_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`),AVV_ERR_PLUGIN_EXEC_TIMEOUT:n(`AVV_ERR_PLUGIN_EXEC_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`)}})),su=o(((e,t)=>{t.exports={kAvvio:Symbol(`avvio.Boot`),kIsOnCloseHandler:Symbol(`isOnCloseHandler`),kThenifyDoNotWrap:Symbol(`avvio.ThenifyDoNotWrap`),kUntrackNode:Symbol(`avvio.TimeTree.untrackNode`),kTrackNode:Symbol(`avvio.TimeTree.trackNode`),kGetParent:Symbol(`avvio.TimeTree.getParent`),kGetNode:Symbol(`avvio.TimeTree.getNode`),kAddNode:Symbol(`avvio.TimeTree.addNode`),kPluginMeta:Symbol.for(`plugin-meta`)}})),cu=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=su();var s=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[r](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[n](e){this.tableId.delete(e.id);let t=this.tableLabel.get(e.label);t.pop(),t.length===0&&this.tableLabel.delete(e.label)}[i](e){if(e===null)return null;if(this.tableLabel.has(e)){let t=this.tableLabel.get(e);return t[t.length-1]}else return null}[a](e){return this.tableId.get(e)}[o](e,t,n){let a=this[i](e);if(a===null)return this.root={parent:null,id:`root`,label:t,nodes:[],start:n,stop:null,diff:-1},this[r](this.root),this.root.id;let o=`${t}-${Math.random()}`,s={parent:e,id:o,label:t,nodes:[],start:n,stop:null,diff:-1};return a.nodes.push(s),this[r](s),o}start(e,t,n=Date.now()){return this[o](e,t,n)}stop(e,t=Date.now()){let r=this[a](e);r&&(r.stop=t,r.diff=r.stop-r.start||0,this[n](r))}toJSON(){return Object.assign({},this.root)}prettyPrint(){return c(this.toJSON())}};function c(e,t=``){let n=t,r=e.nodes.length,i=r-1;n+=`${e.label} ${e.diff} ms\n`;for(let a=0;a<r;++a){let r=e.nodes[a],o=t+(a===i?` `:`│ `);n+=t,n+=a===i?`└─`:`├─`,n+=r.nodes.length===0?`─ `:`┬ `,n+=c(r,o).slice(t.length+2)}return n}t.exports={TimeTree:s}})),lu=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),uu=o(((e,t)=>{function n(){let e={resolve:null,reject:null,promise:null};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}t.exports={createPromise:n}})),du=o(((e,t)=>{let{kPluginMeta:n}=su();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
|
|
123
|
+
`)}function ml(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function hl(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function gl(e){try{let t=new URL(e).hostname;return _l(t)}catch{return!1}}function _l(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const vl={platform:v.default.platform,now:()=>new Date,currentContext:()=>({pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}),runCommand:(e,t,n={})=>{let r=(0,m.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0,...n});return{status:r.status,stdout:typeof r.stdout==`string`?r.stdout:r.stdout?.toString(`utf8`)??``,stderr:typeof r.stderr==`string`?r.stderr:r.stderr?.toString(`utf8`)??``,...r.error?{error:r.error}:{}}}};function yl(){return p.default.join(nc(),`update-state.json`)}function bl(e){return Fa.parse({type:`gateway.update.status`,payload:e})}var xl=class{packageName;currentVersion;sessionHub;logger;consoleWrite;getRunningSessionCount;requestPreparedUpdate;stateFilePath;checkIntervalMs;runtime;state;scheduledCheckTimer=null;recurringCheckTimer=null;checkPromise=null;applyPromise=null;constructor(e){this.packageName=e.packageName,this.currentVersion=e.currentVersion,this.sessionHub=e.sessionHub,this.logger=e.logger,this.consoleWrite=e.consoleWrite,this.getRunningSessionCount=e.getRunningSessionCount,this.requestPreparedUpdate=e.requestPreparedUpdate,this.stateFilePath=e.stateFilePath??yl(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??vl,this.state=Pa.parse({packageName:this.packageName,currentVersion:this.currentVersion,available:!1,canApply:!1,status:`unknown`,install:{manager:`unknown`,installType:`unknown`,packageName:this.packageName,canSelfUpdate:!1}})}async start(){await this.reconcilePersistedState(),this.scheduledCheckTimer=setTimeout(()=>{this.checkForUpdates(`system`),this.scheduleRecurringChecks()},5e3)}async shutdown(){this.scheduledCheckTimer&&=(clearTimeout(this.scheduledCheckTimer),null),this.recurringCheckTimer&&=(clearInterval(this.recurringCheckTimer),null)}getInfo(){return Pa.parse(this.state)}async getOrCheckInfo(e){if(this.checkPromise)return this.checkPromise;let t=this.getInfo();return t.status===`unknown`||t.status===`failed`?this.checkForUpdates(e):t}async checkForUpdates(e){return this.checkPromise||=(async()=>{let t=this.runtime.now().toISOString(),n=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=wl(this.packageName,this.runtime);if(!r)return this.patchState({status:`failed`,available:!1,canApply:!1,latestVersion:void 0,checkedAt:t,install:n,lastError:`failed to query latest published gateway version`}),this.getInfo();let i=A(r,this.currentVersion)>0,a=i&&n.canSelfUpdate,o=i?a?`available`:`unsupported_install`:`up_to_date`;if(this.patchState({status:o,latestVersion:r,available:i,canApply:a,checkedAt:t,install:n,job:void 0,lastError:void 0}),i&&e!==`mobile`){let e=a?`[gateway] update available ${this.currentVersion} -> ${r}. Type update and press Enter to install and restart.`:`[gateway] update available ${this.currentVersion} -> ${r}, but this installation cannot self-update (${n.reason??`unsupported install`}).`;this.consoleWrite?.(e)}else e===`console`&&this.consoleWrite?.(`[gateway] already up to date at ${this.currentVersion}`);return this.getInfo()})().finally(()=>{this.checkPromise=null}),this.checkPromise}async applyUpdate(e){return this.applyPromise||=(async()=>{let t=await this.checkForUpdates(e);if(!t.available)throw Error(`gateway is already up to date`);if(!t.canApply||t.install.manager===`unknown`)throw Error(t.install.reason??`gateway installation does not support self-update`);if(t.status===`updating`||t.status===`restarting`)return Ia.parse({started:!1,update:t});let n=await this.getRunningSessionCount();if(n>0)throw Error(`gateway update requires idle runtime, found ${n} running session${n===1?``:`s`}`);let r=t.latestVersion;if(!r)throw Error(`latest gateway version is unknown`);let i=this.runtime.currentContext(),a={id:`gwupd_${Date.now()}`,targetVersion:r,requestedBy:e,requestedAt:this.runtime.now().toISOString(),startedAt:this.runtime.now().toISOString()},o={version:1,update:{...t,status:`updating`,job:a,lastError:void 0},helper:{manager:t.install.manager,packageName:this.packageName,targetVersion:r,originalPid:i.pid,restart:Pl(t.install,{cwd:i.cwd,argv:[...i.argv]}),requestedBy:e,requestedAt:a.requestedAt}},s=o.helper;if(!s)throw Error(`gateway update helper state was not prepared`);await Il(this.stateFilePath,o),this.patchState({status:`updating`,job:a,lastError:void 0}),this.consoleWrite?.(`[gateway] updating ${this.packageName} to ${r} via ${t.install.manager}; gateway will restart automatically.`),this.patchState({status:`restarting`,job:a}),this.logger.info?.({job:a,stateFilePath:this.stateFilePath,originalPid:i.pid,install:t.install,restart:s.restart},`gateway update handoff prepared`);try{await this.requestPreparedUpdate?.({stateFilePath:this.stateFilePath,targetVersion:r,requestedBy:e})}catch(e){let t=Pa.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await Il(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(bl(t)),e}return Ia.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=Pa.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(bl(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await Fl(this.stateFilePath);if(!e)return;let t=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime}),n=e.helper?.targetVersion??e.update.job?.targetVersion;if((e.update.status===`updating`||e.update.status===`restarting`)&&n){let r=A(this.currentVersion,n)>=0,i=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,latestVersion:r?this.currentVersion:n,available:!r,canApply:!r&&t.canSelfUpdate,status:r?`up_to_date`:`failed`,checkedAt:this.runtime.now().toISOString(),install:t,job:void 0,...r?{lastError:void 0}:{lastError:e.update.lastError??`gateway restarted before update completed`}});await Il(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Sl(e,t={}){let n=t.runtime??vl,r=t.waitForProcessExit??Ll,i=t.logger,a=await Fl(e);if(!a?.helper)throw Error(`gateway update helper state is missing`);i?.info?.({stateFilePath:e,originalPid:a.helper.originalPid,packageName:a.helper.packageName,targetVersion:a.helper.targetVersion,manager:a.helper.manager,cwd:a.helper.restart.cwd},`gateway update apply starting`);let o=Date.now();await r(a.helper.originalPid);let s=Date.now()-o,c=Rl(a.helper.originalPid);i?.[c?`warn`:`info`]?.({stateFilePath:e,originalPid:a.helper.originalPid,waitDurationMs:s,processStillRunning:c},c?`gateway update original process still running after wait window`:`gateway update original process exited`);let l=Cl(a.helper.manager,a.helper.packageName,a.helper.targetVersion);i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd},`gateway update install starting`);let u=Date.now(),d=n.runCommand(l.command,l.args,{cwd:a.helper.restart.cwd}),f=Date.now()-u;if(d.status!==0){let t={...a,update:{...a.update,status:`failed`,lastError:Bl(l.command,l.args,d)},helper:void 0};return await Il(e,t),i?.error?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status,error:d.error?.message,stderr:d.stderr.trim()||void 0,stdout:d.stdout.trim()||void 0},`gateway update install failed`),{updated:!1,update:Pa.parse(t.update)}}i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status},`gateway update install completed`);let p={...a,update:{...a.update,status:`restarting`,lastError:void 0},helper:void 0};return await Il(e,p),i?.info?.({stateFilePath:e,targetVersion:a.helper.targetVersion},`gateway update apply completed; worker restart may proceed`),{updated:!0,update:Pa.parse(p.update)}}function Cl(e,t,n){switch(e){case`npm`:return{command:`npm`,args:[`install`,`-g`,`${t}@${n}`]};case`pnpm`:return{command:`pnpm`,args:[`add`,`-g`,`${t}@${n}`]};case`yarn`:return{command:`yarn`,args:[`global`,`add`,`${t}@${n}`]}}}function wl(e,t){let n=t.runCommand(`npm`,[`view`,e,`version`,`--json`]);if(n.error||n.status!==0)return null;let r=n.stdout.trim();if(!r)return null;try{let e=JSON.parse(r);return typeof e==`string`&&e.trim()?e.trim():null}catch{return r.replace(/^"+|"+$/g,``)}}function Tl(e){let t=kl(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?Ma.parse({manager:`unknown`,installType:`dev_workspace`,packageName:e.packageName,packageRoot:t.packageRoot,canSelfUpdate:!1,reason:`workspace/development runtime does not support self-update`}):e.currentScriptPath?El(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Dl(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ol(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ma.parse({manager:`unknown`,installType:t.packageName===e.packageName?`unknown`:`standalone_binary`,packageName:e.packageName,...t.packageRoot?{packageRoot:t.packageRoot}:{},canSelfUpdate:!1,reason:t.packageName===e.packageName?`unable to determine global package manager installation`:`gateway is not running from a supported package-manager installation`}):Ma.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function El(e,t,n,r){let i=r.runCommand(`npm`,[`root`,`-g`]),a=r.runCommand(`npm`,[`prefix`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=jl(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),Nl(r.platform)),m=Ml(l,d)?`global_registry`:`global_file`;return Ma.parse({manager:`npm`,installType:m,packageName:e,packageRoot:l,binPath:f,canSelfUpdate:m===`global_registry`,...m===`global_registry`?{}:{reason:`npm file-linked global install is not supported`}})}function Dl(e,t,n,r){let i=r.runCommand(`pnpm`,[`root`,`-g`]),a=r.runCommand(`pnpm`,[`bin`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=Ml(l,jl(p.default.dirname(o)))?`global_registry`:`global_file`;return Ma.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Ol(e,t,n,r){let i=r.runCommand(`yarn`,[`global`,`dir`]),a=r.runCommand(`yarn`,[`global`,`bin`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,`node_modules`,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);return Al(l,t,n)?Ma.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:!0}):null}function kl(e){if(!e)return{packageRoot:null,packageName:null};let t=p.default.dirname(e);for(;;){let e=p.default.join(t,`package.json`);if(u.default.existsSync(e))try{let n=JSON.parse(u.default.readFileSync(e,`utf8`));if(typeof n.name==`string`)return{packageRoot:t,packageName:n.name}}catch{return{packageRoot:t,packageName:null}}let n=p.default.dirname(t);if(n===t)return{packageRoot:null,packageName:null};t=n}}function Al(e,t,n){let r=jl(e),i=t?jl(t):null,a=jl(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function jl(e){try{return u.default.realpathSync(e)}catch{return e}}function Ml(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function Nl(e=v.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function Pl(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function Fl(e){try{let t=await d.default.readFile(e,`utf8`);return Vl(JSON.parse(t))}catch{return null}}async function Il(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0}),await d.default.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}async function Ll(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!Rl(e))return;await zl(500)}}function Rl(e){try{return v.default.kill(e,0),!0}catch{return!1}}function zl(e){return new Promise(t=>setTimeout(t,e))}function Bl(e,t,n){let r=n.stderr.trim(),i=n.stdout.trim(),a=r||i||n.error?.message||`exit code ${String(n.status)}`;return`${e} ${t.join(` `)} failed: ${a}`}function Vl(e){if(!Wl(e)||e.version!==1)return null;let t=Pa.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=Hl(e.helper);return n?{version:1,update:t.data,helper:n}:null}function Hl(e){if(!Wl(e))return null;let t=ka.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=ja.safeParse(e.requestedBy);if(!n.success||!Gl(e.packageName)||!Gl(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!Kl(e.requestedAt))return null;let r=Ul(e.restart);return r?{manager:t.data,packageName:e.packageName,targetVersion:e.targetVersion,originalPid:e.originalPid,restart:r,requestedBy:n.data,requestedAt:e.requestedAt}:null}function Ul(e){return!Wl(e)||!Gl(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!Gl(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function Wl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gl(e){return typeof e==`string`&&e.trim().length>0}function Kl(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}async function ql(e){let t=Yl(),n=Ql(e.loaded.config.gatewayLogPath),r=new Map,i=0,a=null,o=!1,s=null,c=!1,l=null,u=null,d=null,f=null,p=0,h=Rc(t,`__worker`,e.args),g=new Promise((e,t)=>{s=e}),_=()=>{d&&=(clearTimeout(d),null)},y=()=>{f&&=(clearTimeout(f),null)},b=()=>{u&&=(clearTimeout(u),null)},x=Jl({enabled:v.default.stdin.isTTY&&v.default.stdout.isTTY,onUpdate:async()=>{if(!(!a||c))try{let e=await A(`console`);if(e.started){console.log(`[gateway] update accepted; restarting into ${e.update.job?.targetVersion??`latest`}...`);return}console.log(`[gateway] update already ${e.update.status}`)}catch(e){console.error(`[gateway] update failed: ${String(e)}`)}},onRestartCodex:async()=>{if(!(!a||c))try{let e=await j(`console`);console.log(`[gateway] codex app-server restarted; closed ${e.closedRuntimeSessionCount} runtime session${e.closedRuntimeSessionCount===1?``:`s`}.`)}catch(e){console.error(`[gateway] codex app-server restart failed: ${String(e)}`)}}}),S=e=>{for(let t of r.values())t.reject(e);r.clear()},C=e=>{b(),_(),y(),x(),S(Error(`gateway supervisor shutting down`)),n.close(),v.default.exit(e)},w=(e,t)=>{if(c||l||f)return;p+=1;let r=Math.min(p-1,4),i=Math.min(15e3,1e3*2**r);n.warn({...t,reason:e,delayMs:i,restartAttempt:p,invocation:h,initialReadyReceived:o},`gateway supervisor scheduling worker restart`),console.error(`[gateway] worker exited unexpectedly; restarting in ${i}ms (attempt ${p}).`),f=setTimeout(()=>{f=null,k(h)},i)},T=e=>{if(a){n.info({reason:e,workerPid:a.pid??void 0,preparedUpdate:l},`gateway supervisor requested worker shutdown`);try{a.send?.({type:`supervisor.shutdown`,reason:e})}catch(t){n.warn({reason:e,workerPid:a.pid??void 0,error:t},`gateway supervisor failed to send graceful shutdown message; sending SIGTERM`),a.kill(`SIGTERM`)}_(),d=setTimeout(()=>{a?.kill(`SIGTERM`)},1e4)}},E=async r=>{n.info(r,`gateway supervisor continuing prepared update`),console.log(`[gateway] applying update to ${r.targetVersion}...`);let i=await Sl(r.stateFilePath,{logger:n}),a=i.updated&&i.update.install.binPath?zc(i.update.install,`__worker`,e.args,t.cwd):Rc(t,`__worker`,e.args);n.info({updated:i.updated,update:i.update,nextInvocation:a},`gateway supervisor prepared next worker invocation`),!i.updated&&i.update.lastError&&console.error(`[gateway] update failed: ${i.update.lastError}`),i.updated?console.log(`[gateway] update installed; restarting worker...`):console.log(`[gateway] relaunching current worker after failed update.`),l=null,h=a,k(a)},D=(e,t)=>{if(_(),b(),n.info({workerPid:a?.pid??void 0,code:e,signal:t,preparedUpdate:l,shuttingDown:c},`gateway supervisor observed worker exit`),a=null,l){S(Error(`gateway worker restarting for update`)),E(l).catch(e=>{n.error({error:e,preparedUpdate:l},`gateway update handoff failed`),console.error(`[gateway] update handoff failed: ${String(e)}`),C(1)});return}if(c){C(0);return}S(Error(`gateway worker exited`)),t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),w(`worker_exit`,{code:e,signal:t})},O=t=>{switch(t.type){case`worker.ready`:if(p=0,y(),!o){o=!0,n.info(t.payload,`gateway supervisor received initial worker ready`),console.log(pl({configPath:e.loaded.configPath,createdDefaultConfig:e.loaded.createdDefaultConfig,config:e.loaded.config,doctorReport:e.doctorReport,startedServer:t.payload,logToConsole:e.args.logToConsole})),s?.(),s=null;return}n.info(t.payload,`gateway supervisor received worker ready after update`),console.log(`[gateway] worker ready after update.`);return;case`worker.response`:{let e=r.get(t.id);if(!e)return;r.delete(t.id),t.ok?e.resolve(t.result):e.reject(Error(t.error));return}case`worker.update.prepared`:if(l)return;l=t.payload,n.info(t.payload,`gateway supervisor received worker update prepared`),b(),u=setTimeout(()=>{T(`update`)},250);return}},k=e=>{h=e,y(),n.info(e,`gateway supervisor spawning worker`);let t=(0,m.spawn)(e.command,e.args,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0});a=t,n.info({workerPid:t.pid??void 0,invocation:e},`gateway supervisor spawned worker`),t.stdout&&t.stdout.pipe(v.default.stdout),t.stderr&&t.stderr.pipe(v.default.stderr),t.on(`message`,e=>{let t=Xl(e);t&&O(t)}),t.on(`exit`,(e,n)=>{a===t&&(t.stdout&&t.stdout.unpipe(v.default.stdout),t.stderr&&t.stderr.unpipe(v.default.stderr),D(e,n))}),t.on(`error`,r=>{a===t&&(t.stdout&&t.stdout.unpipe(v.default.stdout),t.stderr&&t.stderr.unpipe(v.default.stderr),a=null,n.error({error:r,invocation:e},`gateway supervisor failed to launch worker`),console.error(`[gateway] failed to launch worker: ${String(r)}`),w(`worker_launch_error`,{error:r}))})},A=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`gateway.update.apply`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},j=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`codex.appServer.restart`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},M=e=>{if(!c){if(c=!0,n.info({signal:e},`gateway supervisor received shutdown signal`),console.log(`[gateway] received ${e}; shutting down...`),!a){C(0);return}T(`signal`)}};v.default.on(`SIGINT`,M),v.default.on(`SIGTERM`,M),k(h),await g}function Jl(e){if(!e.enabled)return()=>{};let t=_.default.createInterface({input:v.default.stdin,output:v.default.stdout,terminal:!0});return t.on(`line`,t=>{let n=t.trim().toLowerCase();if(n===`update`){e.onUpdate();return}if(n===`restart codex`||n===`codex restart`){e.onRestartCodex();return}}),()=>{t.close()}}function Yl(){return{pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}}function Xl(e){if(!Zl(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return Zl(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||typeof e.ok!=`boolean`?null:e.ok?(e.method,{type:`worker.response`,id:e.id,method:e.method,ok:!0,result:e.result}):typeof e.error==`string`?{type:`worker.response`,id:e.id,method:e.method,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!Zl(e.payload)||typeof e.payload.stateFilePath!=`string`||typeof e.payload.targetVersion!=`string`||e.payload.requestedBy!==`console`&&e.payload.requestedBy!==`mobile`&&e.payload.requestedBy!==`system`?null:{type:`worker.update.prepared`,payload:{stateFilePath:e.payload.stateFilePath,targetVersion:e.payload.targetVersion,requestedBy:e.payload.requestedBy}};default:return null}}function Zl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ql(e){let t=f.default.hostname();u.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=(n,r,i)=>{let a={level:n,time:Date.now(),pid:v.default.pid,hostname:t,...$l(r),msg:i??``};try{u.default.appendFileSync(e,`${JSON.stringify(a,eu)}\n`,`utf8`)}catch{}};return{info:(e,t)=>{n(30,e,t)},warn:(e,t)=>{n(40,e,t)},error:(e,t)=>{n(50,e,t)},close:()=>{}}}function $l(e){return Zl(e)?e:{detail:e}}function eu(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t==`bigint`?t.toString():t}async function tu(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function nu(e,t){let n=t.httpsEnabled?t.httpsPort:t.port,r=t.httpsEnabled?`https`:`http`,i=e;return i?.code===`EADDRINUSE`?`[gateway] failed to start: ${r.toUpperCase()} ${t.host}:${n} is already in use.`:i?.code===`EACCES`?`[gateway] failed to start: permission denied for ${r.toUpperCase()} ${t.host}:${n}.`:i?.code===`ENOENT`||i?.code===`EISDIR`?`[gateway] failed to start: log path is invalid or unavailable: ${t.gatewayLogPath}`:i instanceof Error?`[gateway] failed to start: ${i.message}`:`[gateway] failed to start: ${String(e)}`}var ru=o(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),iu=o(((e,t)=>{var n=ru();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:w,abort:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(){var e=s;for(s=null,c=null;e;){var t=e.next,n=e.callback,r=e.errorHandler,a=e.value,o=e.context;e.value=null,e.callback=i,e.errorHandler=null,r&&r(Error(`abort`),a),n.call(o,Error(`abort`)),e.release(e),e=t}d.drain=i}function w(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),au=o(((e,t)=>{let{format:n}=require(`node:util`);function r(){return`${this.name} [${this.code}]: ${this.message}`}let i=Symbol.for(`fastify-error-generic`);function a(e,t,o=500,s=Error,c=a.captureStackTrace){let l=e===i;if(l&&(e=`FST_ERR`),!e)throw Error(`Fastify error code must not be empty`);if(!t)throw Error(`Fastify error message must not be empty`);e=e.toUpperCase(),!o&&(o=void 0);let u=Symbol.for(`fastify-error ${e}`);function d(...r){if(!new.target)return new d(...r);this.code=e,this.name=`FastifyError`,this.statusCode=o;let i=r.length-1;i!==-1&&r[i]&&typeof r[i]==`object`&&`cause`in r[i]&&(this.cause=r.pop().cause),this.message=n(t,...r),Error.stackTraceLimit&&c&&Error.captureStackTrace(this,d)}return d.prototype=Object.create(s.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0},[i]:{value:!0,enumerable:!1,writable:!1,configurable:!1},[u]:{value:!0,enumerable:!1,writable:!1,configurable:!1}}),l?Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[i]},configurable:!1,writable:!1,enumerable:!1}):Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[u]},configurable:!1,writable:!1,enumerable:!1}),d.prototype[Symbol.toStringTag]=`Error`,d.prototype.toString=r,d}a.captureStackTrace=!0;let o=a(i,`Fastify Error`,500,Error);t.exports=a,t.exports.FastifyError=o,t.exports.default=a,t.exports.createError=a})),ou=o(((e,t)=>{let{createError:n}=au();t.exports={AVV_ERR_EXPOSE_ALREADY_DEFINED:n(`AVV_ERR_EXPOSE_ALREADY_DEFINED`,`'%s' is already defined, specify an expose option for '%s'`),AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:n(`AVV_ERR_ATTRIBUTE_ALREADY_DEFINED`,`'%s' is already defined`),AVV_ERR_CALLBACK_NOT_FN:n(`AVV_ERR_CALLBACK_NOT_FN`,`Callback for '%s' hook is not a function. Received: '%s'`),AVV_ERR_PLUGIN_NOT_VALID:n(`AVV_ERR_PLUGIN_NOT_VALID`,`Plugin must be a function or a promise. Received: '%s'`),AVV_ERR_ROOT_PLG_BOOTED:n(`AVV_ERR_ROOT_PLG_BOOTED`,`Root plugin has already booted`),AVV_ERR_PARENT_PLG_LOADED:n(`AVV_ERR_PARENT_PLG_LOADED`,`Impossible to load '%s' plugin because the parent '%s' was already loaded`),AVV_ERR_READY_TIMEOUT:n(`AVV_ERR_READY_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`),AVV_ERR_PLUGIN_EXEC_TIMEOUT:n(`AVV_ERR_PLUGIN_EXEC_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`)}})),su=o(((e,t)=>{t.exports={kAvvio:Symbol(`avvio.Boot`),kIsOnCloseHandler:Symbol(`isOnCloseHandler`),kThenifyDoNotWrap:Symbol(`avvio.ThenifyDoNotWrap`),kUntrackNode:Symbol(`avvio.TimeTree.untrackNode`),kTrackNode:Symbol(`avvio.TimeTree.trackNode`),kGetParent:Symbol(`avvio.TimeTree.getParent`),kGetNode:Symbol(`avvio.TimeTree.getNode`),kAddNode:Symbol(`avvio.TimeTree.addNode`),kPluginMeta:Symbol.for(`plugin-meta`)}})),cu=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=su();var s=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[r](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[n](e){this.tableId.delete(e.id);let t=this.tableLabel.get(e.label);t.pop(),t.length===0&&this.tableLabel.delete(e.label)}[i](e){if(e===null)return null;if(this.tableLabel.has(e)){let t=this.tableLabel.get(e);return t[t.length-1]}else return null}[a](e){return this.tableId.get(e)}[o](e,t,n){let a=this[i](e);if(a===null)return this.root={parent:null,id:`root`,label:t,nodes:[],start:n,stop:null,diff:-1},this[r](this.root),this.root.id;let o=`${t}-${Math.random()}`,s={parent:e,id:o,label:t,nodes:[],start:n,stop:null,diff:-1};return a.nodes.push(s),this[r](s),o}start(e,t,n=Date.now()){return this[o](e,t,n)}stop(e,t=Date.now()){let r=this[a](e);r&&(r.stop=t,r.diff=r.stop-r.start||0,this[n](r))}toJSON(){return Object.assign({},this.root)}prettyPrint(){return c(this.toJSON())}};function c(e,t=``){let n=t,r=e.nodes.length,i=r-1;n+=`${e.label} ${e.diff} ms\n`;for(let a=0;a<r;++a){let r=e.nodes[a],o=t+(a===i?` `:`│ `);n+=t,n+=a===i?`└─`:`├─`,n+=r.nodes.length===0?`─ `:`┬ `,n+=c(r,o).slice(t.length+2)}return n}t.exports={TimeTree:s}})),lu=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),uu=o(((e,t)=>{function n(){let e={resolve:null,reject:null,promise:null};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}t.exports={createPromise:n}})),du=o(((e,t)=>{let{kPluginMeta:n}=su();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
|
|
124
124
|
`).slice(0,2).map(e=>e.trim()).join(` -- `)}t.exports={getPluginName:r}})),fu=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}t.exports={isPromiseLike:n}})),pu=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{inherits:r}=require(`node:util`),{debug:i}=lu(),{createPromise:a}=uu(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:o}=ou(),{getPluginName:s}=du(),{isPromiseLike:c}=fu();function l(e,t,n,r,i){this.queue=e,this.func=t,this.options=n,this.isAfter=r,this.timeout=i,this.started=!1,this.name=s(t,n),this.queue.pause(),this._error=null,this.loaded=!1,this._promise=null,this.startTime=null}r(l,n),l.prototype.exec=function(e,t){i(`exec`,this.name),this.server=e;let n=this.func,r=this.name,a=!1;this.options=typeof this.options==`function`?this.options(this.server):this.options;let s=null,l=e=>{if(a){i(`loading complete`,r);return}this._error=e,i(e?`exec errored`:`exec completed`,r),a=!0,s&&clearTimeout(s),t(e)};this.timeout>0&&(i(`setting up timeout`,r,this.timeout),s=setTimeout(function(){i(`timed out`,r),s=null;let e=new o(r);e.fn=n,l(e)},this.timeout)),this.started=!0,this.startTime=Date.now(),this.emit(`start`,this.server?this.server.name:null,this.name,Date.now());let u=n(this.server,this.options,l);c(u)?(i(`exec: resolving promise`,r),u.then(()=>process.nextTick(l),e=>process.nextTick(l,e))):n.length<3&&l()},l.prototype.loadedSoFar=function(){if(i(`loadedSoFar`,this.name),this.loaded)return Promise.resolve();let e=()=>{this.server.after((e,t)=>{this._error=e,this.queue.pause(),this._promise&&=(e?(i(`rejecting promise`,this.name,e),this._promise.reject(e)):(i(`resolving promise`,this.name),this._promise.resolve()),null),process.nextTick(t,e)}),this.queue.resume()},t;return this._promise?t=Promise.resolve():(this._promise=a(),t=this._promise.promise,this.server?e():this.on(`start`,e)),t},l.prototype.enqueue=function(e,t){i(`enqueue`,this.name,e.name),this.emit(`enqueue`,this.server?this.server.name:null,this.name,Date.now()),this.queue.push(e,t)},l.prototype.finish=function(e,t){i(`finish`,this.name,e);let n=()=>{this.loaded||(i(`loaded`,this.name),this.emit(`loaded`,this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,t(e))};if(e){this._promise&&=(this._promise.reject(e),null),n();return}let r=()=>{if(i(`check`,this.name,this.queue.length(),this.queue.running(),this._promise),this.queue.length()===0&&this.queue.running()===0)if(this._promise){let e=()=>{i(`wrap`),queueMicrotask(r)};this._promise.resolve(),this._promise.promise.then(e,e),this._promise=null}else n();else i(`delayed`,this.name),this.queue.drain=()=>{i(`drain`,this.name),this.queue.drain=u,queueMicrotask(r)}};queueMicrotask(r),this.queue.resume()};function u(){}t.exports={Plugin:l}})),mu=o(((e,t)=>{let{AVV_ERR_PLUGIN_NOT_VALID:n}=ou();function r(e){if(!(e&&(typeof e==`function`||typeof e.then==`function`)))throw Array.isArray(e)?new n(`array`):e===null?new n(`null`):new n(typeof e)}t.exports={validatePlugin:r}})),hu=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.default==`function`}t.exports={isBundledOrTypescriptPlugin:n}})),gu=o(((e,t)=>{let{debug:n}=lu(),{kThenifyDoNotWrap:r}=su();function i(){if(this.booted){n(`thenify returning undefined because we are already booted`);return}if(this[r]){this[r]=!1;return}return n(`thenify`),(e,t)=>this._loadRegistered().then(()=>(this[r]=!0,e(this._server)),t)}t.exports={thenify:i}})),_u=o(((e,t)=>{let{isPromiseLike:n}=fu(),{kAvvio:r}=su();function i(e,t,i){let a;try{a=e.apply(e,t)}catch(e){i&&process.nextTick(i,e);return}n(a)&&!a[r]?a.then(()=>process.nextTick(i),e=>process.nextTick(i,e)):i&&process.nextTick(i)}t.exports={executeWithThenable:i}})),vu=o(((e,t)=>{let n=iu(),r=require(`node:events`).EventEmitter,i=require(`node:util`).inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:a,AVV_ERR_CALLBACK_NOT_FN:o,AVV_ERR_ROOT_PLG_BOOTED:s,AVV_ERR_READY_TIMEOUT:c,AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:l}=ou(),{kAvvio:u,kIsOnCloseHandler:d}=su(),{TimeTree:f}=cu(),{Plugin:p}=pu(),{debug:m}=lu(),{validatePlugin:h}=mu(),{isBundledOrTypescriptPlugin:g}=hu(),{isPromiseLike:_}=fu(),{thenify:v}=gu(),{executeWithThenable:y}=_u();function b(e,t,r){if(typeof e==`function`&&arguments.length===1&&(r=e,t={},e=null),typeof t==`function`&&(r=t,t={}),t||={},t.autostart=t.autostart!==!1,t.timeout=Number(t.timeout)||0,t.expose=t.expose||{},!new.target)return new b(e,t,r);this._server=e||this,this._opts=t,e&&this._expose(),this._current=[],this._error=null,this._lastUsed=null,this.setMaxListeners(0),r&&this.once(`start`,r),this.started=!1,this.booted=!1,this.pluginTree=new f,this._readyQ=n(this,S,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit(`start`),this._readyQ.drain=x},this._closeQ=n(this,w,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit(`close`),this._closeQ.drain=x},this._doStart=null;let i=this;this._root=new p(n(this,this._loadPluginNextTick,1),function(e,t,n){i._doStart=n,t.autostart&&i.start()},t,!1,0),this._trackPluginLoading(this._root),this._loadPlugin(this._root,e=>{m(`root plugin ready`);try{this.emit(`preReady`),this._root=null}catch(t){e=e||this._error||t}if(e){if(this._error=e,this._readyQ.length()===0)throw e}else this.booted=!0;this._readyQ.resume()})}i(b,r),`asyncDispose`in Symbol&&(b.prototype[Symbol.asyncDispose]=function(){return new Promise((e,t)=>{this.close(n=>{if(n)return t(n);e()})})}),b.prototype.start=function(){return this.started=!0,process.nextTick(this._doStart),this},b.prototype.override=function(e,t,n){return e},b.prototype[u]=!0,b.prototype.use=function(e,t){return this._lastUsed=this._addPlugin(e,t,!1),this},b.prototype._loadRegistered=function(){let e=this._current[0];return!this.started&&!this.booted&&process.nextTick(()=>this._root.queue.resume()),e?e.loadedSoFar():Promise.resolve()},Object.defineProperty(b.prototype,`then`,{get:v}),b.prototype._addPlugin=function(e,t,r){if(g(e)&&(e=e.default),h(e),t||={},this.booted)throw new s;let i=this._current[0],a=this._opts.timeout;if(!i.loaded&&i.timeout>0){let e=Date.now()-i.startTime;a=i.timeout-(e+3)}let o=new p(n(this,this._loadPluginNextTick,1),e,t,r,a);if(this._trackPluginLoading(o),i.loaded)throw Error(o.name,i.name);return i.enqueue(o,e=>{e&&(this._error=e)}),o},b.prototype._expose=function(){let e=this,t=e._server,{use:n=`use`,after:r=`after`,ready:i=`ready`,onClose:s=`onClose`,close:c=`close`}=this._opts.expose;if(t[n])throw new a(n,`use`);if(t[n]=function(t,n){return e.use(t,n),this},t[r])throw new a(r,`after`);if(t[r]=function(t){return typeof t==`function`?(e.after(E(t,this)),this):e._loadRegistered()},t[i])throw new a(i,`ready`);if(t[i]=function(t){if(t&&typeof t!=`function`)throw new o(i,typeof t);return e.ready(t?E(t,this):void 0)},t[s])throw new a(s,`onClose`);if(t[s]=function(t){if(typeof t!=`function`)throw new o(s,typeof t);return e.onClose(T(t,this)),this},t[c])throw new a(c,`close`);if(t[c]=function(t){if(t&&typeof t!=`function`)throw new o(c,typeof t);return t?(e.close(E(t,this)),this):e.close()},t.then)throw new l(`then`);Object.defineProperty(t,`then`,{get:v.bind(e)}),t[u]=!0},b.prototype.after=function(e){if(!e)return this._loadRegistered();this._addPlugin(t.bind(this),{},!0);function t(t,n,r){S.call(this,e,r)}return this},b.prototype.onClose=function(e){if(typeof e!=`function`)throw new o(`onClose`,typeof e);return e[d]=!0,this._closeQ.unshift(e,e=>{e&&(this._error=e)}),this},b.prototype.close=function(e){let t;if(e){if(typeof e!=`function`)throw new o(`close`,typeof e)}else t=new Promise(function(t,n){e=function(e){if(e)return n(e);t()}});return this.ready(()=>{this._error=null,this._closeQ.push(e),process.nextTick(this._closeQ.resume.bind(this._closeQ))}),t},b.prototype.ready=function(e){if(e){if(typeof e!=`function`)throw new o(`ready`,typeof e);this._readyQ.push(e),queueMicrotask(this.start.bind(this));return}return new Promise((e,t)=>{this._readyQ.push(r),this.start();let n=this._current[0].server;function r(r,i,a){r?t(r):e(n),process.nextTick(a)}})},b.prototype._trackPluginLoading=function(e){let t=this._current[0]?.name||null;e.once(`start`,(n,r,i)=>{let a=this.pluginTree.start(t||null,r,i);e.once(`loaded`,(e,t,n)=>{this.pluginTree.stop(a,n)})})},b.prototype.prettyPrint=function(){return this.pluginTree.prettyPrint()},b.prototype.toJSON=function(){return this.pluginTree.toJSON()},b.prototype._loadPlugin=function(e,t){let n=this;if(_(e.func)){e.func.then(n=>{typeof n.default==`function`&&(n=n.default),e.func=n,this._loadPlugin(e,t)},t);return}let r=n._current[0];if(n._current.unshift(e),n._error&&!e.isAfter){m(`skipping loading of plugin as instance errored and it is not an after`,e.name),process.nextTick(a);return}let i=r?.server||n._server;if(!e.isAfter)try{i=n.override(i,e.func,e.options)}catch(t){return m(`override errored`,e.name),a(t)}e.exec(i,a);function a(r){e.finish(r,e=>{n._current.shift(),t(e)})}},b.prototype._loadPluginNextTick=function(e,t){process.nextTick(this._loadPlugin.bind(this),e,t)};function x(){}function S(e,t){let n=this._server,r=this._error;if(this._error=null,e.length===0)this._error=r,y(e,[],t);else if(e.length===1)y(e,[r],t);else if(this._opts.timeout===0){let i=e=>{this._error=e,t(this._error)};e.length===2?e(r,i):e(r,n,i)}else C.call(this,e,r,n,t)}function C(e,t,n,r){let i=e.unwrappedName??e.name;m(`setting up ready timeout`,i,this._opts.timeout);let a=setTimeout(()=>{m(`timed out`,i),a=null;let t=new c(i);t.fn=e,this._error=t,r(t)},this._opts.timeout);e.length===2?e(t,o.bind(this)):e(t,n,o.bind(this));function o(e){a&&(clearTimeout(a),this._error=e,r(this._error))}}function w(e,t){let n=this._server,r=e[d];if(e.length===0||e.length===1){let i;i=e(r?n:this._error),i&&typeof i.then==`function`?(m(`resolving close/onClose promise`),i.then(()=>process.nextTick(t),e=>process.nextTick(t,e))):process.nextTick(t)}else e.length===2?e(r?n:this._error,t):r?e(n,t):e(this._error,n,t)}function T(e,t){return n.bind(t);function n(t,n){let r;e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===1?(r=e(this),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e(this,n)}}function E(e,t){let n=r.bind(t);return n.unwrappedName=e.name,n;function r(t,n){let r;e?e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n,t)},n):process.nextTick(n,t)):e.length===1?(r=e(t),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===2?e(t,n):e(t,this,n):process.nextTick(n)}}t.exports=b})),yu=o(((e,t)=>{t.exports={kAvvioBoot:Symbol(`fastify.avvioBoot`),kChildren:Symbol(`fastify.children`),kServerBindings:Symbol(`fastify.serverBindings`),kBodyLimit:Symbol(`fastify.bodyLimit`),kSupportedHTTPMethods:Symbol(`fastify.acceptedHTTPMethods`),kRoutePrefix:Symbol(`fastify.routePrefix`),kLogLevel:Symbol(`fastify.logLevel`),kLogSerializers:Symbol(`fastify.logSerializers`),kHooks:Symbol(`fastify.hooks`),kContentTypeParser:Symbol(`fastify.contentTypeParser`),kState:Symbol(`fastify.state`),kOptions:Symbol(`fastify.options`),kDisableRequestLogging:Symbol(`fastify.disableRequestLogging`),kPluginNameChain:Symbol(`fastify.pluginNameChain`),kRouteContext:Symbol(`fastify.context`),kGenReqId:Symbol(`fastify.genReqId`),kHttp2ServerSessions:Symbol(`fastify.http2ServerSessions`),kSchemaController:Symbol(`fastify.schemaController`),kSchemaHeaders:Symbol(`headers-schema`),kSchemaParams:Symbol(`params-schema`),kSchemaQuerystring:Symbol(`querystring-schema`),kSchemaBody:Symbol(`body-schema`),kSchemaResponse:Symbol(`response-schema`),kSchemaErrorFormatter:Symbol(`fastify.schemaErrorFormatter`),kSchemaVisited:Symbol(`fastify.schemas.visited`),kRequest:Symbol(`fastify.Request`),kRequestPayloadStream:Symbol(`fastify.RequestPayloadStream`),kRequestAcceptVersion:Symbol(`fastify.RequestAcceptVersion`),kRequestCacheValidateFns:Symbol(`fastify.request.cache.validateFns`),kRequestOriginalUrl:Symbol(`fastify.request.originalUrl`),kFourOhFour:Symbol(`fastify.404`),kCanSetNotFoundHandler:Symbol(`fastify.canSetNotFoundHandler`),kFourOhFourLevelInstance:Symbol(`fastify.404LogLevelInstance`),kFourOhFourContext:Symbol(`fastify.404ContextKey`),kDefaultJsonParse:Symbol(`fastify.defaultJSONParse`),kReply:Symbol(`fastify.Reply`),kReplySerializer:Symbol(`fastify.reply.serializer`),kReplyIsError:Symbol(`fastify.reply.isError`),kReplyHeaders:Symbol(`fastify.reply.headers`),kReplyTrailers:Symbol(`fastify.reply.trailers`),kReplyHasStatusCode:Symbol(`fastify.reply.hasStatusCode`),kReplyHijacked:Symbol(`fastify.reply.hijacked`),kReplyStartTime:Symbol(`fastify.reply.startTime`),kReplyNextErrorHandler:Symbol(`fastify.reply.nextErrorHandler`),kReplyEndTime:Symbol(`fastify.reply.endTime`),kReplyErrorHandlerCalled:Symbol(`fastify.reply.errorHandlerCalled`),kReplyIsRunningOnErrorHook:Symbol(`fastify.reply.isRunningOnErrorHook`),kReplySerializerDefault:Symbol(`fastify.replySerializerDefault`),kReplyCacheSerializeFns:Symbol(`fastify.reply.cache.serializeFns`),kTestInternals:Symbol(`fastify.testInternals`),kErrorHandler:Symbol(`fastify.errorHandler`),kErrorHandlerAlreadySet:Symbol(`fastify.errorHandlerAlreadySet`),kChildLoggerFactory:Symbol(`fastify.childLoggerFactory`),kHasBeenDecorated:Symbol(`fastify.hasBeenDecorated`),kKeepAliveConnections:Symbol(`fastify.keepAliveConnections`),kRouteByFastify:Symbol(`fastify.routeByFastify`)}})),bu=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),xu=o(((e,t)=>{let{createWarning:n}=bu();t.exports={FSTWRN001:n({name:`FastifyWarning`,code:`FSTWRN001`,message:`The %s schema for %s: %s is missing. This may indicate the schema is not well specified.`,unlimited:!0}),FSTWRN003:n({name:`FastifyWarning`,code:`FSTWRN003`,message:`The %s mixes async and callback styles that may lead to unhandled rejections. Please use only one of them.`,unlimited:!0}),FSTWRN004:n({name:`FastifyWarning`,code:`FSTWRN004`,message:`It seems that you are overriding an errorHandler in the same scope, which can lead to subtle bugs.`,unlimited:!0}),FSTSEC001:n({name:`FastifySecurity`,code:`FSTSEC001`,message:`You are using /%s/ Content-Type which may be vulnerable to CORS attack. Please make sure your RegExp start with "^" or include ";?" to proper detection of the essence MIME type.`,unlimited:!0}),FSTDEP022:n({name:`FastifyWarning`,code:`FSTDEP022`,message:'The router options for %s property access is deprecated. Please use "options.routerOptions" instead for accessing router options. The router options will be removed in `fastify@6`.',unlimited:!0})}})),Su=o(((e,t)=>{let n=au(),r={FST_ERR_NOT_FOUND:n(`FST_ERR_NOT_FOUND`,`Not Found`,404),FST_ERR_OPTIONS_NOT_OBJ:n(`FST_ERR_OPTIONS_NOT_OBJ`,`Options must be an object`,500,TypeError),FST_ERR_QSP_NOT_FN:n(`FST_ERR_QSP_NOT_FN`,`querystringParser option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:n(`FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN`,`schemaController.bucket option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:n(`FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN`,`schemaErrorFormatter option should be a non async function. Instead got '%s'.`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ`,`ajv.customOptions option should be an object, instead got '%s'`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR`,`ajv.plugins option should be an array, instead got '%s'`,500,TypeError),FST_ERR_VALIDATION:n(`FST_ERR_VALIDATION`,`%s`,400),FST_ERR_LISTEN_OPTIONS_INVALID:n(`FST_ERR_LISTEN_OPTIONS_INVALID`,`Invalid listen options: '%s'`,500,TypeError),FST_ERR_ERROR_HANDLER_NOT_FN:n(`FST_ERR_ERROR_HANDLER_NOT_FN`,`Error Handler must be a function`,500,TypeError),FST_ERR_ERROR_HANDLER_ALREADY_SET:n(`FST_ERR_ERROR_HANDLER_ALREADY_SET`,`Error Handler already set in this scope. Set 'allowErrorHandlerOverride: true' to allow overriding.`,500,TypeError),FST_ERR_CTP_ALREADY_PRESENT:n(`FST_ERR_CTP_ALREADY_PRESENT`,`Content type parser '%s' already present.`),FST_ERR_CTP_INVALID_TYPE:n(`FST_ERR_CTP_INVALID_TYPE`,`The content type should be a string or a RegExp`,500,TypeError),FST_ERR_CTP_EMPTY_TYPE:n(`FST_ERR_CTP_EMPTY_TYPE`,`The content type cannot be an empty string`,500,TypeError),FST_ERR_CTP_INVALID_HANDLER:n(`FST_ERR_CTP_INVALID_HANDLER`,`The content type handler should be a function`,500,TypeError),FST_ERR_CTP_INVALID_PARSE_TYPE:n(`FST_ERR_CTP_INVALID_PARSE_TYPE`,`The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.`,500,TypeError),FST_ERR_CTP_BODY_TOO_LARGE:n(`FST_ERR_CTP_BODY_TOO_LARGE`,`Request body is too large`,413,RangeError),FST_ERR_CTP_INVALID_MEDIA_TYPE:n(`FST_ERR_CTP_INVALID_MEDIA_TYPE`,`Unsupported Media Type: %s`,415),FST_ERR_CTP_INVALID_CONTENT_LENGTH:n(`FST_ERR_CTP_INVALID_CONTENT_LENGTH`,`Request body size did not match Content-Length`,400,RangeError),FST_ERR_CTP_EMPTY_JSON_BODY:n(`FST_ERR_CTP_EMPTY_JSON_BODY`,`Body cannot be empty when content-type is set to 'application/json'`,400),FST_ERR_CTP_INVALID_JSON_BODY:n(`FST_ERR_CTP_INVALID_JSON_BODY`,`Body is not valid JSON but content-type is set to 'application/json'`,400),FST_ERR_CTP_INSTANCE_ALREADY_STARTED:n(`FST_ERR_CTP_INSTANCE_ALREADY_STARTED`,`Cannot call "%s" when fastify instance is already started!`,400),FST_ERR_DEC_ALREADY_PRESENT:n(`FST_ERR_DEC_ALREADY_PRESENT`,`The decorator '%s' has already been added!`),FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:n(`FST_ERR_DEC_DEPENDENCY_INVALID_TYPE`,`The dependencies of decorator '%s' must be of type Array.`,500,TypeError),FST_ERR_DEC_MISSING_DEPENDENCY:n(`FST_ERR_DEC_MISSING_DEPENDENCY`,`The decorator is missing dependency '%s'.`),FST_ERR_DEC_AFTER_START:n(`FST_ERR_DEC_AFTER_START`,`The decorator '%s' has been added after start!`),FST_ERR_DEC_REFERENCE_TYPE:n(`FST_ERR_DEC_REFERENCE_TYPE`,`The decorator '%s' of type '%s' is a reference type. Use the { getter, setter } interface instead.`),FST_ERR_DEC_UNDECLARED:n(`FST_ERR_DEC_UNDECLARED`,`No decorator '%s' has been declared on %s.`),FST_ERR_HOOK_INVALID_TYPE:n(`FST_ERR_HOOK_INVALID_TYPE`,`The hook name must be a string`,500,TypeError),FST_ERR_HOOK_INVALID_HANDLER:n(`FST_ERR_HOOK_INVALID_HANDLER`,`%s hook should be a function, instead got %s`,500,TypeError),FST_ERR_HOOK_INVALID_ASYNC_HANDLER:n(`FST_ERR_HOOK_INVALID_ASYNC_HANDLER`,`Async function has too many arguments. Async hooks should not use the 'done' argument.`,500,TypeError),FST_ERR_HOOK_NOT_SUPPORTED:n(`FST_ERR_HOOK_NOT_SUPPORTED`,`%s hook not supported!`,500,TypeError),FST_ERR_MISSING_MIDDLEWARE:n(`FST_ERR_MISSING_MIDDLEWARE`,`You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.`,500),FST_ERR_HOOK_TIMEOUT:n(`FST_ERR_HOOK_TIMEOUT`,`A callback for '%s' hook%s timed out. You may have forgotten to call 'done' function or to resolve a Promise`),FST_ERR_LOG_INVALID_DESTINATION:n(`FST_ERR_LOG_INVALID_DESTINATION`,`Cannot specify both logger.stream and logger.file options`),FST_ERR_LOG_INVALID_LOGGER:n(`FST_ERR_LOG_INVALID_LOGGER`,`Invalid logger object provided. The logger instance should have these functions(s): '%s'.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_INSTANCE:n(`FST_ERR_LOG_INVALID_LOGGER_INSTANCE`,`loggerInstance only accepts a logger instance.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_CONFIG:n(`FST_ERR_LOG_INVALID_LOGGER_CONFIG`,`logger options only accepts a configuration object.`,500,TypeError),FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:n(`FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED`,`You cannot provide both logger and loggerInstance. Please provide only one.`,500,TypeError),FST_ERR_REP_INVALID_PAYLOAD_TYPE:n(`FST_ERR_REP_INVALID_PAYLOAD_TYPE`,`Attempted to send payload of invalid type '%s'. Expected a string or Buffer.`,500,TypeError),FST_ERR_REP_RESPONSE_BODY_CONSUMED:n(`FST_ERR_REP_RESPONSE_BODY_CONSUMED`,`Response.body is already consumed.`),FST_ERR_REP_READABLE_STREAM_LOCKED:n(`FST_ERR_REP_READABLE_STREAM_LOCKED`,`ReadableStream was locked. You should call releaseLock() method on reader before sending.`),FST_ERR_REP_ALREADY_SENT:n(`FST_ERR_REP_ALREADY_SENT`,`Reply was already sent, did you forget to "return reply" in "%s" (%s)?`),FST_ERR_REP_SENT_VALUE:n(`FST_ERR_REP_SENT_VALUE`,`The only possible value for reply.sent is true.`,500,TypeError),FST_ERR_SEND_INSIDE_ONERR:n(`FST_ERR_SEND_INSIDE_ONERR`,"You cannot use `send` inside the `onError` hook"),FST_ERR_SEND_UNDEFINED_ERR:n(`FST_ERR_SEND_UNDEFINED_ERR`,`Undefined error has occurred`),FST_ERR_BAD_STATUS_CODE:n(`FST_ERR_BAD_STATUS_CODE`,`Called reply with an invalid status code: %s`),FST_ERR_BAD_TRAILER_NAME:n(`FST_ERR_BAD_TRAILER_NAME`,`Called reply.trailer with an invalid header name: %s`),FST_ERR_BAD_TRAILER_VALUE:n(`FST_ERR_BAD_TRAILER_VALUE`,`Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function.`),FST_ERR_FAILED_ERROR_SERIALIZATION:n(`FST_ERR_FAILED_ERROR_SERIALIZATION`,`Failed to serialize an error. Error: %s. Original error: %s`),FST_ERR_MISSING_SERIALIZATION_FN:n(`FST_ERR_MISSING_SERIALIZATION_FN`,`Missing serialization function. Key "%s"`),FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:n(`FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN`,`Missing serialization function. Key "%s:%s"`),FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:n(`FST_ERR_REQ_INVALID_VALIDATION_INVOCATION`,`Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.`),FST_ERR_SCH_MISSING_ID:n(`FST_ERR_SCH_MISSING_ID`,`Missing schema $id property`),FST_ERR_SCH_ALREADY_PRESENT:n(`FST_ERR_SCH_ALREADY_PRESENT`,`Schema with id '%s' already declared!`),FST_ERR_SCH_CONTENT_MISSING_SCHEMA:n(`FST_ERR_SCH_CONTENT_MISSING_SCHEMA`,`Schema is missing for the content type '%s'`),FST_ERR_SCH_DUPLICATE:n(`FST_ERR_SCH_DUPLICATE`,`Schema with '%s' already present!`),FST_ERR_SCH_VALIDATION_BUILD:n(`FST_ERR_SCH_VALIDATION_BUILD`,`Failed building the validation schema for %s: %s, due to error %s`),FST_ERR_SCH_SERIALIZATION_BUILD:n(`FST_ERR_SCH_SERIALIZATION_BUILD`,`Failed building the serialization schema for %s: %s, due to error %s`),FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:n(`FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX`,`response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }`),FST_ERR_INIT_OPTS_INVALID:n(`FST_ERR_INIT_OPTS_INVALID`,`Invalid initialization options: '%s'`),FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:n(`FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE`,`Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method`),FST_ERR_DUPLICATED_ROUTE:n(`FST_ERR_DUPLICATED_ROUTE`,`Method '%s' already declared for route '%s'`),FST_ERR_BAD_URL:n(`FST_ERR_BAD_URL`,`'%s' is not a valid url component`,400,URIError),FST_ERR_ASYNC_CONSTRAINT:n(`FST_ERR_ASYNC_CONSTRAINT`,`Unexpected error from async constraint`,500),FST_ERR_INVALID_URL:n(`FST_ERR_INVALID_URL`,`URL must be a string. Received '%s'`,400,TypeError),FST_ERR_ROUTE_OPTIONS_NOT_OBJ:n(`FST_ERR_ROUTE_OPTIONS_NOT_OBJ`,`Options for "%s:%s" route must be an object`,500,TypeError),FST_ERR_ROUTE_DUPLICATED_HANDLER:n(`FST_ERR_ROUTE_DUPLICATED_HANDLER`,`Duplicate handler for "%s:%s" route is not allowed!`,500),FST_ERR_ROUTE_HANDLER_NOT_FN:n(`FST_ERR_ROUTE_HANDLER_NOT_FN`,`Error Handler for %s:%s route, if defined, must be a function`,500,TypeError),FST_ERR_ROUTE_MISSING_HANDLER:n(`FST_ERR_ROUTE_MISSING_HANDLER`,`Missing handler function for "%s:%s" route.`,500),FST_ERR_ROUTE_METHOD_INVALID:n(`FST_ERR_ROUTE_METHOD_INVALID`,`Provided method is invalid!`,500,TypeError),FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:n(`FST_ERR_ROUTE_METHOD_NOT_SUPPORTED`,`%s method is not supported.`,500),FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:n(`FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED`,`Body validation schema for %s:%s route is not supported!`,500),FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:n(`FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT`,`'bodyLimit' option must be an integer > 0. Got '%s'`,500,TypeError),FST_ERR_ROUTE_REWRITE_NOT_STR:n(`FST_ERR_ROUTE_REWRITE_NOT_STR`,`Rewrite url for "%s" needs to be of type "string" but received "%s"`,500,TypeError),FST_ERR_REOPENED_CLOSE_SERVER:n(`FST_ERR_REOPENED_CLOSE_SERVER`,`Fastify has already been closed and cannot be reopened`),FST_ERR_REOPENED_SERVER:n(`FST_ERR_REOPENED_SERVER`,`Fastify is already listening`),FST_ERR_INSTANCE_ALREADY_LISTENING:n(`FST_ERR_INSTANCE_ALREADY_LISTENING`,`Fastify instance is already listening. %s`),FST_ERR_PLUGIN_VERSION_MISMATCH:n(`FST_ERR_PLUGIN_VERSION_MISMATCH`,`fastify-plugin: %s - expected '%s' fastify version, '%s' is installed`),FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:n(`FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE`,`The decorator '%s'%s is not present in %s`),FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:n(`FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER`,`The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.`,500,TypeError),FST_ERR_PLUGIN_CALLBACK_NOT_FN:n(`FST_ERR_PLUGIN_CALLBACK_NOT_FN`,`fastify-plugin: %s`,500,TypeError),FST_ERR_PLUGIN_NOT_VALID:n(`FST_ERR_PLUGIN_NOT_VALID`,`fastify-plugin: %s`),FST_ERR_ROOT_PLG_BOOTED:n(`FST_ERR_ROOT_PLG_BOOTED`,`fastify-plugin: %s`),FST_ERR_PARENT_PLUGIN_BOOTED:n(`FST_ERR_PARENT_PLUGIN_BOOTED`,`fastify-plugin: %s`),FST_ERR_PLUGIN_TIMEOUT:n(`FST_ERR_PLUGIN_TIMEOUT`,`fastify-plugin: %s`)};function i(e,t){return t.cause=e,t}t.exports=r,t.exports.appendStackTrace=i,t.exports.AVVIO_ERRORS_MAP={AVV_ERR_CALLBACK_NOT_FN:r.FST_ERR_PLUGIN_CALLBACK_NOT_FN,AVV_ERR_PLUGIN_NOT_VALID:r.FST_ERR_PLUGIN_NOT_VALID,AVV_ERR_ROOT_PLG_BOOTED:r.FST_ERR_ROOT_PLG_BOOTED,AVV_ERR_PARENT_PLG_LOADED:r.FST_ERR_PARENT_PLUGIN_BOOTED,AVV_ERR_READY_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT,AVV_ERR_PLUGIN_EXEC_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT}})),Cu=o(((e,t)=>{let n=[`onRoute`,`onRegister`,`onReady`,`onListen`,`preClose`,`onClose`],r=[`onTimeout`,`onRequest`,`preParsing`,`preValidation`,`preSerialization`,`preHandler`,`onSend`,`onResponse`,`onError`,`onRequestAbort`],i=r.concat(n),{FST_ERR_HOOK_INVALID_TYPE:a,FST_ERR_HOOK_INVALID_HANDLER:o,FST_ERR_SEND_UNDEFINED_ERR:s,FST_ERR_HOOK_TIMEOUT:c,FST_ERR_HOOK_NOT_SUPPORTED:l,AVVIO_ERRORS_MAP:u,appendStackTrace:d}=Su(),{kChildren:f,kHooks:p,kRequestPayloadStream:m}=yu();function h(){this.onRequest=[],this.preParsing=[],this.preValidation=[],this.preSerialization=[],this.preHandler=[],this.onResponse=[],this.onSend=[],this.onError=[],this.onRoute=[],this.onRegister=[],this.onReady=[],this.onListen=[],this.onTimeout=[],this.onRequestAbort=[],this.preClose=[]}h.prototype=Object.create(null),h.prototype.validate=function(e,t){if(typeof e!=`string`)throw new a;if(Array.isArray(this[e])===!1)throw new l(e);if(typeof t!=`function`)throw new o(e,Object.prototype.toString.call(t))},h.prototype.add=function(e,t){this.validate(e,t),this[e].push(t)};function g(e){let t=new h;return t.onRequest=e.onRequest.slice(),t.preParsing=e.preParsing.slice(),t.preValidation=e.preValidation.slice(),t.preSerialization=e.preSerialization.slice(),t.preHandler=e.preHandler.slice(),t.onSend=e.onSend.slice(),t.onResponse=e.onResponse.slice(),t.onError=e.onError.slice(),t.onRoute=e.onRoute.slice(),t.onRegister=e.onRegister.slice(),t.onTimeout=e.onTimeout.slice(),t.onRequestAbort=e.onRequestAbort.slice(),t.onReady=[],t.onListen=[],t.preClose=[],t}function _(e,t,n,r){let i=n[p][e],a=0,o=0;l();function s(t){let n=i[a-1]?.name,o=n?` "${n}"`:``;if(t){t=t.code===`AVV_ERR_READY_TIMEOUT`?d(t,new c(e,o)):u[t.code]==null?t:d(t,new u[t.code](t.message)),r(t);return}r()}function l(r){if(r){s(r);return}if(a===i.length&&o===n[f].length){a===0&&o===0?s():t(function(e,t){s(e),t(e)});return}if(a===i.length&&o<n[f].length){let r=n[f][o++];_(e,t,r,l);return}t(m(i[a++],n)),l()}function m(e,t){return function(n,r){if(n){r(n);return}if(e.length===1){try{e.call(t,r)}catch(e){r(e)}return}try{let n=e.call(t);if(n&&typeof n.then==`function`){n.then(r,r);return}}catch(e){n=e}r(n)}}}function v(e){let t=e[p].onListen,n=t.length,r=0,i=0;a();function a(s){if(s&&e.log.error(s),r===n){for(;i<e[f].length;){let t=e[f][i++];v(t)}return}o(t[r++],e,a)}async function o(e,t,n){if(e.length===1){try{e.call(t,n)}catch(e){n(e)}return}try{let r=e.call(t);if(r&&typeof r.then==`function`){r.then(n,n);return}n()}catch(e){n(e)}}}function y(e){return function(t,n,r,i){let a=0;function o(s){if(s||a===t.length){i(s,n,r);return}let u;try{u=e(t[a++],n,r,o)}catch(e){i(e,n,r);return}u&&typeof u.then==`function`&&u.then(c,l)}function c(){o()}function l(e){e||=new s,i(e,n,r)}o()}}function b(e,t,n,r){return e(t,n,r)}let x=y(b),S=y(A),C=y(A),w=y(A),T=y(A);function E(e,t,n,r,i){let a=0;function o(s,u){if(s){i(s,t,n,r);return}if(u!==void 0&&(r=u),a===e.length){i(null,t,n,r);return}let d;try{d=e[a++](t,n,r,o)}catch(e){i(e,t,n);return}d&&typeof d.then==`function`&&d.then(c,l)}function c(e){o(null,e)}function l(e){e||=new s,i(e,t,n,r)}o()}let D=E;function O(e,t,n,r){let i=0;function a(s,l){if(n.sent)return;if(l!==void 0&&(t[m]=l),s||i===e.length){r(s,t,n);return}let u;try{u=e[i++](t,n,t[m],a)}catch(e){r(e,t,n);return}u&&typeof u.then==`function`&&u.then(o,c)}function o(e){a(null,e)}function c(e){e||=new s,r(e,t,n)}a()}function k(e,t,n){let r=0;function i(s){if(s||r===e.length){n(s,t);return}let c;try{c=e[r++](t,i)}catch(e){n(e,t);return}c&&typeof c.then==`function`&&c.then(a,o)}function a(){i()}function o(e){e||=new s,n(e,t)}i()}function A(e,t,n,r){if(n.sent!==!0)return e(t,n,r)}t.exports={Hooks:h,buildHooks:g,hookRunnerGenerator:y,preParsingHookRunner:O,onResponseHookRunner:x,onSendHookRunner:E,preSerializationHookRunner:D,onRequestAbortHookRunner:k,hookIterator:A,hookRunnerApplication:_,onListenHookRunner:v,preHandlerHookRunner:C,preValidationHookRunner:S,onRequestHookRunner:T,onTimeoutHookRunner:w,lifecycleHooks:r,supportedHooks:i}})),wu=o(((e,t)=>{t.exports=function(){return{[Symbol.iterator]:function*(){},add(){},delete(){},has(){return!0}}}})),Tu=o(((e,t)=>{let{kTestInternals:n}=yu();function r(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}t.exports={withResolvers:typeof Promise.withResolvers==`function`?Promise.withResolvers.bind(Promise):r,[n]:{withResolvers:r}}})),Eu=o(((e,t)=>{let n=require(`node:http`),r=require(`node:https`),i=require(`node:http2`),a=require(`node:dns`),o=require(`node:os`),{kState:s,kOptions:c,kServerBindings:l,kHttp2ServerSessions:u}=yu(),{FSTWRN003:d}=xu(),{onListenHookRunner:f}=Cu(),{FST_ERR_REOPENED_CLOSE_SERVER:p,FST_ERR_REOPENED_SERVER:m,FST_ERR_LISTEN_OPTIONS_INVALID:h,FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:g}=Su(),_=wu(),v=Tu();t.exports.createServer=b;function y(e){return`Server listening at ${e}`}function b(e,t){let n=w(e,t);function r(r={port:0,host:`localhost`},i=void 0){if(typeof i==`function`&&(i.constructor.name===`AsyncFunction`&&d(`listen method`),r.cb=i),r.signal){if(typeof r.signal.on!=`function`&&typeof r.signal.addEventListener!=`function`)throw new h(`Invalid options.signal`);if(this[s].aborted=r.signal.aborted,this[s].aborted)return this.close();r.signal.addEventListener(`abort`,()=>{this[s].aborted=!0,this.close()},{once:!0})}let a;if(a=r.path==null?r.host??`localhost`:r.host,(!Object.hasOwn(r,`host`)||r.host==null)&&(r.host=a),a===`localhost`?r.cb=(a,o)=>{if(a){i(a,o);return}x.call(this,n,t,e,r,()=>{this[s].listening=!0,i(null,o),f(this)})}:r.cb=(e,t)=>{if(e){i(e,t);return}this[s].listening=!0,i(null,t),f(this)},i===void 0)return C.call(this,n,r).then(i=>{let{promise:o,resolve:c}=v.withResolvers();return a===`localhost`?x.call(this,n,t,e,r,()=>{this[s].listening=!0,c(i),f(this)}):(c(i),f(this)),o});this.ready(S.call(this,n,r))}let i=typeof n.closeAllConnections==`function`,a=typeof n.closeIdleConnections==`function`,o=typeof n.closeHttp2Sessions==`function`,c=e.forceCloseConnections;if(c===`idle`&&!a)throw new g;typeof c!=`boolean`&&(c=a?`idle`:!1);let l=!i&&c===!0?new Set:_();return{server:n,listen:r,forceCloseConnections:c,serverHasCloseAllConnections:i,serverHasCloseHttp2Sessions:o,keepAliveConnections:l}}function x(e,t,n,r,i){this[s].listening=!1,a.lookup(r.host,{all:!0},(a,o)=>{if(a||this[s].aborted){i();return}let c=e.listening&&n.serverFactory,u=0,d=0;if(!c){let a=e.address();for(let c of o)if(c.address!==a.address){u++;let o=Object.assign({},r,{host:c.address,port:a.port,cb:e=>{d++,e||this[l].push(f),d===u&&i()}}),f=w(n,t),p=()=>{f.close(()=>{}),typeof f.closeAllConnections==`function`&&n.forceCloseConnections===!0&&f.closeAllConnections(),typeof f.closeHttp2Sessions==`function`&&f.closeHttp2Sessions()};f.on(`upgrade`,e.emit.bind(e,`upgrade`)),e.on(`unref`,p),e.on(`close`,p),e.on(`error`,p),this[s].listening=!1,S.call(this,f,o)()}}if(u===0){i();return}let f=e.unref;e.unref=function(){f.call(e),e.emit(`unref`)}})}function S(e,t){let n=r=>{if(e.removeListener(`error`,n),e.removeListener(`listening`,n),r)this[s].listening=!1,t.cb(r,null);else{let n=E.call(this,e,t.listenTextResolver||y);t.cb(null,n)}};return r=>{if(r!=null)return t.cb(r);if(this[s].listening&&this[s].closing)return t.cb(new p,null);if(this[s].listening)return t.cb(new m,null);e.once(`error`,n),this[s].closing||(e.once(`listening`,n),e.listen(t),this[s].listening=!0)}}function C(e,t){return this[s].listening&&this[s].closing?Promise.reject(new p):this[s].listening?Promise.reject(new m):this.ready().then(()=>{if(this[s].aborted)return;let{promise:n,resolve:r,reject:i}=v.withResolvers(),a=e=>{c(),this[s].listening=!1,i(e)},o=()=>{c(),this[s].listening=!0,r(E.call(this,e,t.listenTextResolver||y))};function c(){e.removeListener(`error`,a),e.removeListener(`listening`,o)}return e.once(`error`,a),e.once(`listening`,o),e.listen(t),n})}function w(e,t){if(e.serverFactory)return e.serverFactory(t,e);let a=e.https===!0?{}:e.https;if(e.http2){let n=typeof a==`object`?i.createSecureServer(a,t):i.createServer(e.http,t);return n.on(`session`,t=>t.setTimeout(e.http2SessionTimeout,()=>{t.close()})),e.forceCloseConnections===!0&&(n.closeHttp2Sessions=D(n)),n.setTimeout(e.connectionTimeout),n}let o=a?r.createServer(a,t):n.createServer(e.http,t);return o.keepAliveTimeout=e.keepAliveTimeout,o.requestTimeout=e.requestTimeout,o.setTimeout(e.connectionTimeout),e.maxRequestsPerSocket>0&&(o.maxRequestsPerSocket=e.maxRequestsPerSocket),o}function T(e){return e.address===`0.0.0.0`?Object.values(o.networkInterfaces()).flatMap(e=>e.filter(e=>e.family===`IPv4`)).sort(e=>e.internal?-1:1).map(e=>e.address):[e.address]}function E(e,t){let n;typeof e.address()==`string`?n=[e.address()]:(n=e.address().address.indexOf(`:`)===-1?T(e.address()).map(t=>t+`:`+e.address().port):[`[`+e.address().address+`]:`+e.address().port],n=n.map(e=>`http`+(this[c].https?`s`:``)+`://`+e));for(let e of n)this.log.info(t(e));return n[0]}function D(e){return e[u]=new Set,e.on(`session`,function(t){t.once(`connect`,function(){e[u].add(t)}),t.once(`close`,function(){e[u].delete(t)}),t.once(`frameError`,function(n,r,i){i===0&&e[u].delete(t)}),t.once(`goaway`,function(){e[u].delete(t)})}),function(){if(e[u].size!==0)for(let t of e[u])t.close()}}})),Du=o(((e,t)=>{let n=/([\w!#$%&'*+.^`|~-]+)=([^;]*)/gm,r=/^[\w!#$%&'*+.^`|~-]+$/,i=/^[\w!#$%&'*+.^`|~-]+\s*/;t.exports=class{#e=!1;#t=!0;#n=``;#r=``;#i=new Map;#a;constructor(e){if(e==null||e===``||e===`undefined`)return;let t=e.indexOf(`;`);if(t===-1){if(t=e.indexOf(`/`),t===-1)return;let n=e.slice(0,t).trimStart().toLowerCase(),a=e.slice(t+1).trimEnd().toLowerCase();r.test(n)===!0&&i.test(a)===!0&&(this.#e=!0,this.#t=!1,this.#n=n,this.#r=a);return}let a=e.slice(0,t).toLowerCase(),o=e.slice(t+1).trim();if(t=a.indexOf(`/`),t===-1)return;let s=a.slice(0,t).trimStart(),c=a.slice(t+1).trimEnd();if(r.test(s)===!1||i.test(c)===!1)return;this.#n=s,this.#r=c,this.#e=!0,this.#t=!1;let l=n.exec(o);for(;l;){let e=l[1],t=l[2];if(t[0]===`"`){if(t.at(-1)!==`"`){this.#i.set(e,`invalid quoted string`),l=n.exec(o);continue}this.#i.set(e,t.slice(1,t.length-1))}else this.#i.set(e,t);l=n.exec(o)}}get[Symbol.toStringTag](){return`ContentType`}get isEmpty(){return this.#t}get isValid(){return this.#e}get mediaType(){return`${this.#n}/${this.#r}`}get type(){return this.#n}get subtype(){return this.#r}get parameters(){return this.#i}toString(){if(this.#a)return this.#a;let e=[];for(let[t,n]of this.#i.entries())e.push(`${t}="${n}"`);let t=[this.#n,`/`,this.#r];return e.length>0&&(t.push(`; `),t.push(e.join(`; `))),this.#a=t.join(``),this.#a}}})),Ou=o(((e,t)=>{let{kReplyHasStatusCode:n}=yu();function r(e,t){if(!e[n]||e.statusCode===200){let n=t&&(t.statusCode||t.status);e.code(n>=400?n:500)}}t.exports={setErrorStatusCode:r}})),ku=o(((e,t)=>{let{kReplyIsError:n,kReplyHijacked:r}=yu(),{setErrorStatusCode:i}=Ou(),a=require(`node:diagnostics_channel`).tracingChannel(`fastify.request.handler`);function o(e,t,o){o&&(o.async=!0),e.then(function(e){if(t[r]!==!0){o&&a.asyncStart.publish(o);try{if(e!==void 0||t.sent===!1&&t.raw.headersSent===!1&&t.request.raw.aborted===!1&&t.request.socket&&!t.request.socket.destroyed)try{t.send(e)}catch(e){t[n]=!0,t.send(e)}}finally{o&&a.asyncEnd.publish(o)}}},function(e){o&&(o.error=e,i(t,e),a.error.publish(o),a.asyncStart.publish(o));try{if(t.sent===!0){t.log.error({err:e},`Promise errored, but reply.sent = true was set`);return}t[n]=!0,t.send(e)}catch(e){t.send(e)}finally{o&&a.asyncEnd.publish(o)}})}t.exports=o})),Au=o(((e,t)=>{let{kSchemaHeaders:n,kSchemaParams:r,kSchemaQuerystring:i,kSchemaBody:a,kSchemaResponse:o}=yu(),s=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:c}=Su(),{FSTWRN001:l}=xu();function u(e,t){if(!e.schema||!e.schema.response)return;let{method:n,url:r}=e.config||{};e[o]=Object.keys(e.schema.response).reduce(function(i,a){let o=e.schema.response[a];if(a=a.toLowerCase(),!s.test(a))throw new c;if(o.content){let e={};for(let i of Object.keys(o.content)){let s=o.content[i].schema;e[i]=t({schema:s,url:r,method:n,httpStatus:a,contentType:i})}i[a]=e}else i[a]=t({schema:o,url:r,method:n,httpStatus:a});return i},{})}function d(e,t,o){let{schema:s}=e;if(!s)return;let{method:c,url:u}=e.config||{},d=s.headers;if(d&&(o||Object.getPrototypeOf(d)!==Object.prototype))e[n]=t({schema:d,method:c,url:u,httpPart:`headers`});else if(d){let r={};Object.keys(d).forEach(e=>{r[e]=d[e]}),r.required instanceof Array&&(r.required=r.required.map(e=>e.toLowerCase())),d.properties&&(r.properties={},Object.keys(d.properties).forEach(e=>{r.properties[e.toLowerCase()]=d.properties[e]})),e[n]=t({schema:r,method:c,url:u,httpPart:`headers`})}else Object.hasOwn(s,`headers`)&&l(`headers`,c,u);if(s.body){let n=s.body.content;if(n){let r={};for(let e of Object.keys(n)){let i=n[e].schema;r[e]=t({schema:i,method:c,url:u,httpPart:`body`,contentType:e})}e[a]=r}else e[a]=t({schema:s.body,method:c,url:u,httpPart:`body`})}else Object.hasOwn(s,`body`)&&l(`body`,c,u);s.querystring?e[i]=t({schema:s.querystring,method:c,url:u,httpPart:`querystring`}):Object.hasOwn(s,`querystring`)&&l(`querystring`,c,u),s.params?e[r]=t({schema:s.params,method:c,url:u,httpPart:`params`}):Object.hasOwn(s,`params`)&&l(`params`,c,u)}function f(e,t,n){let r=t[n]===void 0,i;try{i=e?.(r?null:t[n])}catch(e){return e.statusCode=500,e}if(i&&typeof i.then==`function`)return i.then(e=>a(e)).catch(e=>e);return a(i);function a(r){return r===!1?e.errors:r&&r.error?r.error:(r&&r.value&&(t[n]=r.value),!1)}}function p(e,t,o){let s=o===void 0;if(s||!o.skipParams){let n=f(e[r],t,`params`);if(n)return typeof n.then==`function`?m(n,e,t):v(n,`params`,e.schemaErrorFormatter)}if(s||!o.skipBody){let n=null;if(typeof e[a]==`function`)n=e[a];else if(e[a]){let r=y(t.headers[`content-type`]),i=e[a][r];i&&(n=i)}let r=f(n,t,`body`);if(r)return typeof r.then==`function`?h(r,e,t):v(r,`body`,e.schemaErrorFormatter)}if(s||!o.skipQuery){let n=f(e[i],t,`query`);if(n)return typeof n.then==`function`?g(n,e,t):v(n,`querystring`,e.schemaErrorFormatter)}let c=f(e[n],t,`headers`);return c?typeof c.then==`function`?_(c,e,t):v(c,`headers`,e.schemaErrorFormatter):!1}function m(e,t,n){return e.then(e=>e?v(e,`params`,t.schemaErrorFormatter):p(t,n,{skipParams:!0}))}function h(e,t,n){return e.then(e=>e?v(e,`body`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0}))}function g(e,t,n){return e.then(e=>e?v(e,`querystring`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0,skipQuery:!0}))}function _(e,t,n){return e.then(e=>e?v(e,`headers`,t.schemaErrorFormatter):!1)}function v(e,t,n){if(e instanceof Error)return e.statusCode=e.statusCode||400,e.code=e.code||`FST_ERR_VALIDATION`,e.validationContext=e.validationContext||t,e;let r=n(e,t);return r.statusCode=r.statusCode||400,r.code=r.code||`FST_ERR_VALIDATION`,r.validation=e,r.validationContext=t,r}function y(e){return e?e.split(/[ ;]/,1)[0].trim().toLowerCase():``}t.exports={symbols:{bodySchema:a,querystringSchema:i,responseSchema:o,paramsSchema:r,headersSchema:n},compileSchemasForValidation:d,compileSchemasForSerialization:u,validate:p}})),ju=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Du(),i=ku(),{validate:a}=Au(),{preValidationHookRunner:o,preHandlerHookRunner:s}=Cu(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:c}=Su(),{setErrorStatusCode:l}=Ou(),{kReplyIsError:u,kRouteContext:d,kFourOhFourContext:f,kSupportedHTTPMethods:p}=yu(),m=n.tracingChannel(`fastify.request.handler`);function h(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let i=t.method;if(this[p].bodyless.has(i)){g(t,n);return}if(this[p].bodywith.has(i)){let e=t.headers,i=e[`content-type`];if(i===void 0){let r=e[`content-length`];if(e[`transfer-encoding`]===void 0&&(r===void 0||r===`0`)){g(t,n);return}t[d].contentTypeParser.run(``,g,t,n);return}let a=new r(i);if(a.isValid===!1){n[u]=!0,n.status(415).send(new c);return}t[d].contentTypeParser.run(a.toString(),g,t,n);return}g(t,n)}function g(e,t){try{e[d].preValidation===null?_(null,e,t):o(e[d].preValidation,e,t,_)}catch(n){_(n,e,t)}}function _(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let r=a(n[d],t);if(r&&typeof r.then==`function`){let e=v.bind(null,t,n);r.then(e,e)}else v(t,n,r)}function v(e,t,n){if(n){if(t[d].attachValidation===!1){t.send(n);return}t.request.validationError=n}e[d].preHandler===null?y(null,e,t):s(e[d].preHandler,e,t,y)}function y(e,t,n){if(n.sent)return;let r=t[d];if(!m.hasSubscribers||r[f]===null)b(e,t,n);else{let i={request:t,reply:n,async:!1,route:{url:r.config.url,method:r.config.method}};m.start.runStores(i,b,void 0,e,t,n,i)}}function b(e,t,n,r){let a=t[d];try{if(e!=null){n[u]=!0,r&&(r.error=e,l(n,e),m.error.publish(r)),n.send(e);return}let o;try{o=a.handler(t,n)}catch(e){r&&(r.error=e,l(n,e),m.error.publish(r)),n[u]=!0,n.send(e);return}o!==void 0&&(o!==null&&typeof o.then==`function`?i(o,n,r):n.send(o))}finally{r&&m.end.publish(r)}}t.exports=h,t.exports[Symbol.for(`internals`)]={handler:g,preHandlerCallback:y}})),Mu=o(((e,t)=>{function n(){}let r={fatal:n,error:n,warn:n,info:n,debug:n,trace:n};Object.defineProperty(t,`exports`,{get(){return Object.create(r)}})})),Nu=o(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
|
|
125
125
|
causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
|
|
126
126
|
caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),Pu=o(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),Fu=o(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=Nu(),{pinoErrProto:a,pinoErrorSymbols:o}=Pu(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),Iu=o(((e,t)=>{t.exports=s;let{isErrorLike:n}=Nu(),{pinoErrProto:r,pinoErrorSymbols:i}=Pu(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),Lu=o(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),Ru=o(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),zu=o(((e,t)=>{let n=Fu(),r=Iu(),i=Lu(),a=Ru();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),Bu=o(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),Vu=o(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),Hu=o(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),Uu=o(((e,t)=>{let n=Vu(),{redactFmtSym:r,wildcardFirstSym:i}=Hu(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),Wu=o(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),Gu=o(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),Ku=o(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),qu=o(((e,t)=>{let n=require(`fs`),r=require(`events`),i=require(`util`).inherits,a=require(`path`),o=Ku(),s=require(`assert`),c=Buffer.allocUnsafe(0),l=`buffer`,u=`utf8`,[d,f]=(process.versions.node||`0.0`).split(`.`).map(Number),p=d>=22&&f>=7;function m(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,o=t.mode;if(t.sync)try{t.mkdir&&n.mkdirSync(a.dirname(e),{recursive:!0}),r(null,n.openSync(e,i,o))}catch(e){throw r(e),e}else t.mkdir?n.mkdir(a.dirname(e),{recursive:!0},t=>{if(t)return r(t);n.open(e,i,o,r)}):n.open(e,i,o,r)}function h(e){if(!(this instanceof h))return new h(e);let{fd:t,dest:r,minLength:i,maxLength:a,maxWrite:s,periodicFlush:d,sync:f,append:p=!0,mkdir:v,retryEAGAIN:x,fsync:k,contentMode:A,mode:j}=e||{};t||=r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=s||16384,this._periodicFlush=d||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=k||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=x||(()=>!0),this.mkdir=v||!1;let M,ee;if(A===l)this._writingBuf=c,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>n.writeSync(this.fd,this._writingBuf),ee=()=>n.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===u)this._writingBuf=``,this.write=y,this.flush=S,this.flushSync=w,this._actualWrite=E,M=()=>Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`),ee=()=>Buffer.isBuffer(this._writingBuf)?n.write(this.fd,this._writingBuf,this.release):n.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${u}" and "${l}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)m(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{o(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(ee,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let r=g(this._writingBuf,this._len,t);if(this._len=r.len,this._writingBuf=r.writingBuf,this._writingBuf.length){if(!this.sync){ee();return}try{do{let e=M(),t=g(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&n.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,O(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(_,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function g(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function _(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}i(h,r);function v(e,t){return e.length===0?c:e.length===1?e[0]:Buffer.concat(e,t)}function y(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{n.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,r)},r=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,r)}function S(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}h.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&n.close(t,e=>{if(e)return this.emit(`error`,e)})}),m(this.file,this)},h.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():O(this)))};function w(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?n.writeSync(this.fd,e):n.writeSync(this.fd,e,`utf8`),r=g(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}try{n.fsyncSync(this.fd)}catch{}}function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=c);let e=c;for(;this._bufs.length||e.length;){e.length<=0&&(e=v(this._bufs[0],this._lens[0]));try{let t=n.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}}h.prototype.destroy=function(){this.destroyed||O(this)};function E(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else n.write(this.fd,this._writingBuf,e)}function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:v(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,n.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else p&&(this._writingBuf=Buffer.from(this._writingBuf)),n.write(this.fd,this._writingBuf,e)}function O(e){if(e.fd===-1){e.once(`ready`,O.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],s(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{n.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?n.close(e.fd,r):r()}function r(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}h.SonicBoom=h,h.default=h,t.exports=h})),Ju=o(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),Yu=o(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),Xu=o(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),Zu=o(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),Qu=o(((e,t)=>{let{version:n}=Yu(),{EventEmitter:r}=require(`events`),{Worker:i}=require(`worker_threads`),{join:a}=require(`path`),{pathToFileURL:o}=require(`url`),{wait:s}=Xu(),{WRITE_INDEX:c,READ_INDEX:l}=Zu(),u=require(`buffer`),d=require(`assert`),f=Symbol(`kImpl`),p=u.constants.MAX_STRING_LENGTH;var m=class{constructor(e){this._value=e}deref(){return this._value}},h=class{register(){}unregister(){}};let g=process.env.NODE_V8_COVERAGE?h:global.FinalizationRegistry||h,_=process.env.NODE_V8_COVERAGE?m:global.WeakRef||m,v=new g(e=>{e.exited||e.terminate()});function y(e,t){let{filename:r,workerData:s}=t,c=new i((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||a(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf(`file://`)===0?r:o(r).href,dataBuf:e[f].dataBuf,stateBuf:e[f].stateBuf,workerData:{$context:{threadStreamVersion:n},...s}}});return c.stream=new m(e),c.on(`message`,S),c.on(`exit`,C),v.register(e,c),c}function b(e){d(!e[f].sync),e[f].needDrain&&(e[f].needDrain=!1,e.emit(`drain`))}function x(e){let t=Atomics.load(e[f].state,c),n=e[f].data.length-t;if(n>0){if(e[f].buf.length===0){e[f].flushing=!1,e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e);return}let t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);r>e[f].data.length;)n/=2,t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))}})}else if(n===0){if(t===0&&e[f].buf.length===0)return;e.flush(()=>{Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l),x(e)})}else E(e,Error(`overwritten`))}function S(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new _(t),t.flush(()=>{t[f].ready=!0,t.emit(`ready`)});break;case`ERROR`:E(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:E(t,Error(`this should not happen: `+e.code))}}function C(e){let t=this.stream.deref();t!==void 0&&(v.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,C),E(t,e===0?null:Error(`the worker thread exited`)))}var w=class extends r{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[f]={},this[f].stateBuf=new SharedArrayBuffer(128),this[f].state=new Int32Array(this[f].stateBuf),this[f].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[f].data=Buffer.from(this[f].dataBuf),this[f].sync=e.sync||!1,this[f].ending=!1,this[f].ended=!1,this[f].needDrain=!1,this[f].destroyed=!1,this[f].flushing=!1,this[f].ready=!1,this[f].finished=!1,this[f].errored=null,this[f].closed=!1,this[f].buf=``,this.worker=y(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[f].destroyed)return T(this,Error(`the worker has exited`)),!1;if(this[f].ending)return T(this,Error(`the worker is ending`)),!1;if(this[f].flushing&&this[f].buf.length+e.length>=p)try{k(this),this[f].flushing=!0}catch(e){return E(this,e),!1}if(this[f].buf+=e,this[f].sync)try{return k(this),!0}catch(e){return E(this,e),!1}return this[f].flushing||(this[f].flushing=!0,setImmediate(x,this)),this[f].needDrain=this[f].data.length-this[f].buf.length-Atomics.load(this[f].state,c)<=0,!this[f].needDrain}end(){this[f].destroyed||(this[f].ending=!0,O(this))}flush(e){if(this[f].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[f].state,c);s(this[f].state,l,t,1/0,(t,n)=>{if(t){E(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[f].destroyed||(k(this),A(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[f].ready}get destroyed(){return this[f].destroyed}get closed(){return this[f].closed}get writable(){return!this[f].destroyed&&!this[f].ending}get writableEnded(){return this[f].ending}get writableFinished(){return this[f].finished}get writableNeedDrain(){return this[f].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[f].errored}};function T(e,t){setImmediate(()=>{e.emit(`error`,t)})}function E(e,t){e[f].destroyed||(e[f].destroyed=!0,t&&(e[f].errored=t,T(e,t)),e.worker.exited?setImmediate(()=>{e[f].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[f].closed=!0,e.emit(`close`)}))}function D(e,t,n){let r=Atomics.load(e[f].state,c),i=Buffer.byteLength(t);return e[f].data.write(t,r),Atomics.store(e[f].state,c,r+i),Atomics.notify(e[f].state,c),n(),!0}function O(e){if(!(e[f].ended||!e[f].ending||e[f].flushing)){e[f].ended=!0;try{e.flushSync();let t=Atomics.load(e[f].state,l);Atomics.store(e[f].state,c,-1),Atomics.notify(e[f].state,c);let n=0;for(;t!==-1;){if(Atomics.wait(e[f].state,l,t,1e3),t=Atomics.load(e[f].state,l),t===-2){E(e,Error(`end() failed`));return}if(++n===10){E(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[f].finished=!0,e.emit(`finish`)})}catch(t){E(e,t)}}}function k(e){let t=()=>{e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e)};for(e[f].flushing=!1;e[f].buf.length!==0;){let n=Atomics.load(e[f].state,c),r=e[f].data.length-n;if(r===0){A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);continue}else if(r<0)throw Error(`overwritten`);let i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[f].buf=e[f].buf.slice(r),D(e,i,t);else{for(A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);a>e[f].buf.length;)r/=2,i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);e[f].buf=e[f].buf.slice(r),D(e,i,t)}}}function A(e){if(e[f].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[f].state,c),n=0;for(;;){let r=Atomics.load(e[f].state,l);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[f].state,l,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=w})),$u=o(((e,t)=>{let{createRequire:n}=require(`module`),{existsSync:r}=require(`node:fs`),i=Bu(),{join:a,isAbsolute:o,sep:s}=require(`node:path`),{fileURLToPath:c}=require(`node:url`),l=Ku(),u=Ju(),d=Qu();function f(e){u.register(e,v),u.registerBeforeExit(e,y),e.on(`close`,function(){u.unregister(e)})}function p(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function m(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&h(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&h(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function h(e){let t=g(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=c(n)}catch{return!1}return o(n)&&!r(n)}function g(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function _(e,t,n,r,i){if(!n.execArgv&&p()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let e=m(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:e}})}n={...n,name:i};let a=new d({filename:e,workerData:t,workerOpts:n,sync:r});a.on(`ready`,o),a.on(`close`,function(){process.removeListener(`exit`,s)}),process.on(`exit`,s);function o(){process.removeListener(`exit`,s),a.unref(),n.autoEnd!==!1&&f(a)}function s(){a.closed||(a.flushSync(),l(100),a.end())}return a}function v(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function y(e){e.flushSync()}function b(e){let{pipeline:t,targets:r,levels:c,dedupe:l,worker:u={},caller:d=i(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&r)throw Error(`only one of target or targets can be specified`);r?(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.targets=r.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=r.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),c&&(p.levels=c),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let v=r||t?`pino.transport`:g;return _(y(g),p,u,f,v);function y(e){if(e=h[e]||e,o(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return a(__dirname,`..`,`file.js`);let t;for(let r of m)try{t=n(r===`node:repl`?process.cwd()+s:r).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=b})),ed=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Gu(),{mapHttpRequest:i,mapHttpResponse:a}=zu(),o=qu(),s=Ju(),{lsCacheSym:c,chindingsSym:l,writeSym:u,serializersSym:d,formatOptsSym:f,endSym:p,stringifiersSym:m,stringifySym:h,stringifySafeSym:g,wildcardFirstSym:_,nestedKeySym:v,formattersSym:y,messageKeySym:b,errorKeySym:x,nestedKeyStrSym:S,msgPrefixSym:C}=Hu(),{isMainThread:w}=require(`worker_threads`),T=$u(),[E]=process.versions.node.split(`.`).map(e=>Number(e)),D=n.tracingChannel(`pino_asJson`),O=E>=25?e=>JSON.stringify(e):j;function k(){}function A(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let o=t;t!==null&&(t.method&&t.headers&&t.socket?t=i(t):typeof t.setHeader==`function`&&(t=a(t)));let s;o===null&&n.length===0?s=[null]:(o=n.shift(),s=n),typeof this[C]==`string`&&o!=null&&(o=this[C]+o),this[u](t,r(o,s,this[f]),e)}else{let i=t===void 0?n.shift():t;typeof this[C]==`string`&&i!=null&&(i=this[C]+i),this[u](null,r(i,n,this[f]),e)}}}function j(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function M(e,t,n,r){if(D.hasSubscribers===!1)return ee.call(this,e,t,n,r);let i={instance:this,arguments};return D.traceSync(ee,i,this,e,t,n,r)}function ee(e,t,n,r){let i=this[h],a=this[g],o=this[m],s=this[p],u=this[l],f=this[d],C=this[y],w=this[b],T=this[x],E=this[c][n]+r;E+=u;let D;C.log&&(e=C.log(e));let k=o[_],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){f[t]?D=f[t](D):t===T&&f.err&&(D=f.err(D));let e=o[t]||k;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||O)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=O(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=f[w]?f[w](t):t;let e=o[w]||k;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||O)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[v]&&A?E+this[S]+A.slice(1)+`}`+j+s:E+A+j+s}function N(e,t){let n,r=e[l],i=e[h],a=e[g],o=e[m],s=o[_],c=e[d],u=e[y].bindings;t=u(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function te(e){return e.write!==e.constructor.prototype.write}function P(e){let t=new o(e);return t.on(`error`,n),!e.sync&&w&&(s.register(t,ne),t.on(`close`,function(){s.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=k,t.end=k,t.flushSync=k,t.destroy=k;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function ne(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function re(e){return function(t,n,r={},i){if(typeof r==`string`)i=P({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=P({dest:i})}else if(r instanceof o||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof o||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=T({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:s}=r;return a===!1&&(r.level=`silent`),s||(r.onChild=k),i||=te(process.stdout)?process.stdout:P({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function F(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[g])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ie(e,t,n){return{level:e,bindings:t,log:n}}function I(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:k,buildSafeSonicBoom:P,asChindings:N,asJson:M,genLog:A,createArgsNormalizer:re,stringify:F,buildFormatters:ie,normalizeDestFileDescriptor:I}})),td=o(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),nd=o(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=Hu(),{noop:l,genLog:u}=ed(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=td(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),rd=o(((e,t)=>{t.exports={version:`10.3.1`}})),id=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{lsCacheSym:r,levelValSym:i,setLevelSym:a,getLevelSym:o,chindingsSym:s,mixinSym:c,asJsonSym:l,writeSym:u,mixinMergeStrategySym:d,timeSym:f,timeSliceIndexSym:p,streamSym:m,serializersSym:h,formattersSym:g,errorKeySym:_,messageKeySym:v,useOnlyCustomLevelsSym:y,needsMetadataGsym:b,redactFmtSym:x,stringifySym:S,formatOptsSym:C,stringifiersSym:w,msgPrefixSym:T,hooksSym:E}=Hu(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:ee}=nd(),{asChindings:N,asJson:te,buildFormatters:P,stringify:ne,noop:re}=ed(),{version:F}=rd(),ie=Uu(),I={constructor:class{},child:oe,bindings:L,setBindings:se,flush:ue,isLevelEnabled:k,version:F,get level(){return this[o]()},set level(e){this[a](e)},get levelVal(){return this[i]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[T]},get[Symbol.toStringTag](){return`Pino`},[r]:j,[u]:le,[l]:te,[o]:D,[a]:O};Object.setPrototypeOf(I,n.prototype),t.exports=function(){return Object.create(I)};let ae=e=>e;function oe(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[h],r=this[g],i=Object.create(this);if(t==null)return i[g].bindings!==ae&&(i[g]=P(r.level,ae,r.log)),i[s]=N(i,e),this.onChild!==re&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[h]=Object.create(null);for(let e in n)i[h][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var o=0;o<e.length;o++){let t=e[o];i[h][t]=n[t]}for(let e in t.serializers)i[h][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var c=0;c<r.length;c++){let e=r[c];i[h][e]=t.serializers[e]}}else i[h]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[g]=P(e||r.level,n||ae,a||r.log)}else i[g]=P(r.level,ae,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(ee(this.levels,t.customLevels),i.levels=A(t.customLevels,i[y]),M(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=ie(i.redact,ne),n={stringify:e[x]};i[S]=ne,i[w]=e,i[C]=n}if(typeof t.msgPrefix==`string`&&(i[T]=(this[T]||``)+t.msgPrefix),i[s]=N(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[a](e)}return this.onChild(i),i}function L(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function se(e){this[s]=N(this,e)}function ce(e,t){return Object.assign(t,e)}function le(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||ce,u,h=this[E].streamWrite;e==null?u={}:e instanceof Error?(u={[a]:e},t===void 0&&(t=e.message)):(u=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(u=s(u,i(u,n,this)));let g=this[l](u,t,n,r),y=this[m];y[b]===!0&&(y.lastLevel=n,y.lastObj=u,y.lastMsg=t,y.lastTime=r.slice(this[p]),y.lastLogger=this),y.write(h?h(g):g)}function ue(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[m];typeof t.flush==`function`?t.flush(e||re):e&&e()}})),ad=o(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),od=o(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=td(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),sd=o(((e,t)=>{let n=require(`node:os`),r=zu(),i=Bu(),a=Uu(),o=Wu(),s=id(),c=Hu(),{configure:l}=ad(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=nd(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=td(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=ed(),{version:w}=rd(),{chindingsSym:T,redactFmtSym:E,serializersSym:D,timeSym:O,timeSliceIndexSym:k,streamSym:A,stringifySym:j,stringifySafeSym:M,stringifiersSym:ee,setLevelSym:N,endSym:te,formatOptsSym:P,messageKeySym:ne,errorKeySym:re,nestedKeySym:F,mixinSym:ie,levelCompSym:I,useOnlyCustomLevelsSym:ae,formattersSym:oe,hooksSym:L,nestedKeyStrSym:se,mixinMergeStrategySym:ce,msgPrefixSym:le}=c,{epochTime:ue,nullTime:de}=o,{pid:fe}=process,pe=n.hostname(),me=r.err,he=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:fe,hostname:pe},serializers:Object.assign(Object.create(null),{err:me}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ue,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),ge=Object.assign(Object.create(null),r);function _e(...e){let t={},{opts:n,stream:r}=he(t,i(),...e);n.level&&typeof n.level==`string`&&h[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:o,crlf:c,serializers:g,timestamp:_,messageKey:y,errorKey:S,nestedKey:w,base:fe,name:pe,level:me,customLevels:ge,levelComparison:_e,mixin:ve,mixinMergeStrategy:ye,useOnlyCustomLevels:be,formatters:xe,hooks:Se,depthLimit:Ce,edgeLimit:we,onChild:Te,msgPrefix:Ee}=n,De=l({maximumDepth:Ce,maximumBreadth:we}),Oe=b(xe.level,xe.bindings,xe.log),ke=x.bind({[M]:De}),Ae=o?a(o,ke):{},je=o?{stringify:Ae[E]}:{stringify:ke},Me=`}`+(c?`\r
|
|
@@ -471,17 +471,17 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
471
471
|
`}function X_(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;J_(e,t,n,r,i,a,P_(P_({},o),{},{callback:function(e){e?c(Y_(e)):c()}}))}else{var l=J_(e,t,n,r,i,a,o);return l?Y_(l):void 0}}function Z_(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 Q_=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return ov(r,await iv(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await av(e,n),i=p.default.parse(r).root;return ov(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await $_(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 $_(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:X_(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=ev(t),a=await tv(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 $_(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=ev(t),i=await tv(n,r),a=await d.default.realpath(i);return nv(n,a,r),{absolutePath:a,normalizedPath:r}}function ev(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function tv(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 nv(e,n,t),n}function nv(e,t,n){let r=rv(e),i=rv(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function rv(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function iv(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;nv(e,r,n??`.`);let i=await d.default.realpath(r);if(nv(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function av(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 ov(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 sv=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 lv(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=cv(t)??(p.default.basename(n)||n),o=r?{...r,title:cv(t)??r.title,updatedAt:i}:{id:`proj_${pg(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 lv(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 cv(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function lv(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)}Mh(),Dh(),Oh();var uv=c(jh(),1);Ph();var dv=uv.default,fv=120,pv=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_${pg(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 mv(fv);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 mv(e){return new Promise(t=>setTimeout(t,e))}var hv=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new pv(this.provider,e)}};function gv(e){let t=bv(vv(e)),n=Q(t.type);return n&&(t.type=_v(n)),t}function _v(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 yv(e)}}function vv(e){if(Array.isArray(e))return e.map(e=>vv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[yv(n)]=vv(r);return t}return e}function yv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function bv(e){return typeof e==`object`&&e?e:{}}function Q(e){if(typeof e==`string`)return e}function xv(e){return typeof e==`string`||typeof e==`number`?String(e):``}var Sv=[...`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}`)],Cv=3,wv=250;function Tv(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function Ev(e,t){let n=Math.max(1,t?.maxAttempts??Cv),r=Math.max(0,t?.retryDelayMs??wv),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!Tv(e)||t>=n)throw e;r>0&&await Dv(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function Dv(e){return new Promise(t=>{setTimeout(t,e)})}var 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}function jv(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 Mv(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var Nv=5e3;async function Pv(e=Nv){let t=Fv();return new Promise(n=>{let r=!1,i=(0,w.spawn)(t.command,[...t.args,`app-server`,`--help`],{stdio:[`ignore`,`ignore`,`ignore`],windowsHide:!0}),a=e=>{r||(r=!0,clearTimeout(o),n(e))},o=setTimeout(()=>{!i.killed&&i.exitCode===null&&i.kill(),a(!1)},e);i.on(`error`,()=>{a(!1)}),i.on(`exit`,e=>{a(e===0)})})}function Fv(){let e=process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(e)return{command:process.execPath,args:[x.default.resolve(e)]};try{let e=kv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}var Iv=1e4,Lv=100,Rv=2e3;function zv(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function Bv(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var Vv=new Map;async function Hv(e){return Kv(e).createConnection()}async function Uv(){let e=[...Vv.values()];await Promise.allSettled(e.map(e=>e.shutdown())),Vv.clear()}async function Wv(e){let t=Vv.size>0?[...Vv.values()]:[Kv(e)];await Promise.all(t.map(e=>e.restart()))}function Gv(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 Kv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=Vv.get(t);if(n)return n;let r=new qv(e);return Vv.set(t,r),r}var qv=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await Yv(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 Yv(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 $v(e.child,Rv)||(e.child.kill(`SIGKILL`),await $v(e.child,Rv)))}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=Gv(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 Zv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await $v(n,Rv)),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`}},Jv=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){Bv(`connection.close_failed`,{readyState:this.socket.readyState,...zv(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=ey(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 Yv(e,t){let n=Date.now()+Iv,r=null;for(;Date.now()<n;)try{return await Xv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await ty(Lv)}throw r??Error(t())}async function Xv(e,t){let n=new dv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),Bv(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){Bv(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...zv(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 Jv(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`)}`:``;Bv(`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 Zv(e,t,n){let r=Date.now()+Iv;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Xv(e,500)).close(),!0}catch{await ty(Lv)}}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 $v(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 ey(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 ty(e){return new Promise(t=>{setTimeout(t,e)})}var ny=3e4,ry=8,iy=160,ay={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},oy=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 Hv(),n.requestTimeoutMs??ny);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=jv(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=hy(this.activeSessionConfig.reasoningEffort),o,s=gy(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`&&_y(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:gy(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=yy(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:Mv(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:ay,capabilities:{experimentalApi:!0,optOutNotificationMethods:Sv}};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 Ev(()=>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:fy(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=xv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=bv(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=bv(r),a=Q(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${pg(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:vv(i)})}registerUserInputRequest(e,t,n){let r=Q(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${pg(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(vy).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:vv(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:vv(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:vv(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:vv(t.turn),error:vv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:vv(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:gv(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:gv(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=bv(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:vv(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:vv(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=xv(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=py(e),n=my(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(xv(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Q(bv(e.params).threadId)}extractThreadIdFromNotification(e){let t=bv(e.params);return Q(t.threadId)||Q(bv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Q(bv(bv(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>ry&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-ry)}};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=bv(e.message.error),i=uy(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:ly(t,n,e.direction),method:t,requestId:n?xv(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??fy(Q(r.message))}}function ly(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function uy(e,t){let n=bv(t),r=bv(n.thread),i=bv(n.turn),a=bv(n.item),o=Q(n.delta)??Q(n.text),s=dy(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:fy(s)}}function dy(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(bv(t.error).message)??Q(t.message)}function fy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=iy?t:`${t.slice(0,iy)}...`}function py(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 my(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function hy(e){return e?e===`max`?`xhigh`:e:null}function gy(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 _y(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function vy(e){let t=bv(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=bv(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 yy(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var by=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new hv(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await Pv()}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??oy.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)}}},xy=15e3,Sy={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Cy=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??xy,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:Sy,capabilities:{experimentalApi:!1,optOutNotificationMethods:Sv}};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=xv(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=xv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=bv(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 wy(e,t={}){let n=new Cy(await Ty(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function Ty(e){return e.spawnProcess?new Dy(e.spawnProcess()):new Ey(await Hv(e.codexBinOverride))}var Ey=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()}},Dy=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 Q_=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return ov(r,await iv(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await av(e,n),i=p.default.parse(r).root;return ov(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await $_(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 $_(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:X_(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=ev(t),a=await tv(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 $_(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=ev(t),i=await tv(n,r),a=await d.default.realpath(i);return nv(n,a,r),{absolutePath:a,normalizedPath:r}}function ev(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function tv(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 nv(e,n,t),n}function nv(e,t,n){let r=rv(e),i=rv(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function rv(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function iv(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;nv(e,r,n??`.`);let i=await d.default.realpath(r);if(nv(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function av(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 ov(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 sv=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 lv(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=cv(t)??(p.default.basename(n)||n),o=r?{...r,title:cv(t)??r.title,updatedAt:i}:{id:`proj_${pg(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 lv(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 cv(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function lv(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)}Mh(),Dh(),Oh();var uv=c(jh(),1);Ph();var dv=uv.default,fv=120,pv=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_${pg(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 mv(fv);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 mv(e){return new Promise(t=>setTimeout(t,e))}var hv=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new pv(this.provider,e)}};function gv(e){let t=bv(vv(e)),n=Q(t.type);return n&&(t.type=_v(n)),t}function _v(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 yv(e)}}function vv(e){if(Array.isArray(e))return e.map(e=>vv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[yv(n)]=vv(r);return t}return e}function yv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function bv(e){return typeof e==`object`&&e?e:{}}function Q(e){if(typeof e==`string`)return e}function xv(e){return typeof e==`string`||typeof e==`number`?String(e):``}var Sv=[...`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}`)],Cv=[x.default.join(x.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),x.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function wv(e,t){let n=Tv(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 Tv(e){for(let t of Cv)try{return(0,S.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}var Ev=1e4,Dv=100,Ov=2e3;function kv(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function Av(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var jv=new Map;async function Mv(e){return Iv(e).createConnection()}async function Nv(){let e=[...jv.values()];await Promise.allSettled(e.map(e=>e.shutdown())),jv.clear()}async function Pv(e){let t=jv.size>0?[...jv.values()]:[Iv(e)];await Promise.all(t.map(e=>e.restart()))}function Fv(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=wv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function Iv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=jv.get(t);if(n)return n;let r=new Lv(e);return jv.set(t,r),r}var Lv=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await zv(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 zv(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 Uv(e.child,Ov)||(e.child.kill(`SIGKILL`),await Uv(e.child,Ov)))}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 Hv()}`,t=Fv(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 Vv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await Uv(n,Ov)),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`}},Rv=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){Av(`connection.close_failed`,{readyState:this.socket.readyState,...kv(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=Wv(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 zv(e,t){let n=Date.now()+Ev,r=null;for(;Date.now()<n;)try{return await Bv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await Gv(Dv)}throw r??Error(t())}async function Bv(e,t){let n=new dv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),Av(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){Av(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...kv(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 Rv(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`)}`:``;Av(`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 Vv(e,t,n){let r=Date.now()+Ev;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Bv(e,500)).close(),!0}catch{await Gv(Dv)}}return!1}async function Hv(){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 Uv(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 Wv(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 Gv(e){return new Promise(t=>{setTimeout(t,e)})}var Kv=15e3,qv=5e3,Jv={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Yv=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??Kv,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:Jv,capabilities:{experimentalApi:!1,optOutNotificationMethods:Sv}};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=xv(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=xv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=bv(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 Xv(e,t={}){let n=new Yv(await Qv(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function Zv(e={}){try{return await Xv(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??qv}),!0}catch{return!1}}async function Qv(e){return e.spawnProcess?new ey(e.spawnProcess()):new $v(await Mv(e.codexBinOverride))}var $v=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()}},ey=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)}}};async function Oy(e){let t=[],n=null;do{let r=await ky({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function ky(e){return wy(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>Ny(e)),nextCursor:n.nextCursor}})}async function Ay(e,t=!0){return wy(async n=>Ny((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function jy(e){return wy(async t=>{let n=!1;try{let r=await Ev(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,Fy(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function My(){let e=[],t=null;do{let n=await wy(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>Py(e))),t=n.nextCursor}while(t);return e}function Ny(e){let t=Q(bv(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,path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:Ly(e.source),gitInfo:e.gitInfo?bv(vv(e.gitInfo)):null,turns:e.turns.map(e=>Iy(e))}}function Py(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 Fy(e){let t=Ry(e.model),n=zy(e.reasoningEffort),r=By(e.approvalPolicy),i=Vy(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 Iy(e){return{id:e.id,status:e.status,error:e.error?bv(vv(e.error)):null,items:e.items.map(e=>gv(e))}}function Ly(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 Ry(e){return Q(e)?.trim()||void 0}function zy(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function By(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function Vy(e){let t=typeof e==`string`?e:Q(bv(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 Hy=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=jv(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=qy(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:Mv(r),questions:Gy(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=fb(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:pb(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)=>Wy(e,t)?this.requestUserInput(e,t,n):Uy(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${pg(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=Gy(t),i=`req_${pg(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=fb(e),n=pb(t.session_id)??pb(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_${pg(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=_b(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=pb(e.tool_id)??pb(e.tool_use_id)??hb(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=pb(e.uuid);if(n)return this.activeToolItemId=n,n;let r=vb(pb(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=fb(e),n=pb(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!sb(t))return[];let n=cb(fb(t.message));return n?[{type:`item.completed`,item:{id:pb(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:pb(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=ob(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=fb(t.event);if(pb(e.type)===`message_start`){let t=_b(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=lb(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||pb(t.subtype)?.startsWith(`error_`)===!0){let n=ub(t);return[...e,{type:`turn.failed`,error:{message:n},usage:db(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:db(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=pb(t.summary)??`tool summary`,i=pb(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=pb(t.tool_name)??`tool`,i=pb(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=pb(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(pb(t.session_id)??pb(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:pb(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=pb(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=Jy(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=Yy(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Xy({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 Uy(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 Wy(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function Gy(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=Ky(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 Ky(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 qy(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function Jy(e){let t=fb(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=fb(e);if(t.type!==`tool_use`)continue;let n=pb(t.id),i=pb(t.name),a=fb(t.input);if(!(!n||!i)){if(i===`Task`){let e=pb(a.subagent_type),t=pb(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:pb(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=pb(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=pb(a.file_path);r.push({id:n,toolName:`Write`,title:tb(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Yy(e){let t=fb(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=fb(e);if(t.type!==`tool_result`)continue;let n=pb(t.tool_use_id);if(n)return{toolUseId:n}}return null}function Xy(e){let t=fb(e.raw.tool_use_result),n=Zy(t.content)??cb(fb(e.raw.message)),r=fb(t.usage),i=gb(t.totalTokens)??gb(r.total_tokens)??gb(r.output_tokens),a=gb(t.totalToolUseCount),o=gb(t.totalDurationMs),s=pb(t.agentId),c=pb(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=$y(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=Qy(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=mb(t.content),r=eb(rb(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 Zy(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=fb(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
|
|
478
|
-
`).length}function
|
|
479
|
-
`)}function
|
|
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
|
|
481
|
-
`))}function Qb(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=ex(e),r=tx(t.text)??tx(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function $b(e,t=60){if(!e)return;let n=ix(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 ex(e){return typeof e==`object`&&e?e:{}}function tx(e){return typeof e==`string`&&e.trim()||void 0}function nx(e){if(typeof e==`string`)return rx(e)}function rx(e){if(!e)return;let t=ix(e).trim();return t.length>0?t:void 0}function ix(e){return e.replace(Mb,``)}function ax(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function ox(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var sx=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}=lx(r,[t,n]);if(ux(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=fx(await this.refreshProjects()),r=!0);let i=await dx(n.projects,t);if(!i)throw n_(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=fx(await this.refreshProjects()),i=await dx(n.projects,t),!i)throw n_(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 ky({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 cx({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>hx(e.cwd),mapSession:e=>{let t=gx(e.createdAt),n=gx(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:hx(e.name)??hx(e.preview),model:hx(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 cx({sessions:await Nb(),canonicalPathCache:e,getRawPath:e=>hx(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:hx(e.title),model:hx(e.model),createdAt:hx(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 cx(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 px(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function lx(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:mx(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=_x(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(yx)})).sort((e,t)=>vx(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function ux(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 lv(t);return e.find(e=>e.path===r)}function fx(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function px(e,t){let n=t.get(e);return n||(n=lv(e),t.set(e,n)),n}function mx(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function hx(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function gx(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function _x(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function vx(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 yx(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var bx=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 xx(this.getProjectPath(e),wx);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 Sx(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 Sx(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 xx(this.indexPath,Cx)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function xx(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 Sx(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 Cx(e){return!Tx(e)||e.v!==1||typeof e.generatedAt!=`string`||!qa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ja.safeParse(e).success)}function wx(e){return!Tx(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ja.safeParse(e.project).success||!qa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ya.safeParse(e).success)}function Tx(e){return typeof e==`object`&&!!e}const Ex=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function Dx(e){let t=xo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=ss(us(jx(i.export({format:`jwk`})))),o=Zo({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:So.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 Ox(e){let t=xo.parse(e.clientHello),n=So.parse(e.gatewayHello),r=Co.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!uo.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([Ex,cs(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Qo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,cs(r.signature)))throw Error(`transcript_invalid`)}function kx(e){let t=So.parse(e.gatewayHello),n=Co.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:ls(cs(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return ts({role:`gateway`,keySchedule:es({gatewayId:e.gatewayId,clientHello:xo.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function Ax(e){return Do.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function jx(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var Mx=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}},Nx=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(Jo.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=>ca.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(Jo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Fx(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Jo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Fx(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:{...Px(`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=>Oo.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(Jo.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=jo.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:Px(`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=Dx({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(Jo.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{Ox({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Ix(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=kx({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(Jo.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,Rx(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new Mx(t=>{try{let n=Jo.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,Lx(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:Ax({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:Px(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 os({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,Lx(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:as({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 Px(e,t,n){return jo.parse({code:e,status:t,message:n})}function Fx(e,t){if(Gg(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`||o_(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Ix(e){return Bx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function Lx(e){return Bx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function Rx(e){if(Gg(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 Bx(e,t){let n=zx(e);return t.find(e=>e===n)}function Vx(e){return e?e.readyState:null}var Hx=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??Gx}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=Vx(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=Jo.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=Ux(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=Jo.parse(JSON.parse(Wx(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 Ux(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 Wx(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 Gx(e){return new dv(e)}function Kx(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(Yo(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function qx(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(Jx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx({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 Lo.parse(JSON.parse(r)).token}function Jx(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 Yx(e){return e?.trim()||void 0}function Xx(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 Zx(e,t){return{modeDefault:`default`,model:Yx(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 Qx(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function $x(e,t){let n=Qx(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 eS(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function tS(e){let t=$x(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Yx(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?nS({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function nS(e){let t=$x(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?eS(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=$x(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=Yx(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??Yx(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:Xx(r.execution)}}}const rS=[],iS=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],aS=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],oS=Ni.options,sS=[`read-only`,`workspace-write`,`danger-full-access`],cS=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],lS=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function uS(e,t){lS&&(!e.startsWith(`config.get`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function dS(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}:{sessionFound:!1}}const fS={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`}}]},pS={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function mS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function hS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function gS(e,t){let n=t?.trim().toLowerCase();return n?(fS[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function _S(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:aS}:{}},...e.map(e=>({...e,isDefault:!1}))]}function vS(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function yS(e){let t=new Set;for(let n of e){let e=vS(n);e&&t.add(e)}return[...t]}function bS(e){return e?.trim()||void 0}function xS(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 SS(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:yS(e.supportedReasoningEfforts)}));return t.length===0?rS:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function CS(e){let t=Date.now();try{let n=SS(await My());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(nc(),`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=ES(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?yS(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 TS(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 ES(...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 DS=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:mS(e.runtimeLifecycle?.idleTtlMs,pS.idleTtlMs),sweepIntervalMs:hS(e.runtimeLifecycle?.sweepIntervalMs,pS.sweepIntervalMs),maxSessions:mS(e.runtimeLifecycle?.maxSessions,pS.maxSessions),maxCodexSessions:mS(e.runtimeLifecycle?.maxCodexSessions,pS.maxCodexSessions),maxClaudeSessions:mS(e.runtimeLifecycle?.maxClaudeSessions,pS.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 Uv(),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 e_(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.listAllSessionsWithRuntime(`running`).length;if(e>0)throw t_(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 Wv(),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=fS.claude.length>0?fS.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 Zg(t);let r=gS(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=Ab(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 CS(this.options.logger)??rS:rS,l=e===`claude`&&a?await wS(this.options.logger)??iS:iS,d=yS(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:aS,approvalPolicies:oS,sandboxModes:sS,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:cS},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:TS(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?_S(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 Zx(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Zg(e);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),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(uS(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:dS(n),runtime:dS(r)}),r)return uS(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...dS(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return uS(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...dS(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw Zg(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 Qg(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.syncExternalRawHistory(r,e,i);return{session:this.options.historyStore.getProjectSession(e,r.id)??r,rawEvents:a}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw Zg(e);let i=0,a=0,o,s=(s,c)=>{uS(`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 Qg(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 Zg(e);let n=this.options.historyStore.getProjectSession(e,t);if(!n)throw Qg(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${pg(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=Ab(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?$x(e.provider,e.sessionTurnConfig):tS({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=nS({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.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw $g(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=nS({provider:i.provider,providerDefaults:a,currentSessionTurnConfig:i.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});i.dispatchInFlight=!0,this.touchSession(i);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),!i.title){let e=ZS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=$x(i.provider,o.sessionTurnConfig),i.sessionTurnConfigUpdatedAt=a,o.model&&i.model!==o.model&&(i.model=o.model),i.updatedAt=a,await this.persistSessionSnapshot(i)}finally{i.dispatchInFlight=!1,this.touchSession(i)}}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:$S(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 $g(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_${pg(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=Ab(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=$x(t.provider,t.sessionTurnConfig),o=nS({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){if(!this.options.preferNativeProviders)return;let t;try{t=await Oy(e.path)}catch{return}let n=new Set(t.filter(t=>t.cwd===e.path).map(e=>e.id)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`codex`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){if(n.cwd!==e.path)continue;let t=[...r.values()].find(e=>e.provider===`codex`&&(e.id===n.id||e.nativeSessionId===n.id)),i=t?.id??n.id,a=this.sessions.get(i)??this.sessions.get(n.id),o=eC(n.createdAt),s=eC(n.updatedAt),c=a?.status===`running`?`running`:`idle`,l=c===`running`?a?.pendingToolApprovals.size??0:0,u=c===`running`?a?.pendingUserInputs.size??0:0,d={id:i,nativeSessionId:n.id,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:a?.providerMode??t?.providerMode??`native`,model:xS({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??ZS(n.name??n.preview)??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??o,updatedAt:c===`running`?a?.updatedAt??s:s,status:c,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),r.set(i,d)}}async syncClaudeSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await Pb(e.path)}catch{return}let n=new Set(t.map(e=>e.nativeSessionId)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`claude`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){let t=[...r.values()].find(e=>e.provider===`claude`&&(e.id===n.nativeSessionId||e.nativeSessionId===n.nativeSessionId)),i=t?.id??n.nativeSessionId,a=this.sessions.get(i),o=a?.status===`running`?`running`:`idle`,s=o===`running`?a?.pendingToolApprovals.size??0:0,c=o===`running`?a?.pendingUserInputs.size??0:0,l={id:i,nativeSessionId:n.nativeSessionId,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:a?.providerMode??t?.providerMode??`native`,model:a?.model??t?.model??n.model,title:a?.title??n.title??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??n.createdAt,updatedAt:o===`running`?a?.updatedAt??n.updatedAt:n.updatedAt,status:o,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c};await this.options.historyStore.upsertSession(l),r.set(i,l)}}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=HS([e.nativeSessionId,e.id]);for(let n of t)try{uS(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:n,...dS(e)});let t=await jy(n);if(!t){uS(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:n});continue}let r={...e,model:bS(t.model)??e.model,sessionTurnConfig:t.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt};return await this.options.historyStore.upsertSession(r),uS(`config.get.probe.result`,{projectId:e.projectId,sessionId:e.id,threadId:n,snapshotModel:t.model??null,snapshotSessionTurnConfigModel:t.sessionTurnConfig?.model??null,snapshotReasoningEffort:t.sessionTurnConfig?.reasoningEffort??null,snapshotApprovalPolicy:t.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,snapshotSandboxMode:t.sessionTurnConfig?.execution?.codex?.sandboxMode??null,snapshotUpdatedAt:t.sessionTurnConfigUpdatedAt,next:dS(r)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??r}catch(t){uS(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:n,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=e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt,n=e.sessionTurnConfigUpdatedAt||``;return!e.sessionTurnConfig||!bS(e.model)||!n?!0:t?n.localeCompare(t)>0?!0:t.localeCompare(n)>0:!1}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 Zg(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await tC(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Zg(e);return await tC(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=QS(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=QS(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_${pg(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_${pg(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=WS(e);if(!r)return n;try{let i=Date.now(),a=await Fb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t}),o=Date.now(),s=await this.finalizeExternalRawHistorySync(e,n,a);return uS(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,historyEventCount:a.length,resultEventCount:s.length,readHistoryDurationMs:o-i,finalizeDurationMs:Date.now()-o}),s}catch(r){return e.source===`native_discovered`&&US(r)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),uS(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,error:r instanceof Error?r.message:String(r)}),n}}if(e.provider!==`codex`)return n;let r=HS([e.nativeSessionId,e.id]);for(let i of r)try{let r=Date.now(),a=await Ay(i,!0),o=Date.now(),s=e.source===`gateway`&&n.length>0?JS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):GS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localTerminalTurnStatusById:KS(n),localTurnLastEventTsById:qS(n)}),c=Date.now(),l=await this.finalizeExternalRawHistorySync(e,n,s,eC(a.updatedAt));return uS(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,localEventCount:n.length,historyEventCount:s.length,resultEventCount:l.length,readThreadDurationMs:o-r,buildHistoryDurationMs:c-o,finalizeDurationMs:Date.now()-c}),l}catch{}return n}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt){let i=Date.now(),a=kS(e.provider,t,n),o=Date.now(),s=await this.maybePersistSyncedExternalRawEvents(e,a,!0);return await this.markExternalHistoryHydrated(e.id,r),uS(`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 markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw $g(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,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=XS(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 OS=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function kS(e,t,n){let r=new Map,i=new Set,a=AS(e),o=AS(e);for(let n of t){r.set(n.eventId,n);for(let t of jS(e,n,a))i.add(t)}for(let t of n){if(r.has(t.eventId))continue;let n=jS(e,t,o);if(!(n.length>0&&n.every(e=>i.has(e)))){r.set(t.eventId,t);for(let e of n)i.add(e)}}return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function AS(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function jS(e,t,n){return e===`codex`?MS(t,n):e===`claude`?FS(t):[]}function MS(e,t){let n=RS(e.payload.raw),r=new Set,i=IS(e.type,n);if(i){let a=NS(e.type,n);a?r.add(PS(a,t)):r.add(i)}if(e.type!==`native.raw`||$(n.source)!==`codex.history.thread_read`)return[...r];let a=RS(n.message),o=$(a.scope);if(o===`thread`){let e=RS(a.thread),t=$(e.id);t&&r.add(LS(`thread.started`,{thread_id:t,thread:e}));let n=ZS(zS(e.preview)??zS(e.name)??``);return n&&r.add(LS(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(o===`turn`){let e=RS(a.turn),t=$(e.status);return r.add(LS(`turn.started`,{turn:e})),t===`completed`?r.add(LS(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(LS(`turn.failed`,{status:t,turn:e})),[...r]}if(o===`item`){let e={turn_id:$(a.turn_id)??$(RS(a.item).turn_id),item:RS(a.item)},n=NS(`item.completed`,e);return n?r.add(PS(n,t)):r.add(LS(`item.completed`,e)),[...r]}return[...r]}function NS(e,t){if(!e.startsWith(`item.`))return;let n=RS(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)??``,BS(n)??``].join(`|`)}function PS(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 FS(e){let t=RS(e.payload.raw),n=IS(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!OS.has(r))return[];let i=RS(t.message),a=$(t.native_type)??$(i.type),o=RS(i.message);if(a===`user`){let e=VS(o),t=$(i.uuid);return!e||!t?[]:[LS(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=VS(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[LS(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function IS(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 LS(e,t);default:return}}function LS(e,t){let n=RS(t.item),r=RS(t.turn),i=RS(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=BS(n),m=zS(t.message)??``,h=zS(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 RS(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function zS(e){if(typeof e==`string`)return e.length>0?e:void 0}function BS(e){let t=zS(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=zS(RS(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=>
|
|
483
|
-
`)}return``}function
|
|
484
|
-
`)}function HS(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function US(e){return String(e).includes(`returned no messages from getSessionMessages`)}function WS(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function GS(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=t=>{let r=e.localTurnLastEventTsById?.get(t);typeof r==`number`&&Number.isFinite(r)&&(n=Math.max(n,r))},o=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),s=t=>{let n=t.map(o).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(`_`)}`},c=(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:s(r),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};c({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){if(e.localTerminalTurnStatusById?.get(t.id)===t.status&&YS(t.status)){a(t.id);continue}c({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)c({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,QS(n.id)??null])}return t}function KS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=RS(n.payload.raw);if(n.type===`turn.completed`||n.type===`turn.failed`){let r=$(e.turn_id)??$(e.turnId)??$(RS(e.turn).id)??$(RS(e.item).turn_id)??$(RS(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=RS(e.message);if($(r.scope)===`turn`){let e=RS(r.turn),n=$(e.id),i=$(e.status);n&&i&&YS(i)&&t.set(n,i)}}return t}function qS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=Date.parse(n.ts);if(!Number.isFinite(e))continue;let r=RS(n.payload.raw),i=$(r.turn_id)??$(r.turnId)??$(RS(r.turn).id);if(!i&&n.type===`native.raw`){if($(r.source)!==`codex.history.thread_read`)continue;let e=RS(r.message),t=$(e.scope);t===`turn`?i=$(RS(e.turn).id):t===`item`&&(i=$(e.turn_id)??$(e.turnId))}i&&t.set(i,Math.max(t.get(i)??0,e))}return t}function JS(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=RS(o.payload.raw);if(o.type===`item.started`||o.type===`item.updated`||o.type===`item.completed`){if(o.type===`item.completed`){let e=$(RS(s.item).id);e&&n.add(e)}}else if(o.type===`turn.started`){let e=$(s.turn_id)??$(RS(s.turn).id);e&&t.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=$(s.turn_id)??$(RS(s.turn).id);if(!e)continue;t.add(e);let n=$(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||$(s.source)!==`codex.history.thread_read`)continue;let c=RS(s.message),l=$(c.scope);if(l===`turn`){let e=RS(c.turn),n=$(e.id);if(!n)continue;t.add(n);let i=$(e.status);i&&YS(i)&&r.set(n,i);continue}if(l===`item`){let e=$(RS(c.item).id);e&&n.add(e)}}let o=Math.max(i,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),s=0,c=()=>(s+=1,new Date(o+s).toISOString()),l=[],u=(t,n)=>{let r=c();l.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_sync_codex_${e.sessionId}_${a.toString().padStart(6,`0`)}`,ts:r,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);if(!(e===i.status&&YS(i.status))){t.has(i.id)||u(`turn.started`,{type:`turn.started`,turn:{id:i.id,status:i.status,items:[],error:i.error}});for(let e of i.items){let t=$(e.id);t&&n.has(t)||u(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e})}if(YS(i.status)&&e!==i.status){if(i.status===`completed`){u(`turn.completed`,{type:`turn.completed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error}});continue}u(`turn.failed`,{type:`turn.failed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error},...i.error?{error:i.error}:{}})}}}return l}function YS(e){return e===`completed`||e===`failed`||e===`interrupted`}function XS(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function ZS(e,t=60){let n=XS(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function QS(e){if(typeof e!=`string`)return;let t=XS(e);if(t)return t}function $S(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function eC(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function tC(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var nC=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,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(fC(e)){let t=As([...await this.readSessionRawEventsLocked(e.sessionId),e]);await this.replaceRawEventFile(e.sessionId,t),this.rawEventsCacheBySession.set(e.sessionId,t),this.compactedRawEventsCacheBySession.set(e.sessionId,sC(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=pC(await this.readSessionRawEventsLocked(e),n),await this.replaceRawEventFile(e,r),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.set(e,sC(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 As(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=As((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 oC(t);let n=null;return await this.enqueueWrite(async()=>{n=oC(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`,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
|
|
486
|
-
`).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!
|
|
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 cC(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=sC(n);return this.compactedRawEventsCacheBySession.set(e,r),cC(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 rC(e){return typeof e==`object`&&!!e}function iC(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 oC(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}}function sC(e){let t=ks(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=js(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function cC(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function lC(e,t){let n=js(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=Ms(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 uC(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function dC(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=rC(e.payload.raw)?e.payload.raw:{},n=rC(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function fC(e){return dC(e)}function pC(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 As([...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 mC=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${pg(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()]:[]}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))}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)}};async function hC(e,t={}){await tu(e.gatewayLogPath);let n=_C(e,t),r=gC(e,n.instance);await r.register(cg.default,{origin:!0}),await r.register(sg.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new s_(e);await s.init();let c=new p_(e.auditLogPath),l=new mC,u=new Q_,d=new sv(e.projectStoreDir),f=new nC(e.sessionHistoryDir);await f.init();let m=new bx(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new sx({store:m});await h.init();let g,_=null,v=await qs(e.authStoreDir),y=new DS({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)}});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let b=new xl({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{_?.close(),x.close(),await b.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:N(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:il(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>$c({gatewayId:e.gatewayId,machineName:il(),relayBaseUrl:e.relayEnabled?fl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:ul({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(!ee(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=xa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=fe(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}}),DC(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=wa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await bC({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(I(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(I(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!I(e,t))return;let n=e.body,r=ja.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Ia.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(I(e,t))try{return Da.parse(await y.restartCodexAppServer())}catch(e){let n=Gg(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(I(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(I(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(!I(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 Gg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):jC(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!I(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(!I(e,t))return;let n=L(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Gg(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(!I(e,t))return;let n=L(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Gg(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(!I(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(!I(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(!I(e,t))return;let n=e.params,r=e.query,i=ae(r.status,t);if(!i)return;let a=oe(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Gg(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(!I(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(!I(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(!I(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 Gg(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(!I(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})();try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i)}}catch(e){return Gg(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(!I(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)=>ee(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ee(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=se(t.headers.authorization)??ce(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 C(la(e),r.sub,i)}catch(e){await w({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{l.removeClient(i)})});let x=new Nx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=fe(e.deviceName);return DC(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await bC({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return yC(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>TC(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:b,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await C(e,t,n)}catch(r){await w({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),S=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.stream.subscribe`:{let t=e.payload.sessions.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`}}));await T(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)}`)}}},C=async(e,t,n)=>{await S(e,t,n)},w=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`}})},T=async(e,t,n)=>{let r=E(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 D(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},E=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},D=async(e,t)=>{let n=await O(t);if(t.cursor.kind===`all`){await k(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await k(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await k(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,j({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)},O=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 Qg(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`}},k=async(e,t,n)=>{let r=`snap_${pg(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,j({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=A(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},A=(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},j=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${pg(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),M=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}}}),ee=t=>t.headers[`x-api-key`]===e.apiKey,N=e=>{if(e==null)return e;if(typeof e==`string`){let t=te(e);return t===void 0?ne(e,a):F(re(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=te(t);return n===void 0?ne(t,a):F(re(n))}return typeof e==`object`?F(re(e)):String(e)},te=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,re=e=>{if(Array.isArray(e))return e.map(e=>re(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]=re(r)}return n}return e},F=e=>{let t=ie(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},ie=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},I=(e,t)=>{let n=se(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}},ae=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},oe=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},L=(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)},se=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},ce=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},le=e.httpsEnabled?e.httpsPort:e.port,ue=e.httpsEnabled?`https`:`http`,de=il(),fe=e=>e?.trim()||de||`Gateway`;await r.listen({host:e.host,port:le});let pe=r.server.address(),me=typeof pe==`object`&&pe?pe.port:le;if(r.log.info({host:e.host,port:me,protocol:ue,machineName:de},vC(ue,e.host,me)),e.relayEnabled&&(_=new Hx({gatewayId:e.gatewayId,machineName:de,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>qx({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:ul({protocol:ue,host:e.host,port:me}),logger:r.log,onFrame:async e=>{await x.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 b.start(),{protocol:ue,listenPort:me,machineName:de,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function gC(e,t){let n=t;if(!e.httpsEnabled)return(0,lg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,lg.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 _C(e,t){let n=process.env.NODE_ENV!==`production`,r=Ug.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Ug.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Ug.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function vC(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function yC(e,t){if(e&&e!==t)throw Xg()}async function bC(e){let t=xC(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:SC(t)},`auth refresh attempt`);try{let t=await e.execute(),n=xC(e.authService,e.refreshToken),r=xC(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:SC(n),nextRefreshToken:SC(r)},`auth refresh succeeded`),t}catch(t){let n=xC(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:SC(n),error:CC(t)},`auth refresh failed`),t}}function xC(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function SC(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:wC(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:wC(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function CC(e){return Gg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function wC(e){return e?e.slice(-8):null}async function TC(e,t){try{let n=Oo.parse(e);switch(n.method){case`auth.refresh`:{let e=await bC({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 yC(n.params.deviceId??t.relayDeviceId,e.deviceId),ko.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return ko.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return ko.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return ko.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return ko.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return ko.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return ko.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return ko.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw kC(n.method,`NOT_FOUND`,404,`Project not found`);return ko.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 ko.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 ko.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return ko.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw kC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.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 kC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return ko.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=await t.sessionManager.getProjectSessionRawEvents(n.params.projectId,n.params.sessionId,n.params.limit===`all`?2**53-1:n.params.limit);return ko.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),ko.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 ko.parse({method:n.method,result:e})}case`devices.list`:return ko.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw kC(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return ko.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw kC(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw EC(e)}}function EC(e){if(Gg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return kC(`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 kC(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return kC(`BAD_REQUEST`,e.status,String(e),e.details);default:return kC(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=jo.safeParse(e);if(t.success)return t.data;let n=Ao.safeParse(e);if(n.success)return kC(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 kC(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?kC(`BAD_REQUEST`,400,r):AC(e)?kC(`UNAUTHORIZED`,401,r):jC(r)?kC(`BAD_REQUEST`,400,r):kC(`INTERNAL`,500,r)}function DC(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:OC(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Xs(e.identity,e.privateKeyPem,i)}}function OC(e){return e.replace(/\s+/gu,``).toUpperCase()}function kC(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 jo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function AC(e){return Gg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||o_(e)}function jC(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 MC(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function NC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await hC(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{FC({type:`worker.update.prepared`,payload:e})}});FC({type:`worker.ready`,payload:PC(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=IC(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: ${MC(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${MC(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);FC({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);FC({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){FC({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function PC(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function FC(e){process.send&&process.send(e)}function IC(e){if(!LC(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 LC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}RC(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function RC(e){let t=ne(e);switch(t.command){case`help`:UC();return;case`version`:console.log(P.version);return;case`init`:await BC(t);return;case`doctor`:await VC(t);return;case`start`:await zC(t);return;case`__worker`:await HC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function zC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await ql({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(nu(e,t.config))}Oc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function BC(e){let t=await ic({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 ac({configPath:t.configPath,ensureConfigFile:!1}),r=await Dc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(kc(r))}async function VC(e){let t=await ac({configPath:rc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(kc(n)),Oc(n)&&(process.exitCode=1)}async function HC(e){try{await NC(e)}catch(t){let n=await ac({configPath:e.configPath,ensureConfigFile:!0});throw Error(nu(t,n.config))}}function UC(){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=RC;
|
|
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)}}},ty=3,ny=250;function ry(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function iy(e,t){let n=Math.max(1,t?.maxAttempts??ty),r=Math.max(0,t?.retryDelayMs??ny),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!ry(e)||t>=n)throw e;r>0&&await ay(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function ay(e){return new Promise(t=>{setTimeout(t,e)})}function oy(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 sy(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var cy=3e4,ly=8,uy=160,dy={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},fy=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 Mv(),n.requestTimeoutMs??cy);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=oy(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=xy(this.activeSessionConfig.reasoningEffort),o,s=Sy(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`&&Cy(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:Sy(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=Ty(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:sy(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:dy,capabilities:{experimentalApi:!0,optOutNotificationMethods:Sv}};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 iy(()=>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:vy(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=xv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=bv(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=bv(r),a=Q(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${pg(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:vv(i)})}registerUserInputRequest(e,t,n){let r=Q(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${pg(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(wy).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:vv(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:vv(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:vv(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:vv(t.turn),error:vv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:vv(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:gv(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:gv(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=bv(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:vv(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:vv(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=xv(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=py(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=yy(e),n=by(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(xv(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Q(bv(e.params).threadId)}extractThreadIdFromNotification(e){let t=bv(e.params);return Q(t.threadId)||Q(bv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Q(bv(bv(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(my({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(my({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>ly&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-ly)}};function py(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function my(e){let t=Q(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=bv(e.message.error),i=gy(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:hy(t,n,e.direction),method:t,requestId:n?xv(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??vy(Q(r.message))}}function hy(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function gy(e,t){let n=bv(t),r=bv(n.thread),i=bv(n.turn),a=bv(n.item),o=Q(n.delta)??Q(n.text),s=_y(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:vy(s)}}function _y(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(bv(t.error).message)??Q(t.message)}function vy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=uy?t:`${t.slice(0,uy)}...`}function yy(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 by(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function xy(e){return e?e===`max`?`xhigh`:e:null}function Sy(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 Cy(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function wy(e){let t=bv(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=bv(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 Ty(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var Ey=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new hv(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await Zv()}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??fy.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 Dy(e){let t=[],n=null;do{let r=await Oy({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function Oy(e){return Xv(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>My(e)),nextCursor:n.nextCursor}})}async function ky(e,t=!0){return Xv(async n=>My((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function Ay(e){return Xv(async t=>{let n=!1;try{let r=await iy(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,Py(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function jy(){let e=[],t=null;do{let n=await Xv(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>Ny(e))),t=n.nextCursor}while(t);return e}function My(e){let t=Q(bv(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,path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:Iy(e.source),gitInfo:e.gitInfo?bv(vv(e.gitInfo)):null,turns:e.turns.map(e=>Fy(e))}}function Ny(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 Py(e){let t=Ly(e.model),n=Ry(e.reasoningEffort),r=zy(e.approvalPolicy),i=By(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 Fy(e){return{id:e.id,status:e.status,error:e.error?bv(vv(e.error)):null,items:e.items.map(e=>gv(e))}}function Iy(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 Ly(e){return Q(e)?.trim()||void 0}function Ry(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function zy(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function By(e){let t=typeof e==`string`?e:Q(bv(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 Vy=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=oy(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=Ky(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:sy(r),questions:Wy(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=db(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:fb(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)=>Uy(e,t)?this.requestUserInput(e,t,n):Hy(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${pg(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=Wy(t),i=`req_${pg(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=db(e),n=fb(t.session_id)??fb(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_${pg(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=gb(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=fb(e.tool_id)??fb(e.tool_use_id)??mb(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=fb(e.uuid);if(n)return this.activeToolItemId=n,n;let r=_b(fb(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=db(e),n=fb(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!ob(t))return[];let n=sb(db(t.message));return n?[{type:`item.completed`,item:{id:fb(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:fb(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=ab(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=db(t.event);if(fb(e.type)===`message_start`){let t=gb(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=cb(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||fb(t.subtype)?.startsWith(`error_`)===!0){let n=lb(t);return[...e,{type:`turn.failed`,error:{message:n},usage:ub(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:ub(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=fb(t.summary)??`tool summary`,i=fb(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=fb(t.tool_name)??`tool`,i=fb(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=fb(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(fb(t.session_id)??fb(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:fb(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=fb(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=qy(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=Jy(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Yy({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 Hy(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 Uy(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function Wy(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=Gy(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 Gy(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 Ky(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function qy(e){let t=db(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=db(e);if(t.type!==`tool_use`)continue;let n=fb(t.id),i=fb(t.name),a=db(t.input);if(!(!n||!i)){if(i===`Task`){let e=fb(a.subagent_type),t=fb(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:fb(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=fb(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=fb(a.file_path);r.push({id:n,toolName:`Write`,title:eb(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Jy(e){let t=db(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=db(e);if(t.type!==`tool_result`)continue;let n=fb(t.tool_use_id);if(n)return{toolUseId:n}}return null}function Yy(e){let t=db(e.raw.tool_use_result),n=Xy(t.content)??sb(db(e.raw.message)),r=db(t.usage),i=hb(t.totalTokens)??hb(r.total_tokens)??hb(r.output_tokens),a=hb(t.totalToolUseCount),o=hb(t.totalDurationMs),s=fb(t.agentId),c=fb(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=Qy(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=Zy(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=pb(t.content),r=$y(nb(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 Xy(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=db(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 Zy(e){return pb(db(e.file).content)||Xy(e.content)}function Qy(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${rb(t)} tokens`),typeof n==`number`&&r.push(ib(n)),r.join(` · `)}function $y(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function eb(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${tb(e)})`:`Write`}function tb(e){let t=e.split(`/`);return t[t.length-1]||e}function nb(e){if(e)return e.split(`
|
|
478
|
+
`).length}function rb(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function ib(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 ab(e){return sb(db(e.message))||(pb(e.result)??``)}function ob(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=db(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>db(e).type===`tool_result`)}function sb(e){let t=pb(e.content);if(t)return t;let n=pb(e.text)??pb(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=db(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 cb(e){let t=db(db(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function lb(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):fb(e.subtype)||`Claude turn failed`}function ub(e){let t=db(e);return{input_tokens:hb(t.input_tokens)??hb(t.inputTokens)??0,cached_input_tokens:hb(t.cached_input_tokens)??hb(t.cache_read_input_tokens)??hb(t.cacheReadInputTokens)??0,output_tokens:hb(t.output_tokens)??hb(t.outputTokens)??0}}function db(e){return typeof e==`object`&&e?e:{}}function fb(e){if(typeof e==`string`&&e.trim())return e}function pb(e){if(typeof e==`string`&&e.length>0)return e}function mb(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function hb(e){if(typeof e==`number`&&Number.isFinite(e))return e}function gb(e){let t=fb(db(e.message).id);if(t)return t;let n=fb(db(db(e.event).message).id);if(n)return n}function _b(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var vb=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=yb(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 yb(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var bb=`@anthropic-ai/claude-agent-sdk`,xb=`claude-sonnet-4-6`,Sb=1e4,Cb=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(bb),!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(bb),n=await wb(Tb(t,e),Sb,`Claude native query session creation timed out`);if(n)return n;let r=await wb(Eb(t,e),Sb,`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 wb(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 Tb(e,t){let n=Db(e);if(!n)return null;let r=t.model??xb;return new Vy(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=Ob(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 Eb(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 vb(`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 vb(`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 vb(`claude`,t.sessionId,t.model,n)}return null}function Db(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function Ob(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 kb(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new Ey(n,r):new Cb(n,r)}const Ab=p.default.join(`.claude`,`projects`),jb=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function Mb(e){return(await(0,T.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>Rb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Nb(e,t){let n=Ib(e,t?.homeDir),r=p.default.resolve(e),i=[];try{i=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}let a=[];for(let e of i){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),i=await Wb(t);if(!Vb(i))continue;let o=await d.default.stat(t),s=Bb(i,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});a.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}let o;try{o=new Map((await(0,T.listSessions)({dir:e})).map(e=>Rb(e)).filter(e=>typeof e.cwd==`string`?p.default.resolve(e.cwd)===r:!1).map(e=>[e.nativeSessionId,e]))}catch{}if(o)for(let e=0;e<a.length;e+=1){let t=a[e];if(!t)continue;let n=o.get(t.nativeSessionId);n&&(a[e]={...t,title:n.title??t.title,updatedAt:n.updatedAt})}return a.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Pb(e){let t=await Gb(e.nativeSessionId,e.projectPath),n=await Kb(e.projectPath,e.nativeSessionId,e.homeDir);return zb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function Fb(e,t,n){return p.default.join(Ib(e,n),`${t}.jsonl`)}function Ib(e,t){let n=t??f.default.homedir();return p.default.join(n,Ab,Lb(e))}function Lb(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function Rb(e){let t=tx(e.customTitle)??tx(e.summary)??tx(e.firstPrompt),n=Ub(e.lastModified);return{nativeSessionId:e.sessionId,cwd:Hb(e.cwd),title:t,createdAt:n,updatedAt:n}}function zb(e){let t=[],n=Bb(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 Bb(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=Qb(Xb($b(t.raw.message)))),!n&&t.type===`assistant`&&(n=ex($b(t.raw.message).model));let o=i??ax(t.createdAtFallbackMs)??0,s=a??ax(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function Vb(e){for(let t of e){if(t.type===`user`){let e=$b(t.raw.message);if(Xb(e)||Yb(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=$b(t.raw.message);if(Xb(e)||Jb(e).length>0||ex(t.raw.error))return!0}return!1}function Hb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ub(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Wb(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=$b(i),o=ex(a.timestamp),s=o?ix(o):void 0;n.push({line:e+1,raw:a,type:ex(a.type),timestamp:o,timestampMs:s})}return n}async function Gb(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)=>qb(e,t+1))}async function Kb(e,t,n){let r=Fb(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function qb(e,t){let n=$b(e),r=$b(n.message),i=ex(n.timestamp)??ex(r.timestamp)??ex(r.created_at)??ex(r.createdAt);return{line:t,raw:{...n,message:r},type:ex(n.type),timestamp:i,timestampMs:i?ix(i):void 0}}function Jb(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=$b(e);if(ex(t.type)!==`tool_use`)continue;let r=$b(t.input),i=ex(r.command),a=ex(t.name)??`tool`,o=ex(r.description);n.push({id:ex(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function Yb(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=$b(e);if(ex(t.type)!==`tool_result`)continue;let r=nx(ex(t.content)??ex($b(t.toolUseResult).stdout)??ex($b(t.tool_use_result).stdout)??ex(t.text));n.push({toolUseId:ex(t.tool_use_id)??ex(t.toolUseId),toolName:ex(t.tool_name)??ex(t.toolName),text:r,isError:t.is_error===!0})}return n}function Xb(e){let t=ex(e.content);if(t)return nx(t);let n=ex(e.text)??ex(e.prompt);if(n)return nx(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=$b(e),n=ex(t.type);if(n&&n!==`text`)continue;let r=ex(t.text)??ex(t.content)??Zb(t);r&&i.push(r)}if(i.length!==0)return nx(i.join(`
|
|
481
|
+
`))}function Zb(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=$b(e),r=ex(t.text)??ex(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function Qb(e,t=60){if(!e)return;let n=rx(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 $b(e){return typeof e==`object`&&e?e:{}}function ex(e){return typeof e==`string`&&e.trim()||void 0}function tx(e){if(typeof e==`string`)return nx(e)}function nx(e){if(!e)return;let t=rx(e).trim();return t.length>0?t:void 0}function rx(e){return e.replace(jb,``)}function ix(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function ax(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var ox=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}=cx(r,[t,n]);if(lx(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=dx(await this.refreshProjects()),r=!0);let i=await ux(n.projects,t);if(!i)throw n_(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=dx(await this.refreshProjects()),i=await ux(n.projects,t),!i)throw n_(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 Oy({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 sx({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>mx(e.cwd),mapSession:e=>{let t=hx(e.createdAt),n=hx(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:mx(e.name)??mx(e.preview),model:mx(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 sx({sessions:await Mb(),canonicalPathCache:e,getRawPath:e=>mx(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:mx(e.title),model:mx(e.model),createdAt:mx(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 sx(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 fx(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function cx(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:px(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=gx(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(vx)})).sort((e,t)=>_x(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function lx(e){return Object.values(e).some(e=>e?.status===`failed`)}async function ux(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await lv(t);return e.find(e=>e.path===r)}function dx(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function fx(e,t){let n=t.get(e);return n||(n=lv(e),t.set(e,n)),n}function px(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function mx(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function hx(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function gx(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function _x(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 vx(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var yx=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 bx(this.getProjectPath(e),Cx);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 xx(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 xx(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 bx(this.indexPath,Sx)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function bx(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 xx(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 Sx(e){return!wx(e)||e.v!==1||typeof e.generatedAt!=`string`||!qa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ja.safeParse(e).success)}function Cx(e){return!wx(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ja.safeParse(e.project).success||!qa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ya.safeParse(e).success)}function wx(e){return typeof e==`object`&&!!e}const Tx=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function Ex(e){let t=xo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=ss(us(Ax(i.export({format:`jwk`})))),o=Zo({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:So.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 Dx(e){let t=xo.parse(e.clientHello),n=So.parse(e.gatewayHello),r=Co.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!uo.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([Tx,cs(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Qo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,cs(r.signature)))throw Error(`transcript_invalid`)}function Ox(e){let t=So.parse(e.gatewayHello),n=Co.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:ls(cs(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return ts({role:`gateway`,keySchedule:es({gatewayId:e.gatewayId,clientHello:xo.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 Do.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function Ax(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}},Mx=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(Jo.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=>ca.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(Jo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Px(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Jo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Px(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:{...Nx(`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=>Oo.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(Jo.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=jo.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:Nx(`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=Ex({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(Jo.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{Dx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Fx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=Ox({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(Jo.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,Lx(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new jx(t=>{try{let n=Jo.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,Ix(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:Nx(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 os({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,Ix(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:as({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 Nx(e,t,n){return jo.parse({code:e,status:t,message:n})}function Px(e,t){if(Gg(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=Rx(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`||o_(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Fx(e){return zx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function Ix(e){return zx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function Lx(e){if(Gg(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=Rx(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 Rx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function zx(e,t){let n=Rx(e);return t.find(e=>e===n)}function Bx(e){return e?e.readyState:null}var Vx=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??Wx}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=Bx(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=Jo.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=Hx(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=Jo.parse(JSON.parse(Ux(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 Hx(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 Ux(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 Wx(e){return new dv(e)}function Gx(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(Yo(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function Kx(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(qx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Gx({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 Lo.parse(JSON.parse(r)).token}function qx(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 Jx(e){return e?.trim()||void 0}function Yx(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 Xx(e,t){return{modeDefault:`default`,model:Jx(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 Zx(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function Qx(e,t){let n=Zx(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 $x(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function eS(e){let t=Qx(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Jx(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?tS({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function tS(e){let t=Qx(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?$x(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=Qx(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=Jx(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??Jx(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:Yx(r.execution)}}}const nS=[],rS=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],iS=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],aS=Ni.options,oS=[`read-only`,`workspace-write`,`danger-full-access`],sS=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],cS=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function lS(e,t){cS&&(!e.startsWith(`config.get`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function uS(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}:{sessionFound:!1}}const dS={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`}}]},fS={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 mS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function hS(e,t){let n=t?.trim().toLowerCase();return n?(dS[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function gS(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:iS}:{}},...e.map(e=>({...e,isDefault:!1}))]}function _S(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function vS(e){let t=new Set;for(let n of e){let e=_S(n);e&&t.add(e)}return[...t]}function yS(e){return e?.trim()||void 0}function bS(e){let t=yS(e.runtimeModel);if(t)return t;let n=yS(e.discoveredModel);if(n)return n;let r=yS(e.existingModel),i=yS(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function xS(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:vS(e.supportedReasoningEfforts)}));return t.length===0?nS:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function SS(e){let t=Date.now();try{let n=xS(await jy());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 CS(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(nc(),`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=TS(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?vS(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 wS(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 TS(...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 ES=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,fS.idleTtlMs),sweepIntervalMs:mS(e.runtimeLifecycle?.sweepIntervalMs,fS.sweepIntervalMs),maxSessions:pS(e.runtimeLifecycle?.maxSessions,fS.maxSessions),maxCodexSessions:pS(e.runtimeLifecycle?.maxCodexSessions,fS.maxCodexSessions),maxClaudeSessions:pS(e.runtimeLifecycle?.maxClaudeSessions,fS.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 Nv(),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 e_(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.listAllSessionsWithRuntime(`running`).length;if(e>0)throw t_(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 Pv(),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=dS.claude.length>0?dS.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 Zg(t);let r=hS(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=kb(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 SS(this.options.logger)??nS:nS,l=e===`claude`&&a?await CS(this.options.logger)??rS:rS,d=vS(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:iS,approvalPolicies:aS,sandboxModes:oS,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:sS},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:wS(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?gS(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 Xx(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Zg(e);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),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(lS(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:uS(n),runtime:uS(r)}),r)return lS(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...uS(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return lS(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...uS(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw Zg(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 Qg(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.syncExternalRawHistory(r,e,i);return{session:this.options.historyStore.getProjectSession(e,r.id)??r,rawEvents:a}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw Zg(e);let i=0,a=0,o,s=(s,c)=>{lS(`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 Qg(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 Zg(e);let n=this.options.historyStore.getProjectSession(e,t);if(!n)throw Qg(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${pg(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=kb(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?Qx(e.provider,e.sessionTurnConfig):eS({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=tS({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.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw $g(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=tS({provider:i.provider,providerDefaults:a,currentSessionTurnConfig:i.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});i.dispatchInFlight=!0,this.touchSession(i);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),!i.title){let e=XS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=Qx(i.provider,o.sessionTurnConfig),i.sessionTurnConfigUpdatedAt=a,o.model&&i.model!==o.model&&(i.model=o.model),i.updatedAt=a,await this.persistSessionSnapshot(i)}finally{i.dispatchInFlight=!1,this.touchSession(i)}}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:QS(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 $g(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_${pg(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=kb(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=Qx(t.provider,t.sessionTurnConfig),o=tS({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){if(!this.options.preferNativeProviders)return;let t;try{t=await Dy(e.path)}catch{return}let n=new Set(t.filter(t=>t.cwd===e.path).map(e=>e.id)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`codex`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){if(n.cwd!==e.path)continue;let t=[...r.values()].find(e=>e.provider===`codex`&&(e.id===n.id||e.nativeSessionId===n.id)),i=t?.id??n.id,a=this.sessions.get(i)??this.sessions.get(n.id),o=$S(n.createdAt),s=$S(n.updatedAt),c=a?.status===`running`?`running`:`idle`,l=c===`running`?a?.pendingToolApprovals.size??0:0,u=c===`running`?a?.pendingUserInputs.size??0:0,d={id:i,nativeSessionId:n.id,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:a?.providerMode??t?.providerMode??`native`,model:bS({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??XS(n.name??n.preview)??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??o,updatedAt:c===`running`?a?.updatedAt??s:s,status:c,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),r.set(i,d)}}async syncClaudeSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await Nb(e.path)}catch{return}let n=new Set(t.map(e=>e.nativeSessionId)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`claude`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){let t=[...r.values()].find(e=>e.provider===`claude`&&(e.id===n.nativeSessionId||e.nativeSessionId===n.nativeSessionId)),i=t?.id??n.nativeSessionId,a=this.sessions.get(i),o=a?.status===`running`?`running`:`idle`,s=o===`running`?a?.pendingToolApprovals.size??0:0,c=o===`running`?a?.pendingUserInputs.size??0:0,l={id:i,nativeSessionId:n.nativeSessionId,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:a?.providerMode??t?.providerMode??`native`,model:a?.model??t?.model??n.model,title:a?.title??n.title??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??n.createdAt,updatedAt:o===`running`?a?.updatedAt??n.updatedAt:n.updatedAt,status:o,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c};await this.options.historyStore.upsertSession(l),r.set(i,l)}}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=VS([e.nativeSessionId,e.id]);for(let n of t)try{lS(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:n,...uS(e)});let t=await Ay(n);if(!t){lS(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:n});continue}let r={...e,model:yS(t.model)??e.model,sessionTurnConfig:t.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt};return await this.options.historyStore.upsertSession(r),lS(`config.get.probe.result`,{projectId:e.projectId,sessionId:e.id,threadId:n,snapshotModel:t.model??null,snapshotSessionTurnConfigModel:t.sessionTurnConfig?.model??null,snapshotReasoningEffort:t.sessionTurnConfig?.reasoningEffort??null,snapshotApprovalPolicy:t.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,snapshotSandboxMode:t.sessionTurnConfig?.execution?.codex?.sandboxMode??null,snapshotUpdatedAt:t.sessionTurnConfigUpdatedAt,next:uS(r)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??r}catch(t){lS(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:n,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=e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt,n=e.sessionTurnConfigUpdatedAt||``;return!e.sessionTurnConfig||!yS(e.model)||!n?!0:t?n.localeCompare(t)>0?!0:t.localeCompare(n)>0:!1}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 Zg(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 Zg(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=ZS(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=ZS(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_${pg(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_${pg(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=US(e);if(!r)return n;try{let i=Date.now(),a=await Pb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t}),o=Date.now(),s=await this.finalizeExternalRawHistorySync(e,n,a);return lS(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,historyEventCount:a.length,resultEventCount:s.length,readHistoryDurationMs:o-i,finalizeDurationMs:Date.now()-o}),s}catch(r){return e.source===`native_discovered`&&HS(r)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),lS(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,error:r instanceof Error?r.message:String(r)}),n}}if(e.provider!==`codex`)return n;let r=VS([e.nativeSessionId,e.id]);for(let i of r)try{let r=Date.now(),a=await ky(i,!0),o=Date.now(),s=e.source===`gateway`&&n.length>0?qS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):WS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localTerminalTurnStatusById:GS(n),localTurnLastEventTsById:KS(n)}),c=Date.now(),l=await this.finalizeExternalRawHistorySync(e,n,s,$S(a.updatedAt));return lS(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,localEventCount:n.length,historyEventCount:s.length,resultEventCount:l.length,readThreadDurationMs:o-r,buildHistoryDurationMs:c-o,finalizeDurationMs:Date.now()-c}),l}catch{}return n}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt){let i=Date.now(),a=OS(e.provider,t,n),o=Date.now(),s=await this.maybePersistSyncedExternalRawEvents(e,a,!0);return await this.markExternalHistoryHydrated(e.id,r),lS(`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 markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw $g(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,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=YS(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 DS=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function OS(e,t,n){let r=new Map,i=new Set,a=kS(e),o=kS(e);for(let n of t){r.set(n.eventId,n);for(let t of AS(e,n,a))i.add(t)}for(let t of n){if(r.has(t.eventId))continue;let n=AS(e,t,o);if(!(n.length>0&&n.every(e=>i.has(e)))){r.set(t.eventId,t);for(let e of n)i.add(e)}}return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function kS(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function AS(e,t,n){return e===`codex`?jS(t,n):e===`claude`?PS(t):[]}function jS(e,t){let n=LS(e.payload.raw),r=new Set,i=FS(e.type,n);if(i){let a=MS(e.type,n);a?r.add(NS(a,t)):r.add(i)}if(e.type!==`native.raw`||$(n.source)!==`codex.history.thread_read`)return[...r];let a=LS(n.message),o=$(a.scope);if(o===`thread`){let e=LS(a.thread),t=$(e.id);t&&r.add(IS(`thread.started`,{thread_id:t,thread:e}));let n=XS(RS(e.preview)??RS(e.name)??``);return n&&r.add(IS(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(o===`turn`){let e=LS(a.turn),t=$(e.status);return r.add(IS(`turn.started`,{turn:e})),t===`completed`?r.add(IS(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(IS(`turn.failed`,{status:t,turn:e})),[...r]}if(o===`item`){let e={turn_id:$(a.turn_id)??$(LS(a.item).turn_id),item:LS(a.item)},n=MS(`item.completed`,e);return n?r.add(NS(n,t)):r.add(IS(`item.completed`,e)),[...r]}return[...r]}function MS(e,t){if(!e.startsWith(`item.`))return;let n=LS(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)??``,zS(n)??``].join(`|`)}function NS(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 PS(e){let t=LS(e.payload.raw),n=FS(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!DS.has(r))return[];let i=LS(t.message),a=$(t.native_type)??$(i.type),o=LS(i.message);if(a===`user`){let e=BS(o),t=$(i.uuid);return!e||!t?[]:[IS(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=BS(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[IS(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function FS(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 IS(e,t);default:return}}function IS(e,t){let n=LS(t.item),r=LS(t.turn),i=LS(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=zS(n),m=RS(t.message)??``,h=RS(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 LS(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function RS(e){if(typeof e==`string`)return e.length>0?e:void 0}function zS(e){let t=RS(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=RS(LS(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=>RS(e)).filter(e=>!!e);if(e.length>0)return e.join(`
|
|
483
|
+
`)}return``}function BS(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=LS(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 VS(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function HS(e){return String(e).includes(`returned no messages from getSessionMessages`)}function US(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function WS(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=t=>{let r=e.localTurnLastEventTsById?.get(t);typeof r==`number`&&Number.isFinite(r)&&(n=Math.max(n,r))},o=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),s=t=>{let n=t.map(o).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(`_`)}`},c=(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:s(r),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};c({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){if(e.localTerminalTurnStatusById?.get(t.id)===t.status&&JS(t.status)){a(t.id);continue}c({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)c({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,ZS(n.id)??null])}return t}function GS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=LS(n.payload.raw);if(n.type===`turn.completed`||n.type===`turn.failed`){let r=$(e.turn_id)??$(e.turnId)??$(LS(e.turn).id)??$(LS(e.item).turn_id)??$(LS(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=LS(e.message);if($(r.scope)===`turn`){let e=LS(r.turn),n=$(e.id),i=$(e.status);n&&i&&JS(i)&&t.set(n,i)}}return t}function KS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=Date.parse(n.ts);if(!Number.isFinite(e))continue;let r=LS(n.payload.raw),i=$(r.turn_id)??$(r.turnId)??$(LS(r.turn).id);if(!i&&n.type===`native.raw`){if($(r.source)!==`codex.history.thread_read`)continue;let e=LS(r.message),t=$(e.scope);t===`turn`?i=$(LS(e.turn).id):t===`item`&&(i=$(e.turn_id)??$(e.turnId))}i&&t.set(i,Math.max(t.get(i)??0,e))}return t}function qS(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=LS(o.payload.raw);if(o.type===`item.started`||o.type===`item.updated`||o.type===`item.completed`){if(o.type===`item.completed`){let e=$(LS(s.item).id);e&&n.add(e)}}else if(o.type===`turn.started`){let e=$(s.turn_id)??$(LS(s.turn).id);e&&t.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=$(s.turn_id)??$(LS(s.turn).id);if(!e)continue;t.add(e);let n=$(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||$(s.source)!==`codex.history.thread_read`)continue;let c=LS(s.message),l=$(c.scope);if(l===`turn`){let e=LS(c.turn),n=$(e.id);if(!n)continue;t.add(n);let i=$(e.status);i&&JS(i)&&r.set(n,i);continue}if(l===`item`){let e=$(LS(c.item).id);e&&n.add(e)}}let o=Math.max(i,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),s=0,c=()=>(s+=1,new Date(o+s).toISOString()),l=[],u=(t,n)=>{let r=c();l.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_sync_codex_${e.sessionId}_${a.toString().padStart(6,`0`)}`,ts:r,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);if(!(e===i.status&&JS(i.status))){t.has(i.id)||u(`turn.started`,{type:`turn.started`,turn:{id:i.id,status:i.status,items:[],error:i.error}});for(let e of i.items){let t=$(e.id);t&&n.has(t)||u(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e})}if(JS(i.status)&&e!==i.status){if(i.status===`completed`){u(`turn.completed`,{type:`turn.completed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error}});continue}u(`turn.failed`,{type:`turn.failed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error},...i.error?{error:i.error}:{}})}}}return l}function JS(e){return e===`completed`||e===`failed`||e===`interrupted`}function YS(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function XS(e,t=60){let n=YS(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function ZS(e){if(typeof e!=`string`)return;let t=YS(e);if(t)return t}function QS(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function $S(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 tC=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,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(fC(e)){let t=As([...await this.readSessionRawEventsLocked(e.sessionId),e]);await this.replaceRawEventFile(e.sessionId,t),this.rawEventsCacheBySession.set(e.sessionId,t),this.compactedRawEventsCacheBySession.set(e.sessionId,sC(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=pC(await this.readSessionRawEventsLocked(e),n),await this.replaceRawEventFile(e,r),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.set(e,sC(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 As(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=As((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 aC(t);let n=null;return await this.enqueueWrite(async()=>{n=aC(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`,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=`${iC(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=>iC(e)).join(`
|
|
485
|
+
`);await oC(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(dC(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&uC(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}lC(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return cC(t);let n=sC(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),cC(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(!nC(t)||t.kind!==`provider.raw`)continue;let n=rC(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=fa.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>iC(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 cC(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=sC(n);return this.compactedRawEventsCacheBySession.set(e,r),cC(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 nC(e){return typeof e==`object`&&!!e}function rC(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function iC(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 aC(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 oC(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 sC(e){let t=ks(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=js(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function cC(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function lC(e,t){let n=js(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=Ms(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 uC(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function dC(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=nC(e.payload.raw)?e.payload.raw:{},n=nC(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function fC(e){return dC(e)}function pC(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 As([...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 mC=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${pg(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()]:[]}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))}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)}};async function hC(e,t={}){await tu(e.gatewayLogPath);let n=_C(e,t),r=gC(e,n.instance);await r.register(cg.default,{origin:!0}),await r.register(sg.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new s_(e);await s.init();let c=new p_(e.auditLogPath),l=new mC,u=new Q_,d=new sv(e.projectStoreDir),f=new tC(e.sessionHistoryDir);await f.init();let m=new yx(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new ox({store:m});await h.init();let g,_=null,v=await qs(e.authStoreDir),y=new ES({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)}});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let b=new xl({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{_?.close(),x.close(),await b.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:N(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:il(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>$c({gatewayId:e.gatewayId,machineName:il(),relayBaseUrl:e.relayEnabled?fl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:ul({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(!ee(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=xa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=fe(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}}),DC(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=wa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await bC({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(I(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(I(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!I(e,t))return;let n=e.body,r=ja.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Ia.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(I(e,t))try{return Da.parse(await y.restartCodexAppServer())}catch(e){let n=Gg(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(I(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(I(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(!I(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 Gg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):jC(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!I(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(!I(e,t))return;let n=L(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Gg(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(!I(e,t))return;let n=L(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Gg(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(!I(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(!I(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(!I(e,t))return;let n=e.params,r=e.query,i=ae(r.status,t);if(!i)return;let a=oe(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Gg(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(!I(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(!I(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(!I(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 Gg(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(!I(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})();try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i)}}catch(e){return Gg(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(!I(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)=>ee(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ee(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=se(t.headers.authorization)??ce(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 C(la(e),r.sub,i)}catch(e){await w({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{l.removeClient(i)})});let x=new Mx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=fe(e.deviceName);return DC(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await bC({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return yC(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>TC(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:b,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await C(e,t,n)}catch(r){await w({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),S=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.stream.subscribe`:{let t=e.payload.sessions.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`}}));await T(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)}`)}}},C=async(e,t,n)=>{await S(e,t,n)},w=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`}})},T=async(e,t,n)=>{let r=E(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 D(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},E=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},D=async(e,t)=>{let n=await O(t);if(t.cursor.kind===`all`){await k(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await k(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await k(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,j({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)},O=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 Qg(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`}},k=async(e,t,n)=>{let r=`snap_${pg(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,j({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=A(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},A=(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},j=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${pg(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),M=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}}}),ee=t=>t.headers[`x-api-key`]===e.apiKey,N=e=>{if(e==null)return e;if(typeof e==`string`){let t=te(e);return t===void 0?ne(e,a):F(re(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=te(t);return n===void 0?ne(t,a):F(re(n))}return typeof e==`object`?F(re(e)):String(e)},te=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,re=e=>{if(Array.isArray(e))return e.map(e=>re(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]=re(r)}return n}return e},F=e=>{let t=ie(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},ie=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},I=(e,t)=>{let n=se(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}},ae=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},oe=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},L=(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)},se=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},ce=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},le=e.httpsEnabled?e.httpsPort:e.port,ue=e.httpsEnabled?`https`:`http`,de=il(),fe=e=>e?.trim()||de||`Gateway`;await r.listen({host:e.host,port:le});let pe=r.server.address(),me=typeof pe==`object`&&pe?pe.port:le;if(r.log.info({host:e.host,port:me,protocol:ue,machineName:de},vC(ue,e.host,me)),e.relayEnabled&&(_=new Vx({gatewayId:e.gatewayId,machineName:de,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>Kx({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:ul({protocol:ue,host:e.host,port:me}),logger:r.log,onFrame:async e=>{await x.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 b.start(),{protocol:ue,listenPort:me,machineName:de,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function gC(e,t){let n=t;if(!e.httpsEnabled)return(0,lg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,lg.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 _C(e,t){let n=process.env.NODE_ENV!==`production`,r=Ug.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Ug.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Ug.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function vC(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function yC(e,t){if(e&&e!==t)throw Xg()}async function bC(e){let t=xC(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:SC(t)},`auth refresh attempt`);try{let t=await e.execute(),n=xC(e.authService,e.refreshToken),r=xC(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:SC(n),nextRefreshToken:SC(r)},`auth refresh succeeded`),t}catch(t){let n=xC(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:SC(n),error:CC(t)},`auth refresh failed`),t}}function xC(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function SC(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:wC(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:wC(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function CC(e){return Gg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function wC(e){return e?e.slice(-8):null}async function TC(e,t){try{let n=Oo.parse(e);switch(n.method){case`auth.refresh`:{let e=await bC({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 yC(n.params.deviceId??t.relayDeviceId,e.deviceId),ko.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return ko.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return ko.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return ko.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return ko.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return ko.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return ko.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return ko.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw kC(n.method,`NOT_FOUND`,404,`Project not found`);return ko.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 ko.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 ko.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return ko.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw kC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.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 kC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return ko.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=await t.sessionManager.getProjectSessionRawEvents(n.params.projectId,n.params.sessionId,n.params.limit===`all`?2**53-1:n.params.limit);return ko.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),ko.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 ko.parse({method:n.method,result:e})}case`devices.list`:return ko.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw kC(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return ko.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw kC(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw EC(e)}}function EC(e){if(Gg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return kC(`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 kC(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return kC(`BAD_REQUEST`,e.status,String(e),e.details);default:return kC(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=jo.safeParse(e);if(t.success)return t.data;let n=Ao.safeParse(e);if(n.success)return kC(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 kC(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?kC(`BAD_REQUEST`,400,r):AC(e)?kC(`UNAUTHORIZED`,401,r):jC(r)?kC(`BAD_REQUEST`,400,r):kC(`INTERNAL`,500,r)}function DC(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:OC(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Xs(e.identity,e.privateKeyPem,i)}}function OC(e){return e.replace(/\s+/gu,``).toUpperCase()}function kC(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 jo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function AC(e){return Gg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||o_(e)}function jC(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 MC(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function NC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await hC(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{FC({type:`worker.update.prepared`,payload:e})}});FC({type:`worker.ready`,payload:PC(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=IC(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: ${MC(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${MC(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);FC({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);FC({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){FC({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function PC(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function FC(e){process.send&&process.send(e)}function IC(e){if(!LC(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 LC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}RC(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function RC(e){let t=ne(e);switch(t.command){case`help`:UC();return;case`version`:console.log(P.version);return;case`init`:await BC(t);return;case`doctor`:await VC(t);return;case`start`:await zC(t);return;case`__worker`:await HC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function zC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await ql({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(nu(e,t.config))}Oc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function BC(e){let t=await ic({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 ac({configPath:t.configPath,ensureConfigFile:!1}),r=await Dc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(kc(r))}async function VC(e){let t=await ac({configPath:rc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(kc(n)),Oc(n)&&(process.exitCode=1)}async function HC(e){try{await NC(e)}catch(t){let n=await ac({configPath:e.configPath,ensureConfigFile:!0});throw Error(nu(t,n.config))}}function UC(){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=RC;
|