craby-gateway 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`fs`);y=c(y);let b=require(`path`);b=c(b);let x=require(`module`),S=require(`net`),C=require(`child_process`),w=require(`@anthropic-ai/claude-agent-sdk`);var T={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.9.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.71`,"@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 E=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function D(e){let t=e.match(E);return t?t[0]:null}function O(e){return typeof e==`string`?D(e):null}function k(e,t){let n=j(e),r=j(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 A(e,t){return k(e,t)>=0}function j(e){let t=e.match(E);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const M=T,ee=M.dependencies??{};function N(e){return ee[e]??``}const te={packageName:`craby-gateway`,cliName:`craby-gateway`,version:M.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:N(`@anthropic-ai/claude-agent-sdk`),minimumVersion:O(N(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function P(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=ne(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 ne(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})),I=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})),re=o((e=>{var t=F(),n=I();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(`fs`);y=c(y);let b=require(`path`);b=c(b);let x=require(`module`),S=require(`net`),C=require(`child_process`),w=require(`@anthropic-ai/claude-agent-sdk`);var T={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.9.2`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.71`,"@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 E=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function D(e){let t=e.match(E);return t?t[0]:null}function O(e){return typeof e==`string`?D(e):null}function k(e,t){let n=j(e),r=j(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 A(e,t){return k(e,t)>=0}function j(e){let t=e.match(E);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const M=T,ee=M.dependencies??{};function N(e){return ee[e]??``}const te={packageName:`craby-gateway`,cliName:`craby-gateway`,version:M.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:N(`@anthropic-ai/claude-agent-sdk`),minimumVersion:O(N(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function P(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=ne(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 ne(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})),I=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})),re=o((e=>{var t=F(),n=I();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})),L=o((e=>{var t=F(),n=I();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})),ie=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})),ae=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})),R=o((e=>{var t=ie(),n=F(),r=ae();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),oe=o((e=>{var t=L(),n=I(),r=F(),i=R(),a=ae(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),se=o((e=>{var t=F(),n=R(),r=ae();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ce=o((e=>{var t=oe(),n=F(),r=se();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??=c(e),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),le=o((e=>{var t=ce(),n=F(),r=R();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),ue=o((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
4
4
  `)?n(r,t):r.includes(`
5
5
  `)?`
@@ -458,7 +458,7 @@ const asInteger = serializer.asInteger.bind(serializer)
458
458
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
459
459
  var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),zh=o((e=>{var t=Rh().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Bh=o(((e,t)=>{var n=jh().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),Vh=o(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Bh(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),Hh=o(((e,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=jh().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),Uh=o(((e,t)=>{t.exports=E;var n;E.ReadableState=T,require(`events`).EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Oh(),a=require(`buffer`).Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=require(`util`),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=kh(),f=Ah(),p=Mh().getHighWaterMark,m=jh().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;Ph()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=Lh(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=zh().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Lh(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0)if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1);else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=zh().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?oe(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&oe(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?R(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&oe(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,te(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(te,e))}function te(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,ae(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(ne,e,t))}function ne(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=F(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&ce(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function F(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,ae(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=ce(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(re,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(I,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(I,this),t};function I(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function re(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,L(this,e)),e.paused=!1,this};function L(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ie,e,t))}function ie(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),ae(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function ae(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Vh()),b(this)}),Object.defineProperty(E.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=R,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function R(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function oe(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(se,t,e))}function se(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=Hh()),x(E,e,t)});function ce(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Wh=o(((e,t)=>{t.exports=l;var n=jh().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=Lh();Ph()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),Gh=o(((e,t)=>{t.exports=r;var n=Wh();Ph()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),Kh=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=jh().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Bh()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a(`streams`);var i,o=t.map(function(e,n){var a=n<t.length-1;return l(e,a,n>0,function(e){i||=e,e&&o.forEach(u),!a&&(o.forEach(u),r(i))})});return t.reduce(d)}t.exports=p})),qh=o(((e,t)=>{var n=require(`stream`);process.env.READABLE_STREAM===`disable`&&n?(t.exports=n.Readable,Object.assign(t.exports,n),t.exports.Stream=n):(e=t.exports=Uh(),e.Stream=n||e,e.Readable=e,e.Writable=Ih(),e.Duplex=Lh(),e.Transform=Wh(),e.PassThrough=Gh(),e.finished=Bh(),e.pipeline=Kh())})),Jh=o(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),Yh=o(((e,t)=>{var n=Jh();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),Xh=o(((e,t)=>{var n=Yh(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),Zh=o(((e,t)=>{t.exports=n;function n(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState==`number`?e.read():e.read(r(t)):null}function r(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}})),Qh=o(((e,t)=>{var n=qh(),r=Xh(),i=Ph(),a=Zh(),o=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),s=function(e,t){e._corked?e.once(`uncork`,t):t()},c=function(e,t){e._autoDestroy&&e.destroy(t)},l=function(e,t){return function(n){n?c(e,n.message===`premature close`?null:n):t&&!e._ended&&e.end()}},u=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t()},d=function(){},f=function(e){return new n.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},p=function(e,t,r){if(!(this instanceof p))return new p(e,t,r);n.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==!1,this._forwardDestroy=!r||r.destroy!==!1,this._forwardEnd=!r||r.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};i(p,n.Duplex),p.obj=function(e,t,n){return n||={},n.objectMode=!0,n.highWaterMark=16,new p(e,t,n)},p.prototype.cork=function(){++this._corked===1&&this.emit(`cork`)},p.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit(`uncork`)},p.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.end();return}var t=this,n=r(e,{writable:!0,readable:!1},l(this,this._forwardEnd)),i=function(){var e=t._ondrain;t._ondrain=null,e&&e()};this._unwrite&&process.nextTick(i),this._writable=e,this._writable.on(`drain`,i),this._unwrite=function(){t._writable.removeListener(`drain`,i),n()},this.uncork()},p.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.push(null),this.resume();return}var t=this,n=r(e,{writable:!1,readable:!0},l(this)),i=function(){t._forward()},a=function(){t.push(null)};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on(`readable`,i),this._readable2.on(`end`,a),this._unread=function(){t._readable2.removeListener(`readable`,i),t._readable2.removeListener(`end`,a),n()},this._forward()},p.prototype._read=function(){this._drained=!0,this._forward()},p.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var e;this._drained&&(e=a(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},p.prototype.destroy=function(e,t){if(t||=d,this.destroyed)return t(null);this.destroyed=!0;var n=this;process.nextTick(function(){n._destroy(e),t(null)})},p.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit(`error`,e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit(`close`)},p.prototype._write=function(e,t,n){if(!this.destroyed){if(this._corked)return s(this,this._write.bind(this,e,t,n));if(e===o)return this._finish(n);if(!this._writable)return n();this._writable.write(e)===!1?this._ondrain=n:this.destroyed||n()}},p.prototype._finish=function(e){var t=this;this.emit(`preend`),s(this,function(){u(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===!1&&(t._writableState.prefinished=!0),t.emit(`prefinish`),s(t,e)})})},p.prototype.end=function(e,t,r){return typeof e==`function`?this.end(null,null,e):typeof t==`function`?this.end(e,null,t):(this._ended=!0,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(o),n.Writable.prototype.end.call(this,r))},t.exports=p})),$h=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=ah(),o=Dh(),s=Qh(),c=Symbol(`ws-socket`),l=Symbol(`ws-head`),u=/HTTP\/1.1 (\d+)/u;function d(e,t,a){e.decorateRequest(`ws`,null);let d=x;if(t.errorHandler){if(typeof t.errorHandler!=`function`)return a(Error(`invalid errorHandler function`));d=t.errorHandler}let f=y;if(t?.preClose){if(typeof t.preClose!=`function`)return a(Error(`invalid preClose function`));f=t.preClose}if(t.options?.noServer)return a(Error(`fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly.`));let p=Object.assign({noServer:!0},t.options);p.path&&e.log.warn(`ws server path option shouldn't be provided, use a route instead`);let m=p.server||e.server;delete p.server;let h=new o.Server(p);e.decorate(`websocketServer`,h);async function g(e=`/`,t={},n={}){let a=new r,d=new r,f=new s(a,d),p=new s(d,a),h=new o(null,void 0,{isServer:!1}),g=Buffer.from([]),_,v,y=new Promise((e,t)=>{_=e,v=t});typeof n.onInit==`function`&&n.onInit(h),h.on(`open`,()=>{typeof n.onOpen==`function`&&n.onOpen(h),p.removeListener(`data`,b),_(h)});let b=e=>{if(e.toString().includes(`HTTP/1.1 101 Switching Protocols`))h._isServer=!1,h.setSocket(p,g,{maxPayload:0});else{p.removeListener(`data`,b);let t=Number(u.exec(e.toString())[1]);v(Error(`Unexpected server response: `+t))}};p.on(`data`,b);let x={...t,method:`GET`,headers:{...t.headers,connection:`upgrade`,upgrade:`websocket`,"sec-websocket-version":13,"sec-websocket-key":i(16).toString(`base64`)},httpVersion:`1.1`,url:e,[c]:f,[l]:g};return m.emit(`upgrade`,x,x[c],x[l]),y}e.decorate(`injectWS`,g);function _(t,r,i){t[c]=r,t[l]=i;let a=new n(t);try{a.assignSocket(r),e.routing(t,a)}catch(t){e.log.warn({err:t},`websocket upgrade failed`)}}m.on(`upgrade`,_);let v=(t,n)=>{h.handleUpgrade(t,t[c],t[l],r=>{h.emit(`connection`,r,t),r.on(`error`,t=>{e.log.error(t)}),n(r)})};e.addHook(`onRequest`,(e,t,n)=>{e.raw[c]?e.ws=!0:e.ws=!1,n()}),e.addHook(`onResponse`,(e,t,n)=>{e.ws&&e.raw[c].destroy(),n()}),e.addHook(`onRoute`,e=>{let t=!1,n=e.wsHandler,r=e.handler;if(e.websocket||e.wsHandler){if(e.method===`HEAD`)return;if(e.method!==`GET`)throw Error(`websocket handler can only be declared in GET method`);if(t=!0,e.websocket&&(e.schema||={},e.schema.hide=!0,n=e.handler,r=function(e,t){t.code(404).send()}),typeof n!=`function`)throw TypeError(`invalid wsHandler function`)}e.handler=function(e,i){if(e.raw[c])i.hijack(),v(e.raw,r=>{let a;try{a=t?n.call(this,r,e):b.call(this,r,e)}catch(t){return d.call(this,t,r,e,i)}a&&typeof a.catch==`function`&&a.catch(t=>d.call(this,t,r,e,i))});else return r.call(this,e,i)}}),e.addHook(`preClose`,f);function y(t){let n=this.websocketServer;if(n.clients)for(let e of n.clients)e.close();e.server.removeListener(`upgrade`,_),n.close(t),t()}function b(e,t){this.log.info({path:t.url},`closed incoming websocket connection for path with no websocket handler`),e.close()}function x(e,t,n){n.log.error(e),t.terminate()}a()}t.exports=a(d,{fastify:`5.x`,name:`@fastify/websocket`}),t.exports.default=d,t.exports.fastifyWebsocket=d}))(),1),eg=c(ph(),1),tg=c(nh(),1);let ng,rg;function ig(e){!ng||ng.length<e?(ng=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(ng),rg=0):rg+e>ng.length&&(l.webcrypto.getRandomValues(ng),rg=0),rg+=e}function ag(e=21){ig(e|=0);let t=``;for(let n=rg-e;n<rg;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[ng[n]&63];return t}var og=o(((e,t)=>{var n=Rh().Buffer,r=require(`stream`),i=require(`util`);function a(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if(typeof e.pipe==`function`)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||typeof e==`object`)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit(`end`,e),this.readable=!1,this.emit(`close`)}.bind(this)),this;throw TypeError(`Unexpected data type (`+typeof e+`)`)}i.inherits(a,r),a.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit(`data`,e)},a.prototype.end=function(e){e&&this.write(e),this.emit(`end`,e),this.emit(`close`),this.writable=!1,this.readable=!1},t.exports=a})),sg=o(((e,t)=>{function n(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:n(256),ES384:n(384),ES512:n(521)};function i(e){var t=r[e];if(t)return t;throw Error(`Unknown algorithm "`+e+`"`)}t.exports=i})),cg=o(((e,t)=>{var n=Rh().Buffer,r=sg(),i=128,a=0,o=32,s=16,c=2,l=s|o|a<<6,u=c|a<<6;function d(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function f(e){if(n.isBuffer(e))return e;if(typeof e==`string`)return n.from(e,`base64`);throw TypeError(`ECDSA signature must be a Base64 string or a Buffer`)}function p(e,t){e=f(e);var a=r(t),o=a+1,s=e.length,c=0;if(e[c++]!==l)throw Error(`Could not find expected "seq"`);var p=e[c++];if(p===(i|1)&&(p=e[c++]),s-c<p)throw Error(`"seq" specified length of "`+p+`", only "`+(s-c)+`" remaining`);if(e[c++]!==u)throw Error(`Could not find expected "int" for "r"`);var m=e[c++];if(s-c-2<m)throw Error(`"r" specified length of "`+m+`", only "`+(s-c-2)+`" available`);if(o<m)throw Error(`"r" specified length of "`+m+`", max of "`+o+`" is acceptable`);var h=c;if(c+=m,e[c++]!==u)throw Error(`Could not find expected "int" for "s"`);var g=e[c++];if(s-c!==g)throw Error(`"s" specified length of "`+g+`", expected "`+(s-c)+`"`);if(o<g)throw Error(`"s" specified length of "`+g+`", max of "`+o+`" is acceptable`);var _=c;if(c+=g,c!==s)throw Error(`Expected to consume entire buffer, but "`+(s-c)+`" bytes remain`);var v=a-m,y=a-g,b=n.allocUnsafe(v+m+y+g);for(c=0;c<v;++c)b[c]=0;e.copy(b,c,h+Math.max(-v,0),h+m),c=a;for(var x=c;c<x+y;++c)b[c]=0;return e.copy(b,c,_+Math.max(-y,0),_+g),b=b.toString(`base64`),b=d(b),b}function m(e,t,n){for(var r=0;t+r<n&&e[t+r]===0;)++r;return e[t+r]>=i&&--r,r}function h(e,t){e=f(e);var a=r(t),o=e.length;if(o!==a*2)throw TypeError(`"`+t+`" signatures must be "`+a*2+`" bytes, saw "`+o+`"`);var s=m(e,0,a),c=m(e,a,e.length),d=a-s,p=a-c,h=2+d+1+1+p,g=h<i,_=n.allocUnsafe((g?2:3)+h),v=0;return _[v++]=l,g?_[v++]=h:(_[v++]=i|1,_[v++]=h&255),_[v++]=u,_[v++]=d,s<0?(_[v++]=0,v+=e.copy(_,v,0,a)):v+=e.copy(_,v,s,a),_[v++]=u,_[v++]=p,c<0?(_[v++]=0,e.copy(_,v,a)):e.copy(_,v,a+c),_}t.exports={derToJose:p,joseToDer:h}})),lg=o(((e,t)=>{var n=require(`buffer`).Buffer,r=require(`buffer`).SlowBuffer;t.exports=i;function i(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}i.install=function(){n.prototype.equal=r.prototype.equal=function(e){return i(this,e)}};var a=n.prototype.equal,o=r.prototype.equal;i.restore=function(){n.prototype.equal=a,r.prototype.equal=o}})),ug=o(((e,t)=>{var n=Rh().Buffer,r=require(`crypto`),i=cg(),a=require(`util`),o=`"%s" is not a valid algorithm.
