craby-gateway 0.16.5 → 0.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`node:util`),b=require(`fs`);b=c(b);let x=require(`path`);x=c(x);let S=require(`module`),C=require(`net`),w=require(`child_process`),T=require(`@anthropic-ai/claude-agent-sdk`);var E={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.16.5`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.86`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@openai/codex":`^0.111.0`,"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const D=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function O(e){let t=e.match(D);return t?t[0]:null}function k(e){return typeof e==`string`?O(e):null}function A(e,t){let n=M(e),r=M(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function j(e,t){return A(e,t)>=0}function M(e){let t=e.match(D);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const ee=E,N=ee.dependencies??{};function te(e){return N[e]??``}const P={packageName:`craby-gateway`,cliName:`craby-gateway`,version:ee.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:te(`@anthropic-ai/claude-agent-sdk`),minimumVersion:k(te(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ne(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=re(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function re(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),ie=o((e=>{var t=F();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),I=o((e=>{var t=F(),n=ie();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`node:util`),b=require(`fs`);b=c(b);let x=require(`path`);x=c(x);let S=require(`module`),C=require(`net`),w=require(`child_process`),T=require(`@anthropic-ai/claude-agent-sdk`);var E={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.16.6`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.86`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@openai/codex":`^0.111.0`,"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const D=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function O(e){let t=e.match(D);return t?t[0]:null}function k(e){return typeof e==`string`?O(e):null}function A(e,t){let n=M(e),r=M(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function j(e,t){return A(e,t)>=0}function M(e){let t=e.match(D);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const ee=E,N=ee.dependencies??{};function te(e){return N[e]??``}const P={packageName:`craby-gateway`,cliName:`craby-gateway`,version:ee.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:te(`@anthropic-ai/claude-agent-sdk`),minimumVersion:k(te(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ne(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=re(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function re(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),ie=o((e=>{var t=F();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),I=o((e=>{var t=F(),n=ie();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
3
3
  `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),ae=o((e=>{var t=F(),n=ie();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),oe=o((e=>{function t(e,n,r,i){if(i&&typeof i==`object`)if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return e.call(n,r,i)}e.applyReviver=t})),L=o((e=>{var t=F();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),se=o((e=>{var t=oe(),n=F(),r=L();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),ce=o((e=>{var t=ae(),n=ie(),r=F(),i=se(),a=L(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),le=o((e=>{var t=F(),n=se(),r=L();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ue=o((e=>{var t=ce(),n=F(),r=le();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??=c(e),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),de=o((e=>{var t=ue(),n=F(),r=se();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),fe=o((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
4
4
  `)?n(r,t):r.includes(`
5
5
  `)?`
@@ -484,4 +484,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
484
484
  `)}function SC(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function CC(e){return String(e).includes(`returned no messages from getSessionMessages`)}function wC(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function TC(e){return e?{rawSeq:e.rawSeq,type:e.type,eventId:e.eventId,ts:e.ts}:null}function EC(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(!DC(n,i))return r}return e.length===t.length?null:n}function DC(e,t){return JSON.stringify(OC(e))===JSON.stringify(OC(t))}function OC(e){let{ts:t,...n}=e;return n}function kC(e,t,n,r){if(!n.historyUpdated)return`unchanged`;if(n.refreshMode===`delta`)return`append_only_delta`;if(t.length<e.length)return`history_shrunk`;let i=Math.min(e.length,t.length);return r!==null&&r<i?`prefix_rewrite`:`snapshot_fallback`}function AC(e){let t=e.previousEvents[e.previousEvents.length-1]?.rawSeq??null,n=e.nextEvents[e.nextEvents.length-1]?.rawSeq??null,r=EC(e.previousEvents,e.nextEvents),i=r??Math.min(e.previousEvents.length,e.nextEvents.length);return{projectId:e.projectId,sessionId:e.sessionId,provider:e.session.provider,source:e.session.source,providerMode:e.session.providerMode,decision:e.classification.refreshMode,reason:kC(e.previousEvents,e.nextEvents,e.classification,r),historyUpdated:e.classification.historyUpdated,fromRawSeq:e.classification.fromRawSeq??null,toRawSeq:e.classification.toRawSeq??null,previousEventCount:e.previousEvents.length,nextEventCount:e.nextEvents.length,sharedPrefixCount:i,appendedCount:Math.max(0,e.nextEvents.length-e.previousEvents.length),firstMismatchIndex:r,previousLastRawSeq:t,nextLastRawSeq:n,previousMismatchEvent:TC(r===null?void 0:e.previousEvents[r]),nextMismatchEvent:TC(r===null?void 0:e.nextEvents[r])}}function jC(e,t){let n=e[e.length-1]?.rawSeq,r=t[t.length-1]?.rawSeq;return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&DC(e,r)})?{historyUpdated:!1,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}:t.length>e.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&DC(e,r)})?{historyUpdated:!0,refreshMode:`delta`,fromRawSeq:n??0,toRawSeq:r??n??0}:{historyUpdated:!0,refreshMode:`snapshot`,...r===void 0?{}:{toRawSeq:r}}}function MC(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,n+=1,new Date(n).toISOString()),a=(n,a)=>{let o=t.length+1;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:o,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:VC(e.sessionId,r,a),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};a({scope:`thread`,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo}},[`thread`,e.thread.id,e.thread.updatedAt]);for(let t of e.thread.turns){let n=e.localTerminalTurnStatusById?.get(t.id);GC(n,t.status)||a({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}},[`turn`,t.id,t.status]);for(let n of t.items)a({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,JC(n.id)??null])}return t}function NC(e){let t=PC(e.localEvents);if(!t.hasHistoryReplay||!t.hasThreadEnvelope)return null;let n=e.thread.turns.map(e=>e.id);if(t.turnOrder.length>n.length)return null;for(let[e,r]of t.turnOrder.entries())if(n[e]!==r)return null;let r=[],i=Math.max(oC(e.localEvents)??0,e.thread.updatedAt>0?e.thread.updatedAt*1e3:Date.now()),a=0,o=()=>(a+=1,i+=1,new Date(i).toISOString()),s=(t,n)=>{r.push({v:`1.0`,kind:`provider.raw`,rawSeq:r.length+1,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:VC(e.sessionId,a,n),ts:o(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:t,historyReplay:!0,replaySynthetic:!0}}})},c=t.turnOrder.length-1;for(let[n,r]of e.thread.turns.entries()){let i=t.turnsById.get(r.id);if(!i){s({scope:`turn`,thread_id:e.thread.id,turn:{id:r.id,status:r.status,error:r.error}},[`turn`,r.id,r.status]);for(let t of r.items)s({scope:`item`,thread_id:e.thread.id,turn_id:r.id,item:t},[`item`,r.id,JC(t.id)??null]);continue}let a=n!==c,o=IC(i,r);if(!o.safe||a&&(o.appendedItems.length>0||o.statusChanged))return null;if(!a){o.statusChanged&&s({scope:`turn`,thread_id:e.thread.id,turn:{id:r.id,status:r.status,error:r.error}},[`turn`,r.id,r.status]);for(let t of o.appendedItems)s({scope:`item`,thread_id:e.thread.id,turn_id:r.id,item:t},[`item`,r.id,JC(t.id)??null])}}return r}function PC(e){let t={hasHistoryReplay:!1,hasThreadEnvelope:!1,turnOrder:[],turnsById:new Map};for(let n of e){if(n.type!==`native.raw`)continue;let e=Q(n.payload.raw);if($(e.source)!==`codex.history.thread_read`)continue;let r=Q(e.message),i=$(r.scope);if(t.hasHistoryReplay=!0,i===`thread`){t.hasThreadEnvelope=!0;continue}if(i===`turn`){let e=Q(r.turn),n=$(e.id);if(!n)continue;let i=FC(t,n),a=$(e.status);a&&(i.status=a),i.fingerprint=zC(e);continue}if(i!==`item`)continue;let a=Q(r.item),o=$(r.turn_id)??$(a.turn_id);if(!o)continue;let s=LC(o,a,void 0);if(!s)continue;let c=FC(t,o);c.itemFingerprintByKey.has(s)||c.itemOrder.push(s),c.itemFingerprintByKey.set(s,RC(a))}return t}function FC(e,t){let n=e.turnsById.get(t);if(n)return n;let r={itemOrder:[],itemFingerprintByKey:new Map};return e.turnsById.set(t,r),e.turnOrder.push(t),r}function IC(e,t){if(t.items.length<e.itemOrder.length)return{safe:!1,appendedItems:[],statusChanged:!1};for(let[n,r]of e.itemOrder.entries()){let i=t.items[n];if(!i||LC(t.id,i,n)!==r||e.itemFingerprintByKey.get(r)!==RC(i))return{safe:!1,appendedItems:[],statusChanged:!1}}return e.fingerprint!==void 0&&e.fingerprint!==zC(t)&&(e.status??``)===t.status?{safe:!1,appendedItems:[],statusChanged:!1}:{safe:!0,appendedItems:t.items.slice(e.itemOrder.length),statusChanged:(e.status??``)!==t.status}}function LC(e,t,n){let r=JC(t.id);if(r)return r;if(n!==void 0)return`${e}::${n}`}function RC(e){return JSON.stringify(e)}function zC(e){return JSON.stringify({status:$(e.status)??null,error:Q(e.error)})}function BC(e){return String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``)}function VC(e,t,n){let r=n.map(BC).filter(e=>e.length>0);return r.length===0?`raw_hist_codex_${e}_${t.toString().padStart(6,`0`)}`:`raw_hist_codex_${e}_${r.join(`_`)}`}function HC(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=Q(n.payload.raw);if(n.type===`turn.completed`||n.type===`turn.failed`){let r=$(e.turn_id)??$(e.turnId)??$(Q(e.turn).id)??$(Q(e.item).turn_id)??$(Q(e.item).turnId),i=$(e.status)??(n.type===`turn.completed`?`completed`:`failed`);r&&t.set(r,i);continue}if(n.type!==`native.raw`||$(e.source)!==`codex.history.thread_read`)continue;let r=Q(e.message);if($(r.scope)===`turn`){let e=Q(r.turn),n=$(e.id),i=$(e.status);n&&i&&WC(i)&&t.set(n,i)}}return t}function UC(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=Q(o.payload.raw),c=$(s.source),l=c===`codex.history.thread_read.incremental`;if(o.type===`item.started`||o.type===`item.updated`||o.type===`item.completed`){if(o.type===`item.completed`){let e=$(Q(s.item).id);e&&!l&&n.add(e)}}else if(o.type===`turn.started`){let e=$(s.turn_id)??$(Q(s.turn).id);e&&!l&&t.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=$(s.turn_id)??$(Q(s.turn).id);if(!e)continue;l||t.add(e);let n=$(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||c!==`codex.history.thread_read`)continue;let u=Q(s.message);if($(u.scope)===`turn`){let e=Q(u.turn),t=$(e.id);if(!t)continue;let n=$(e.status);n&&WC(n)&&r.set(t,n);continue}}let o=Math.max(i,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),s=0,c=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),l=t=>{let n=t.map(c).filter(e=>e.length>0);return n.length===0?`raw_sync_codex_${e.sessionId}_${a.toString().padStart(6,`0`)}`:`raw_sync_codex_${e.sessionId}_${n.join(`_`)}`},u=()=>(s+=1,new Date(o+s).toISOString()),d=[],f=(t,n,r)=>{let i=u();d.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:l(r),ts:i,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),a+=1};for(let i of e.thread.turns){let e=r.get(i.id),o=GC(e,i.status);!t.has(i.id)&&!o&&f(`turn.started`,{type:`turn.started`,turn:{id:i.id,status:i.status,items:[],error:i.error}},[`turn_started`,i.id]);for(let e of i.items){let t=$(e.id);t&&n.has(t)||f(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e},[`item_completed`,i.id,t??`seq_${a}`])}if(WC(i.status)&&e!==i.status){if(i.status===`completed`){f(`turn.completed`,{type:`turn.completed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error}},[`turn_terminal`,i.id]);continue}f(`turn.failed`,{type:`turn.failed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error},...i.error?{error:i.error}:{}},[`turn_terminal`,i.id])}}return d}function WC(e){return e===`completed`||e===`failed`||e===`interrupted`}function GC(e,t){return e===t&&WC(t)}function KC(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function qC(e,t=60){let n=KC(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function JC(e){if(typeof e!=`string`)return;let t=KC(e);if(t)return t}function YC(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function XC(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function ZC(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var QC=class{indexPath;eventsDir;sessions=new Map;rawEventsCacheBySession=new Map;compactedRawEventsCacheBySession=new Map;pendingRawMutationsBySession=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`session-index.json`),this.eventsDir=p.default.join(e,`session-events`),this.ready=this.loadFromDisk()}async init(){await this.ready}async flushRawCompactions(e){await this.ready}async shutdown(){await this.ready}async upsertSession(e){await this.ready;let t=this.sessions.get(e.id);this.sessions.set(e.id,{...t,...e}),await this.enqueueWrite(async()=>{await this.persistIndex()})}async patchSession(e,t){await this.ready;let n=this.sessions.get(e);return n?(this.sessions.set(e,{...n,...t}),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async setSessionStatus(e,t,n){await this.ready;let r=this.sessions.get(e);r&&(this.sessions.set(e,{...r,status:t,updatedAt:n,interactionLockReason:void 0,pendingApprovals:t===`running`?r.pendingApprovals:0,pendingUserInputs:t===`running`?r.pendingUserInputs:0,pendingActions:t===`running`?r.pendingActions:0}),await this.enqueueWrite(async()=>{await this.persistIndex()}))}async removeSession(e){if(await this.ready,!this.sessions.has(e))return;this.sessions.delete(e),this.rawEventsCacheBySession.delete(e),this.compactedRawEventsCacheBySession.delete(e);let t=p.default.join(this.eventsDir,`${e}.jsonl`),n=p.default.join(this.eventsDir,`${e}.raw.jsonl`);await this.enqueueWrite(async()=>{await Promise.all([this.persistIndex(),d.default.rm(t,{force:!0}),d.default.rm(n,{force:!0})])})}hasSession(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}getProjectSession(e,t){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return n}listSessions(e=`all`){return[...this.sessions.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessions(e,t=`all`){return this.listSessions(t).filter(t=>t.projectId===e)}async appendRawEvent(e){await this.ready,this.sessions.has(e.sessionId)&&await this.enqueueRawSessionWrite(e.sessionId,async()=>{if(lw(e)){let t=gw([...await this.readSessionRawEventsLocked(e.sessionId),e]);await this.replaceRawEventFile(e.sessionId,t),this.rawEventsCacheBySession.set(e.sessionId,t),this.compactedRawEventsCacheBySession.set(e.sessionId,iw(t));return}await this.appendRawEventLine(e),this.appendRawEventToCache(e)})}async mergeSessionRawEvents(e,t,n){if(await this.ready,!this.sessions.has(e))return[];let r=t.filter(t=>t.sessionId===e),i=[];return await this.enqueueRawSessionWrite(e,async()=>{let t=uw(await this.readSessionRawEventsLocked(e),r,n);await this.replaceRawEventFile(e,t);let a=iw(t);i=aw(a),this.rawEventsCacheBySession.set(e,t),this.compactedRawEventsCacheBySession.set(e,a)}),i}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 Ps(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=Ps((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 nw(t);let n=null;return await this.enqueueWrite(async()=>{n=nw(await this.readSessionRawEventsLocked(e))}),n}async loadFromDisk(){await d.default.mkdir(this.eventsDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.sessions))return;for(let e of t.sessions)e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath&&this.sessions.set(e.id,{...e,status:`idle`,interactionLockReason:void 0,pendingApprovals:0,pendingUserInputs:0,pendingActions:0})}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,sessions:[...this.sessions.values()].sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}async enqueueRawSessionWrite(e,t){this.incrementPendingRawMutation(e);try{let e;return await this.enqueueWrite(async()=>{e=await t()}),e}finally{this.decrementPendingRawMutation(e)}}async appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${tw(e)}\n`;await d.default.appendFile(t,n,`utf8`)}async replaceRawEventFile(e,t){let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r=t.map(e=>tw(e)).join(`
485
485
  `);await rw(n,r?`${r}\n`:``)}appendRawEventToCache(e){let t=this.rawEventsCacheBySession.get(e.sessionId),n=t?.[t.length-1];t&&t.push(e);let r=this.compactedRawEventsCacheBySession.get(e.sessionId);if(r){if(cw(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&sw(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}ow(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return aw(t);let n=iw(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),aw(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(!$C(t)||t.kind!==`provider.raw`)continue;let n=ew(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=ha.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>tw(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 aw(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=iw(n);return this.compactedRawEventsCacheBySession.set(e,r),aw(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 $C(e){return typeof e==`object`&&!!e}function ew(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function tw(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 nw(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function rw(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{await d.default.writeFile(n,t,`utf8`),await d.default.rename(n,e)}catch(e){try{await d.default.rm(n,{force:!0})}catch{}throw e}}function iw(e){let t=Ns(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Is(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function aw(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function ow(e,t){let n=Is(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=Ls(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 sw(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function cw(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function lw(e){return cw(e)}function uw(e,t,n){if(n?.replaceMissing)return dw(e,t,n);let r=[...e].sort(hw),i=new Map,a=1;for(let[e,t]of r.entries())i.set(t.eventId,e),a=Math.max(a,t.rawSeq+1);for(let e of t){let t=i.get(e.eventId);if(t!==void 0){let n=r[t];n&&fw(n,e)&&(r[t]=mw(n,e));continue}let n={...e,rawSeq:a};a+=1,i.set(n.eventId,r.length),r.push(n)}return gw(r.sort(hw)).sort(hw)}function dw(e,t,n){let r=new Map(e.map(e=>[e.eventId,e])),i=new Set(t.map(e=>e.eventId)),a=n?.baseEventIds?new Set(n.baseEventIds):null,o=a?e.filter(e=>!a.has(e.eventId)&&!i.has(e.eventId)):[],s=[...t,...o].sort(hw),c=1;for(let t of e)c=Math.max(c,t.rawSeq+1);return gw(s.map(e=>{let t=r.get(e.eventId);if(t)return fw(t,e)?mw(t,e):{...e,rawSeq:t.rawSeq};let n={...e,rawSeq:c};return c+=1,n})).sort(hw)}function fw(e,t){return pw(e)&&pw(t)}function pw(e){return e.type===`native.raw`?xw(($C(e.payload.raw)?e.payload.raw:{}).source)===`codex.history.thread_read`:!1}function mw(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function hw(e,t){let n=e.rawSeq-t.rawSeq;if(n!==0)return n;let r=e.ts.localeCompare(t.ts);return r===0?e.eventId.localeCompare(t.eventId):r}function gw(e){let t=Fs(e),n=new Set;for(let e of t){let t=_w(e);t&&n.add(t)}return n.size===0?t:t.filter(e=>{let t=vw(e);return!t||!n.has(t)})}function _w(e){if(e.type===`item.completed`){let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.item)?t.item:{};return yw(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.message)?t.message:{},r=$C(n.params)?n.params:{};if((xw(n.method)??xw(t.method))!==`item/completed`)return null;let i=$C(r.item)?r.item:{};return yw(e.sessionId,i)}function vw(e){if(e.type===`item.updated`){let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.item)?t.item:{},r=xw(n.original_method)??xw(n.originalMethod)??``,i=$C(n.payload)?n.payload:{};return!(typeof i.delta==`string`||typeof i.output_delta==`string`||typeof i.outputDelta==`string`||typeof n.output_delta==`string`||typeof n.outputDelta==`string`||typeof n.text==`string`)&&!bw(r)?null:yw(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.message)?t.message:{},r=$C(n.params)?n.params:{};if(!bw(xw(n.method)??xw(t.method)??``))return null;let i=$C(r.msg)?r.msg:{},a=xw(r.itemId)??xw(r.item_id)??xw(i.itemId)??xw(i.item_id);return a?`${e.sessionId}|${a}`:null}function yw(e,t){let n=xw(t.id)??xw(t.item_id)??xw(t.itemId);return n?`${e}|${n}`:null}function bw(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function xw(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}var Sw=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${Cg(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}getWatchSubscriptions(e){let t=new Map;for(let n of this.clients.values())for(let r of n.subscriptionsBySessionId.values())r.purpose===e&&t.set(r.sessionId,r);return[...t.values()]}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=null;for(let r of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);if(!(!i||i.socket.readyState!==i.socket.OPEN)){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),i.socket.send(n)}}}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}i.socket.send(JSON.stringify(e))}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendBroadcastMessage(e,t){let n=JSON.stringify(e);for(let e of this.clients.values())if(e.socket.readyState===e.socket.OPEN){if(t?.sessionId){let n=e.subscriptionsBySessionId.get(t.sessionId);if(!n||t.purpose&&n.purpose!==t.purpose)continue}e.socket.send(n)}}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}};const Cw=1200,ww=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var Tw=class{statesByKey=new Map;targetsByClientId=new Map;constructor(e){this.options=e}setClientWatchTargets(e,t,n){let r=new Map;for(let e of t){let t=e.sessionId.trim(),n=e.projectId?.trim()??``;!t||!n||r.set(this.stateKey(n,t),{sessionId:t,projectId:n})}let i=this.targetsByClientId.get(e)??new Map,a=n?new Map:new Map(i);for(let[e,t]of r)a.set(e,t);for(let[t,n]of i)a.has(t)||this.removeClientFromState(e,n.projectId??``,n.sessionId);for(let[t,n]of a)i.get(t)||this.addClientToState(e,n.projectId??``,n.sessionId);return this.targetsByClientId.set(e,a),[...a.values()]}removeClient(e){let t=this.targetsByClientId.get(e);if(t){for(let n of t.values())this.removeClientFromState(e,n.projectId??``,n.sessionId);this.targetsByClientId.delete(e)}}close(){for(let e of this.statesByKey.values())this.disposeState(e);this.statesByKey.clear(),this.targetsByClientId.clear()}logDebug(e,t){ww&&(console.log(`[native-watch][gateway]`,e,t),this.options.logger.info?.({event:e,...t},`native session watch debug`))}addClientToState(e,t,n){if(!t||!n)return;let r=this.stateKey(t,n),i=this.statesByKey.get(r);i||(i={provider:`codex`,sessionId:n,projectId:t,ownerClientIds:new Set,fileWatcher:null,debounceTimer:null,catchupRetryTimer:null,reconcileTimer:setInterval(()=>{this.requestSync(r,`reconcile`)},25e3),syncInFlight:!1,rerunRequested:!1,stableIdleSyncCount:0,watchCatchupRetryCount:0,lastObservedRawSeq:0,lastObservedRawEventCount:0,lastTriggeredAt:0,lastSyncStartedAt:null,lastSyncCompletedAt:null},this.statesByKey.set(r,i),this.logDebug(`state.created`,{clientId:e,projectId:t,sessionId:n})),i.ownerClientIds.add(e),this.logDebug(`lease.added`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:i.ownerClientIds.size}),this.requestSync(r,`lease_added`)}removeClientFromState(e,t,n){let r=this.statesByKey.get(this.stateKey(t,n));r&&(r.ownerClientIds.delete(e),this.logDebug(`lease.removed`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:r.ownerClientIds.size}),!(r.ownerClientIds.size>0)&&(this.disposeState(r),this.statesByKey.delete(this.stateKey(t,n))))}disposeState(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null),this.clearCatchupRetry(e,{resetAttempts:!0}),clearInterval(e.reconcileTimer),e.fileWatcher?.close(),e.fileWatcher=null,this.logDebug(`state.disposed`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:e.watchedPath})}async requestSync(e,t){let n=this.statesByKey.get(e);if(n){if(n.lastTriggeredAt=Date.now(),n.syncInFlight){n.rerunRequested=!0;return}n.syncInFlight=!0,n.rerunRequested=!1,n.lastSyncStartedAt=Date.now(),this.logDebug(`sync.begin`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,ownerClientCount:n.ownerClientIds.size,watchedPath:n.watchedPath,watchedDir:n.watchedDir,watchedBaseName:n.watchedBaseName,stableIdleSyncCount:n.stableIdleSyncCount});try{let r=await this.options.sessionManager.getProjectSessionSummary(n.projectId,n.sessionId);if(!r||r.providerMode!==`native`||r.provider!==`codex`&&r.provider!==`claude`){this.logDebug(`sync.stop.unwatchable_summary`,{projectId:n.projectId,sessionId:n.sessionId,summarySource:r?.source,summaryProvider:r?.provider,summaryProviderMode:r?.providerMode,summaryStatus:r?.status}),this.stopState(e);return}n.provider=r.provider;let i=await this.options.sessionManager.syncProjectSessionHistory(n.projectId,n.sessionId);n.lastSyncCompletedAt=Date.now(),this.applyWatchPath(n,i.nativeWatchPath);let a=n.lastObservedRawSeq,o=n.lastObservedRawEventCount,s=this.resolveObservedRawSeq(i),c=s>a||i.rawEvents.length>o;if(c?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,s),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),i.session.status!==`running`&&!i.historyUpdated?n.stableIdleSyncCount+=1:n.stableIdleSyncCount=0,this.logDebug(`sync.result`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,status:i.session.status,interactionLockReason:i.session.interactionLockReason,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,nativeWatchPath:i.nativeWatchPath,rawEventCount:i.rawEvents.length,cursorAdvanced:c,previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount}),i.historyUpdated||i.statusChanged){let e=this.options.createExternalUpdateMessage({provider:i.session.provider,sessionId:i.session.id,projectId:i.session.projectId,updatedAt:i.session.updatedAt,status:i.session.status,interactionLockReason:i.session.interactionLockReason,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e)}}catch(e){this.options.logger.warn({err:e,projectId:n.projectId,sessionId:n.sessionId,reason:t},`native session watch sync failed`)}finally{let n=this.statesByKey.get(e);if(!n)return;n.syncInFlight=!1,n.rerunRequested&&(this.logDebug(`sync.rerun`,{projectId:n.projectId,sessionId:n.sessionId,reason:t}),n.rerunRequested=!1,this.requestSync(e,`rerun`))}}}stopState(e){let t=this.statesByKey.get(e);if(t){this.disposeState(t),this.statesByKey.delete(e);for(let t of this.targetsByClientId.values())t.delete(e)}}applyWatchPath(e,t){let n=t?.trim()??``;if(!n)return;let r=p.default.resolve(n);if(e.watchedPath===r&&e.fileWatcher)return;let i=p.default.dirname(r),a=p.default.basename(r);e.fileWatcher?.close(),e.fileWatcher=null,e.watchedPath=r,e.watchedDir=i,e.watchedBaseName=a,this.logDebug(`watch.path.applied`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,watchedDir:i,watchedBaseName:a});try{e.fileWatcher=this.createPathWatcher(r,(t,n)=>{let i=n?Buffer.isBuffer(n)?n.toString(`utf8`):n:void 0;this.logDebug(`watch.fs.event`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,eventType:t,filename:i}),this.scheduleDebouncedSync(this.stateKey(e.projectId,e.sessionId))}),e.fileWatcher.on(`error`,t=>{this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`native session watcher error`)})}catch(t){this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`failed to start native session watcher`)}}createPathWatcher(e,t){return this.options.createWatcher?this.options.createWatcher(e,t):(0,u.watch)(e,(e,n)=>{t(e,n)})}scheduleDebouncedSync(e){let t=this.statesByKey.get(e);if(!t)return;let n=!!t.debounceTimer;t.debounceTimer&&clearTimeout(t.debounceTimer),this.clearCatchupRetry(t,{resetAttempts:!0}),this.logDebug(`watch.debounce.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath,delayMs:300,replacedExistingTimer:n}),t.debounceTimer=setTimeout(()=>{t.debounceTimer=null,this.logDebug(`watch.debounce.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath}),this.requestSync(e,`watch`)},300)}resolveObservedRawSeq(e){let t=e.rawEvents[e.rawEvents.length-1],n=t&&typeof t==`object`&&t&&`rawSeq`in t&&typeof t.rawSeq==`number`?t.rawSeq:void 0;return e.toRawSeq??n??0}clearCatchupRetry(e,t){e.catchupRetryTimer&&=(clearTimeout(e.catchupRetryTimer),null),t?.resetAttempts&&(e.watchCatchupRetryCount=0)}maybeScheduleWatchCatchupRetry(e,t,n,r,i){n!==`watch`&&n!==`watch_catchup`||t.ownerClientIds.size!==0&&(t.watchCatchupRetryCount>=2||(t.catchupRetryTimer||=(t.watchCatchupRetryCount+=1,this.logDebug(`watch.catchup.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,reason:n,delayMs:Cw,historyUpdated:r.historyUpdated,refreshMode:r.refreshMode,previousObservedRawSeq:i.previousObservedRawSeq,previousObservedRawEventCount:i.previousObservedRawEventCount,nextObservedRawSeq:i.nextObservedRawSeq,nextObservedRawEventCount:i.nextObservedRawEventCount,watchCatchupRetryCount:t.watchCatchupRetryCount}),setTimeout(()=>{t.catchupRetryTimer=null,this.logDebug(`watch.catchup.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchCatchupRetryCount:t.watchCatchupRetryCount}),this.requestSync(e,`watch_catchup`)},Cw))))}stateKey(e,t){return`${e}::${t}`}};function Ew(e){return e.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`},purpose:e.purpose}))}const Dw=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`,Ow=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function kw(e,t){Dw&&console.log(`[native-watch][gateway]`,e,t)}function Aw(e,t){Ow&&console.log(`[session-fetch][gateway] ${e}`,t)}async function jw(e){let t=e.limit??300,n=(n,r)=>{Aw(`raw-events.list`,{requestSource:e.requestSource,projectId:e.projectId,sessionId:e.sessionId,limit:t,requestedCursor:e.fromRawSeqExclusive??null,decision:n.decision,reason:n.reason,fromRawSeqExclusive:n.fromRawSeqExclusive??null,toRawSeq:n.toRawSeq??null,returnedCount:n.events.length,returnedFirstRawSeq:n.events[0]?.rawSeq??null,returnedLastRawSeq:n.events[n.events.length-1]?.rawSeq??null,...r})};if(e.fromRawSeqExclusive===void 0){let r=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),i={decision:`snapshot`,reason:r.length===0?`empty_history_snapshot`:`initial_snapshot`,events:r};return n(i),i}let r=await e.sessionManager.getProjectSessionRawSeqRange(e.projectId,e.sessionId);if(!r){let e={decision:`snapshot`,reason:`empty_history_snapshot`,events:[]};return n(e,{rangeMin:null,rangeMax:null,minExpectedCursor:null}),e}let i=Math.max(0,r.min-1);if(e.fromRawSeqExclusive<i||e.fromRawSeqExclusive>r.max){let a={decision:`snapshot`,reason:`cursor_out_of_range`,events:await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t)};return n(a,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),a}let a=await e.sessionManager.getProjectSessionRawEventsSinceSeq(e.projectId,e.sessionId,e.fromRawSeqExclusive,t),o={decision:`delta`,reason:`cursor_valid_delta`,fromRawSeqExclusive:e.fromRawSeqExclusive,toRawSeq:a[a.length-1]?.rawSeq??e.fromRawSeqExclusive,events:a};return n(o,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),o}async function Mw(e,t={}){await uu(e.gatewayLogPath);let n=Pw(e,t),r=Nw(e,n.instance);await r.register(vg.default,{origin:!0}),await r.register(_g.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new v_(e);await s.init();let c=new O_(e.auditLogPath),l=new Sw,u=new pv,d=new Sv(e.projectStoreDir),f=new QC(e.sessionHistoryDir);await f.init();let m=new Hx(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new kx({store:m});await h.init();let g,_=null,v=await tc(e.authStoreDir),y=new $S({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}}),b=new Tw({sessionManager:y,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>N(e)});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let x=new kl({packageName:P.packageName,currentVersion:P.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>y.getRunningRuntimeSessionCount(),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{b.close(),_?.close(),S.close(),await x.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:re(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:fl(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>sl({gatewayId:e.gatewayId,machineName:fl(),relayBaseUrl:e.relayEnabled?bl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:vl({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ne(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(e,t)=>{let n=wa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=he(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),Ww(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=Da.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await Lw({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await x.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Pa.safeParse(n?.requestedBy);try{let e=await x.applyUpdate(r.success?r.data:`mobile`);return za.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.post(`/api/codex/app-server/restart`,async(e,t)=>{if(L(e,t))try{return Aa.parse(await y.restartCodexAppServer())}catch(e){let n=t_(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(L(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(L(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return t_(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):Jw(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return t_(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return t_(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=se(r.status,t);if(!i)return;let a=ce(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return t_(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/config`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionConfig(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.post(`/api/projects/:projectId/sessions/:sessionId/history-sync`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{let e=await y.syncProjectSessionHistory(n.projectId,n.sessionId);return{session:e.session,rawEventCount:e.rawEvents.length}}catch(e){return t_(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=typeof r.fromRawSeqExclusive==`string`?Number(r.fromRawSeqExclusive):void 0;try{return await te(n.projectId,n.sessionId,i,typeof a==`number`&&Number.isFinite(a)?Math.max(0,Math.floor(a)):void 0,`http`)}catch(e){return t_(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>ne(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ne(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=ue(t.headers.authorization)??de(t.url);if(!n){e.close(1008,`Missing access token`);return}let r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await w(fa(e),r.sub,i)}catch(e){await T({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{b.removeClient(i),l.removeClient(i)})});let S=new tS({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=he(e.deviceName);return Ww(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await Lw({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return Iw(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>Hw(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:x,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await w(e,t,n)}catch(r){await T({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),C=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.external.watch.set`:{kw(`command.received`,{clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions},`received session.external.watch.set`);let i=b.setClientWatchTargets(n,e.payload.sessions,e.payload.replace);kw(`command.applied`,{clientId:n,deviceId:t,replace:e.payload.replace,targetCount:i.length,targets:i}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,targetCount:i.length,targets:i},`applied session.external.watch.set`),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:i.map(e=>e.sessionId)}});return}case`session.stream.subscribe`:{let t=Ew(e.payload.sessions);await E(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},w=async(e,t,n)=>{await C(e,t,n)},T=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},E=async(e,t,n)=>{let r=D(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await O(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},D=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},O=async(e,t)=>{let n=await k(t);if(t.cursor.kind===`all`){await A(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await A(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await A(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,M({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},k=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw c_(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},A=async(e,t,n)=>{let r=`snap_${Cg(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=j(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,ee({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},j=(e,t)=>{if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r},M=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${Cg(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),ee=e=>({v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events}}}),N=e=>({v:`1.0`,kind:`session.external.update`,type:`session.external.update`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`session_external_update_${Cg(12)}`,ts:new Date().toISOString(),payload:{raw:{updatedAt:e.updatedAt,status:e.status,interactionLockReason:e.interactionLockReason,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged}}}),te=async(e,t,n=300,r,i=`http`)=>jw({sessionManager:y,projectId:e,sessionId:t,limit:n,fromRawSeqExclusive:r,requestSource:i}),ne=t=>t.headers[`x-api-key`]===e.apiKey,re=e=>{if(e==null)return e;if(typeof e==`string`){let t=F(e);return t===void 0?ie(e,a):ae(I(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=F(t);return n===void 0?ie(t,a):ae(I(n))}return typeof e==`object`?ae(I(e)):String(e)},F=e=>{try{return JSON.parse(e)}catch{return}},ie=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,I=e=>{if(Array.isArray(e))return e.map(e=>I(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=I(r)}return n}return e},ae=e=>{let t=oe(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ie(t,a)}},oe=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=ue(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},se=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ce=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},le=(e,t)=>{let n=e.params,r=e.query,i=Mi.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},ue=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},de=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},fe=e.httpsEnabled?e.httpsPort:e.port,pe=e.httpsEnabled?`https`:`http`,me=fl(),he=e=>e?.trim()||me||`Gateway`;await r.listen({host:e.host,port:fe});let ge=r.server.address(),_e=typeof ge==`object`&&ge?ge.port:fe;if(r.log.info({host:e.host,port:_e,protocol:pe,machineName:me},Fw(pe,e.host,_e)),e.relayEnabled&&(_=new uS({gatewayId:e.gatewayId,machineName:me,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>hS({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:vl({protocol:pe,host:e.host,port:_e}),logger:r.log,onFrame:async e=>{await S.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await x.start(),{protocol:pe,listenPort:_e,machineName:me,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>x.getInfo(),requestGatewayUpdate:(e=`console`)=>x.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function Nw(e,t){let n=t;if(!e.httpsEnabled)return(0,yg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,yg.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 Pw(e,t){let n=process.env.NODE_ENV!==`production`,r=$g.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?$g.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,$g.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function Fw(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function Iw(e,t){if(e&&e!==t)throw o_()}async function Lw(e){let t=Rw(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:zw(t)},`auth refresh attempt`);try{let t=await e.execute(),n=Rw(e.authService,e.refreshToken),r=Rw(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:zw(n),nextRefreshToken:zw(r)},`auth refresh succeeded`),t}catch(t){let n=Rw(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:zw(n),error:Bw(t)},`auth refresh failed`),t}}function Rw(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function zw(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:Vw(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:Vw(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function Bw(e){return t_(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function Vw(e){return e?e.slice(-8):null}async function Hw(e,t){try{let n=Mo.parse(e);switch(n.method){case`auth.refresh`:{let e=await Lw({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 Iw(n.params.deviceId??t.relayDeviceId,e.deviceId),No.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return No.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return No.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return No.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return No.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return No.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return No.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return No.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw Kw(n.method,`NOT_FOUND`,404,`Project not found`);return No.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 No.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 No.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return No.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw Kw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return No.parse({method:n.method,result:{session:e}})}case`sessions.config.get`:{let e=await t.sessionManager.getProjectSessionConfig(n.params.projectId,n.params.sessionId);if(!e)throw Kw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return No.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return No.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=n.params.limit===`all`?2**53-1:n.params.limit,r=await jw({sessionManager:t.sessionManager,projectId:n.params.projectId,sessionId:n.params.sessionId,limit:e,fromRawSeqExclusive:n.params.fromRawSeqExclusive,requestSource:`rpc`});return No.parse({method:n.method,result:r})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),No.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return No.parse({method:n.method,result:e})}case`devices.list`:return No.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw Kw(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return No.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw Kw(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw Uw(e)}}function Uw(e){if(t_(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return Kw(`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 Kw(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return Kw(`BAD_REQUEST`,e.status,String(e),e.details);default:return Kw(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Fo.safeParse(e);if(t.success)return t.data;let n=Po.safeParse(e);if(n.success)return Kw(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 Kw(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?Kw(`BAD_REQUEST`,400,r):qw(e)?Kw(`UNAUTHORIZED`,401,r):Jw(r)?Kw(`BAD_REQUEST`,400,r):Kw(`INTERNAL`,500,r)}function Ww(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:Gw(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:ic(e.identity,e.privateKeyPem,i)}}function Gw(e){return e.replace(/\s+/gu,``).toUpperCase()}function Kw(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 Fo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function qw(e){return t_(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||__(e)}function Jw(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}function Yw(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function Xw(e){let t=await pc({configPath:e.configPath,ensureConfigFile:!0});_c(t.config);let n=await Mw(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{Qw({type:`worker.update.prepared`,payload:e})}});Qw({type:`worker.ready`,payload:Zw(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=$w(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${Yw(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${Yw(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);Qw({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}case`codex.appServer.restart`:{if(!n.requestCodexAppServerRestart)throw Error(`codex app-server restart is unavailable`);let t=await n.requestCodexAppServerRestart(e.requestedBy);Qw({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){Qw({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function Zw(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function Qw(e){process.send&&process.send(e)}function $w(e){if(!eT(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:e.method,requestedBy:e.requestedBy};default:return null}}function eT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}tT(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function tT(e){let t=ne(e);switch(t.command){case`help`:oT();return;case`version`:console.log(P.version);return;case`init`:await rT(t);return;case`doctor`:await iT(t);return;case`start`:await nT(t);return;case`__worker`:await aT(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function nT(e){let t=await pc({configPath:e.configPath,ensureConfigFile:!0});_c(t.config);let n=await Fc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await nu({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(du(e,t.config))}Ic(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function rT(e){let t=await fc({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 pc({configPath:t.configPath,ensureConfigFile:!1}),r=await Fc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Lc(r))}async function iT(e){let t=await pc({configPath:dc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Fc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Lc(n)),Ic(n)&&(process.exitCode=1)}async function aT(e){try{await Xw(e)}catch(t){let n=await pc({configPath:e.configPath,ensureConfigFile:!0});throw Error(du(t,n.config))}}function oT(){console.log(`${P.cliName} ${P.version}`),console.log(``),console.log(`Usage:`),console.log(` ${P.cliName} [start] [--config <path>] [--log]`),console.log(` ${P.cliName} init [--config <path>] [--force]`),console.log(` ${P.cliName} doctor [--config <path>]`),console.log(` ${P.cliName} --version`)}exports.runCli=tT;
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 aw(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=iw(n);return this.compactedRawEventsCacheBySession.set(e,r),aw(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 $C(e){return typeof e==`object`&&!!e}function ew(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function tw(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 nw(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function rw(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{await d.default.writeFile(n,t,`utf8`),await d.default.rename(n,e)}catch(e){try{await d.default.rm(n,{force:!0})}catch{}throw e}}function iw(e){let t=Ns(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=Is(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function aw(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function ow(e,t){let n=Is(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=Ls(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 sw(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function cw(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function lw(e){return cw(e)}function uw(e,t,n){if(n?.replaceMissing)return dw(e,t,n);let r=[...e].sort(hw),i=new Map,a=1;for(let[e,t]of r.entries())i.set(t.eventId,e),a=Math.max(a,t.rawSeq+1);for(let e of t){let t=i.get(e.eventId);if(t!==void 0){let n=r[t];n&&fw(n,e)&&(r[t]=mw(n,e));continue}let n={...e,rawSeq:a};a+=1,i.set(n.eventId,r.length),r.push(n)}return gw(r.sort(hw)).sort(hw)}function dw(e,t,n){let r=new Map(e.map(e=>[e.eventId,e])),i=new Set(t.map(e=>e.eventId)),a=n?.baseEventIds?new Set(n.baseEventIds):null,o=a?e.filter(e=>!a.has(e.eventId)&&!i.has(e.eventId)):[],s=[...t,...o].sort(hw),c=1;for(let t of e)c=Math.max(c,t.rawSeq+1);return gw(s.map(e=>{let t=r.get(e.eventId);if(t)return fw(t,e)?mw(t,e):{...e,rawSeq:t.rawSeq};let n={...e,rawSeq:c};return c+=1,n})).sort(hw)}function fw(e,t){return pw(e)&&pw(t)}function pw(e){return e.type===`native.raw`?xw(($C(e.payload.raw)?e.payload.raw:{}).source)===`codex.history.thread_read`:!1}function mw(e,t){return{...t,rawSeq:e.rawSeq,ts:e.ts}}function hw(e,t){let n=e.rawSeq-t.rawSeq;if(n!==0)return n;let r=e.ts.localeCompare(t.ts);return r===0?e.eventId.localeCompare(t.eventId):r}function gw(e){let t=Fs(e),n=new Set;for(let e of t){let t=_w(e);t&&n.add(t)}return n.size===0?t:t.filter(e=>{let t=vw(e);return!t||!n.has(t)})}function _w(e){if(e.type===`item.completed`){let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.item)?t.item:{};return yw(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.message)?t.message:{},r=$C(n.params)?n.params:{};if((xw(n.method)??xw(t.method))!==`item/completed`)return null;let i=$C(r.item)?r.item:{};return yw(e.sessionId,i)}function vw(e){if(e.type===`item.updated`){let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.item)?t.item:{},r=xw(n.original_method)??xw(n.originalMethod)??``,i=$C(n.payload)?n.payload:{};return!(typeof i.delta==`string`||typeof i.output_delta==`string`||typeof i.outputDelta==`string`||typeof n.output_delta==`string`||typeof n.outputDelta==`string`||typeof n.text==`string`)&&!bw(r)?null:yw(e.sessionId,n)}if(e.type!==`native.raw`)return null;let t=$C(e.payload.raw)?e.payload.raw:{},n=$C(t.message)?t.message:{},r=$C(n.params)?n.params:{};if(!bw(xw(n.method)??xw(t.method)??``))return null;let i=$C(r.msg)?r.msg:{},a=xw(r.itemId)??xw(r.item_id)??xw(i.itemId)??xw(i.item_id);return a?`${e.sessionId}|${a}`:null}function yw(e,t){let n=xw(t.id)??xw(t.item_id)??xw(t.itemId);return n?`${e}|${n}`:null}function bw(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function xw(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}var Sw=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${Cg(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}getWatchSubscriptions(e){let t=new Map;for(let n of this.clients.values())for(let r of n.subscriptionsBySessionId.values())r.purpose===e&&t.set(r.sessionId,r);return[...t.values()]}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=null;for(let r of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);if(!(!i||i.socket.readyState!==i.socket.OPEN)){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),i.socket.send(n)}}}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}i.socket.send(JSON.stringify(e))}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendBroadcastMessage(e,t){let n=JSON.stringify(e);for(let e of this.clients.values())if(e.socket.readyState===e.socket.OPEN){if(t?.sessionId){let n=e.subscriptionsBySessionId.get(t.sessionId);if(!n||t.purpose&&n.purpose!==t.purpose)continue}e.socket.send(n)}}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}};const Cw=1200,ww=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`;var Tw=class{statesByKey=new Map;targetsByClientId=new Map;constructor(e){this.options=e}setClientWatchTargets(e,t,n){let r=new Map;for(let e of t){let t=e.sessionId.trim(),n=e.projectId?.trim()??``;!t||!n||r.set(this.stateKey(n,t),{sessionId:t,projectId:n})}let i=this.targetsByClientId.get(e)??new Map,a=n?new Map:new Map(i);for(let[e,t]of r)a.set(e,t);for(let[t,n]of i)a.has(t)||this.removeClientFromState(e,n.projectId??``,n.sessionId);for(let[t,n]of a)i.get(t)||this.addClientToState(e,n.projectId??``,n.sessionId);return this.targetsByClientId.set(e,a),[...a.values()]}removeClient(e){let t=this.targetsByClientId.get(e);if(t){for(let n of t.values())this.removeClientFromState(e,n.projectId??``,n.sessionId);this.targetsByClientId.delete(e)}}close(){for(let e of this.statesByKey.values())this.disposeState(e);this.statesByKey.clear(),this.targetsByClientId.clear()}logDebug(e,t){ww&&(console.log(`[native-watch][gateway]`,e,t),this.options.logger.info?.({event:e,...t},`native session watch debug`))}addClientToState(e,t,n){if(!t||!n)return;let r=this.stateKey(t,n),i=this.statesByKey.get(r);i||(i={provider:`codex`,sessionId:n,projectId:t,ownerClientIds:new Set,fileWatcher:null,debounceTimer:null,catchupRetryTimer:null,reconcileTimer:setInterval(()=>{this.requestSync(r,`reconcile`)},25e3),syncInFlight:!1,rerunRequested:!1,stableIdleSyncCount:0,watchCatchupRetryCount:0,lastObservedRawSeq:0,lastObservedRawEventCount:0,lastTriggeredAt:0,lastSyncStartedAt:null,lastSyncCompletedAt:null},this.statesByKey.set(r,i),this.logDebug(`state.created`,{clientId:e,projectId:t,sessionId:n})),i.ownerClientIds.add(e),this.logDebug(`lease.added`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:i.ownerClientIds.size}),this.requestSync(r,`lease_added`)}removeClientFromState(e,t,n){let r=this.statesByKey.get(this.stateKey(t,n));r&&(r.ownerClientIds.delete(e),this.logDebug(`lease.removed`,{clientId:e,projectId:t,sessionId:n,ownerClientCount:r.ownerClientIds.size}),!(r.ownerClientIds.size>0)&&(this.disposeState(r),this.statesByKey.delete(this.stateKey(t,n))))}disposeState(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null),this.clearCatchupRetry(e,{resetAttempts:!0}),clearInterval(e.reconcileTimer),e.fileWatcher?.close(),e.fileWatcher=null,this.logDebug(`state.disposed`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:e.watchedPath})}async requestSync(e,t){let n=this.statesByKey.get(e);if(n){if(n.lastTriggeredAt=Date.now(),n.syncInFlight){n.rerunRequested=!0;return}n.syncInFlight=!0,n.rerunRequested=!1,n.lastSyncStartedAt=Date.now(),this.logDebug(`sync.begin`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,ownerClientCount:n.ownerClientIds.size,watchedPath:n.watchedPath,watchedDir:n.watchedDir,watchedBaseName:n.watchedBaseName,stableIdleSyncCount:n.stableIdleSyncCount});try{let r=await this.options.sessionManager.getProjectSessionSummary(n.projectId,n.sessionId);if(!r||r.providerMode!==`native`||r.provider!==`codex`&&r.provider!==`claude`){this.logDebug(`sync.stop.unwatchable_summary`,{projectId:n.projectId,sessionId:n.sessionId,summarySource:r?.source,summaryProvider:r?.provider,summaryProviderMode:r?.providerMode,summaryStatus:r?.status}),this.stopState(e);return}n.provider=r.provider;let i=await this.options.sessionManager.syncProjectSessionHistory(n.projectId,n.sessionId);n.lastSyncCompletedAt=Date.now(),this.applyWatchPath(n,i.nativeWatchPath);let a=n.lastObservedRawSeq,o=n.lastObservedRawEventCount,s=this.resolveObservedRawSeq(i),c=s>a||i.rawEvents.length>o;if(c?this.clearCatchupRetry(n,{resetAttempts:!0}):this.maybeScheduleWatchCatchupRetry(e,n,t,i,{previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length}),n.lastObservedRawSeq=Math.max(n.lastObservedRawSeq,s),n.lastObservedRawEventCount=Math.max(n.lastObservedRawEventCount,i.rawEvents.length),i.session.status!==`running`&&!i.historyUpdated?n.stableIdleSyncCount+=1:n.stableIdleSyncCount=0,this.logDebug(`sync.result`,{projectId:n.projectId,sessionId:n.sessionId,reason:t,status:i.session.status,interactionLockReason:i.session.interactionLockReason,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,nativeWatchPath:i.nativeWatchPath,rawEventCount:i.rawEvents.length,cursorAdvanced:c,previousObservedRawSeq:a,previousObservedRawEventCount:o,nextObservedRawSeq:s,nextObservedRawEventCount:i.rawEvents.length,watchCatchupRetryCount:n.watchCatchupRetryCount,stableIdleSyncCount:n.stableIdleSyncCount}),i.historyUpdated||i.statusChanged){let e=this.options.createExternalUpdateMessage({provider:i.session.provider,sessionId:i.session.id,projectId:i.session.projectId,updatedAt:i.session.updatedAt,status:i.session.status,interactionLockReason:i.session.interactionLockReason,refreshMode:i.refreshMode,fromRawSeq:i.fromRawSeq,toRawSeq:i.toRawSeq,historyUpdated:i.historyUpdated,statusChanged:i.statusChanged});for(let t of n.ownerClientIds)this.options.sendStreamMessage(t,e)}}catch(e){this.options.logger.warn({err:e,projectId:n.projectId,sessionId:n.sessionId,reason:t},`native session watch sync failed`)}finally{let n=this.statesByKey.get(e);if(!n)return;n.syncInFlight=!1,n.rerunRequested&&(this.logDebug(`sync.rerun`,{projectId:n.projectId,sessionId:n.sessionId,reason:t}),n.rerunRequested=!1,this.requestSync(e,`rerun`))}}}stopState(e){let t=this.statesByKey.get(e);if(t){this.disposeState(t),this.statesByKey.delete(e);for(let t of this.targetsByClientId.values())t.delete(e)}}applyWatchPath(e,t){let n=t?.trim()??``;if(!n)return;let r=p.default.resolve(n);if(e.watchedPath===r&&e.fileWatcher)return;let i=p.default.dirname(r),a=p.default.basename(r);e.fileWatcher?.close(),e.fileWatcher=null,e.watchedPath=r,e.watchedDir=i,e.watchedBaseName=a,this.logDebug(`watch.path.applied`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,watchedDir:i,watchedBaseName:a});try{e.fileWatcher=this.createPathWatcher(r,(t,n)=>{let i=n?Buffer.isBuffer(n)?n.toString(`utf8`):n:void 0;this.logDebug(`watch.fs.event`,{projectId:e.projectId,sessionId:e.sessionId,watchedPath:r,eventType:t,filename:i}),this.scheduleDebouncedSync(this.stateKey(e.projectId,e.sessionId))}),e.fileWatcher.on(`error`,t=>{this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`native session watcher error`)})}catch(t){this.options.logger.warn({err:t,projectId:e.projectId,sessionId:e.sessionId,watchedPath:r},`failed to start native session watcher`)}}createPathWatcher(e,t){return this.options.createWatcher?this.options.createWatcher(e,t):(0,u.watch)(e,(e,n)=>{t(e,n)})}scheduleDebouncedSync(e){let t=this.statesByKey.get(e);if(!t)return;let n=!!t.debounceTimer;t.debounceTimer&&clearTimeout(t.debounceTimer),this.clearCatchupRetry(t,{resetAttempts:!0}),this.logDebug(`watch.debounce.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath,delayMs:300,replacedExistingTimer:n}),t.debounceTimer=setTimeout(()=>{t.debounceTimer=null,this.logDebug(`watch.debounce.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchedPath:t.watchedPath}),this.requestSync(e,`watch`)},300)}resolveObservedRawSeq(e){let t=e.rawEvents[e.rawEvents.length-1],n=t&&typeof t==`object`&&t&&`rawSeq`in t&&typeof t.rawSeq==`number`?t.rawSeq:void 0;return e.toRawSeq??n??0}clearCatchupRetry(e,t){e.catchupRetryTimer&&=(clearTimeout(e.catchupRetryTimer),null),t?.resetAttempts&&(e.watchCatchupRetryCount=0)}maybeScheduleWatchCatchupRetry(e,t,n,r,i){n!==`watch`&&n!==`watch_catchup`||t.ownerClientIds.size!==0&&(t.watchCatchupRetryCount>=2||(t.catchupRetryTimer||=(t.watchCatchupRetryCount+=1,this.logDebug(`watch.catchup.scheduled`,{projectId:t.projectId,sessionId:t.sessionId,reason:n,delayMs:Cw,historyUpdated:r.historyUpdated,refreshMode:r.refreshMode,previousObservedRawSeq:i.previousObservedRawSeq,previousObservedRawEventCount:i.previousObservedRawEventCount,nextObservedRawSeq:i.nextObservedRawSeq,nextObservedRawEventCount:i.nextObservedRawEventCount,watchCatchupRetryCount:t.watchCatchupRetryCount}),setTimeout(()=>{t.catchupRetryTimer=null,this.logDebug(`watch.catchup.fired`,{projectId:t.projectId,sessionId:t.sessionId,watchCatchupRetryCount:t.watchCatchupRetryCount}),this.requestSync(e,`watch_catchup`)},Cw))))}stateKey(e,t){return`${e}::${t}`}};function Ew(e){return e.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`},purpose:e.purpose}))}const Dw=process.env.NATIVE_SESSION_WATCH_DEBUG===`1`||process.env.EXPO_PUBLIC_NATIVE_SESSION_WATCH_DEBUG===`1`,Ow=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function kw(e,t){Dw&&console.log(`[native-watch][gateway]`,e,t)}function Aw(e,t){Ow&&console.log(`[session-fetch][gateway] ${e}`,t)}async function jw(e){let t=e.limit??300,n=(n,r)=>{Aw(`raw-events.list`,{requestSource:e.requestSource,projectId:e.projectId,sessionId:e.sessionId,limit:t,requestedCursor:e.fromRawSeqExclusive??null,decision:n.decision,reason:n.reason,fromRawSeqExclusive:n.fromRawSeqExclusive??null,toRawSeq:n.toRawSeq??null,returnedCount:n.events.length,returnedFirstRawSeq:n.events[0]?.rawSeq??null,returnedLastRawSeq:n.events[n.events.length-1]?.rawSeq??null,...r})};if(e.fromRawSeqExclusive===void 0){let r=await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t),i={decision:`snapshot`,reason:r.length===0?`empty_history_snapshot`:`initial_snapshot`,events:r};return n(i),i}let r=await e.sessionManager.getProjectSessionRawSeqRange(e.projectId,e.sessionId);if(!r){let e={decision:`snapshot`,reason:`empty_history_snapshot`,events:[]};return n(e,{rangeMin:null,rangeMax:null,minExpectedCursor:null}),e}let i=Math.max(0,r.min-1);if(e.fromRawSeqExclusive<i||e.fromRawSeqExclusive>r.max){let a={decision:`snapshot`,reason:`cursor_out_of_range`,events:await e.sessionManager.getProjectSessionRawEvents(e.projectId,e.sessionId,t)};return n(a,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),a}let a=await e.sessionManager.getProjectSessionRawEventsSinceSeq(e.projectId,e.sessionId,e.fromRawSeqExclusive,t),o={decision:`delta`,reason:`cursor_valid_delta`,fromRawSeqExclusive:e.fromRawSeqExclusive,toRawSeq:a[a.length-1]?.rawSeq??e.fromRawSeqExclusive,events:a};return n(o,{rangeMin:r.min,rangeMax:r.max,minExpectedCursor:i}),o}async function Mw(e,t={}){await uu(e.gatewayLogPath);let n=Pw(e,t),r=Nw(e,n.instance);await r.register(vg.default,{origin:!0}),await r.register(_g.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new v_(e);await s.init();let c=new O_(e.auditLogPath),l=new Sw,u=new pv,d=new Sv(e.projectStoreDir),f=new QC(e.sessionHistoryDir);await f.init();let m=new Hx(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new kx({store:m});await h.init();let g,_=null,v=await tc(e.authStoreDir),y=new $S({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}}),b=new Tw({sessionManager:y,logger:r.log,sendStreamMessage:(e,t)=>{l.sendStreamMessage(e,t)},createExternalUpdateMessage:e=>N(e)});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let x=new kl({packageName:P.packageName,currentVersion:P.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>y.getRunningRuntimeSessionCount(),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{b.close(),_?.close(),S.close(),await x.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:re(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:fl(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>sl({gatewayId:e.gatewayId,machineName:fl(),relayBaseUrl:e.relayEnabled?bl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:vl({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ne(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(e,t)=>{let n=wa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=he(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),Ww(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=Da.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await Lw({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(e,t))try{return await x.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!L(e,t))return;let n=e.body,r=Pa.safeParse(n?.requestedBy);try{let e=await x.applyUpdate(r.success?r.data:`mobile`);return za.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.post(`/api/codex/app-server/restart`,async(e,t)=>{if(L(e,t))try{return Aa.parse(await y.restartCodexAppServer())}catch(e){let n=t_(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(L(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(L(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return t_(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):Jw(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return t_(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=le(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return t_(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=se(r.status,t);if(!i)return;let a=ce(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return t_(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/config`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=await y.getProjectSessionConfig(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.post(`/api/projects/:projectId/sessions/:sessionId/history-sync`,async(e,t)=>{if(!L(e,t))return;let n=e.params;try{let e=await y.syncProjectSessionHistory(n.projectId,n.sessionId);return{session:e.session,rawEventCount:e.rawEvents.length}}catch(e){return t_(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})(),a=typeof r.fromRawSeqExclusive==`string`?Number(r.fromRawSeqExclusive):void 0;try{return await te(n.projectId,n.sessionId,i,typeof a==`number`&&Number.isFinite(a)?Math.max(0,Math.floor(a)):void 0,`http`)}catch(e){return t_(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>ne(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ne(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=ue(t.headers.authorization)??de(t.url);if(!n){e.close(1008,`Missing access token`);return}let r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await w(fa(e),r.sub,i)}catch(e){await T({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{b.removeClient(i),l.removeClient(i)})});let S=new tS({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=he(e.deviceName);return Ww(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await Lw({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return Iw(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>Hw(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:x,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await w(e,t,n)}catch(r){await T({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),C=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.external.watch.set`:{kw(`command.received`,{clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,sessionCount:e.payload.sessions.length,sessions:e.payload.sessions},`received session.external.watch.set`);let i=b.setClientWatchTargets(n,e.payload.sessions,e.payload.replace);kw(`command.applied`,{clientId:n,deviceId:t,replace:e.payload.replace,targetCount:i.length,targets:i}),r.log.info({clientId:n,deviceId:t,replace:e.payload.replace,targetCount:i.length,targets:i},`applied session.external.watch.set`),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:i.map(e=>e.sessionId)}});return}case`session.stream.subscribe`:{let t=Ew(e.payload.sessions);await E(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},w=async(e,t,n)=>{await C(e,t,n)},T=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},E=async(e,t,n)=>{let r=D(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await O(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},D=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},O=async(e,t)=>{let n=await k(t);if(t.cursor.kind===`all`){await A(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await A(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await A(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,M({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},k=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw c_(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},A=async(e,t,n)=>{let r=`snap_${Cg(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=j(i,500),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,ee({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},j=(e,t)=>{if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r},M=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${Cg(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),ee=e=>({v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events}}}),N=e=>({v:`1.0`,kind:`session.external.update`,type:`session.external.update`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`session_external_update_${Cg(12)}`,ts:new Date().toISOString(),payload:{raw:{updatedAt:e.updatedAt,status:e.status,interactionLockReason:e.interactionLockReason,refreshMode:e.refreshMode,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq,historyUpdated:e.historyUpdated,statusChanged:e.statusChanged}}}),te=async(e,t,n=300,r,i=`http`)=>jw({sessionManager:y,projectId:e,sessionId:t,limit:n,fromRawSeqExclusive:r,requestSource:i}),ne=t=>t.headers[`x-api-key`]===e.apiKey,re=e=>{if(e==null)return e;if(typeof e==`string`){let t=F(e);return t===void 0?ie(e,a):ae(I(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=F(t);return n===void 0?ie(t,a):ae(I(n))}return typeof e==`object`?ae(I(e)):String(e)},F=e=>{try{return JSON.parse(e)}catch{return}},ie=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,I=e=>{if(Array.isArray(e))return e.map(e=>I(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=I(r)}return n}return e},ae=e=>{let t=oe(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ie(t,a)}},oe=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=ue(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},se=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ce=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},le=(e,t)=>{let n=e.params,r=e.query,i=Mi.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},ue=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},de=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},fe=e.httpsEnabled?e.httpsPort:e.port,pe=e.httpsEnabled?`https`:`http`,me=fl(),he=e=>e?.trim()||me||`Gateway`;await r.listen({host:e.host,port:fe});let ge=r.server.address(),_e=typeof ge==`object`&&ge?ge.port:fe;if(r.log.info({host:e.host,port:_e,protocol:pe,machineName:me},Fw(pe,e.host,_e)),e.relayEnabled&&(_=new uS({gatewayId:e.gatewayId,machineName:me,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>hS({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:vl({protocol:pe,host:e.host,port:_e}),logger:r.log,onFrame:async e=>{await S.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await x.start(),{protocol:pe,listenPort:_e,machineName:me,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>x.getInfo(),requestGatewayUpdate:(e=`console`)=>x.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function Nw(e,t){let n=t;if(!e.httpsEnabled)return(0,yg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,yg.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 Pw(e,t){let n=process.env.NODE_ENV!==`production`,r=$g.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?$g.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,$g.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function Fw(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function Iw(e,t){if(e&&e!==t)throw o_()}async function Lw(e){let t=Rw(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:zw(t)},`auth refresh attempt`);try{let t=await e.execute(),n=Rw(e.authService,e.refreshToken),r=Rw(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:zw(n),nextRefreshToken:zw(r)},`auth refresh succeeded`),t}catch(t){let n=Rw(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:zw(n),error:Bw(t)},`auth refresh failed`),t}}function Rw(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function zw(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:Vw(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:Vw(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function Bw(e){return t_(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function Vw(e){return e?e.slice(-8):null}async function Hw(e,t){try{let n=Mo.parse(e);switch(n.method){case`auth.refresh`:{let e=await Lw({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 Iw(n.params.deviceId??t.relayDeviceId,e.deviceId),No.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return No.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return No.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return No.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return No.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return No.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return No.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return No.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw Kw(n.method,`NOT_FOUND`,404,`Project not found`);return No.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 No.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 No.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return No.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw Kw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return No.parse({method:n.method,result:{session:e}})}case`sessions.config.get`:{let e=await t.sessionManager.getProjectSessionConfig(n.params.projectId,n.params.sessionId);if(!e)throw Kw(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return No.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return No.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=n.params.limit===`all`?2**53-1:n.params.limit,r=await jw({sessionManager:t.sessionManager,projectId:n.params.projectId,sessionId:n.params.sessionId,limit:e,fromRawSeqExclusive:n.params.fromRawSeqExclusive,requestSource:`rpc`});return No.parse({method:n.method,result:r})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),No.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return No.parse({method:n.method,result:e})}case`devices.list`:return No.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw Kw(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return No.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw Kw(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw Uw(e)}}function Uw(e){if(t_(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return Kw(`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 Kw(`NOT_FOUND`,e.status,String(e),e.details);case`SESSION_TURN_CONFLICT`:case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return Kw(`BAD_REQUEST`,e.status,String(e),e.details);default:return Kw(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=Fo.safeParse(e);if(t.success)return t.data;let n=Po.safeParse(e);if(n.success)return Kw(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 Kw(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?Kw(`BAD_REQUEST`,400,r):qw(e)?Kw(`UNAUTHORIZED`,401,r):Jw(r)?Kw(`BAD_REQUEST`,400,r):Kw(`INTERNAL`,500,r)}function Ww(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:Gw(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:ic(e.identity,e.privateKeyPem,i)}}function Gw(e){return e.replace(/\s+/gu,``).toUpperCase()}function Kw(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 Fo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function qw(e){return t_(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||__(e)}function Jw(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}function Yw(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function Xw(e){let t=await pc({configPath:e.configPath,ensureConfigFile:!0});_c(t.config);let n=await Mw(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{Qw({type:`worker.update.prepared`,payload:e})}});Qw({type:`worker.ready`,payload:Zw(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=$w(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${Yw(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${Yw(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);Qw({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}case`codex.appServer.restart`:{if(!n.requestCodexAppServerRestart)throw Error(`codex app-server restart is unavailable`);let t=await n.requestCodexAppServerRestart(e.requestedBy);Qw({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){Qw({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function Zw(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function Qw(e){process.send&&process.send(e)}function $w(e){if(!eT(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:e.method,requestedBy:e.requestedBy};default:return null}}function eT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}tT(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function tT(e){let t=ne(e);switch(t.command){case`help`:oT();return;case`version`:console.log(P.version);return;case`init`:await rT(t);return;case`doctor`:await iT(t);return;case`start`:await nT(t);return;case`__worker`:await aT(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function nT(e){let t=await pc({configPath:e.configPath,ensureConfigFile:!0});_c(t.config);let n=await Fc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await nu({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(du(e,t.config))}Ic(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function rT(e){let t=await fc({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 pc({configPath:t.configPath,ensureConfigFile:!1}),r=await Fc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Lc(r))}async function iT(e){let t=await pc({configPath:dc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Fc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Lc(n)),Ic(n)&&(process.exitCode=1)}async function aT(e){try{await Xw(e)}catch(t){let n=await pc({configPath:e.configPath,ensureConfigFile:!0});throw Error(du(t,n.config))}}function oT(){console.log(`${P.cliName} ${P.version}`),console.log(``),console.log(`Usage:`),console.log(` ${P.cliName} [start] [--config <path>] [--log]`),console.log(` ${P.cliName} init [--config <path>] [--force]`),console.log(` ${P.cliName} doctor [--config <path>]`),console.log(` ${P.cliName} --version`)}exports.runCli=tT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "craby-gateway",
3
- "version": "0.16.5",
3
+ "version": "0.16.6",
4
4
  "description": "Craby desktop gateway CLI",
5
5
  "bin": {
6
6
  "craby-gateway": "dist-sea/gateway.cjs"