460
460
  Supported algorithms are:
461
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=lg(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),dg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),fg=o(((e,t)=>{var n=Rh().Buffer,r=og(),i=ug(),a=require(`stream`),o=dg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),pg=o(((e,t)=>{var n=Rh().Buffer,r=og(),i=ug(),a=require(`stream`),o=dg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),mg=o((e=>{var t=fg(),n=pg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),hg=o(((e,t)=>{var n=mg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),gg=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),_g=o(((e,t)=>{var n=gg(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),vg=o(((e,t)=>{var n=gg(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),yg=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),bg=o(((e,t)=>{var n=yg();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),xg=o(((e,t)=>{t.exports=um().satisfies(process.version,`>=15.7.0`)})),Sg=o(((e,t)=>{t.exports=um().satisfies(process.version,`>=16.9.0`)})),Cg=o(((e,t)=>{let n=xg(),r=Sg(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),wg=o(((e,t)=>{t.exports=um().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Tg=o(((e,t)=>{let n=gg(),r=_g(),i=vg(),a=hg(),o=bg(),s=Cg(),c=wg(),l=mg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Eg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:ue(e),n=n&&!r?se(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),ae(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return F(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&re(e.length)&&!I(e)}function F(e){return ie(e)&&ne(e)}function I(e){var t=L(e)?E.call(e):``;return t==s||t==c}function re(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function L(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ie(e){return!!e&&typeof e==`object`}function ae(e){return typeof e==`string`||!P(e)&&ie(e)&&E.call(e)==l}function R(e){return typeof e==`symbol`||ie(e)&&E.call(e)==u}function oe(e){return e?(e=ce(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function se(e){var t=oe(e),n=t%1;return t===t?n?t-n:t:0}function ce(e){if(typeof e==`number`)return e;if(R(e))return a;if(L(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=L(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function le(e){return ne(e)?A(e):j(e)}function ue(e){return e?S(e,le(e)):[]}t.exports=N})),Dg=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),Og=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),kg=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),Ag=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),jg=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Mg=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Ng=o(((e,t)=>{let n=bg(),r=wg(),i=Cg(),a=mg(),o=Eg(),s=Dg(),c=Og(),l=kg(),u=Ag(),d=jg(),f=Mg(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Pg=c(o(((e,t)=>{t.exports={decode:hg(),verify:Tg(),sign:Ng(),JsonWebTokenError:gg(),NotBeforeError:_g(),TokenExpiredError:vg()}}))(),1),Fg=c($u(),1),Ig=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Lg(e){return e instanceof Ig}function Rg(){return new Ig({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function zg(){return new Ig({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Bg(){return new Ig({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function Vg(e=`Device revoked`){return new Ig({code:`DEVICE_REVOKED`,status:401,message:e})}function Hg(){return new Ig({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function Ug(e){return new Ig({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function Wg(e,t){return new Ig({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function Gg(e){return new Ig({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function Kg(e){return new Ig({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function qg(e){return new Ig({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function Jg(){return new Ig({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function Yg(){return new Ig({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function Xg(e){return new Ig({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function Zg(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var Qg=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=$g(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw Rg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),zg();this.pairingCodes.delete(e);let i=`dev_${ag(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...o,gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Pg.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n||n.revoked)throw Bg();let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Vg();let i=new Date().toISOString();n.revoked=!0,n.revokedAt=i,this.refreshTokens.set(t.jti,n);let a=this.issueTokenPair(t.sub);return await this.persistState(),{...a,deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Pg.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw Vg(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw Vg(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw Jg();if(!t_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw Yg();if(n.identityStatus!==`active`)throw Xg(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}issueTokenPair(e){let t=Pg.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${ag(14)}`,r=Pg.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Pg.default.decode(r);this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0});let a=Pg.default.decode(t);return{accessToken:t,refreshToken:r,expiresInSeconds:a.exp-a.iat}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await r_(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await r_(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await r_(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:e_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return n_(this.pairingCodes,e),n_(this.devices,t),n_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function $g(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function e_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function t_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function n_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function r_(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var i_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function a_(){}a_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(o_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(o_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function o_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new a_;function s_(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function c_(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function l_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function u_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function d_(e,t){return l_(e,t,``)}function f_(e,t){return u_(e,t,``)}function p_(e,t){return t.slice(0,m_(e,t))}function m_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var h_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,g_=RegExp(`[${h_}]+|\\s+|[^${h_}]`,`ug`),__=new a_;__.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},__.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(g_)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},__.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},__.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&v_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&v_(n,i,r,null),e};function v_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=s_(i,o);e.value=u_(e.value,o,c),t.value=d_(t.value,c),n.value=d_(n.value,c)}if(r){var l=c_(a,s);r.value=l_(r.value,s,l),t.value=f_(t.value,l),n.value=f_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=s_(u,d);t.value=d_(t.value,p);var m=c_(d_(u,p),f);t.value=f_(t.value,m),r.value=l_(r.value,u,m),e.value=u_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=p_(g,h);t.value=f_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=p_(v,y);t.value=d_(t.value,b)}}var y_=new a_;y_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${h_}]+|[^\\S\\n\\r]+|[^${h_}]`,`ug`);return e.match(t)||[]};var b_=new a_;b_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
461
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=lg(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),dg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),fg=o(((e,t)=>{var n=Rh().Buffer,r=og(),i=ug(),a=require(`stream`),o=dg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),pg=o(((e,t)=>{var n=Rh().Buffer,r=og(),i=ug(),a=require(`stream`),o=dg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),mg=o((e=>{var t=fg(),n=pg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),hg=o(((e,t)=>{var n=mg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),gg=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),_g=o(((e,t)=>{var n=gg(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),vg=o(((e,t)=>{var n=gg(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),yg=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),bg=o(((e,t)=>{var n=yg();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),xg=o(((e,t)=>{t.exports=um().satisfies(process.version,`>=15.7.0`)})),Sg=o(((e,t)=>{t.exports=um().satisfies(process.version,`>=16.9.0`)})),Cg=o(((e,t)=>{let n=xg(),r=Sg(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),wg=o(((e,t)=>{t.exports=um().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Tg=o(((e,t)=>{let n=gg(),r=_g(),i=vg(),a=hg(),o=bg(),s=Cg(),c=wg(),l=mg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Eg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:ue(e),n=n&&!r?se(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),ae(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return F(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&re(e.length)&&!I(e)}function F(e){return ie(e)&&ne(e)}function I(e){var t=L(e)?E.call(e):``;return t==s||t==c}function re(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function L(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ie(e){return!!e&&typeof e==`object`}function ae(e){return typeof e==`string`||!P(e)&&ie(e)&&E.call(e)==l}function R(e){return typeof e==`symbol`||ie(e)&&E.call(e)==u}function oe(e){return e?(e=ce(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function se(e){var t=oe(e),n=t%1;return t===t?n?t-n:t:0}function ce(e){if(typeof e==`number`)return e;if(R(e))return a;if(L(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=L(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function le(e){return ne(e)?A(e):j(e)}function ue(e){return e?S(e,le(e)):[]}t.exports=N})),Dg=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),Og=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),kg=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),Ag=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),jg=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Mg=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Ng=o(((e,t)=>{let n=bg(),r=wg(),i=Cg(),a=mg(),o=Eg(),s=Dg(),c=Og(),l=kg(),u=Ag(),d=jg(),f=Mg(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Pg=c(o(((e,t)=>{t.exports={decode:hg(),verify:Tg(),sign:Ng(),JsonWebTokenError:gg(),NotBeforeError:_g(),TokenExpiredError:vg()}}))(),1),Fg=c($u(),1),Ig=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Lg(e){return e instanceof Ig}function Rg(){return new Ig({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function zg(){return new Ig({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Bg(){return new Ig({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function Vg(e=`Device revoked`){return new Ig({code:`DEVICE_REVOKED`,status:401,message:e})}function Hg(){return new Ig({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function Ug(e){return new Ig({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function Wg(e,t){return new Ig({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function Gg(e){return new Ig({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function Kg(e){return new Ig({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function qg(e){return new Ig({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function Jg(){return new Ig({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function Yg(){return new Ig({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function Xg(e){return new Ig({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function Zg(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var Qg=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=$g(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw Rg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),zg();this.pairingCodes.delete(e);let i=`dev_${ag(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...o,gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Pg.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n||n.revoked)throw Bg();let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Vg();let i=new Date().toISOString();n.revoked=!0,n.revokedAt=i,this.refreshTokens.set(t.jti,n);let a=this.issueTokenPair(t.sub);return await this.persistState(),{...a,deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Pg.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw Vg(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw Vg(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw Jg();if(!t_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw Yg();if(n.identityStatus!==`active`)throw Xg(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}inspectRefreshToken(e){let t=Pg.default.decode(e),n=t&&typeof t==`object`?t:null,r=typeof n?.jti==`string`?n.jti:void 0,i=typeof n?.sub==`string`?n.sub:void 0,a=r?this.refreshTokens.get(r):void 0,o=i||a?.deviceId?[...this.refreshTokens.values()].filter(e=>e.deviceId===(i??a?.deviceId)&&!e.revoked).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]:void 0;return{claimDeviceId:i,claimExpAt:typeof n?.exp==`number`?new Date(n.exp*1e3).toISOString():void 0,claimIssuedAt:typeof n?.iat==`number`?new Date(n.iat*1e3).toISOString():void 0,claimJti:r,claimType:typeof n?.type==`string`?n.type:void 0,latestActiveTokenCreatedAt:o?.createdAt,latestActiveTokenJti:o?.jti,tokenRecordCreatedAt:a?.createdAt,tokenRecordDeviceId:a?.deviceId,tokenRecordRevokedAt:a?.revokedAt,tokenRecordState:a?a.revoked?`revoked`:`active`:`missing`}}issueTokenPair(e){let t=Pg.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${ag(14)}`,r=Pg.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Pg.default.decode(r);this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0});let a=Pg.default.decode(t);return{accessToken:t,refreshToken:r,expiresInSeconds:a.exp-a.iat}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await r_(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await r_(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await r_(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:e_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return n_(this.pairingCodes,e),n_(this.devices,t),n_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function $g(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function e_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function t_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function n_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function r_(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var i_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function a_(){}a_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(o_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(o_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function o_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new a_;function s_(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function c_(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function l_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function u_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function d_(e,t){return l_(e,t,``)}function f_(e,t){return u_(e,t,``)}function p_(e,t){return t.slice(0,m_(e,t))}function m_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var h_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,g_=RegExp(`[${h_}]+|\\s+|[^${h_}]`,`ug`),__=new a_;__.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},__.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(g_)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},__.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},__.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&v_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&v_(n,i,r,null),e};function v_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=s_(i,o);e.value=u_(e.value,o,c),t.value=d_(t.value,c),n.value=d_(n.value,c)}if(r){var l=c_(a,s);r.value=l_(r.value,s,l),t.value=f_(t.value,l),n.value=f_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=s_(u,d);t.value=d_(t.value,p);var m=c_(d_(u,p),f);t.value=f_(t.value,m),r.value=l_(r.value,u,m),e.value=u_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=p_(g,h);t.value=f_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=p_(v,y);t.value=d_(t.value,b)}}var y_=new a_;y_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${h_}]+|[^\\S\\n\\r]+|[^${h_}]`,`ug`);return e.match(t)||[]};var b_=new a_;b_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
462
462
  `));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var i=0;i<r.length;i++){var a=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n},b_.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
463
463
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
464
464
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
@@ -478,10 +478,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
478
478
  `).length}function Fy(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function Iy(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 Ly(e){return zy(Uy(e.message))||(Gy(e.result)??``)}function Ry(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=Uy(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>Uy(e).type===`tool_result`)}function zy(e){let t=Gy(e.content);if(t)return t;let n=Gy(e.text)??Gy(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=Uy(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
479
479
  `)}function By(e){let t=Uy(Uy(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function Vy(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):Wy(e.subtype)||`Claude turn failed`}function Hy(e){let t=Uy(e);return{input_tokens:qy(t.input_tokens)??qy(t.inputTokens)??0,cached_input_tokens:qy(t.cached_input_tokens)??qy(t.cache_read_input_tokens)??qy(t.cacheReadInputTokens)??0,output_tokens:qy(t.output_tokens)??qy(t.outputTokens)??0}}function Uy(e){return typeof e==`object`&&e?e:{}}function Wy(e){if(typeof e==`string`&&e.trim())return e}function Gy(e){if(typeof e==`string`&&e.length>0)return e}function Ky(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function qy(e){if(typeof e==`number`&&Number.isFinite(e))return e}function Jy(e){let t=Wy(Uy(e.message).id);if(t)return t;let n=Wy(Uy(Uy(e.event).message).id);if(n)return n}function Yy(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var Xy=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=Zy(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 Zy(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var Qy=`@anthropic-ai/claude-agent-sdk`,$y=`claude-sonnet-4-6`,eb=1e4,tb=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(Qy),!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(Qy),n=await nb(rb(t,e),eb,`Claude native query session creation timed out`);if(n)return n;let r=await nb(ib(t,e),eb,`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 nb(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 rb(e,t){let n=ab(e);if(!n)return null;let r=t.model??$y;return new yy(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 ib(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 Xy(`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 Xy(`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 Xy(`claude`,t.sessionId,t.model,n)}return null}function ab(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 sb(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new ry(n,r):new tb(n,r)}const cb=p.default.join(`.claude`,`projects`);async function lb(e){return(await(0,w.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>gb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function ub(e,t){let n=mb(e,t?.homeDir),r;try{r=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),a=await Cb(t);if(!bb(a))continue;let o=await d.default.stat(t),s=yb(a,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});i.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}return i.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function db(e){let t=await wb(e.nativeSessionId,e.projectPath),n=await Tb(e.projectPath,e.nativeSessionId,e.homeDir);return _b({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}async function fb(e){let t=await wb(e.nativeSessionId,e.projectPath),n=await Tb(e.projectPath,e.nativeSessionId,e.homeDir);return vb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function pb(e,t,n){return p.default.join(mb(e,n),`${t}.jsonl`)}function mb(e,t){let n=t??f.default.homedir();return p.default.join(n,cb,hb(e))}function hb(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function gb(e){let t=xb(e.customTitle)??xb(e.summary)??xb(e.firstPrompt),n=Sb(e.lastModified);return{nativeSessionId:e.sessionId,cwd:xb(e.cwd),title:t,createdAt:n,updatedAt:n}}function _b(e){let t=[],n=yb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=0,s,c=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()},l=(n,r,a)=>{i+=1,t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`,ts:c(a),type:n,payload:{raw:r}})},u=(e,t)=>s||(o+=1,s={id:`claude_hist_turn_${o}`,terminal:!1,failed:!1},l(`turn.started`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s),d=(e,t)=>{if(!s||s.terminal){s=void 0;return}s.terminal=!0,l(`turn.completed`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s=void 0},f=(e,t,n)=>{let r=u(t,n);r.terminal||(r.terminal=!0,r.failed=!0,l(`turn.failed`,{turn_id:r.id,source_event_type:`claude.history`,source_line:n,error:{message:e}},t),s=void 0)};l(`thread.started`,{thread_id:e.nativeSessionId,source:`claude.history.getSessionMessages`},n.createdAt),n.title&&l(`thread.title.updated`,{title:n.title,source:`claude.history.first_user_message`,thread_id:e.nativeSessionId},n.createdAt);for(let t of e.rows){let e=t.type;if(!e||e===`queue-operation`)continue;if(e===`user`){let e=Mb(t.raw.message),n=kb(e),r=Ob(e);if(n){d(t.timestamp,t.line);let e=u(t.timestamp,t.line);l(`item.completed`,{item:{id:Nb(t.raw.uuid)??`claude_user_${t.line}`,type:`user_message`,text:n,turn_id:e.id,source_event_type:`claude.user`},source_line:t.line},t.timestamp)}for(let e=0;e<r.length;e+=1){let n=r[e],i=u(t.timestamp,t.line);l(`item.completed`,{item:{id:n.toolUseId??`claude_tool_result_${t.line}_${e+1}`,type:`tool_status`,status:n.isError?`failed`:`completed`,tool_name:n.toolName??`tool`,text:n.text,turn_id:i.id,source_event_type:`claude.tool_result`},source_line:t.line},t.timestamp)}continue}if(e!==`assistant`)continue;let n=Mb(t.raw.message),r=u(t.timestamp,t.line),i=Db(n);for(let e=0;e<i.length;e+=1){let n=i[e];l(`item.started`,{item:{id:n.id??`claude_tool_use_${t.line}_${e+1}`,type:`tool_status`,status:`running`,tool_name:n.name,text:n.summary,command:n.command,turn_id:r.id,source_event_type:`claude.tool_use`},source_line:t.line},t.timestamp)}let a=kb(n);a&&l(`item.completed`,{item:{id:Nb(n.id)??Nb(t.raw.uuid)??`claude_assistant_${t.line}`,type:`agent_message`,text:a,turn_id:r.id,source_event_type:`claude.assistant`},source_line:t.line},t.timestamp);let o=Nb(t.raw.error);o&&f(o,t.timestamp,t.line)}return d(n.updatedAt),t}function vb(e){let t=[],n=yb(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 yb(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=jb(kb(Mb(t.raw.message)))),!n&&t.type===`assistant`&&(n=Nb(Mb(t.raw.message).model));let o=i??Fb(t.createdAtFallbackMs)??0,s=a??Fb(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function bb(e){for(let t of e){if(t.type===`user`){let e=Mb(t.raw.message);if(kb(e)||Ob(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=Mb(t.raw.message);if(kb(e)||Db(e).length>0||Nb(t.raw.error))return!0}return!1}function xb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Sb(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Cb(e){let t=(await d.default.readFile(e,`utf8`)).split(`
480
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=Mb(i),o=Nb(a.timestamp),s=o?Pb(o):void 0;n.push({line:e+1,raw:a,type:Nb(a.type),timestamp:o,timestampMs:s})}return n}async function wb(e,t){let n=await(0,w.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>Eb(e,t+1))}async function Tb(e,t,n){let r=pb(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function Eb(e,t){let n=Mb(e),r=Mb(n.message),i=Nb(n.timestamp)??Nb(r.timestamp)??Nb(r.created_at)??Nb(r.createdAt);return{line:t,raw:{...n,message:r},type:Nb(n.type),timestamp:i,timestampMs:i?Pb(i):void 0}}function Db(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=Mb(e);if(Nb(t.type)!==`tool_use`)continue;let r=Mb(t.input),i=Nb(r.command),a=Nb(t.name)??`tool`,o=Nb(r.description);n.push({id:Nb(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function Ob(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=Mb(e);if(Nb(t.type)!==`tool_result`)continue;let r=Nb(t.content)??Nb(Mb(t.toolUseResult).stdout)??Nb(Mb(t.tool_use_result).stdout)??Nb(t.text);n.push({toolUseId:Nb(t.tool_use_id)??Nb(t.toolUseId),toolName:Nb(t.tool_name)??Nb(t.toolName),text:r,isError:t.is_error===!0})}return n}function kb(e){let t=Nb(e.content);if(t)return t;let n=Nb(e.text)??Nb(e.prompt);if(n)return 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=Mb(e),n=Nb(t.type);if(n&&n!==`text`)continue;let r=Nb(t.text)??Nb(t.content)??Ab(t);r&&i.push(r)}if(i.length!==0)return i.join(`
481
- `)}function Ab(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=Mb(e),r=Nb(t.text)??Nb(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function jb(e,t=60){if(!e)return;let n=e.replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function Mb(e){return typeof e==`object`&&e?e:{}}function Nb(e){return typeof e==`string`&&e.trim()||void 0}function Pb(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function Fb(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var Ib=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}=Rb(r,[t,n]);if(zb(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=Vb(await this.refreshProjects()),r=!0);let i=await Bb(n.projects,t);if(!i)throw qg(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Vb(await this.refreshProjects()),i=await Bb(n.projects,t),!i)throw qg(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 fy({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 Lb({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>Wb(e.cwd),mapSession:e=>{let t=Gb(e.createdAt),n=Gb(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:Wb(e.name)??Wb(e.preview),model:Wb(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 Lb({sessions:await lb(),canonicalPathCache:e,getRawPath:e=>Wb(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:Wb(e.title),model:Wb(e.model),createdAt:Wb(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 Lb(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 Hb(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Rb(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:Ub(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=Kb(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(Jb)})).sort((e,t)=>qb(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function zb(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Bb(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await ev(t);return e.find(e=>e.path===r)}function Vb(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function Hb(e,t){let n=t.get(e);return n||(n=ev(e),t.set(e,n)),n}function Ub(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function Wb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Gb(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Kb(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function qb(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 Jb(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Yb=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 Xb(this.getProjectPath(e),$b);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 Zb(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 Zb(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 Xb(this.indexPath,Qb)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Xb(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 Zb(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 Qb(e){return!ex(e)||e.v!==1||typeof e.generatedAt!=`string`||!Wa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ga.safeParse(e).success)}function $b(e){return!ex(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ga.safeParse(e.project).success||!Wa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ka.safeParse(e).success)}function ex(e){return typeof e==`object`&&!!e}const tx=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function nx(e){let t=vo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=is(ss(ox(i.export({format:`jwk`})))),o=Jo({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:yo.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 rx(e){let t=vo.parse(e.clientHello),n=yo.parse(e.gatewayHello),r=bo.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!so.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,as(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Yo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,as(r.signature)))throw Error(`transcript_invalid`)}function ix(e){let t=yo.parse(e.gatewayHello),n=bo.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:os(as(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return Qo({role:`gateway`,keySchedule:Zo({gatewayId:e.gatewayId,clientHello:vo.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 wo.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function ox(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var sx=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}close(){this.readyState=3}},cx=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(Go.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=>oa.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(Go.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...ux(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Go.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...ux(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:{...lx(`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=>To.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(Go.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=Oo.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:lx(`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=nx({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(Go.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{rx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,dx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=ix({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(Go.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,px(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new sx(t=>{try{let n=Go.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,fx(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:lx(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 rs({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,fx(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:ns({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 lx(e,t,n){return Oo.parse({code:e,status:t,message:n})}function ux(e,t){if(Lg(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=mx(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`||Zg(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function dx(e){return hx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function fx(e){return hx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function px(e){if(Lg(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=mx(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 mx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function hx(e,t){let n=mx(e);return t.find(e=>e===n)}var gx=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??yx}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;this.socket=void 0,this.stopHeartbeat(),e?.close(1e3,`Gateway shutting down`)}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=Go.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=_x(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=Go.parse(JSON.parse(vx(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 _x(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 vx(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 yx(e){return new nv(e)}function bx(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(Ko(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function xx(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(Sx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(bx({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 Po.parse(JSON.parse(r)).token}function Sx(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 Cx(e){return e?.trim()||void 0}function wx(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 Tx(e,t){return{modeDefault:`default`,model:Cx(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 Ex(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function Dx(e,t){let n=Ex(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 Ox(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function kx(e){let t=Dx(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Cx(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?Ax({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function Ax(e){let t=Dx(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?Ox(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=Dx(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=Cx(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??Cx(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:wx(r.execution)}}}const jx=[{id:`gpt-5.3-codex`,label:`GPT-5.3 Codex`,isDefault:!0,supportedReasoningEfforts:[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]}],Mx=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],Nx=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],Px=ji.options,Fx=[`read-only`,`workspace-write`,`danger-full-access`],Ix=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],Lx={codex:[{version:`codex-mobile-v1`,defaults:{model:`gpt-5.3-codex`,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{model:`gpt-5.3-codex`,reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]},Rx={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16},zx=30*1e3;function Bx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function Vx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function Hx(e,t){let n=t?.trim().toLowerCase();return n?(Lx[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function Ux(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:Nx}:{}},...e.map(e=>({...e,isDefault:!1}))]}function Wx(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function Gx(e){let t=new Set;for(let n of e){let e=Wx(n);e&&t.add(e)}return[...t]}function Kx(e){return e?.trim()||void 0}function qx(e){let t=Kx(e.runtimeModel);if(t)return t;let n=Kx(e.discoveredModel);if(n)return n;let r=Kx(e.existingModel),i=Kx(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function Jx(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,isDefault:e.isDefault,supportedReasoningEfforts:Gx(e.supportedReasoningEfforts)}));return t.length===0?jx:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function Yx(){try{return Jx(await my())}catch{return null}}async function Xx(){try{let e=await import(`@anthropic-ai/claude-agent-sdk`),t=e.query??e.default?.query;if(typeof t!=`function`)return null;let n=t,r=p.default.join(Js(),`claude-capability-probe`);await d.default.mkdir(r,{recursive:!0,mode:448});let i=n({prompt:`/clear`,options:{cwd:r,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let e=await i.supportedModels(),t=[];for(let n of e){let e=typeof n.value==`string`?n.value:``;if(!e)continue;let r=Array.isArray(n.supportedEffortLevels)&&n.supportedEffortLevels.length>0,i=Qx(n.description,n.displayName,e),a=n.supportsEffort===!1?[]:n.supportsEffort||r?Gx(n.supportedEffortLevels??[]):i===`haiku`?[]:void 0;t.push({id:e,label:n.displayName||e,description:typeof n.description==`string`&&n.description.trim()?n.description.trim():void 0,isDefault:e===`default`,supportedReasoningEfforts:a})}return t.length===0?null:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}finally{i.close()}}catch{return null}}function Zx(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 Qx(...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 $x=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:Bx(e.runtimeLifecycle?.idleTtlMs,Rx.idleTtlMs),sweepIntervalMs:Vx(e.runtimeLifecycle?.sweepIntervalMs,Rx.sweepIntervalMs),maxSessions:Bx(e.runtimeLifecycle?.maxSessions,Rx.maxSessions),maxCodexSessions:Bx(e.runtimeLifecycle?.maxCodexSessions,Rx.maxCodexSessions),maxClaudeSessions:Bx(e.runtimeLifecycle?.maxClaudeSessions,Rx.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 Dv(),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 Kg(e);return this.options.projectStore.remove(e)}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=Lx.claude.length>0?Lx.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 Ug(t);let r=Hx(e,n),i=r?.version??`default`,a=`${e}::${i}`,o=Date.now(),s=this.providerCapabilitiesCache.get(a);if(s){if(s.expiresAt>o)return s.value;this.providerCapabilitiesCache.delete(a)}let c=this.providerCapabilitiesInFlight.get(a);if(c)return c;let l=(async()=>{let t=sb(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1,a=n?`native`:`fallback`,o=e===`codex`&&n?await Yx()??jx:jx,s=e===`claude`&&n?await Xx()??Mx:Mx,c=Gx(s.flatMap(e=>e.supportedReasoningEfforts??[])),l=e===`codex`?{provider:e,source:a,models:o,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:Nx,approvalPolicies:Px,sandboxModes:Fx,permissionModes:[]},defaults:{model:o.find(e=>e.isDefault)?.id??o[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:a,models:s,support:{reasoningEffort:c.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:c,approvalPolicies:[],sandboxModes:[],permissionModes:Ix},defaults:{model:s.find(e=>e.isDefault)?.id??s[0]?.id,reasoningEffort:Zx(s),permissionMode:`default`}};if(!r)return{capabilities:l,resolvedAgentVersion:i};let u={...l.defaults,...r.defaults},d=u.model?.trim(),f=d?Ux(l.models,d,e):l.models;return{capabilities:{...l,models:f,defaults:u},resolvedAgentVersion:r.version}})();this.providerCapabilitiesInFlight.set(a,l);try{let e=await l;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return Tx(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Ug(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 getProjectSessionEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Ug(e);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Wg(e,t);let s=await this.options.historyStore.getSessionEvents(t,Math.max(n,300));if(o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0)return s.slice(-Math.max(1,n));if(o.provider===`claude`){let t=fS(o);if(!t)return s.slice(-Math.max(1,n));try{let r=await db({projectPath:o.projectPath,nativeSessionId:t,provider:o.provider,sessionId:o.id,projectId:e});return o.source===`native_discovered`?nS(r,s.filter(e=>!tS.has(e.type)),n):iS(s,r,tS,n)}catch{return s.slice(-Math.max(1,n))}}if(o.provider!==`codex`)return s.slice(-Math.max(1,n));let c=uS([o.nativeSessionId,o.id]);for(let t of c)try{return iS(s,pS({thread:await py(t,!0),provider:o.provider,sessionId:o.id,projectId:e}),eS,n)}catch{}return s.slice(-Math.max(1,n))}async getProjectSessionRawEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Ug(e);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Wg(e,t);let s=await this.options.historyStore.getSessionRawEvents(o.id,Math.max(n,300));if(o.source===`native_discovered`&&!a)return s.slice(-Math.max(1,n));let c=await this.maybeSyncExternalRawHistoryForRead(o,e,s,{forceSyncExternal:a});return o.source!==`native_discovered`&&!a&&c.rawEvents===s?s.slice(-Math.max(1,n)):c.rawEvents.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300,r){let i=await this.resolveProjectSessionForRawRead(e,t,r);return this.options.historyStore.getSessionRawEventsCompacted(i.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3,i){let a=await this.resolveProjectSessionForRawRead(e,t,i);return this.options.historyStore.getSessionRawEventsSinceSeq(a.id,n,r)}async getProjectSessionRawSeqRange(e,t,n){let r=await this.resolveProjectSessionForRawRead(e,t,n);return this.options.historyStore.getSessionRawSeqRange(r.id)}async resolveProjectSessionForRawRead(e,t,n){let r=await this.options.projectStore.getById(e);if(!r)throw Ug(e);let i=n?.syncExternal===!0,a=this.options.historyStore.getProjectSession(e,t);if(!a&&i&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)):a?.provider===`codex`&&i?(await this.syncCodexSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a):a?.provider===`claude`&&i&&(await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a),!a)throw Wg(e,t);let o=await this.options.historyStore.getSessionRawEvents(a.id,2**53-1);return(await this.maybeSyncExternalRawHistoryForRead(a,e,o,{forceSyncExternal:i})).session}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${ag(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=sb(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?Dx(e.provider,e.sessionTurnConfig):kx({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=Ax({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 Gg(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=Ax({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=vS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=Dx(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:bS(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 Gg(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_${ag(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=sb(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=Dx(t.provider,t.sessionTurnConfig),o=Ax({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=xS(n.createdAt),s=xS(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:qx({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??vS(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 ub(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??t?.title??n.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 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 Ug(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await SS(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Ug(e);return await SS(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=yS(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=yS(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_${ag(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_${ag(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=fS(e);if(!r)return n;try{let i=await fb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,i)}catch(t){return e.source===`native_discovered`&&dS(t)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),n}}if(e.provider!==`codex`)return n;let r=uS([e.nativeSessionId,e.id]);for(let i of r)try{let r=await py(i,!0),a=e.source===`gateway`&&n.length>0?hS({thread:r,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):mS({thread:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,a)}catch{}return n}async finalizeExternalRawHistorySync(e,t,n){let r=rS(t,n),i=await this.maybePersistSyncedExternalRawEvents(e,r,!0);return await this.markExternalHistoryHydrated(e.id,e.updatedAt),i}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}shouldAutoSyncGatewayCodexRawHistory(e,t){if(e.provider!==`codex`||e.providerMode!==`native`||e.source!==`gateway`||e.status===`running`)return!1;let n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;let r=e.lastHydratedExternalUpdatedAt?Date.parse(e.lastHydratedExternalUpdatedAt):NaN;if(Number.isFinite(r))return n>r+zx;let i=t[t.length-1]?.ts,a=i?Date.parse(i):NaN;return Number.isFinite(a)?n>a+zx:!1}async maybeSyncExternalRawHistoryForRead(e,t,n,r){if(!(r?.forceSyncExternal===!0||this.shouldAutoSyncGatewayCodexRawHistory(e,n)))return{session:e,rawEvents:n};let i=await this.options.historyStore.getSessionRawEvents(e.id,2**53-1),a=await this.syncExternalRawHistory(e,t,i);return{session:this.options.historyStore.getProjectSession(t,e.id)??e,rawEvents:a}}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw Gg(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=_S(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 eS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]),tS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]);function nS(e,t,n){let r=new Map;for(let t of e)r.set(t.eventId,t);for(let e of t)r.set(e.eventId,e);return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,n))}function rS(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[...n.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function iS(e,t,n,r){let i=new Map,a=new Map;for(let t of e)if(i.set(t.eventId,t),n.has(t.type)){let e=aS(t);a.set(e,(a.get(e)??0)+1)}for(let e of t){if(!n.has(e.type))continue;let t=aS(e),r=a.get(t)??0;if(r>0){r===1?a.delete(t):a.set(t,r-1);continue}i.set(e.eventId,e)}return[...i.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,r))}function aS(e){let t=oS(e.payload.raw),n=oS(t.item),r=oS(t.turn),i=sS(t.turn_id)??sS(t.turnId)??sS(r.id)??``,a=sS(r.status)??sS(t.status)??``,o=sS(t.thread_id)??sS(t.threadId)??``,s=sS(n.type)??``,c=sS(n.phase)??``,l=sS(n.status)??``,u=sS(n.command)??``,d=lS(n),f=cS(t.message)??``,p=cS(t.title)??``;return e.type.startsWith(`item.`)?[e.type,s,c,l,u,d||f].join(`|`):e.type.startsWith(`turn.`)?[e.type,i,a].join(`|`):e.type===`thread.title.updated`?[e.type,p].join(`|`):[e.type,o,i,s,p||f].join(`|`)}function oS(e){return typeof e==`object`&&e?e:{}}function sS(e){return typeof e==`string`&&e.trim()||void 0}function cS(e){if(typeof e==`string`)return e.length>0?e:void 0}function lS(e){let t=cS(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=cS(oS(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
481
+ `)}function Ab(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=Mb(e),r=Nb(t.text)??Nb(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function jb(e,t=60){if(!e)return;let n=e.replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function Mb(e){return typeof e==`object`&&e?e:{}}function Nb(e){return typeof e==`string`&&e.trim()||void 0}function Pb(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function Fb(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var Ib=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}=Rb(r,[t,n]);if(zb(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=Vb(await this.refreshProjects()),r=!0);let i=await Bb(n.projects,t);if(!i)throw qg(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=Vb(await this.refreshProjects()),i=await Bb(n.projects,t),!i)throw qg(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 fy({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 Lb({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>Wb(e.cwd),mapSession:e=>{let t=Gb(e.createdAt),n=Gb(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:Wb(e.name)??Wb(e.preview),model:Wb(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 Lb({sessions:await lb(),canonicalPathCache:e,getRawPath:e=>Wb(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:Wb(e.title),model:Wb(e.model),createdAt:Wb(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 Lb(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 Hb(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function Rb(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:Ub(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=Kb(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(Jb)})).sort((e,t)=>qb(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function zb(e){return Object.values(e).some(e=>e?.status===`failed`)}async function Bb(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await ev(t);return e.find(e=>e.path===r)}function Vb(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function Hb(e,t){let n=t.get(e);return n||(n=ev(e),t.set(e,n)),n}function Ub(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function Wb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Gb(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Kb(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function qb(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 Jb(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Yb=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 Xb(this.getProjectPath(e),$b);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 Zb(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 Zb(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 Xb(this.indexPath,Qb)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Xb(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 Zb(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 Qb(e){return!ex(e)||e.v!==1||typeof e.generatedAt!=`string`||!Wa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ga.safeParse(e).success)}function $b(e){return!ex(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ga.safeParse(e.project).success||!Wa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ka.safeParse(e).success)}function ex(e){return typeof e==`object`&&!!e}const tx=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function nx(e){let t=vo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=is(ss(ox(i.export({format:`jwk`})))),o=Jo({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:yo.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 rx(e){let t=vo.parse(e.clientHello),n=yo.parse(e.gatewayHello),r=bo.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!so.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,as(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Yo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,as(r.signature)))throw Error(`transcript_invalid`)}function ix(e){let t=yo.parse(e.gatewayHello),n=bo.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:os(as(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return Qo({role:`gateway`,keySchedule:Zo({gatewayId:e.gatewayId,clientHello:vo.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 wo.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function ox(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var sx=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}close(){this.readyState=3}},cx=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(Go.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=>oa.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(Go.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...ux(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Go.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...ux(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:{...lx(`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=>To.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(Go.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=Oo.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:lx(`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=nx({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(Go.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{rx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,dx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=ix({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(Go.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,px(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new sx(t=>{try{let n=Go.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,fx(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:lx(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 rs({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,fx(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:ns({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 lx(e,t,n){return Oo.parse({code:e,status:t,message:n})}function ux(e,t){if(Lg(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=mx(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`||Zg(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function dx(e){return hx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function fx(e){return hx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function px(e){if(Lg(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=mx(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 mx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function hx(e,t){let n=mx(e);return t.find(e=>e===n)}var gx=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??yx}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;this.socket=void 0,this.stopHeartbeat(),e?.close(1e3,`Gateway shutting down`)}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=Go.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=_x(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=Go.parse(JSON.parse(vx(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 _x(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 vx(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 yx(e){return new nv(e)}function bx(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(Ko(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function xx(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(Sx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(bx({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 Po.parse(JSON.parse(r)).token}function Sx(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 Cx(e){return e?.trim()||void 0}function wx(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 Tx(e,t){return{modeDefault:`default`,model:Cx(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 Ex(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function Dx(e,t){let n=Ex(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 Ox(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function kx(e){let t=Dx(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Cx(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?Ax({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function Ax(e){let t=Dx(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?Ox(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=Dx(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=Cx(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??Cx(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:wx(r.execution)}}}const jx=[],Mx=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],Nx=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],Px=ji.options,Fx=[`read-only`,`workspace-write`,`danger-full-access`],Ix=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],Lx={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`}}]},Rx={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16},zx=30*1e3;function Bx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function Vx(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function Hx(e,t){let n=t?.trim().toLowerCase();return n?(Lx[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function Ux(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:Nx}:{}},...e.map(e=>({...e,isDefault:!1}))]}function Wx(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function Gx(e){let t=new Set;for(let n of e){let e=Wx(n);e&&t.add(e)}return[...t]}function Kx(e){return e?.trim()||void 0}function qx(e){let t=Kx(e.runtimeModel);if(t)return t;let n=Kx(e.discoveredModel);if(n)return n;let r=Kx(e.existingModel),i=Kx(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function Jx(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:Gx(e.supportedReasoningEfforts)}));return t.length===0?jx:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function Yx(){try{return Jx(await my())}catch{return null}}async function Xx(){try{let e=await import(`@anthropic-ai/claude-agent-sdk`),t=e.query??e.default?.query;if(typeof t!=`function`)return null;let n=t,r=p.default.join(Js(),`claude-capability-probe`);await d.default.mkdir(r,{recursive:!0,mode:448});let i=n({prompt:`/clear`,options:{cwd:r,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let e=await i.supportedModels(),t=[];for(let n of e){let e=typeof n.value==`string`?n.value:``;if(!e)continue;let r=Array.isArray(n.supportedEffortLevels)&&n.supportedEffortLevels.length>0,i=Qx(n.description,n.displayName,e),a=n.supportsEffort===!1?[]:n.supportsEffort||r?Gx(n.supportedEffortLevels??[]):i===`haiku`?[]:void 0;t.push({id:e,label:n.displayName||e,description:typeof n.description==`string`&&n.description.trim()?n.description.trim():void 0,isDefault:e===`default`,supportedReasoningEfforts:a})}return t.length===0?null:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}finally{i.close()}}catch{return null}}function Zx(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 Qx(...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 $x=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:Bx(e.runtimeLifecycle?.idleTtlMs,Rx.idleTtlMs),sweepIntervalMs:Vx(e.runtimeLifecycle?.sweepIntervalMs,Rx.sweepIntervalMs),maxSessions:Bx(e.runtimeLifecycle?.maxSessions,Rx.maxSessions),maxCodexSessions:Bx(e.runtimeLifecycle?.maxCodexSessions,Rx.maxCodexSessions),maxClaudeSessions:Bx(e.runtimeLifecycle?.maxClaudeSessions,Rx.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 Dv(),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 Kg(e);return this.options.projectStore.remove(e)}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=Lx.claude.length>0?Lx.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 Ug(t);let r=Hx(e,n),i=r?.version??`default`,a=`${e}::${i}`,o=Date.now(),s=this.providerCapabilitiesCache.get(a);if(s){if(s.expiresAt>o)return s.value;this.providerCapabilitiesCache.delete(a)}let c=this.providerCapabilitiesInFlight.get(a);if(c)return c;let l=(async()=>{let t=sb(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1,a=n?`native`:`fallback`,o=e===`codex`&&n?await Yx()??jx:jx,s=e===`claude`&&n?await Xx()??Mx:Mx,c=Gx(s.flatMap(e=>e.supportedReasoningEfforts??[])),l=e===`codex`?{provider:e,source:a,models:o,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:Nx,approvalPolicies:Px,sandboxModes:Fx,permissionModes:[]},defaults:{model:o.find(e=>e.isDefault)?.id??o[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:a,models:s,support:{reasoningEffort:c.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:c,approvalPolicies:[],sandboxModes:[],permissionModes:Ix},defaults:{model:s.find(e=>e.isDefault)?.id??s[0]?.id,reasoningEffort:Zx(s),permissionMode:`default`}};if(!r)return{capabilities:l,resolvedAgentVersion:i};let u={...l.defaults,...r.defaults},d=u.model?.trim(),f=a===`native`?l.models:d?Ux(l.models,d,e):l.models;return{capabilities:{...l,models:f,defaults:u},resolvedAgentVersion:r.version}})();this.providerCapabilitiesInFlight.set(a,l);try{let e=await l;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return Tx(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Ug(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 getProjectSessionEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Ug(e);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Wg(e,t);let s=await this.options.historyStore.getSessionEvents(t,Math.max(n,300));if(o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0)return s.slice(-Math.max(1,n));if(o.provider===`claude`){let t=fS(o);if(!t)return s.slice(-Math.max(1,n));try{let r=await db({projectPath:o.projectPath,nativeSessionId:t,provider:o.provider,sessionId:o.id,projectId:e});return o.source===`native_discovered`?nS(r,s.filter(e=>!tS.has(e.type)),n):iS(s,r,tS,n)}catch{return s.slice(-Math.max(1,n))}}if(o.provider!==`codex`)return s.slice(-Math.max(1,n));let c=uS([o.nativeSessionId,o.id]);for(let t of c)try{return iS(s,pS({thread:await py(t,!0),provider:o.provider,sessionId:o.id,projectId:e}),eS,n)}catch{}return s.slice(-Math.max(1,n))}async getProjectSessionRawEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Ug(e);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Wg(e,t);let s=await this.options.historyStore.getSessionRawEvents(o.id,Math.max(n,300));if(o.source===`native_discovered`&&!a)return s.slice(-Math.max(1,n));let c=await this.maybeSyncExternalRawHistoryForRead(o,e,s,{forceSyncExternal:a});return o.source!==`native_discovered`&&!a&&c.rawEvents===s?s.slice(-Math.max(1,n)):c.rawEvents.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300,r){let i=await this.resolveProjectSessionForRawRead(e,t,r);return this.options.historyStore.getSessionRawEventsCompacted(i.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3,i){let a=await this.resolveProjectSessionForRawRead(e,t,i);return this.options.historyStore.getSessionRawEventsSinceSeq(a.id,n,r)}async getProjectSessionRawSeqRange(e,t,n){let r=await this.resolveProjectSessionForRawRead(e,t,n);return this.options.historyStore.getSessionRawSeqRange(r.id)}async resolveProjectSessionForRawRead(e,t,n){let r=await this.options.projectStore.getById(e);if(!r)throw Ug(e);let i=n?.syncExternal===!0,a=this.options.historyStore.getProjectSession(e,t);if(!a&&i&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)):a?.provider===`codex`&&i?(await this.syncCodexSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a):a?.provider===`claude`&&i&&(await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a),!a)throw Wg(e,t);let o=await this.options.historyStore.getSessionRawEvents(a.id,2**53-1);return(await this.maybeSyncExternalRawHistoryForRead(a,e,o,{forceSyncExternal:i})).session}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${ag(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=sb(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?Dx(e.provider,e.sessionTurnConfig):kx({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=Ax({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 Gg(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=Ax({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=vS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=Dx(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:bS(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 Gg(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_${ag(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=sb(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=Dx(t.provider,t.sessionTurnConfig),o=Ax({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=xS(n.createdAt),s=xS(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:qx({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??vS(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 ub(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??t?.title??n.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 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 Ug(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await SS(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Ug(e);return await SS(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=yS(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=yS(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_${ag(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_${ag(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=fS(e);if(!r)return n;try{let i=await fb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,i)}catch(t){return e.source===`native_discovered`&&dS(t)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),n}}if(e.provider!==`codex`)return n;let r=uS([e.nativeSessionId,e.id]);for(let i of r)try{let r=await py(i,!0),a=e.source===`gateway`&&n.length>0?hS({thread:r,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):mS({thread:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,a)}catch{}return n}async finalizeExternalRawHistorySync(e,t,n){let r=rS(t,n),i=await this.maybePersistSyncedExternalRawEvents(e,r,!0);return await this.markExternalHistoryHydrated(e.id,e.updatedAt),i}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}shouldAutoSyncGatewayCodexRawHistory(e,t){if(e.provider!==`codex`||e.providerMode!==`native`||e.source!==`gateway`||e.status===`running`)return!1;let n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;let r=e.lastHydratedExternalUpdatedAt?Date.parse(e.lastHydratedExternalUpdatedAt):NaN;if(Number.isFinite(r))return n>r+zx;let i=t[t.length-1]?.ts,a=i?Date.parse(i):NaN;return Number.isFinite(a)?n>a+zx:!1}async maybeSyncExternalRawHistoryForRead(e,t,n,r){if(!(r?.forceSyncExternal===!0||this.shouldAutoSyncGatewayCodexRawHistory(e,n)))return{session:e,rawEvents:n};let i=await this.options.historyStore.getSessionRawEvents(e.id,2**53-1),a=await this.syncExternalRawHistory(e,t,i);return{session:this.options.historyStore.getProjectSession(t,e.id)??e,rawEvents:a}}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw Gg(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=_S(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 eS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]),tS=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]);function nS(e,t,n){let r=new Map;for(let t of e)r.set(t.eventId,t);for(let e of t)r.set(e.eventId,e);return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,n))}function rS(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[...n.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function iS(e,t,n,r){let i=new Map,a=new Map;for(let t of e)if(i.set(t.eventId,t),n.has(t.type)){let e=aS(t);a.set(e,(a.get(e)??0)+1)}for(let e of t){if(!n.has(e.type))continue;let t=aS(e),r=a.get(t)??0;if(r>0){r===1?a.delete(t):a.set(t,r-1);continue}i.set(e.eventId,e)}return[...i.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,r))}function aS(e){let t=oS(e.payload.raw),n=oS(t.item),r=oS(t.turn),i=sS(t.turn_id)??sS(t.turnId)??sS(r.id)??``,a=sS(r.status)??sS(t.status)??``,o=sS(t.thread_id)??sS(t.threadId)??``,s=sS(n.type)??``,c=sS(n.phase)??``,l=sS(n.status)??``,u=sS(n.command)??``,d=lS(n),f=cS(t.message)??``,p=cS(t.title)??``;return e.type.startsWith(`item.`)?[e.type,s,c,l,u,d||f].join(`|`):e.type.startsWith(`turn.`)?[e.type,i,a].join(`|`):e.type===`thread.title.updated`?[e.type,p].join(`|`):[e.type,o,i,s,p||f].join(`|`)}function oS(e){return typeof e==`object`&&e?e:{}}function sS(e){return typeof e==`string`&&e.trim()||void 0}function cS(e){if(typeof e==`string`)return e.length>0?e:void 0}function lS(e){let t=cS(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=cS(oS(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
482
482
  `)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>cS(e)).filter(e=>!!e);if(e.length>0)return e.join(`
483
483
  `)}return``}function uS(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function dS(e){return String(e).includes(`returned no messages from getSessionMessages`)}function fS(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function pS(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,new Date(n+r).toISOString()),a=(n,a)=>{let o=`hist_${e.sessionId}_${r.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`;t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:o,ts:i(),type:n,payload:{raw:a}})};a(`thread.started`,{thread_id:e.thread.id,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,turns:[]}});let o=vS(e.thread.preview);o&&a(`thread.title.updated`,{title:o,source:`codex.thread_read_preview`,thread_id:e.thread.id});for(let t of e.thread.turns){let e={id:t.id,status:t.status,items:[],error:t.error};a(`turn.started`,{turn:e});for(let e of t.items)a(`item.completed`,{turn_id:t.id,item:e});if(t.status===`failed`||t.status===`interrupted`){a(`turn.failed`,{status:t.status,turn:e,error:t.error??{message:t.status===`interrupted`?`Turn interrupted`:`Turn failed`}});continue}t.status===`completed`&&a(`turn.completed`,{status:t.status,turn:e})}return t}function mS(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,new Date(n+r).toISOString()),a=n=>{let a=t.length+1,o=`raw_hist_codex_${e.sessionId}_${r.toString().padStart(6,`0`)}`;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:o,ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};a({scope:`thread`,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo}});for(let t of e.thread.turns){a({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}});for(let n of t.items)a({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n})}return t}function hS(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=oS(o.payload.raw);if(o.type===`turn.started`){let e=sS(s.turn_id)??sS(oS(s.turn).id);e&&t.add(e);continue}if(o.type===`item.completed`){let e=sS(oS(s.item).id);e&&n.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=sS(s.turn_id)??sS(oS(s.turn).id);if(!e)continue;t.add(e);let n=sS(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||sS(s.source)!==`codex.history.thread_read`)continue;let c=oS(s.message),l=sS(c.scope);if(l===`turn`){let e=oS(c.turn),n=sS(e.id);if(!n)continue;t.add(n);let i=sS(e.status);i&&gS(i)&&r.set(n,i);continue}if(l===`item`){let e=sS(oS(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){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=sS(e.id);t&&n.has(t)||u(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e})}if(gS(i.status)&&r.get(i.id)!==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 gS(e){return e===`completed`||e===`failed`||e===`interrupted`}function _S(e){let t=e.replace(/\s+/g,` `).trim();if(t)return t}function vS(e,t=60){let n=_S(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function yS(e){if(typeof e!=`string`)return;let t=_S(e);if(t)return t}function bS(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function xS(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function SS(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var CS=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 appendEvent(e){if(await this.ready,!this.sessions.has(e.sessionId))return;let t=p.default.join(this.eventsDir,`${e.sessionId}.jsonl`),n=`${JSON.stringify(e)}\n`;await this.enqueueWrite(async()=>{await d.default.appendFile(t,n,`utf8`)})}async appendRawEvent(e){await this.ready,this.sessions.has(e.sessionId)&&await this.enqueueRawSessionWrite(e.sessionId,async()=>{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=MS(await this.readSessionRawEventsLocked(e),n);let t=p.default.join(this.eventsDir,`${e}.raw.jsonl`),i=r.map(e=>ES(e)).join(`
484
484
  `);await d.default.writeFile(t,i?`${i}\n`:``,`utf8`),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.set(e,OS(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 i.filter(e=>e.rawSeq>t).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=(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 DS(t);let n=null;return await this.enqueueWrite(async()=>{n=DS(await this.readSessionRawEventsLocked(e))}),n}async getSessionEvents(e,t=300){await this.ready;let n=p.default.join(this.eventsDir,`${e}.jsonl`);try{return(await d.default.readFile(n,`utf8`)).split(`
485
485
  `).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>e!==null).slice(-Math.max(1,t))}catch(e){if(e.code===`ENOENT`)return[];throw e}}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=`${ES(e)}\n`;await d.default.appendFile(t,n,`utf8`)}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(n&&jS(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}AS(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return kS(t);let n=OS(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),kS(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
486
  `).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!wS(t)||t.kind!==`provider.raw`)continue;let n=TS(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=ua.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>ES(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 kS(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=OS(n);return this.compactedRawEventsCacheBySession.set(e,r),kS(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 wS(e){return typeof e==`object`&&!!e}function TS(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function ES(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 DS(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 OS(e){let t=Es(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ds(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function kS(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function AS(e,t){let n=Ds(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=Os(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 jS(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function MS(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[...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 NS=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${ag(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=JSON.stringify(e);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);!i||i.socket.readyState!==i.socket.OPEN||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)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 PS(e,t={}){await ql(e.gatewayLogPath);let n=IS(e,t),r=FS(e,n.instance);await r.register(eg.default,{origin:!0}),await r.register($h.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new Qg(e);await s.init();let c=new i_(e.auditLogPath),l=new NS,u=new U_,d=new Q_(e.projectStoreDir),f=new CS(e.sessionHistoryDir);await f.init();let m=new Yb(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Ib({store:m});await h.init();let g,_=null,v=await zs(e.authStoreDir),y=new $x({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 pl({packageName:te.packageName,currentVersion:te.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:Xc(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>Gc({gatewayId:e.gatewayId,machineName:Xc(),relayBaseUrl:e.relayEnabled?il({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:nl({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=ya.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=de(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}}),VS(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=Sa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await s.refreshAccessToken(n.data.refreshToken)}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Oa.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Na.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.get(`/api/discovery/projects`,async(e,t)=>{if(L(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(L(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return Lg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):GS(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=ie(r.status,t);if(!i)return;let a=ae(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=ae(r.syncExternal);try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i,{syncExternal:a})}}catch(e){return Lg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>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=oe(t.headers.authorization)??se(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(sa(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 cx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=de(e.deviceName);return VS(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await s.refreshAccessToken(t.refreshToken);return RS(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>zS(e,{authService:s,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 Wg(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_${ag(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_${ag(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=P(e);return t===void 0?ne(e,a):I(F(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=P(t);return n===void 0?ne(t,a):I(F(n))}return typeof e==`object`?I(F(e)):String(e)},P=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,F=e=>{if(Array.isArray(e))return e.map(e=>F(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]=F(r)}return n}return e},I=e=>{let t=re(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},re=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=oe(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}},ie=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ae=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},R=(e,t)=>{let n=e.params,r=e.query,i=ki.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)},oe=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},se=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},ce=e.httpsEnabled?e.httpsPort:e.port,le=e.httpsEnabled?`https`:`http`,ue=Xc(),de=e=>e?.trim()||ue||`Gateway`;await r.listen({host:e.host,port:ce});let z=r.server.address(),fe=typeof z==`object`&&z?z.port:ce;if(r.log.info({host:e.host,port:fe,protocol:le,machineName:ue},LS(le,e.host,fe)),e.relayEnabled&&(_=new gx({gatewayId:e.gatewayId,machineName:ue,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>xx({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:nl({protocol:le,host:e.host,port:fe}),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:le,listenPort:fe,machineName:ue,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),startupPairingCode:g}}function FS(e,t){let n=t;if(!e.httpsEnabled)return(0,tg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,tg.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 IS(e,t){let n=process.env.NODE_ENV!==`production`,r=Fg.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Fg.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Fg.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function LS(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function RS(e,t){if(e&&e!==t)throw Hg()}async function zS(e,t){try{let n=To.parse(e);switch(n.method){case`auth.refresh`:{let e=await t.authService.refreshAccessToken(n.params.refreshToken);return RS(n.params.deviceId??t.relayDeviceId,e.deviceId),Eo.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Eo.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Eo.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Eo.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Eo.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Eo.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Eo.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw US(n.method,`NOT_FOUND`,404,`Project not found`);return Eo.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 Eo.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 Eo.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Eo.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw US(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Eo.parse({method:n.method,result:{session:e}})}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,{syncExternal:n.params.syncExternal});return Eo.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0);return Eo.parse({method:n.method,result:{capabilities:e}})}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Eo.parse({method:n.method,result:e})}case`devices.list`:return Eo.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw US(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Eo.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw US(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw BS(e)}}function BS(e){if(Lg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return US(`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 US(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:return US(`BAD_REQUEST`,e.status,String(e),e.details);default:return US(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Oo.safeParse(e);if(t.success)return t.data;let n=Do.safeParse(e);if(n.success)return US(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 US(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?US(`BAD_REQUEST`,400,r):WS(e)?US(`UNAUTHORIZED`,401,r):GS(r)?US(`BAD_REQUEST`,400,r):US(`INTERNAL`,500,r)}function VS(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:HS(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Hs(e.identity,e.privateKeyPem,i)}}function HS(e){return e.replace(/\s+/gu,``).toUpperCase()}function US(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 Oo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function WS(e){return Lg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||Zg(e)}function GS(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:`)}async function KS(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await PS(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{JS({type:`worker.update.prepared`,payload:e})}});JS({type:`worker.ready`,payload:qS(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=YS(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: ${String(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${String(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);JS({type:`worker.response`,id:e.id,ok:!0,result:t});return}}}catch(t){JS({type:`worker.response`,id:e.id,ok:!1,error:String(t)})}}await new Promise(()=>{})}function qS(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function JS(e){process.send&&process.send(e)}function YS(e){if(!XS(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.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:`gateway.update.apply`,requestedBy:e.requestedBy};default:return null}}function XS(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}ZS(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function ZS(e){let t=P(e);switch(t.command){case`help`:nC();return;case`version`:console.log(te.version);return;case`init`:await $S(t);return;case`doctor`:await eC(t);return;case`start`:await QS(t);return;case`__worker`:await tC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function QS(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await zl({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(Jl(e,t.config))}bc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function $S(e){let t=await Xs({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 Zs({configPath:t.configPath,ensureConfigFile:!1}),r=await yc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(xc(r))}async function eC(e){let t=await Zs({configPath:Ys(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(xc(n)),bc(n)&&(process.exitCode=1)}async function tC(e){try{await KS(e)}catch(t){let n=await Zs({configPath:e.configPath,ensureConfigFile:!0});throw Error(Jl(t,n.config))}}function nC(){console.log(`${te.cliName} ${te.version}`),console.log(``),console.log(`Usage:`),console.log(` ${te.cliName} [start] [--config <path>] [--log]`),console.log(` ${te.cliName} init [--config <path>] [--force]`),console.log(` ${te.cliName} doctor [--config <path>]`),console.log(` ${te.cliName} --version`)}exports.runCli=ZS;
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 kS(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=OS(n);return this.compactedRawEventsCacheBySession.set(e,r),kS(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 wS(e){return typeof e==`object`&&!!e}function TS(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function ES(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 DS(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 OS(e){let t=Es(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Ds(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function kS(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function AS(e,t){let n=Ds(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=Os(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 jS(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function MS(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[...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 NS=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${ag(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=JSON.stringify(e);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);!i||i.socket.readyState!==i.socket.OPEN||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)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 PS(e,t={}){await ql(e.gatewayLogPath);let n=IS(e,t),r=FS(e,n.instance);await r.register(eg.default,{origin:!0}),await r.register($h.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new Qg(e);await s.init();let c=new i_(e.auditLogPath),l=new NS,u=new U_,d=new Q_(e.projectStoreDir),f=new CS(e.sessionHistoryDir);await f.init();let m=new Yb(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new Ib({store:m});await h.init();let g,_=null,v=await zs(e.authStoreDir),y=new $x({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 pl({packageName:te.packageName,currentVersion:te.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:Xc(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>Gc({gatewayId:e.gatewayId,machineName:Xc(),relayBaseUrl:e.relayEnabled?il({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:nl({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=ya.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=de(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}}),KS(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=Sa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await zS({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Oa.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Na.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.get(`/api/discovery/projects`,async(e,t)=>{if(L(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(L(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return Lg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):XS(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=ie(r.status,t);if(!i)return;let a=ae(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Lg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=ae(r.syncExternal);try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i,{syncExternal:a})}}catch(e){return Lg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>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=oe(t.headers.authorization)??se(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(sa(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 cx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=de(e.deviceName);return KS(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await zS({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return RS(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>WS(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 Wg(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_${ag(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_${ag(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=P(e);return t===void 0?ne(e,a):I(F(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=P(t);return n===void 0?ne(t,a):I(F(n))}return typeof e==`object`?I(F(e)):String(e)},P=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,F=e=>{if(Array.isArray(e))return e.map(e=>F(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]=F(r)}return n}return e},I=e=>{let t=re(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},re=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=oe(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}},ie=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ae=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},R=(e,t)=>{let n=e.params,r=e.query,i=ki.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)},oe=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},se=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},ce=e.httpsEnabled?e.httpsPort:e.port,le=e.httpsEnabled?`https`:`http`,ue=Xc(),de=e=>e?.trim()||ue||`Gateway`;await r.listen({host:e.host,port:ce});let z=r.server.address(),fe=typeof z==`object`&&z?z.port:ce;if(r.log.info({host:e.host,port:fe,protocol:le,machineName:ue},LS(le,e.host,fe)),e.relayEnabled&&(_=new gx({gatewayId:e.gatewayId,machineName:ue,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>xx({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:nl({protocol:le,host:e.host,port:fe}),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:le,listenPort:fe,machineName:ue,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),startupPairingCode:g}}function FS(e,t){let n=t;if(!e.httpsEnabled)return(0,tg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,tg.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 IS(e,t){let n=process.env.NODE_ENV!==`production`,r=Fg.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Fg.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Fg.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function LS(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function RS(e,t){if(e&&e!==t)throw Hg()}async function zS(e){let t=BS(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:VS(t)},`auth refresh attempt`);try{let t=await e.execute(),n=BS(e.authService,e.refreshToken),r=BS(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:VS(n),nextRefreshToken:VS(r)},`auth refresh succeeded`),t}catch(t){let n=BS(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:VS(n),error:HS(t)},`auth refresh failed`),t}}function BS(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function VS(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:US(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:US(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function HS(e){return Lg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function US(e){return e?e.slice(-8):null}async function WS(e,t){try{let n=To.parse(e);switch(n.method){case`auth.refresh`:{let e=await zS({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 RS(n.params.deviceId??t.relayDeviceId,e.deviceId),Eo.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return Eo.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return Eo.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return Eo.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return Eo.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return Eo.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return Eo.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw JS(n.method,`NOT_FOUND`,404,`Project not found`);return Eo.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 Eo.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 Eo.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return Eo.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw JS(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return Eo.parse({method:n.method,result:{session:e}})}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,{syncExternal:n.params.syncExternal});return Eo.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0);return Eo.parse({method:n.method,result:{capabilities:e}})}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return Eo.parse({method:n.method,result:e})}case`devices.list`:return Eo.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw JS(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return Eo.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw JS(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw GS(e)}}function GS(e){if(Lg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return JS(`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 JS(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:return JS(`BAD_REQUEST`,e.status,String(e),e.details);default:return JS(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Oo.safeParse(e);if(t.success)return t.data;let n=Do.safeParse(e);if(n.success)return JS(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 JS(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?JS(`BAD_REQUEST`,400,r):YS(e)?JS(`UNAUTHORIZED`,401,r):XS(r)?JS(`BAD_REQUEST`,400,r):JS(`INTERNAL`,500,r)}function KS(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:qS(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Hs(e.identity,e.privateKeyPem,i)}}function qS(e){return e.replace(/\s+/gu,``).toUpperCase()}function JS(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 Oo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function YS(e){return Lg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||Zg(e)}function XS(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:`)}async function ZS(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await PS(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{$S({type:`worker.update.prepared`,payload:e})}});$S({type:`worker.ready`,payload:QS(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=eC(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: ${String(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${String(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);$S({type:`worker.response`,id:e.id,ok:!0,result:t});return}}}catch(t){$S({type:`worker.response`,id:e.id,ok:!1,error:String(t)})}}await new Promise(()=>{})}function QS(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function $S(e){process.send&&process.send(e)}function eC(e){if(!tC(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.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:`gateway.update.apply`,requestedBy:e.requestedBy};default:return null}}function tC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}nC(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function nC(e){let t=P(e);switch(t.command){case`help`:sC();return;case`version`:console.log(te.version);return;case`init`:await iC(t);return;case`doctor`:await aC(t);return;case`start`:await rC(t);return;case`__worker`:await oC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function rC(e){let t=await Zs({configPath:e.configPath,ensureConfigFile:!0});tc(t.config);let n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await zl({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(Jl(e,t.config))}bc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function iC(e){let t=await Xs({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 Zs({configPath:t.configPath,ensureConfigFile:!1}),r=await yc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(xc(r))}async function aC(e){let t=await Zs({configPath:Ys(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await yc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(xc(n)),bc(n)&&(process.exitCode=1)}async function oC(e){try{await ZS(e)}catch(t){let n=await Zs({configPath:e.configPath,ensureConfigFile:!0});throw Error(Jl(t,n.config))}}function sC(){console.log(`${te.cliName} ${te.version}`),console.log(``),console.log(`Usage:`),console.log(` ${te.cliName} [start] [--config <path>] [--log]`),console.log(` ${te.cliName} init [--config <path>] [--force]`),console.log(` ${te.cliName} doctor [--config <path>]`),console.log(` ${te.cliName} --version`)}exports.runCli=nC;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "craby-gateway",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "Craby desktop gateway CLI",
5
5
  "bin": {
6
6
  "craby-gateway": "dist-sea/gateway.cjs"